Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(GBRA-130 A-6): a sync page write that fails the same unclassifiable way three times is held page_write_failed

garrytanb7c52f02780f
diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.ts
index d2cc9fccf7..a826b8099f 100644
--- a/src/core/persistence/sync-fault-class.ts
+++ b/src/core/persistence/sync-fault-class.ts
@@ -78,6 +78,9 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [
// #6712 PR 4b (design v3.2 §3.1): a live pass settled the path three passes in a row and it never classified settled; a gbrain bug or an environment fault, never a loop.
{ code: 'settle_mismatch', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always: the pass cannot tell why the path does not settle',
human_reason: 'Sync settled this file three passes in a row but it never read settled afterwards; read gbrain doctor --json and gbrain sources writer status <source> (read-only), fix what they name, then run gbrain sources retry-held <source> to re-test it.' },
+ // GBRA-130 A-6: one path's write failed the same unclassifiable way on repeated attempts; held so the rest of the source moves.
+ { code: 'page_write_failed', class: 'page', safe_actions: ['upgrade'], needs_human: true, escalate: 'always: the writer cannot place the failure',
+ human_reason: 'The write of this file keeps failing with an error gbrain cannot classify (an owner exception or an unplaced refusal); read its receipt (gbrain write-request <request_id>), report it with the gbrain version or fix the file when the error names its content, then run gbrain sources retry-held <source>.' },
// Older releases recorded these as run failures; a rerun on this release holds the page instead.
{ code: 'revision_conflict', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the same path fails again after a rerun' },
{ code: 'page_identity_changed', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the same path fails again after a rerun' },
diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.ts
index 6304b83171..57aeb2011f 100644
--- a/src/core/persistence/sync-holds.ts
+++ b/src/core/persistence/sync-holds.ts
@@ -71,7 +71,11 @@ type Exec = Pick<BrainEngine, 'executeRaw'>;
export type GitHoldCode = ContentRefusal['code'] | 'rename_held' | 'parser_regression' | 'managed_image_sync_unsupported' | 'concurrent_write' | 'preparation_stalled' | 'worktree_dirty' | 'file_drift'
| 'legacy_slug_conflict'
/** #6712 PR 4b (design v3.2 §3.1): a path a live pass settled in three consecutive passes at one level that never classified settled. */
- | 'settle_mismatch';
+ | 'settle_mismatch'
+ /** GBRA-130 A-6: the path's write failed the same unclassifiable way (an owner exception, an unplaced refusal) on repeated attempts. */
+ | 'page_write_failed';
+/** GBRA-130 A-6: the fault a `page_write_failed` hold stands for (identifiers and classes only, never content). */
+export interface PageWriteFailureMeta { code: string; origin: string | null; error_class: string | null; errno: string | null; request_id: string; attempts: number; gbrain_version: string }
/** #6278: what the owner recorded about a preparation it gave up on (step names and vocabulary only, never content). */
export interface PreparationStallMeta {
request_id: string;
@@ -141,6 +145,8 @@ export interface GitHoldMeta {
content_repair?: ContentHoldRepairState;
/** #6278 `preparation_stalled`: the failed receipt's step, wait cause and attempt count. */
stall?: PreparationStallMeta;
+ /** GBRA-130 A-6 `page_write_failed`: the repeated failure (code, origin, error class, SQLSTATE), its newest receipt and the gbrain that held it. */
+ write_failure?: PageWriteFailureMeta;
/** #6278: the held entry is a deletion (the file is gone); discovery re-screens it on request or a gbrain change, not on its absence. */
deleted?: true;
/**
@@ -524,7 +530,9 @@ export function holdRescreenDue(record: Pick<GitHoldRecord, 'code' | 'meta'>, re
|| (record.code === 'managed_image_sync_unsupported' && isMultimodalEnabled())
|| record.meta.recovery_version < RECOVERY_VERSION
|| (record.code === 'invalid_fence' && (record.meta.fence_version ?? 0) < FENCE_VERSION)
- || (record.code === 'preparation_stalled' && record.meta.stall?.gbrain_version !== VERSION);
+ || (record.code === 'preparation_stalled' && record.meta.stall?.gbrain_version !== VERSION)
+ // GBRA-130 A-6: an owner fault is the writer's, not the file's: an upgrade re-tests the path.
+ || (record.code === 'page_write_failed' && record.meta.write_failure?.gbrain_version !== VERSION);
}
/**
@@ -651,6 +659,16 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'c
switch (record.code) {
case 'invalid_fence':
return fenceHoldFix(record, auto);
+ case 'page_write_failed': {
+ const failure = record.meta.write_failure;
+ const verify = { argv: ['gbrain', 'sources', 'status', source, '--json'] };
+ return { argv: ['gbrain', 'write-request', '--', failure?.request_id ?? '<request_id>'], consent: [], actor: 'agent', requires_exclusive: false, docs: 'docs/guides/write-refusals.md#page_write_failed',
+ why: `The write of ${record.path} failed the same way ${failure?.attempts ?? 'several'} times (${failure?.origin ?? failure?.code ?? 'an unclassified failure'}${failure?.errno ? `, SQLSTATE ${failure.errno}` : ''}${failure?.error_class ? `, ${failure.error_class}` : ''}), so sync held it and the rest of the source kept syncing. `
+ + 'The receipt (read-only) names the error; report it with the gbrain version, or fix the file when the error names its content. An upgrade re-tests the path on its own.',
+ then: { argv: ['gbrain', 'sources', 'retry-held', source], consent: [], actor: 'agent', requires_exclusive: false, verify,
+ why: `Schedules ${record.path} for a re-screen on the next sync once the cause is fixed.` },
+ verify };
+ }
case 'worktree_dirty': {
const verify = { argv: ['gbrain', 'sources', 'status', source, '--json'] };
return { argv: ['gbrain', 'sync', 'unblock', '--source', source, '--apply', '--json'], consent: [], actor: 'agent', requires_exclusive: false, docs: 'docs/guides/write-refusals.md#worktree_dirty',
diff --git a/src/core/persistence/sync-page-fault.ts b/src/core/persistence/sync-page-fault.ts
index 350a0c561d..faa286b6af 100644
--- a/src/core/persistence/sync-page-fault.ts
+++ b/src/core/persistence/sync-page-fault.ts
@@ -36,7 +36,9 @@ import { readSyncFile, syncGitPath, type SyncDiscovery, type SyncEntry, type Syn
import { readTreeBlobs } from './sync-blobs.ts';
import type { SyncIntent } from './sync-prepare.ts';
import type { HeldEntry } from './sync-screen.ts';
-import type { GitHoldMeta, GitHoldRecord } from './sync-holds.ts';
+import type { GitHoldMeta, GitHoldRecord, PageWriteFailureMeta } from './sync-holds.ts';
+import { classifyTerminal } from './terminal-classify.ts';
+import { VERSION } from '../../version.ts';
import { concurrentWriteHold, concurrentWriteProof } from './sync-concurrent-write.ts';
import { KEEP_DISK_ABANDONED_PREFIX } from './verb-errors.ts';
@@ -127,7 +129,7 @@ export async function liveRevision(engine: Pick<BrainEngine, 'executeRaw'>, sour
return row?.revision ?? null;
}
-function base(entry: HoldEntry, slug: string, pageId: number | null, code: 'concurrent_write' | 'worktree_dirty' | 'file_drift',
+function base(entry: HoldEntry, slug: string, pageId: number | null, code: 'concurrent_write' | 'worktree_dirty' | 'file_drift' | 'page_write_failed',
message: string, content: string | null, blobOid: string | null | undefined, meta: Partial<GitHoldMeta>): HeldEntry {
const rename: SyncRename | undefined = entry.renameFrom ?? entry.renameHeld;
return { path: entry.path, source_path: entry.sourcePath, slug, page_id: pageId, code, message, upstream_version: content === null ? null : sha256(content),
@@ -236,8 +238,14 @@ export async function pageMovedSinceAdmission(engine: Pick<BrainEngine, 'execute
* run's receipt branch and the start-of-run conversion of an older release's blocked cursor.
*/
export async function receiptPageFaultHold(engine: Pick<BrainEngine, 'executeRaw'>, input: { sourceId: string; incarnation: string; entry: HoldEntry;
- pending: { slug: string; pageId: number | null; intent: SyncIntent }; done: Pick<WriteRequest, 'state' | 'error_code' | 'error_message'> }): Promise<HeldEntry | null> {
+ pending: { slug: string; pageId: number | null; intent: SyncIntent }; done: Pick<WriteRequest, 'request_id' | 'state' | 'error_code' | 'error_message' | 'error_detail'> }): Promise<HeldEntry | null> {
const { entry, pending, done } = input;
+ const repeated = await repeatedWriteFailure(engine, input.sourceId, input.incarnation, pending.slug, done);
+ if (repeated) return base(entry, pending.slug, pending.pageId, 'page_write_failed',
+ `${entry.path}: its ${entry.action === 'delete' ? 'deletion' : 'import'} failed the same way ${repeated.attempts} times (${repeated.origin ?? repeated.code}${repeated.errno ? `, SQLSTATE ${repeated.errno}` : ''}${repeated.error_class ? `, ${repeated.error_class}` : ''}; request ${done.request_id}), so it is held and the rest of the source synced. `
+ + 'Read the receipt with gbrain write-request, report it or fix the file, then gbrain sources retry-held; an upgrade re-tests it on its own.',
+ typeof pending.intent.content === 'string' ? pending.intent.content : null, typeof pending.intent.blobOid === 'string' ? pending.intent.blobOid : null,
+ { write_failure: { ...repeated, request_id: done.request_id, gbrain_version: VERSION } });
const page = pending.intent.kind === 'managed_sync_import' && typeof pending.intent.content === 'string';
const proof = page ? await concurrentWriteProof(engine, { sourceId: input.sourceId, incarnation: input.incarnation, pending, done }) : null;
if (proof) return concurrentWriteHold(entry, pending.slug, pending.pageId!, pending.intent, proof);
@@ -246,6 +254,38 @@ export async function receiptPageFaultHold(engine: Pick<BrainEngine, 'executeRaw
return page && pinnedWorktreeConflict(done) ? worktreeDirtyHold(entry, pending.slug, pending.pageId, pending.intent, done.error_message === CANONICAL_WRITEBACK_CONFLICT ? 'writeback' : 'page') : null;
}
+/**
+ * GBRA-130 A-6: a sync page write that failed the same unclassifiable way this many times (the receipts of this path in this
+ * source incarnation, this one included) is held `page_write_failed` instead of stopping every later sync at the entry. It
+ * matches `STOPS_PER_ENTRY` (sync-run.ts), the re-freezes a run gives a stopped entry.
+ */
+export const PAGE_WRITE_FAILURE_REPEATS = 3;
+/** The terminal categories that place no fault (an owner exception, a refusal the receipt does not explain); writer, binding and schema stops are not among them. */
+const UNPLACED = new Set(['owner_exception', 'diagnosis_required']);
+/**
+ * GBRA-130 A-6: the fault of a failed sync page receipt the terminal classifier cannot place, once the same path failed with
+ * the same (code, origin, error class, SQLSTATE) `PAGE_WRITE_FAILURE_REPEATS` times; null otherwise (one occurrence still
+ * stops the run, so a transient defect never holds a file).
+ */
+async function repeatedWriteFailure(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, incarnation: string, slug: string,
+ done: Pick<WriteRequest, 'request_id' | 'state' | 'error_code' | 'error_message' | 'error_detail'>): Promise<Omit<PageWriteFailureMeta, 'request_id' | 'gbrain_version'> | null> {
+ if (done.state !== 'failed' || !done.error_code) return null;
+ const detail = (done.error_detail ?? null) as Record<string, unknown> | null;
+ const verdict = classifyTerminal({ source_id: sourceId, slug, operation: 'submit_job', state: 'failed', error_code: done.error_code, error_detail: detail,
+ recovery: null, blocked_reason: null, compacted: false, error_message: done.error_message ?? null, intent_kind: 'managed_sync_import' });
+ // A `publication_timeout` receipt already spent its attempts (A-5): its path is held on the first one.
+ const exhausted = done.error_code === 'publication_timeout';
+ if (!exhausted && (!verdict || !UNPLACED.has(verdict.category))) return null;
+ const field = (key: string) => typeof detail?.[key] === 'string' ? detail[key] as string : null;
+ const fault = { code: done.error_code, origin: field('origin'), error_class: field('error_class'), errno: field('errno') ?? field('sqlstate') };
+ const [row] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND source_incarnation=$2::uuid AND slug=$3
+ AND state='failed' AND intent->>'kind' IN ('managed_sync_import','managed_sync_delete') AND error_code=$4 AND COALESCE(error_detail->>'origin','')=$5
+ AND COALESCE(error_detail->>'error_class','')=$6 AND COALESCE(error_detail->>'errno',error_detail->>'sqlstate','')=$7`,
+ [sourceId, incarnation, slug, fault.code, fault.origin ?? '', fault.error_class ?? '', fault.errno ?? '']);
+ const attempts = Number(row?.n ?? 0);
+ return attempts >= (exhausted ? 1 : PAGE_WRITE_FAILURE_REPEATS) ? { ...fault, attempts } : null;
+}
+
/**
* The `concurrent_write` hold for an entry whose recorded origin no longer identifies the page this sync enumerated
* (`assertSyncPageOrigin` refused at freeze time: the page at that origin was deleted, re-bound or replaced in the database).
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 94141d34da..cde1c8f706 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -254,6 +254,7 @@ test/persistence-sync-lease.test.ts
test/persistence-write-stall.test.ts
test/persistence-writer-fences.test.ts
test/physical-root-birth-tolerance-6501.test.ts
+test/publication-timeout-charge-gbra130.test.ts
test/purge-fact.test.ts
test/purge-global-marker.test.ts
test/purge-missing-cache-6911.test.ts
@@ -308,6 +309,7 @@ test/sync-legacy-holds.test.ts
test/sync-legacy-retry-actions-6696.test.ts
test/sync-legacy-slug-adoption-6727.test.ts
test/sync-origin-live-wins-6517.test.ts
+test/sync-page-write-failed-gbra130.test.ts
test/sync-prescreen-both-delta-6712.test.ts
test/sync-prescreen-drift-6712.test.ts
test/sync-slug-root-mode-6694.test.ts
diff --git a/test/sync-page-write-failed-gbra130.test.ts b/test/sync-page-write-failed-gbra130.test.ts
new file mode 100644
index 0000000000..7e236a9087
--- /dev/null
+++ b/test/sync-page-write-failed-gbra130.test.ts
@@ -0,0 +1,76 @@
+/**
+ * GBRA-130 A-6 (#6712 PR 4b): one page request of a managed sync that ends with an error the terminal classifier cannot
+ * place (an owner exception such as Postgres 54000 from a frontmatter tag over the btree row limit, a TypeError in the
+ * preparer, an unknown code) classified `systemic`: the run stopped `blocked_by_failures` at that entry and every later
+ * sync stopped at the same entry again, so the rest of the source never imported.
+ *
+ * Protects (red before: every sync is `blocked_by_failures` at b.md, c.md never imports):
+ * - the entry is held per path (`page_write_failed`, needs a human, the owner error as its reason) once the run re-froze
+ * it `STOPS_PER_ENTRY` times with the same fault, and the rest of the source imports;
+ * - a later sync is not blocked by it.
+ * Two triggers: a real 3000-character frontmatter tag (Postgres: btree 54000; PGLite has no such limit, so the PGLite
+ * twin injects the same owner exception), and a TypeError thrown at `consumer:preparing` for b.md's requests.
+ * Runs on PGLite and, with DATABASE_URL, on Postgres.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomBytes } from 'node:crypto';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { readGitHold } from '../src/core/persistence/sync-holds.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const commit = (root: string, message: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };
+const note = (title: string, extra = '') => `---\ntype: concept\ntitle: ${title}\n${extra}---\n\nThe body of ${title}.\n`;
+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };
+/** Incompressible, so its btree index tuple stays over the 2704-byte row limit. */
+const LONG_TAG = randomBytes(1500).toString('hex');
+const setup = ({ root }: { root: string }) => {
+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ writeFileSync(join(root, 'notes/seed.md'), note('notes/seed'));
+ commit(root, 'seed');
+};
+const live = async (engine: BrainEngine) => (await engine.executeRaw<{ slug: string }>("SELECT slug FROM pages WHERE source_id='default' AND deleted_at IS NULL ORDER BY slug")).map(row => row.slug);
+const ownerError = () => Object.assign(new Error('index row size 3056 exceeds btree version 4 maximum 2704 for index "idx_tags_tag"'), { code: '54000' });
+
+afterEach(() => installFaultHook(undefined));
+
+for (const backend of testBackends()) describe(`[${backend}] GBRA-130 A-6: one page's unclassifiable write failure`, () => {
+ const databaseUrl = backend === 'postgres' ? process.env.DATABASE_URL : undefined;
+ for (const trigger of ['long tag', 'TypeError at preparation'] as const) test(`${trigger}: b.md is held page_write_failed, a.md and c.md import, and later syncs are not blocked`, () => managedBrain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ writeFileSync(join(root, 'notes/a.md'), note('notes/a'));
+ writeFileSync(join(root, 'notes/b.md'), note('notes/b', trigger === 'long tag' ? `tags:\n - ${LONG_TAG}\n` : ''));
+ writeFileSync(join(root, 'notes/c.md'), note('notes/c'));
+ commit(root, 'a b c');
+ // PGLite has no btree row limit: its twin raises the owner exception Postgres raises, from inside b.md's publication.
+ const injectOwner = trigger === 'long tag' && engine.kind !== 'postgres';
+ // b.md's requests, read at claim (outside any transaction: a PGLite read inside the publication transaction would wait on it).
+ const bRequests = new Set<string>();
+ installFaultHook(async (point, detail) => {
+ if (detail.operation !== 'submit_job' || !detail.requestId) return;
+ if (point === 'consumer:preparing') {
+ const [req] = await engine.executeRaw<{ slug: string }>('SELECT slug FROM persistence_requests WHERE request_id=$1::uuid', [detail.requestId]);
+ if (req?.slug === 'notes/b') bRequests.add(detail.requestId);
+ }
+ if (!bRequests.has(detail.requestId)) return;
+ if (trigger === 'TypeError at preparation' && point === 'consumer:preparing') throw new TypeError("Cannot read properties of undefined (reading 'example')");
+ if (injectOwner && point === 'publication:before_commit') throw ownerError();
+ });
+ const statuses: string[] = [];
+ for (let run = 0; run < 4; run++) statuses.push((await performManagedSync(engine, OPTS)).status);
+ expect(await live(engine)).toEqual(['notes/a', 'notes/c', 'notes/seed']);
+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");
+ const hold = await readGitHold(engine, 'default', incarnation, 'notes/b.md');
+ expect(hold).toMatchObject({ code: 'page_write_failed' });
+ // One occurrence still stops the run (a transient defect never holds a file); the third identical failure holds the path.
+ expect(statuses.slice(0, 2)).toEqual(['blocked_by_failures', 'blocked_by_failures']);
+ expect(statuses.slice(2)).not.toContain('blocked_by_failures');
+ installFaultHook(undefined);
+ }, { databaseUrl, setup }), 240_000);
+});