Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): an aborted sync returns promptly instead of sitting out its 5 s write wait

garrytan3bdfbe54d32f
diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.ts
index 3df08f15fb..6835e40d3b 100644
--- a/src/core/persistence/service.ts
+++ b/src/core/persistence/service.ts
@@ -269,11 +269,31 @@ export async function awaitWrite(engine: BrainEngine, row: WriteRequest, config:
row = { ...row, ...read.row };
if (isTerminal(row)) return { kind: 'terminal', row: await getWriteRequestById(engine, id).catch(() => null) ?? row };
}
+ // A stopped wait settles only what this process can settle at once: one consumer tick (it claims and publishes the
+ // request when nothing holds it back) and the request this consumer is still executing. A write that cannot move
+ // (another owner's lock, a consumer that defers to another process) is left queued under its request id.
+ if (opts.signal?.aborted && !service.stopping && !handed) {
+ const left = () => deadline - performance.now();
+ await Promise.race([consumer.tick().catch(() => undefined), new Promise<void>(resolve => setTimeout(resolve, Math.max(0, left())))]);
+ while (!handed && consumer.holds(id) && left() > 0) {
+ await new Promise<void>(resolve => {
+ const done = () => { clearTimeout(timer); wake = undefined; resolve(); };
+ const timer = setTimeout(done, Math.min(50, left()));
+ wake = done;
+ });
+ }
+ }
} finally {
listeners.delete(listener);
if (!listeners.size && waiters.get(id) === listeners) waiters.delete(id);
}
if (handed) row = handed;
+ // A stopped wait then reads the receipt once, so a write that committed meanwhile is banked rather than reported pending.
+ if (!isTerminal(row) && opts.signal?.aborted && !service.stopping) {
+ const latest = await getWriteRequestProgress(engine, id).catch(() => null);
+ if (latest) row = { ...row, ...latest };
+ if (isTerminal(row)) return { kind: 'terminal', row: await getWriteRequestById(engine, id).catch(() => null) ?? row };
+ }
if (isTerminal(row)) return { kind: 'terminal', row };
if (failure) {
const { classifyPgAccessError } = await import('../pg-access-classify.ts');
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index f5151b8f3b..e40ef797c5 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -1511,7 +1511,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
const freezeAt: FreezeAt = base => async index => { if (base.entries[index]?.prescreened && !prescreen.missed.has(index)) return null; const frozen = await freezeEntry(engine, { ...base, index }, key, assertActive, frozenRun).catch(() => null); return frozen && 'requestId' in frozen ? frozen : null; }; // GBRA-133 S-64: a follower's throw is raised by the single path, naming its own entry
if (bulk.settings.enabled && (bulk.foregroundFirst || !foregroundQueued) && !prior && !cursor.group && !pending.rebound && indexOf(cursor, pending) === cursor.index && groupableIntent(pending.intent)) cursor = await formGroup(engine, cursor, pending, key, bulk, config, freezeAt, assertActive);
if (cursor.group?.[0]?.requestId === pending.requestId && cursor.pending?.requestId === pending.requestId) {
- const step = await groupStep(engine, cursor, key, bulk, config, opts.drainStartedAt ? { waitMs: 30_000, signal } : { waitMs: 5000, ...whileHeld }, drainStartedAt, opts.onProgress,
+ const step = await groupStep(engine, cursor, key, bulk, config, opts.drainStartedAt ? { waitMs: 30_000, signal } : { waitMs: 5000, signal, ...whileHeld }, drainStartedAt, opts.onProgress,
opts.drainStartedAt ? next => admitAhead(engine, next, key, bulk, config, freezeAt, assertActive) : undefined);
if ('result' in step) return step.result;
cursor = step.cursor;
@@ -1525,8 +1525,10 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
assertSyncDispatchActive(); stampDrainStep('await_receipt', signal);
// #5762: a checkpoint's validation runs under the coordinator's 5 s statement timeout, so its wait outlasts that
// budget; a timed-out checkpoint then reports its terminal refusal and hint in this run instead of the next.
- // #5984: a drain re-enters anyway, so it waits longer per page instead of paying a full re-entry; its stop signal bounds the wait.
- const waited = await awaitWrite(engine, row, config, opts.drainStartedAt ? { waitMs: 30_000, signal } : { waitMs: pending.intent.kind === 'managed_sync_checkpoint' ? 8000 : 5000, ...whileHeld });
+ // #5984: a drain re-enters anyway, so it waits longer per page instead of paying a full re-entry. The run's stop signal
+ // bounds every wait: an aborted run reads the receipt once and returns, and an accepted write it did not see commit
+ // stays queued under its request id for the next run.
+ const waited = await awaitWrite(engine, row, config, opts.drainStartedAt ? { waitMs: 30_000, signal } : { waitMs: pending.intent.kind === 'managed_sync_checkpoint' ? 8000 : 5000, signal, ...whileHeld });
const done = waited.row;
assertSyncDispatchActive();
if (!isTerminalWriteState(done.state)) {
diff --git a/test/persistence-sync-options.serial.test.ts b/test/persistence-sync-options.serial.test.ts
index d7c33c1e2f..1347f87cc9 100644
--- a/test/persistence-sync-options.serial.test.ts
+++ b/test/persistence-sync-options.serial.test.ts
@@ -871,6 +871,37 @@ for (const boundary of ['accepted-commit', 'receipt-banking'] as const) check(`c
} finally { engine.executeRaw = execute; engine.transaction = transaction; }
});
+/** How soon an aborted sync returns: a stop check and one receipt read, far under the 5 s write wait it used to sit out. */
+const ABORT_RETURN_MS = 1500;
+
+check('an aborted sync returns promptly, before entry and while it waits on its accepted write, and the write stays queued for resume', async engine => {
+ const before = await fixture(engine), early = new AbortController();
+ early.abort();
+ const started = performance.now();
+ expect(await performSync(engine, { ...before.opts, signal: early.signal })).toMatchObject({ status: 'partial', reason: 'timeout', filesImported: 0 });
+ expect(Math.round(performance.now() - started)).toBeLessThan(ABORT_RETURN_MS);
+ const f = await fixture(engine), abort = new AbortController(), transaction = engine.transaction;
+ const lock = await acquireWorktree((await getWorktreeBinding(engine, f.id))!);
+ expect(lock).not.toBeNull();
+ let abortedAt = 0;
+ engine.transaction = async function (this: BrainEngine, run: (tx: BrainEngine) => Promise<unknown>) {
+ const value = await transaction.call(this, run);
+ if (!abortedAt && value && typeof value === 'object' && 'request_id' in value && 'source_id' in value && value.source_id === f.id) { abortedAt = performance.now(); abort.abort(); }
+ return value;
+ } as BrainEngine['transaction'];
+ try {
+ const pending = await performSync(engine, { ...f.opts, signal: abort.signal });
+ const returnedMs = performance.now() - abortedAt;
+ expect(abortedAt).toBeGreaterThan(0);
+ expect(pending).toMatchObject({ status: 'partial', reason: 'timeout', filesImported: 0, managedWrite: { write_error: 'write_pending' } });
+ expect(Math.round(returnedMs)).toBeLessThan(ABORT_RETURN_MS);
+ const requestId = pending.managedWrite!.write_request.request_id;
+ await disposePersistenceConsumer(engine);
+ expect(await engine.executeRaw('SELECT request_id,state FROM persistence_requests WHERE source_id=$1', [f.id])).toEqual([{ request_id: requestId, state: 'queued' }]);
+ } finally { engine.transaction = transaction; await disposePersistenceConsumer(engine); await lock?.release(); }
+ expect(await performSync(engine, f.opts)).toMatchObject({ status: 'first_sync', added: 1, filesImported: 1 });
+});
+
check('cancelled waits retain the accepted pending receipt and resume it after owner lock release', async engine => {
const f = await fixture(engine), abort = new AbortController(), transaction = engine.transaction;
const lock = await acquireWorktree((await getWorktreeBinding(engine, f.id))!);