Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

WIP #6712 lane C: resumable stops only for retryable database refusals; tests follow one-fate and transient-hold policy

garrytand89c22d2fc5d
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index d69616d0c5..8211887800 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -63,6 +63,7 @@ import { recordSyncRunTrend } from '../fence-repair/census-store.ts';
import { addFencesNormalized, addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, heldGitPaths, fencesNormalizedReport, holdsEscalated, readGitHoldRetryPaths, readGitSourceHolds, readSyncHoldPolicy, recordSyncConversion, recoveredReport, requestGitHoldRetry, writeGitHold, type FencesTally, type GitHoldCode, type SyncHoldPolicy } from './sync-holds.ts';
import { withScreeningPaths } from './screening-paths.ts';
import { withBoundedReadSession } from './bounded-reads.ts';
+import { classifySyncFault } from './sync-fault-class.ts';
import { advanceHeld, committedPast, deletionSettled, entryOf, indexOf, promoteWindow, waivedCursor, withHeldKeys, withoutPending } from './sync-cursor-moves.ts';
export interface ManagedSyncWriteDiagnostic {
@@ -804,6 +805,15 @@ function receiptClass(row: WriteRequest): 'transport' | 'page' | 'systemic' {
if (verdict?.category === 'transport' && verdict.code !== 'graduation_in_progress') return 'transport';
return verdict?.class === 'page' ? 'page' : 'systemic';
}
+/**
+ * #6712 (#6565): a stop the next plain sync re-freezes in place: a database refusal the fault table retries (an
+ * unrecognised P0001 or a 55000 raised under a page write surfaces as `storage_error`). A content, consent or option
+ * refusal is never one: its receipt stays the diagnosis until --retry-failed.
+ */
+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;
@@ -814,8 +824,8 @@ async function stopRecorded(engine: BrainEngine, key: string, requestId: string)
* positively classified page fault is held with its index settled in one cursor step (`holdFailedFenceRequest`), or
* deferred when its file changed after admission; a transport fault, or a legacy knock-on, is re-frozen in place without
* advancing (`refreezeInPlace`); any other fault is recorded in the failure ledger and blocks the run with its
- * diagnostic and the classifier's action, and for a systemic fault the next invocation re-freezes the entry in place
- * (`stopRecorded`), so a plain sync converges once the cause is gone. Nothing after the entry is cancelled: requests
+ * diagnostic and the classifier's action, and for a database refusal the fault table retries (`resumableStop`) the next
+ * invocation re-freezes the entry in place (`stopRecorded`), so a plain sync converges once the cause is gone. Nothing after the entry is cancelled: requests
* admitted after it stay in the cursor's window and are settled by their own receipts.
*/
async function settleFailedRequest(engine: BrainEngine, input: { cursor: Cursor; key: string; pending: Pending; done: WriteRequest; assertActive: () => void;
@@ -830,7 +840,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' && 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, pending.requestId))) {
const refrozen = await refreezeInPlace(engine, input);
if (refrozen) { input.assertActive(); return { cursor: refrozen }; }
}
@@ -1307,7 +1317,7 @@ async function retryFailedStart(engine: BrainEngine, cursor: Cursor, key: string
const failed = cursor.pending ? await getWriteRequest(engine, cursor.authority.writer.principal, cursor.pending.requestId) : null;
assertActive();
// #6712: --retry-failed resets the in-place re-freeze bound of an entry the run stopped on for a fault not its page's; the drain re-freezes it again.
- if (failed && cursor.pending && (cursor.pending.stops ?? 0) >= STOPS_PER_ENTRY && ['failed', 'conflict', 'cancelled'].includes(failed.state) && (isSyncKnockOn(failed) || receiptClass(failed) !== 'page')) {
+ if (failed && cursor.pending && (cursor.pending.stops ?? 0) >= STOPS_PER_ENTRY && ['failed', 'conflict', 'cancelled'].includes(failed.state) && (isSyncKnockOn(failed) || receiptClass(failed) === 'transport' || resumableStop(failed))) {
const { stops: _stops, ...pending } = cursor.pending;
return { cursor: await saveCursor(engine, key, cursor, { ...cursor, pending }, false, assertActive) };
}
diff --git a/test/managed-sync-group-uncommitted-head.test.ts b/test/managed-sync-group-uncommitted-head.test.ts
index 4c0d03ae71..285524cc73 100644
--- a/test/managed-sync-group-uncommitted-head.test.ts
+++ b/test/managed-sync-group-uncommitted-head.test.ts
@@ -1,9 +1,10 @@
/**
* #6252: a bulk managed-sync group whose head ends without committing while
* its members are still queued (the head cancelled with cancel_write_request,
- * or settled on its own before its followers published). The members after it
- * never publish ahead of it: they are cancelled, the run reports the head, and
- * the pages are imported once the head is resolved. Runs on PGLite (bulk
+ * or settled on its own before its followers published). #6712 (one page, one
+ * fate): the members after it are never cancelled for it; each publishes on its
+ * own, the run reports the head, and the head's page is imported once it is
+ * resolved. Runs on PGLite (bulk
* forced) and, with DATABASE_URL, on Postgres. Synthetic content only.
*/
import { afterAll, beforeAll, expect, test } from 'bun:test';
@@ -18,6 +19,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { acquireWorktree, claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { waitFor } from './helpers/wait-for.ts';
import { cancelWriteRequest } from '../src/core/persistence/control.ts';
import { requestPrincipal, type WriteRequest } from '../src/core/persistence/model.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
@@ -55,7 +57,7 @@ async function source(engine: BrainEngine, slugs: string[]) {
}
test.each([['one group', false], ['a group admitted ahead in a drain', true]] as const)(
- 'a group head cancelled while queued (%s): nothing after it publishes, and the retry imports every page once', (_label, drain) => withEnv(env, async () => {
+ 'a group head cancelled while queued (%s): the members after it publish on their own fate, and the retry imports the head', (_label, drain) => withEnv(env, async () => {
for (const engine of engines) {
try {
const slugs = Array.from({ length: drain ? 8 : 4 }, (_, i) => `notes/n${i}`);
@@ -72,11 +74,14 @@ test.each([['one group', false], ['a group admitted ahead in a drain', true]] as
expect(await cancelWriteRequest(engine, requestPrincipal(members[0]!), members[0]!.request_id)).toMatchObject({ state: 'cancelled' });
const blocked = await s.sync({ bulk: BULK });
expect(blocked).toMatchObject({ status: 'blocked_by_failures', added: 0, managedWrite: { slug: 'notes/n0' } });
- const after = await engine.executeRaw<{ slug: string; state: string }>('SELECT slug,state FROM persistence_requests WHERE id=ANY($1::uuid[]) ORDER BY sequence', [members.map(member => member.id)]);
- expect(after.filter(row => row.state !== 'cancelled').map(row => `${row.slug} ${row.state}`)).toEqual([]);
- for (const member of members) expect(await engine.getPage(member.slug, { sourceId: s.id })).toBeNull();
- const retried = await s.sync({ bulk: BULK, retryFailed: true });
- expect(retried.added).toBeGreaterThanOrEqual(members.length);
+ const states = () => engine.executeRaw<{ slug: string; state: string }>('SELECT slug,state FROM persistence_requests WHERE id=ANY($1::uuid[]) ORDER BY sequence', [members.map(member => member.id)]);
+ await waitFor(async () => (await states()).every(row => !['queued', 'running'].includes(row.state)), { timeoutMs: 30_000, label: 'the members settle' });
+ const after = await states();
+ expect(after[0]).toMatchObject({ slug: 'notes/n0', state: 'cancelled' });
+ expect(after.slice(1).filter(row => row.state !== 'committed').map(row => `${row.slug} ${row.state}`)).toEqual([]);
+ expect(await engine.getPage('notes/n0', { sourceId: s.id })).toBeNull();
+ for (const member of members.slice(1)) expect(await engine.getPage(member.slug, { sourceId: s.id })).not.toBeNull();
+ await s.sync({ bulk: BULK, retryFailed: true });
for (const slug of slugs) expect(await engine.getPage(slug, { sourceId: s.id })).not.toBeNull();
} finally { await disposePersistenceConsumer(engine); }
}
diff --git a/test/managed-sync-lanes.test.ts b/test/managed-sync-lanes.test.ts
index 39df3026f1..f0928132cd 100644
--- a/test/managed-sync-lanes.test.ts
+++ b/test/managed-sync-lanes.test.ts
@@ -193,7 +193,7 @@ test('a lane that joins while the last holder is still releasing the native lock
expect(held).toBe(false);
});
-test('a lane waits for its predecessor to commit, yields to a requeued or unadmitted one and stops after a failed one', async () => {
+test('a lane waits for its predecessor to end, yields to a requeued or unadmitted one and takes its turn after a failed one (#6712)', async () => {
openLanes('wt-turn', 'run-turn', 4, null);
const state = laneOf({ worktree_id: 'wt-turn', intent: { lane: 'run-turn' } } as never)!;
const rows = [{ request_id: 'b', principal_kind: 'local_cli', principal_id: 'p', intent: { after: 'a', lane: 'run-turn' } }] as never;
@@ -201,7 +201,9 @@ test('a lane waits for its predecessor to commit, yields to a requeued or unadmi
await awaitLaneTurn(tx(['running', 'running', 'committed']), state, rows);
await expect(awaitLaneTurn(tx(['running', 'queued']), state, rows)).rejects.toMatchObject({ reason: 'predecessor_requeued' });
await expect(awaitLaneTurn(tx([null]), state, rows)).rejects.toMatchObject({ reason: 'predecessor_requeued' });
- await expect(awaitLaneTurn(tx(['running', 'failed']), state, rows)).rejects.toMatchObject({ reason: 'predecessor_failed' });
+ // #6712 (one page, one fate): a predecessor that ended without committing does not stop this group; it commits in its turn.
+ await awaitLaneTurn(tx(['running', 'failed']), state, rows);
+ await awaitLaneTurn(tx(['cancelled']), state, rows);
await expect(awaitLaneTurn(tx(['running', 'running', 'running']), state, rows, 60)).rejects.toMatchObject({ reason: 'order_timeout' });
await closeLaneRun('run-turn');
expect(laneOf({ worktree_id: 'wt-turn', intent: { lane: 'run-turn' } } as never)).toBeNull();
diff --git a/test/managed-sync-preparation-stalled-holds.test.ts b/test/managed-sync-preparation-stalled-holds.test.ts
index a78c0b4545..263c699f06 100644
--- a/test/managed-sync-preparation-stalled-holds.test.ts
+++ b/test/managed-sync-preparation-stalled-holds.test.ts
@@ -1,13 +1,15 @@
/**
* #6278 (B1): a managed sync member whose owner gave up preparing it
- * (`preparation_stalled`) is held, never re-entered: an import by its bytes, a
+ * (`preparation_stalled`) is held: an import by its bytes, a
* delete as a delete hold, a rename with its endpoints; the checkpoint never
* holds; `sync.holds=fail` keeps blocking. The hold lands behind the narrowed
* gate: an unrelated maintenance write on the same source no longer blocks
* it, a write on the same page still does, and a run killed before the cursor
* consumed the failure holds the entry at the start of the next run. Every
* surface routes the hold to writer status, then `sources retry-held` and the
- * same sync with its options, never to frontmatter repair. The forced probe
+ * same sync with its options, never to frontmatter repair. #6712: the hold is
+ * transient, so every sync retries it until it has been held
+ * `HOLD_ATTEMPTS_NEEDS_HUMAN` times; then it waits for `sources retry-held`. The forced probe
* throws the terminal code from the consumer's `consumer:prepared` seam (the
* single path) or the `publication:before_commit` seam inside the group transaction, so
* the receipt is exactly what Lane A's consumer writes. Synthetic content only.
@@ -28,6 +30,7 @@ import { installFaultHook, type FaultPoint } from '../src/core/persistence/fault
import { readGitSourceHolds, holdRescreenDue, readGitHoldRetryPaths, GIT_HOLD_SUMMARY_OP } from '../src/core/persistence/sync-holds.ts';
import { drainManagedSync, readManagedSyncBacklog } from '../src/core/persistence/sync-drain.ts';
import { preparationStallMeta } from '../src/core/persistence/sync-screen.ts';
+import { HOLD_ATTEMPTS_NEEDS_HUMAN } from '../src/core/persistence/sync-fault-class.ts';
import { readHeldCoverage, coverageRoute } from '../src/core/persistence/held-reads.ts';
import { retryHeld } from '../src/commands/sources-retry-held.ts';
import { gitHeldFilesCheck } from '../src/commands/doctor/checks/git-holds.ts';
@@ -147,12 +150,21 @@ test('an import whose preparation stalls is held in the same run, the run finish
expect(record!.meta.deleted).toBeUndefined();
expect(await s.summary()).toMatchObject({ count: 1, stalled: 1, fences: 0 });
expect(coverageRoute((await readHeldCoverage(engine, { sourceId: s.id }))[0]!)).toEqual({ fences: 0, others: 0, stalled: 1 });
- // It waits: the next run neither re-screens the held bytes nor mints another receipt...
- expect(holdRescreenDue(record!, false)).toBe(false);
+ // #6712: a transient hold (the owner stalled, not the file) is retried by every sync until it has been held
+ // HOLD_ATTEMPTS_NEEDS_HUMAN times; a retry that stalls again re-holds it under its new receipt...
+ expect(holdRescreenDue(record!, false)).toBe(true);
+ for (let attempt = 2; attempt <= HOLD_ATTEMPTS_NEEDS_HUMAN; attempt++) {
+ expect(await s.sync()).toMatchObject({ holds_outstanding: 1 });
+ expect(await s.failedRequests()).toHaveLength(attempt);
+ expect((await s.holds())[0]!.meta.attempts).toBe(attempt);
+ }
+ // ...then it waits: the next run neither re-screens the held bytes nor mints another receipt...
+ const waiting = (await s.holds())[0]!;
+ expect(holdRescreenDue(waiting, false)).toBe(false);
expect(await s.sync()).toMatchObject({ status: 'up_to_date', holds_outstanding: 1 });
- expect(await s.failedRequests()).toHaveLength(1);
+ expect(await s.failedRequests()).toHaveLength(HOLD_ATTEMPTS_NEEDS_HUMAN);
// ...a different gbrain version would re-screen it...
- expect(holdRescreenDue({ code: 'preparation_stalled', meta: { ...record!.meta, stall: { ...record!.meta.stall!, gbrain_version: '0.0.1' } } }, false)).toBe(true);
+ expect(holdRescreenDue({ code: 'preparation_stalled', meta: { ...waiting.meta, stall: { ...waiting.meta.stall!, gbrain_version: '0.0.1' } } }, false)).toBe(true);
// ...doctor and retry-held route it the same way, and the retry's sync keeps the run's options.
const check = await gitHeldFilesCheck(engine, [s.id]);
expect(check.status).toBe('warn');
@@ -184,9 +196,12 @@ test('a stalled delete becomes a delete hold (no bytes); the page stays until re
expect(record).toMatchObject({ path: 'notes/gone.md', code: 'preparation_stalled', upstream_version: null, page_id: expect.any(Number), meta: { deleted: true } });
expect(result.held![0]!.fix.why).toContain('its deletion could not finish preparing');
expectRoutedToWriter(result.held![0]!.fix, s.id);
- // The absent file is not "a change": the hold waits instead of re-admitting the delete every run.
+ // #6712: the transient hold is retried by the next syncs (the absent file is not what re-admits it) until its attempt
+ // bound, then it waits instead of re-admitting the delete every run.
+ for (let attempt = 2; attempt <= HOLD_ATTEMPTS_NEEDS_HUMAN; attempt++) expect(await s.sync()).toMatchObject({ holds_outstanding: 1 });
+ expect(await s.failedRequests()).toHaveLength(HOLD_ATTEMPTS_NEEDS_HUMAN);
expect(await s.sync()).toMatchObject({ status: 'up_to_date', holds_outstanding: 1 });
- expect(await s.failedRequests()).toHaveLength(1);
+ expect(await s.failedRequests()).toHaveLength(HOLD_ATTEMPTS_NEEDS_HUMAN);
installFaultHook(undefined);
await retryHeld(engine, s.id);
expect(await s.sync()).toMatchObject({ status: 'synced', deleted: 1 });
@@ -217,7 +232,9 @@ test('a stalled rename holds the destination with its origin; the hold gate lock
const blocked = await s.sync();
expect(blocked).toMatchObject({ status: 'blocked_by_failures', failureCodes: [{ code: 'preparation_stalled', count: 1 }] });
expect(blocked.managedWrite).toMatchObject({ write_error: 'preparation_stalled' });
- expect(await s.holds()).toHaveLength(1);
+ // #6712: the same sync retried the transient rename hold (its stall is gone) and imported it; the checkpoint's stall held nothing.
+ expect(await s.holds()).toEqual([]);
+ expect(await engine.getPage('notes/new', { sourceId: s.id })).not.toBeNull();
}), 180_000);
test('sync.holds=fail keeps blocking with the typed receipt; the next run after holds are on converts it at its start (a kill before the cursor consumed the failure)', () => each(async engine => {
@@ -367,9 +384,11 @@ test('retry-held while the stall persists: the file is re-held once under the ne
expect(await s.summary()).toMatchObject({ count: 1, stalled: 1 });
expect(await readGitHoldRetryPaths(engine, s.id, await s.incarnation())).toEqual([]);
expect(await engine.getPage('notes/stuck', { sourceId: s.id })).toBeNull();
- // It waits again: no third receipt without another retry.
+ // #6712: the automatic retries stop at HOLD_ATTEMPTS_NEEDS_HUMAN holds; past that no receipt without another retry-held.
+ for (let attempt = 3; attempt <= HOLD_ATTEMPTS_NEEDS_HUMAN; attempt++) expect(await s.sync()).toMatchObject({ holds_outstanding: 1 });
expect(await s.sync()).toMatchObject({ status: 'up_to_date', holds_outstanding: 1 });
- expect(await s.failedRequests()).toHaveLength(2);
+ expect(await s.failedRequests()).toHaveLength(HOLD_ATTEMPTS_NEEDS_HUMAN);
+ expect(await s.holds()).toHaveLength(1);
}), 180_000);
test('a scheduled re-screen survives a run killed before it reached the file; a run killed after freezing it carries it in its manifest and leaves no stale schedule', () => each(async engine => {