Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): a pass holds a file edited after its freeze worktree_dirty instead of ending not_converged (GBRA-130, 4b Postgres sweep)

garrytana5d59b35467c
diff --git a/src/core/persistence/sync-pass-batch.ts b/src/core/persistence/sync-pass-batch.ts
index 17db96c9a5..bf23ee00ea 100644
--- a/src/core/persistence/sync-pass-batch.ts
+++ b/src/core/persistence/sync-pass-batch.ts
@@ -25,6 +25,20 @@ export function readPassBatch<T>(key: string): T | null { return (passBatches.ge
export function setPassBatch(key: string, value: BatchHead | null, header = ''): void {
if (value) passBatches.set(key, { value, header }); else passBatches.delete(key);
}
+/**
+ * GBRA-130: whether this pass already passed over the refused receipt of `requestId` (a file changed after admission).
+ * A pass's request ID is its path at its level, so reading the same receipt again means the committed level did not move:
+ * an uncommitted edit, which the settle path holds `worktree_dirty` instead of the pass using its rounds on it.
+ * Records the receipt otherwise. Only the newest passes of this process are kept.
+ */
+export function passedOverBefore(passId: string, requestId: string): boolean {
+ const seen = passedOver.get(passId) ?? new Set<string>();
+ if (seen.has(requestId)) return true;
+ passedOver.delete(passId); passedOver.set(passId, seen.add(requestId));
+ for (const old of passedOver.keys()) if (passedOver.size > 8) passedOver.delete(old);
+ return false;
+}
+const passedOver = new Map<string, Set<string>>();
/**
* One step of an in-memory batch inside `tx`: the drain lease fences it (the pass that holds the lease is the batch's only
* writer), and it lands only while the batch's header still is `beforeHeader` (the cursor row's compare-and-swap contract).
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 3d0b24c68b..a36695853d 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -68,7 +68,7 @@ import { withSyncTail } from './sync-tail.ts';
import { assertDrainLease, currentDrainLease, leaseHeldResult, readDrainHolder, withDrainLease } from './sync-lease.ts';
import { LockStolenError, LockUnavailableError, syncLockId } from '../db-lock.ts';
import { currentSubmissionAuthority } from '../minions/submission-authority.ts';
-import { assertPassAdmission, isPassBatchKey, passBatchStep, passRequestId, readPassBatch, setPassBatch, type PassEntry } from './sync-pass-batch.ts';
+import { assertPassAdmission, isPassBatchKey, passBatchStep, passedOverBefore, passRequestId, readPassBatch, setPassBatch, type PassEntry } from './sync-pass-batch.ts';
import type { PassStamp } from './sync-prepare.ts';
import { runSyncPass } from './sync-pass-run.ts';
import { serr } from '../console-prefix.ts';
@@ -593,7 +593,7 @@ async function holdUnderGate(engine: BrainEngine, input: { cursor: Cursor; key:
}
}
-/** #6712: an entry is retried after the manifest end this many times when its file keeps changing after admission, then held `worktree_dirty`. */
+/** #6712: an entry is retried after the manifest end this many times when its file keeps changing after admission, then held `worktree_dirty` (a pass's at once: GBRA-130). */
export const DEFER_PER_ENTRY = 3;
/** #6712: the most deferrals one run makes; past it a changed file is held at once. */
export const DEFER_PER_RUN = 200;
@@ -611,7 +611,7 @@ async function deferChangedEntry(engine: BrainEngine, input: { cursor: Cursor; k
const { cursor, pending, base } = input;
const index = indexOf(cursor, pending), entry = entryOf(cursor, pending)!;
const attempts = (cursor.deferred?.find(deferred => deferred.index === index)?.attempts ?? 0) + 1;
- if (attempts > DEFER_PER_ENTRY || (cursor.deferrals ?? 0) >= DEFER_PER_RUN) {
+ if (cursor.passId || attempts > DEFER_PER_ENTRY || (cursor.deferrals ?? 0) >= DEFER_PER_RUN) {
let bytes: Buffer | null = null;
try { bytes = readSyncFile(cursor.root, entry.path); } catch { /* the hold records no working hash */ }
return holdUnderGate(engine, { ...input, hold: worktreeDirtyHold(entry, pending.slug, pending.pageId, { ...pending.intent, rawHash: bytes === null ? null : sha256(bytes) }) });
@@ -1527,9 +1527,9 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
}
// #6712 PR 4b (design v3.2 §2): a pass's write refused because its file changed after admission is the level moving, not a
// page failure: the entry is passed over and the next round classifies the new level (a level that never settles ends the
- // pass not_converged). A pinned-worktree conflict is not: it settles as a worktree_dirty hold below. So is an import whose
+ // pass not_converged); its receipt read again (same level: an uncommitted edit) and a pinned-worktree conflict hold worktree_dirty below. So is an import whose
// page identity another writer changed after the freeze (a repair created the page at its slug): its page moved.
- if (cursor.passId && (fileChangedAfterAdmission(done) || (done.error_code === 'page_identity_changed'
+ if (cursor.passId && ((fileChangedAfterAdmission(done) && !passedOverBefore(cursor.passId, pending.requestId)) || (done.error_code === 'page_identity_changed'
&& await liveRevision(engine, context.sourceId, pending) !== (pending.intent.expected_revision == null ? null : String(pending.intent.expected_revision))))) {
cursor = await saveCursor(engine, key, cursor, committedPast({ ...cursor, counts: { ...cursor.counts } }, pending));
assertActive();
diff --git a/test/managed-sync-lanes.test.ts b/test/managed-sync-lanes.test.ts
index ce1976a65c..240266233e 100644
--- a/test/managed-sync-lanes.test.ts
+++ b/test/managed-sync-lanes.test.ts
@@ -333,8 +333,9 @@ test('a page edited after its freeze fails alone inside a lane group; the group
// The edited page's group is held in preparation until a later lane group has applied and waits for its turn behind it,
// so the refusal always lands while that group waits (the window CI hit only under load: the group sent back to the
// queue made every lane group waiting behind it yield, `predecessor_requeued`, and count as a fallback).
+ // #6712 PR 4b: a pass's intents carry no index; the zero-padded paths give the manifest order.
const requestRow = async (requestId: string | undefined) => (await engine!.executeRaw<{ slug: string; idx: number }>(
- "SELECT slug, (intent->>'index')::int AS idx FROM persistence_requests WHERE request_id=$1::uuid", [requestId ?? null]))[0];
+ "SELECT slug, substring(slug from 'n([0-9]+)$')::int AS idx FROM persistence_requests WHERE request_id=$1::uuid", [requestId ?? null]))[0];
let behind: () => void = () => {};
const laterGroupWaiting = new Promise<void>(resolve => { behind = resolve; });
let waited = false, reached = false;
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 64ef39e785..158be9d067 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -314,6 +314,7 @@ 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-pass-dirty-after-freeze-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-pass-dirty-after-freeze-gbra130.test.ts b/test/sync-pass-dirty-after-freeze-gbra130.test.ts
new file mode 100644
index 0000000000..4eb3460839
--- /dev/null
+++ b/test/sync-pass-dirty-after-freeze-gbra130.test.ts
@@ -0,0 +1,52 @@
+/**
+ * GBRA-130 (#6712 PR 4b sweep, found converting managed-sync-lanes' "a page edited after its freeze fails alone"):
+ * a file edited in the working tree after the pass froze it (uncommitted bytes) is refused at publication
+ * `source_changed` ("The imported file changed after sync admission."). The pass passes such a receipt over as the
+ * level moving, but an uncommitted edit does not move the committed level: the next round froze the same path at the
+ * same level under the same request ID (`passRequestId`), read the same refused receipt and passed it over again, so
+ * the pass used its rounds and ended `not_converged` with nothing held, and every later sync of the source repeated it.
+ *
+ * Protects (red before: the sync ends resumable `not_converged`, no hold): the file is held `worktree_dirty` (its
+ * local edit is not overwritten), the other files import, and the pass converges. Runs on PGLite and, with
+ * DATABASE_URL, on Postgres.
+ */
+import { describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { readGitHold } from '../src/core/persistence/sync-holds.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.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, word = 'body') => `---\ntype: concept\ntitle: ${title}\n---\n\nThe ${word} of ${title}.\n`;
+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };
+const setup = ({ root }: { root: string }) => {
+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ for (const name of ['a', 'b', 'c']) writeFileSync(join(root, `notes/${name}.md`), note(`notes/${name}`));
+ commit(root, 'seed');
+};
+
+for (const backend of testBackends()) describe(`[${backend}] GBRA-130: an uncommitted edit after the freeze`, () => {
+ const databaseUrl = backend === 'postgres' ? process.env.DATABASE_URL : undefined;
+ test('the file is held worktree_dirty, the other files import and the pass converges', () => managedBrain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ for (const name of ['a', 'b', 'c']) writeFileSync(join(root, `notes/${name}.md`), note(`notes/${name}`, 'revised body'));
+ commit(root, 'revise');
+ installFaultHook(async (point, detail) => {
+ if (point === 'sync:after_freeze' && detail.path === 'notes/b.md') writeFileSync(join(root, 'notes/b.md'), note('notes/b', 'uncommitted body'));
+ });
+ try {
+ const result = await performManagedSync(engine, OPTS);
+ expect(result.status).toBe('synced');
+ expect(result.held?.map(hold => [hold.path, hold.code])).toEqual([['notes/b.md', 'worktree_dirty']]);
+ } finally { installFaultHook(undefined); }
+ for (const name of ['a', 'c']) expect((await engine.getPage(`notes/${name}`, { sourceId: 'default' }))?.compiled_truth).toContain('revised body');
+ expect((await engine.getPage('notes/b', { sourceId: 'default' }))?.compiled_truth).toContain('The body of notes/b');
+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");
+ expect(await readGitHold(engine, 'default', incarnation, 'notes/b.md')).toMatchObject({ code: 'worktree_dirty' });
+ }, { databaseUrl, setup }), 240_000);
+});