Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

#6712 PR 4b lane F: a waiver never stops a run on an unreadable file; a non-Error rejection keeps its value (GBRA-133 S-68, S-69)

garrytana88ecf1d5340
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 85d5014d61..f87dd3b48d 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -934,6 +934,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.300.0', text: '`gbrain sync status --json` no longer tells an agent to rerun a managed sync forever when every run stops on the same file with the same unclassified `storage_error`: the first such stop is still `connection` with `next` = rerun, but once two runs in a row stop on the same path with the same code and message, `last_error` is `needs_human` (class `page`, `safe_actions` `none`, new field `repeats`), the state is `blocked` / `needs_human`, and `human_reason` names the file. A message that changes between runs stays a rerun.' },
{ since: '0.60.300.0', text: 'A file whose exact bytes an earlier gbrain imported and validated, and which this release refuses (a parser regression), no longer stops the sync by default: it is held `parser_regression` alone (a gbrain bug to report; it needs a person) and the rest of the source syncs. `GBRAIN_SYNC_PARSER_REGRESSION=stop` for the process that syncs restores the old stop (`sync_parser_regression`, the checkpoint does not advance). A refusal this release makes on purpose, such as the YAML alias bound (`frontmatter_alias_limit`), is held as before under either setting.' },
{ since: '0.60.300.0', text: 'Doctor `managed_sync_blocked` (and get_brain_health `sync_blocked`) now count a managed sync pass that stopped with a recorded failure before finishing, in discovery (path `<discovery>`) or on one file, until a later sync of the source succeeds; before, such a source indexed nothing while the check said no run was blocked.' },
+ { since: '0.60.300.0', text: 'A managed sync no longer stops a whole source when a file it would skip as already imported (a no-op waiver) has meanwhile become a symlink, a FIFO or an unreadable file in the working tree: that entry is simply not skipped and goes on like any other, where an unreadable file is held `file_unreadable`.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.ts
index 0921e93be3..d5402eb74e 100644
--- a/src/core/persistence/fault-points.ts
+++ b/src/core/persistence/fault-points.ts
@@ -50,6 +50,9 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect
// #6712 PR 4b: before each round of a pass reads its level (`round`), and after it read it (`level`: its statements and its
// confirm-round verdict), before it applies.
| 'sync:round_start' | 'sync:level_read'
+ // GBRA-133 S-69: as a pass starts batching a level's entries (sync-pass-run.ts `batchEntries`); a hook that throws models a
+ // rejection there, including a non-Error one.
+ | 'sync:batch_entries'
// #6712 PR 4b: the level's overlapping reads, which share one loop budget (sync-yield.ts `turnYield`): a Git chunk as its
// records are visited (`read`: ls-tree or ls-files; a synchronous hook), an `I⋈P` result in hand before the shared budget
// decides whether it waits a turn, and the same result right before its rows are taken.
diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.ts
index e56fd69168..d46b29038c 100644
--- a/src/core/persistence/sync-pass-run.ts
+++ b/src/core/persistence/sync-pass-run.ts
@@ -146,6 +146,7 @@ function entryPaths(level: ShadowLevel, gitPath: string): { path: string; source
async function batchEntries(engine: BrainEngine, level: ShadowLevel, deletes: ShadowPath[], imports: ShadowPath[]):
Promise<{ entries: PassEntry[]; collisions: SyncSlugCollision[]; skipped: ShadowPath[]; downgrades: DowngradedRename[];
identity: Array<{ entry: ShadowPath; origin: ShadowPath | null; slug: string; ids: { page: string; file: string } }> }> {
+ await faultPoint('sync:batch_entries', { sourceId: level.sourceId });
const working = (entry: ShadowPath) => level.mode === 'working' && entry.state.level !== entry.state.tree;
const deleteEntries = new Map<string, PassEntry>(deletes.map(entry => [entry.path, { ...entryPaths(level, entry.path), action: 'delete' as const, working: level.mode === 'working',
slug: entry.slug!, pageId: entry.pageId, revision: entry.revision, level: null }]));
@@ -846,7 +847,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
return synced(false);
}
const built = await batchEntries(engine, level, deletes, imports).catch(async (error: unknown) => {
- if ((error as { code?: string }).code === 'page_identity_changed') await save('blocked', 'page_identity_changed');
+ if ((error as { code?: string } | null | undefined)?.code === 'page_identity_changed') await save('blocked', 'page_identity_changed');
throw error;
});
collisions.push(...built.collisions);
diff --git a/src/core/persistence/sync-screen.ts b/src/core/persistence/sync-screen.ts
index 70cdd66609..fd07f132b7 100644
--- a/src/core/persistence/sync-screen.ts
+++ b/src/core/persistence/sync-screen.ts
@@ -238,6 +238,11 @@ export function oversizeHold(entry: Pick<SyncEntry, 'path' | 'sourcePath' | 'wor
/** File-system errors that make one path unreadable while the rest of its source reads (GBRA-130 A-7). */
const UNREADABLE_ERRNO = new Set(['EACCES', 'EPERM', 'ELOOP', 'EISDIR', 'ENOTDIR']);
+/** GBRA-130 A-7: whether `readSyncFile` refused one path as not a readable regular file inside its root (a per-file error). */
+export function isUnreadableSyncFile(error: unknown): boolean {
+ const errno = (error as NodeJS.ErrnoException | null)?.code;
+ return error instanceof OperationError && error.detail === UNREADABLE_SYNC_FILE || typeof errno === 'string' && UNREADABLE_ERRNO.has(errno);
+}
/**
* GBRA-130 A-7: the hold of a file sync cannot read as a regular file inside its root (a symlink component, a non-regular
* file, a permission or loop error); null for any other error. Its content is never read or followed, and the root-level
@@ -245,10 +250,8 @@ const UNREADABLE_ERRNO = new Set(['EACCES', 'EPERM', 'ELOOP', 'EISDIR', 'ENOTDIR
*/
export function unreadableFileHold(entry: Pick<SyncEntry, 'path' | 'sourcePath' | 'working' | 'renameFrom' | 'renameHeld'>, slug: string, pageId: number | null, error: unknown,
blob: () => TreeBlob | null | undefined): HeldEntry | null {
- const errno = (error as NodeJS.ErrnoException | null)?.code;
- const refused = error instanceof OperationError && error.detail === UNREADABLE_SYNC_FILE;
- if (!refused && !(typeof errno === 'string' && UNREADABLE_ERRNO.has(errno))) return null;
- const why = refused ? (error as OperationError).message : `it cannot be read (${errno})`;
+ if (!isUnreadableSyncFile(error)) return null;
+ const why = error instanceof OperationError && error.detail === UNREADABLE_SYNC_FILE ? error.message : `it cannot be read (${(error as NodeJS.ErrnoException).code})`;
return heldEntry(entry, slug, pageId, { code: 'file_unreadable',
message: `Sync did not read ${entry.path}: ${why} Sync reads only regular files inside the source root and never follows a symlink. Make it a readable regular file there (or exclude it with sync.exclude) and commit, then run gbrain sources retry-held to re-test it.` }, null, blob());
}
diff --git a/src/core/persistence/sync-waivers.ts b/src/core/persistence/sync-waivers.ts
index b2d25b73b5..436039e77f 100644
--- a/src/core/persistence/sync-waivers.ts
+++ b/src/core/persistence/sync-waivers.ts
@@ -11,7 +11,7 @@ import type { GBrainConfig } from '../config.ts';
import { prepareManagedSyncMutation, type SyncIntent } from './sync-prepare.ts';
import { heldGitPaths, readSyncImportProvenances, syncImportParserFor, recordSyncImportProvenances, syncDiskProvenance, type SyncImportProvenance, type SyncImportProvenanceBase } from './sync-holds.ts';
import { sameParser } from './sync-prescreen.ts';
-import { isSyncReadBound } from './sync-screen.ts';
+import { isSyncReadBound, isUnreadableSyncFile } from './sync-screen.ts';
import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';
import { sha256 } from './digest.ts';
import { startClaimPhase } from './claim-phase.ts';
@@ -134,7 +134,7 @@ export async function waiveNoopEntry<C extends WaiverCursor>(engine: BrainEngine
if (held?.run_id !== cursor.runId || Number(held.index) !== cursor.index || held.request_id !== pending.requestId) return reread(tx);
const snapshot = await tx.readPageSnapshot(pending.slug, { sourceId: cursor.sourceId, includeDeleted: true });
if (waived.kind === 'delete') {
- if (!softDeletedAt(snapshot, pending) || readSyncFile(cursor.root, intent.path!) !== null) return null;
+ if (!softDeletedAt(snapshot, pending) || waiverRead(cursor.root, intent.path!) !== null) return null;
try { await assertSyncPageOrigin(tx, cursor.sourceId, intent.sourcePath!, pending.pageId, true, syncOriginScope(cursor)); }
catch { return null; }
} else if (snapshot?.page.id !== pending.pageId || snapshot.page.deleted_at != null || snapshot.revision !== intent.expected_revision) return null;
@@ -233,7 +233,7 @@ export async function waiveNoopRun<C extends WaiverCursor>(engine: BrainEngine,
const page = bySlug.get(pending.slug);
const revision = page ? page.knowledge_revision == null ? REVISION_BACKFILL_PENDING : String(page.knowledge_revision) : null;
if (!page || Number(page.id) !== pending.pageId || revision !== pending.intent.expected_revision) break chunks;
- if (waived.kind === 'delete' ? !page.deleted || readSyncFile(cursor.root, pending.intent.path!) !== null : page.deleted) break chunks;
+ if (waived.kind === 'delete' ? !page.deleted || waiverRead(cursor.root, pending.intent.path!) !== null : page.deleted) break chunks;
if ((checks[2 * i] as unknown[]).length || checks[2 * i + 1] !== true) break chunks;
const provenance = waivedProvenance(cursor, pending, waived, revision!);
if (provenance === false) break chunks;
@@ -308,8 +308,7 @@ export async function waivePrescreenedRun<C extends WaiverCursor & { binding: {
if (!page || Number(page.id) !== entry.pageId || page.knowledge_revision !== entry.revision || unfinished[i]!.length || holds.has(entry.path)) break chunks;
if (kernelPageWork(page, { sourcePath: entry.sourcePath, embeddingRequested: input.embeddingRequested }) !== null) break chunks;
if (!record?.disk_sha256 || record.revision !== entry.revision || !sameParser(record.parser, syncImportParserFor(entry.sourcePath, pack?.identity ?? null))) break chunks;
- let bytes: Buffer | null;
- try { bytes = readSyncFile(cursor.root, entry.path); } catch (error) { if (isSyncReadBound(error)) break chunks; throw error; }
+ const bytes = waiverRead(cursor.root, entry.path);
if (!bytes || sha256(bytes) !== record.disk_sha256) break chunks;
valid++;
}
@@ -335,6 +334,15 @@ export async function wouldWaiveEntry(engine: BrainEngine, cursor: WaiverCursor,
return (await unchangedSyncImport(engine, cursor, pending, config, signal)) !== null;
}
+/**
+ * GBRA-133 S-68: a waiver's read of the working-tree file; undefined when the freeze would hold it (over the read bound, or
+ * `file_unreadable`: a symlink, a FIFO, a permission error), so the entry is not waived and goes on to admission instead of
+ * failing the run.
+ */
+function waiverRead(root: string, path: string): Buffer | null | undefined {
+ try { return readSyncFile(root, path); } catch (error) { if (isSyncReadBound(error) || isUnreadableSyncFile(error)) return undefined; throw error; }
+}
+
/**
* #6712: the import provenance a waived import records in its waiver transaction, from the file read there: false when
* the file no longer has the frozen raw hash (the entry is not waived), null for a waiver that records none (a delete,
@@ -342,8 +350,8 @@ export async function wouldWaiveEntry(engine: BrainEngine, cursor: WaiverCursor,
*/
function waivedProvenance(cursor: WaiverCursor, pending: WaiverEntry, waived: NoopWaiver, revision: string): Omit<SyncImportProvenance, 'recorded_at' | 'validated'> | false | null {
if (waived.kind !== 'import') return null;
- const bytes = readSyncFile(cursor.root, pending.intent.path!);
- if ((bytes === null ? null : sha256(bytes)) !== pending.intent.rawHash) return false;
+ const bytes = waiverRead(cursor.root, pending.intent.path!);
+ if (bytes === undefined || (bytes === null ? null : sha256(bytes)) !== pending.intent.rawHash) return false;
if (!waived.provenance) return null;
return { ...waived.provenance, page_id: pending.pageId!, revision, ...syncDiskProvenance(bytes, pending.intent.target) };
}
diff --git a/test/behavior-change-notice-6712-block.test.ts b/test/behavior-change-notice-6712-block.test.ts
index 70affc03da..914bb7799f 100644
--- a/test/behavior-change-notice-6712-block.test.ts
+++ b/test/behavior-change-notice-6712-block.test.ts
@@ -12,7 +12,7 @@ import { join } from 'node:path';
import { BEHAVIOR_CHANGES, compareReleases } from '../src/core/behavior-change-notice.ts';
const MARKER = '// #6712 PR 4b (the level-triggered sync pass';
-const ROWS = 30;
+const ROWS = 31;
const NOTICE_CAP = 2_000;
/** The array literal's row lines in order, and where the block's rows start and how many there are. */
diff --git a/test/sync-entry-faults-6712.test.ts b/test/sync-entry-faults-6712.test.ts
index 7860fb57f8..c1a0da202f 100644
--- a/test/sync-entry-faults-6712.test.ts
+++ b/test/sync-entry-faults-6712.test.ts
@@ -20,6 +20,8 @@
* changes between runs stays a rerun, and the count survives a resumed cursor's repeated observation.
* - S-61: a pass that stopped in discovery (path `<discovery>`) or on one entry left no cursor and an `open` pass row, so
* doctor `managed_sync_blocked` (`readBlockedManagedSyncs`) said nothing was blocked; it lists the stop until a sync succeeds.
+ * - S-69: a non-Error rejection (`undefined`) while a pass batches a level's entries was replaced by a TypeError about
+ * `.code`; it now reaches the caller and the failure record as itself (red with the `sync:batch_entries` seam alone).
* The deliberate-refusal, systemic and changing-message guards pass before and after.
*
* PGLite here; Postgres through test/e2e/sync-entry-faults-6712-postgres.test.ts.
@@ -224,4 +226,11 @@ for (const backend of testBackends()) describe(`[${backend}] GBRA-133: one odd f
expect(await readBlockedManagedSyncs(engine, ['default'])).toEqual([]);
}), 240_000);
}
+ test('S-69: a non-Error rejection while a pass batches its entries reaches the caller as itself, not as a TypeError about .code', () => brain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ writeFileSync(join(root, 'notes/odd.md'), note('notes/odd')); commit(root, 'odd');
+ installFaultHook(point => { if (point === 'sync:batch_entries') throw undefined; });
+ expect(await performManagedSync(engine, OPTS).then(() => 'resolved', (error: unknown) => error)).toBeUndefined();
+ expect((await readSyncStatus(engine, 'default')).last_error).toMatchObject({ code: 'storage_error', path: '<discovery>', message: 'undefined' });
+ }), 240_000);
});
diff --git a/test/sync-waiver-unreadable-6712.test.ts b/test/sync-waiver-unreadable-6712.test.ts
new file mode 100644
index 0000000000..99fe3f556f
--- /dev/null
+++ b/test/sync-waiver-unreadable-6712.test.ts
@@ -0,0 +1,51 @@
+/**
+ * GBRA-133 S-68 (#6712 PR 4b lane F): a waiver's working-tree read of a file the freeze would hold `file_unreadable` (a
+ * symlink, a FIFO) threw out of the waiver transaction and stopped the run. The entry is now simply not waived, so it goes
+ * on to admission like any other entry. Red at ed7e8e017 (the run threw "Sync cannot publish through a symlink." /
+ * "Sync target is not a regular file."). The engine is the recording fake of test/sync-waivers-chunk.test.ts; synthetic
+ * data only.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { UNFINISHED_PAGE_REQUEST_SQL, waiveNoopRun, type WaiverCursor, type WaiverRunEntry } from '../src/core/persistence/sync-waivers.ts';
+
+const root = mkdtempSync(join(tmpdir(), 'waiver-unreadable-'));
+afterAll(() => rmSync(root, { recursive: true, force: true }));
+writeFileSync(join(root, 'target.md'), 'synthetic');
+symlinkSync('target.md', join(root, 'p1.md'));
+execFileSync('mkfifo', [join(root, 'p2.md')]);
+const cursor = { sourceId: 's1', incarnation: '1', root, gitRoot: root, slugMode: 'git-root', binding: { worktree_id: '00000000-0000-0000-0000-000000000001' },
+ authority: {} as WaiverCursor['authority'], runId: 'run-1', index: 0 } as WaiverCursor;
+const deletes = (n: number): WaiverRunEntry[] => Array.from({ length: n }, (_, i) => ({
+ pending: { requestId: `r${i}`, slug: `p${i}`, pageId: i + 1, intent: { kind: 'managed_sync_delete', path: `p${i}.md`, sourcePath: `p${i}.md`, expected_revision: '7', ownerEpoch: '3' } as never },
+ waived: { kind: 'delete', kernel: [] } }));
+
+const tx = {
+ kind: 'pglite',
+ lockPageKeys: async () => undefined,
+ executeRaw: async (sql: string, params: unknown[] = []) => {
+ if (sql.includes('set_config')) return [];
+ if (sql.includes('FROM op_checkpoints')) return [{ run_id: 'run-1', index: 0, request_id: null }];
+ if (sql.includes('FROM persistence_source_bindings')) return [{ owner_epoch: '3' }];
+ if (sql.startsWith('SELECT id,slug,deleted_at')) return (params[1] as string[]).map(slug => ({ id: Number(slug.slice(1)) + 1, slug, deleted: true, knowledge_revision: '7' }));
+ if (sql === UNFINISHED_PAGE_REQUEST_SQL) return [];
+ if (sql.startsWith('SELECT id,slug,source_path,deleted_at FROM pages')) { const path = (params[1] as string[])[0]!; const i = Number(/p(\d+)\.md/.exec(path)![1]); return [{ id: i + 1, slug: `p${i}`, source_path: path }]; }
+ throw new Error(`unexpected SQL: ${sql.slice(0, 60)}`);
+ },
+};
+const engine = { kind: 'pglite', transaction: async <T>(fn: (t: BrainEngine) => Promise<T>) => fn(tx as unknown as BrainEngine) } as unknown as BrainEngine;
+const waive = (run: WaiverRunEntry[]) => waiveNoopRun(engine, cursor, run, 'key', async (_tx, prefix) => ({ ...cursor, index: prefix.length }), async () => cursor);
+
+describe('GBRA-133 S-68: an unreadable working-tree file is not waived and never stops the run', () => {
+ test('a delete whose path is now a symlink ends the waived prefix before it', async () => {
+ expect(await waive(deletes(3))).toMatchObject({ waived: 1, next: { slug: 'p1' } });
+ });
+
+ test('a delete whose path is now a FIFO is not waived', async () => {
+ expect(await waive(deletes(3).slice(2))).toBeNull();
+ });
+});