Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
WIP #6712 lane C: a failed preparation settles before group publication (no lane livelock); a run's recorded stop re-freezes every page the same refusal failed
garrytana1f19648b7a4
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.tsindex e1d115cd57..3904fc66e0 100644--- a/src/core/persistence/group-publish.ts+++ b/src/core/persistence/group-publish.ts@@ -552,7 +552,8 @@ type MemberOutcome = { ok: PreparedMutation } | { error: unknown } | { released:* batch all at once), publishes it in one transaction when every member* qualifies, and otherwise publishes the members one at a time in order.* #6712: a member that ends in failure is its page's fate alone; the later- * members still publish. In a sync group, after a member is released back+ * members still publish (a failed preparation is settled first, and the rest+ * publish as one group). In a sync group, after a member is released back* to the queue the later ones are released too, so nothing overtakes it* (order, not fate: a released member is claimed again). Claims are renewed* for the whole group while it runs (claim-lease.ts). If the group stops@@ -664,6 +665,20 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteReques}await releaseUnpublishedClaim(engine, row, 'preparation_deadline', { charge: true });}+ // #6712: a member whose preparation failed takes its own fate before publication, so the others still publish as one+ // group: on a lane root the single path's exclusive lock waits behind the lanes that wait on this group's order. A+ // member its failure sends back to the queue is a release: in a sync group the members after it are released too.+ let requeuedAt: number | null = null;+ for (let i = 0; i < rows.length; i++) {+ const row = rows[i]!, outcome = prepared[i];+ if (released.has(row.id) || (requeuedAt === null || !ordered) && !(outcome && 'error' in outcome)) continue;+ held.delete(row.id); released.add(row.id);+ if (requeuedAt !== null && ordered) { await releaseUnpublishedClaim(engine, row, 'group_member_waiting'); continue; }+ const done = await finishUnpublishedFailure(engine, row, (outcome as { error: unknown }).error, 'preparation');+ run.settled(done);+ if (['conflict', 'failed', 'cancelled'].includes(done.state)) progressed = true;+ else requeuedAt ??= i;+ }for (const clock of clocks) if (clock) enterClaimPhase(clock, 'publishing');enterClaimPhase(groupClock, 'publishing');const bounded = <T>(publish: () => Promise<T>): Promise<T> => run.publication ? boundPublication(publish, { ...run.publication, onOverdue: () => {@@ -704,7 +719,7 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteRequesconst p = prepared[i]!;// #6278: a member aborted by our own cancellation (never a deadline here) is released, not failed.if ('released' in p) { await releaseUnpublishedClaim(engine, row, p.released === 'claim_lost' ? 'claim_lost' : 'group_member_waiting'); if (ordered) release = true; continue; }- const done = 'ok' in p ? await bounded(() => publishMutation(engine, row, p.ok, run.hostId)) : await finishUnpublishedFailure(engine, current, p.error, 'preparation');+ const done = await bounded(() => publishMutation(engine, row, (p as { ok: PreparedMutation }).ok, run.hostId));run.settled(done);if (['committed', 'conflict', 'failed', 'cancelled'].includes(done.state)) progressed = true;else release = true;diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 8211887800..8a41b5b680 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -814,9 +814,13 @@ function resumableStop(row: WriteRequest): boolean {const verdict = classifySyncFault({ code: row.error_code ?? 'storage_error', message: row.error_message ?? null });return verdict.class !== 'page' && verdict.safe_actions.includes('retry');}-/** #6712: whether an earlier invocation already stopped this run on `requestId` (its failure is recorded under the cursor key). */-async function stopRecorded(engine: BrainEngine, key: string, requestId: string): Promise<boolean> {- return (await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1 AND completed_keys->0->>'observation_id'=$2", [key, requestId])).length > 0;+/**+ * #6712: whether an earlier invocation already stopped this run (its failure is recorded under the cursor key with the+ * run's id). An invocation records at most one stop and returns, so a recorded stop of the run is always an earlier one's,+ * and the pages its window admitted after the stop and the same refusal failed are re-frozen like the stop itself.+ */+async function stopRecorded(engine: BrainEngine, key: string, runId: string): Promise<boolean> {+ return (await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1 AND completed_keys->0->>'run_id'=$2", [key, runId])).length > 0;}/**@@ -840,7 +844,7 @@ async function settleFailedRequest(engine: BrainEngine, input: { cursor: Cursor;const revived = await reviveCheckpoint(engine, input);if (revived) { input.assertActive(); return { cursor: revived }; }const fault = receiptClass(done);- if (fault === 'transport' || isSyncKnockOn(done) || (fault === 'systemic' && resumableStop(done) && pending.intent.kind !== 'managed_sync_checkpoint' && await stopRecorded(engine, key, pending.requestId))) {+ if (fault === 'transport' || isSyncKnockOn(done) || (fault === 'systemic' && resumableStop(done) && pending.intent.kind !== 'managed_sync_checkpoint' && await stopRecorded(engine, key, cursor.runId))) {const refrozen = await refreezeInPlace(engine, input);if (refrozen) { input.assertActive(); return { cursor: refrozen }; }}diff --git a/test/managed-sync-bulk.test.ts b/test/managed-sync-bulk.test.tsindex b8417c7631..d3755b8684 100644--- a/test/managed-sync-bulk.test.ts+++ b/test/managed-sync-bulk.test.ts@@ -193,6 +193,28 @@ test('#6712: a failed page leaves the groups admitted ahead of it in the cursor} finally { await engine.unsetConfig('sync.holds'); }}), 300_000);+test('#6712 (#6565): a database refusal stops the run, and the next plain sync re-freezes every page the same refusal failed, so one run converges once it is lifted', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {+ if (!engine) return;+ const f = await fixture(engine, notes(24));+ const opts = { sourceId: f.id, noPull: true, noEmbed: true, noExtract: true, drain: true };+ expect((await performSync(engine, opts)).drain).toMatchObject({ outcome: 'synced' });+ for (let i = 0; i < 24; i++) writeFileSync(join(f.root, `notes/n${i}.md`), `---\ntitle: Note ${i}\n---\nA revised observation number ${i}.\n`);+ execFileSync('git', ['-C', f.root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qam', 'revise']);+ const since = (await engine.executeRaw<{ at: string }>('SELECT now()::text AS at'))[0]!.at;+ await engine.executeRaw(`CREATE FUNCTION bulk_systemic_refusal() RETURNS trigger LANGUAGE plpgsql AS $$+ BEGIN RAISE EXCEPTION USING ERRCODE = 'P0001', MESSAGE = 'test: systemic refusal'; END $$`);+ await engine.executeRaw('CREATE TRIGGER bulk_systemic_refusal BEFORE INSERT OR UPDATE ON pages FOR EACH ROW EXECUTE FUNCTION bulk_systemic_refusal()');+ try {+ expect((await performSync(engine, opts)).drain).toMatchObject({ outcome: 'blocked' });+ await settledAll(engine, f.id);+ } finally { await engine.executeRaw('DROP TRIGGER bulk_systemic_refusal ON pages; DROP FUNCTION bulk_systemic_refusal()'); }+ const [refused] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1+ AND intent->>'kind'='managed_sync_import' AND state='failed' AND created_at > $2::timestamptz`, [f.id, since]);+ expect(refused!.n).toBeGreaterThan(1);+ expect((await performSync(engine, opts)).drain).toMatchObject({ outcome: 'synced' });+ for (let i = 0; i < 24; i++) expect((await engine.getPage(`notes/n${i}`, { sourceId: f.id }))?.compiled_truth).toContain(`revised observation number ${i}`);+}), 300_000);+/*** #6712 Eng finding ("followers that commit after the failure CAS"): the group admitted ahead of a failed page is* held back in preparation until the drain has saved the failure and is gone (under `sync.holds=fail` it stops blocked;diff --git a/test/managed-sync-lanes.test.ts b/test/managed-sync-lanes.test.tsindex f0928132cd..c219dcd02c 100644--- a/test/managed-sync-lanes.test.ts+++ b/test/managed-sync-lanes.test.ts@@ -14,7 +14,6 @@ import { claimWorktree } from '../src/core/persistence/ownership.ts';import { performSync } from '../src/commands/sync/perform.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { resolveBulkSettings } from '../src/core/persistence/sync-group.ts';-import { WINDOW_CANCEL_MESSAGE } from '../src/core/persistence/sync-window.ts';import { acquireShared, DEFER_WAIT_MS, deferToLease, exclusiveAcquired, joinLease, leaseDraining, leaseWounded, yieldLease } from '../src/core/persistence/worktree-lease.ts';import type { NativeLockHandle } from '../src/core/persistence/native-lock.ts';import { withEnv } from './helpers/with-env.ts';@@ -296,7 +295,7 @@ test('admit-ahead fits the writer\'s outstanding-request limit instead of stoppi}}), 300_000);-test('a failed page under lanes stops the run: earlier pages commit, nothing after it publishes', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SYNC_BULK_SIZE: '4' }, async () => {+test('a failed page under lanes stops the run and cancels nothing: every other admitted page commits as its own fate (#6712)', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SYNC_BULK_SIZE: '4' }, async () => {if (!engine) return;const f = await fixture(engine, notes(60, i => i === 30 ? '---\ntitle: Conflict\nslug: notes/other\n---\nA conflicting identity must not be imported.\n' : null));await engine.setConfig('sync.holds', 'fail');@@ -307,11 +306,9 @@ test('a failed page under lanes stops the run: earlier pages commit, nothing aftconst rows = await imports(engine, f.id);const failedAt = rows.findIndex(row => row.slug === 'notes/n030');expect(rows[failedAt]!.state).toBe('failed');- expect(rows.slice(0, failedAt).every(row => row.state === 'committed')).toBe(true);- expect(rows.slice(failedAt + 1).filter(row => row.state !== 'cancelled').map(row => `${row.slug} ${row.state} group=${row.grp} lane=${row.lane}`)).toEqual([]);- for (const row of rows.slice(failedAt + 1)) expect(await engine.getPage(row.slug, { sourceId: f.id })).toBeNull();- const laterGroups = rows.slice(failedAt + 1).filter(row => row.grp !== rows[failedAt]!.grp);- for (const row of laterGroups) expect(row.error_message).toBe(WINDOW_CANCEL_MESSAGE);+ expect(rows.filter((_, i) => i !== failedAt && rows[i]!.state !== 'committed').map(row => `${row.slug} ${row.state} group=${row.grp} lane=${row.lane}`)).toEqual([]);+ expect(rows.slice(failedAt + 1).length).toBeGreaterThan(0);+ for (const row of rows.slice(failedAt + 1)) expect(await engine.getPage(row.slug, { sourceId: f.id })).not.toBeNull();}), 300_000);test('a crash right after a group is admitted and saved skips nothing and admits nothing twice; the first group is small', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_BULK_SIZE: '4' }, async () => {