Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): a lane never cancels on an unadmitted predecessor; window admission stops at the first failure

garrytan7fa4a4809e9d
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index 23abf68705..3d972d8ee8 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -241,7 +241,7 @@ function groupFailure(error: unknown): GroupFailure {
/**
* #5984 lanes: a lane group that did not commit. A group whose predecessor ended without committing is
* cancelled; one whose predecessor committed takes the single path like any FIFO head (null); one whose
- * predecessor still publishes releases its claims so the FIFO head runs first. Lock and statement timeouts
+ * predecessor still publishes, waits in the queue or is not admitted yet releases its claims so it runs first. Lock and statement timeouts
* cost one lane for the rest of the drain.
*/
async function laneFallback(engine: BrainEngine, rows: WriteRequest[], reason: GroupFailure | undefined, run: GroupExecution): Promise<boolean | null> {
@@ -251,7 +251,7 @@ async function laneFallback(engine: BrainEngine, rows: WriteRequest[], reason: G
const prior = after ? await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2 AND request_id=$3::uuid',
[rows[0]!.principal_kind, rows[0]!.principal_id, after]).then(found => found[0]?.state ?? null) : 'committed';
if (prior === 'committed') return null;
- if (prior === null || ['failed', 'conflict', 'cancelled'].includes(prior)) {
+ if (prior !== null && ['failed', 'conflict', 'cancelled'].includes(prior)) {
for (const done of await cancelRows(engine, rows)) run.settled(done);
return true;
}
diff --git a/src/core/persistence/sync-lanes.ts b/src/core/persistence/sync-lanes.ts
index 66015cfdee..0d34790433 100644
--- a/src/core/persistence/sync-lanes.ts
+++ b/src/core/persistence/sync-lanes.ts
@@ -97,9 +97,9 @@ export async function awaitLaneTurn(tx: BrainEngine, state: LaneState, rows: Wri
const [prior] = await tx.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2 AND request_id=$3::uuid',
[head.principal_kind, head.principal_id, after]);
if (prior?.state === 'committed') return;
- if (!prior || ['failed', 'conflict', 'cancelled'].includes(prior.state)) throw new LaneAbort('predecessor_failed');
- // A released predecessor goes first: this lane gives its slot and claims back, rather than wait on it.
- if (prior.state === 'queued') throw new LaneAbort('predecessor_requeued');
+ if (prior && ['failed', 'conflict', 'cancelled'].includes(prior.state)) throw new LaneAbort('predecessor_failed');
+ // A released (or not yet admitted) predecessor goes first: this lane gives its slot and claims back, rather than wait on it.
+ if (!prior || prior.state === 'queued') throw new LaneAbort('predecessor_requeued');
if (state.coordinationPath && leaseWounded(state.coordinationPath)) throw new LaneAbort('wounded');
if (Date.now() - started >= maxMs) throw new LaneAbort('order_timeout');
await sleep(Math.min(200, 25 * (poll + 1)));
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 7397e67e72..e91b35dc87 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -481,7 +481,8 @@ async function admitAhead(engine: BrainEngine, cursor: Cursor, key: string, bulk
let current = cursor, foregroundChecked = false;
for (let slot = 0; ; slot++) {
const window = current.window ?? [];
- if (slot < window.length) { await admitWindowGroup(engine, current, key, slot); continue; }
+ // A group admits only after the group before it: a failed admission ends this pass (it is retried on the next).
+ if (slot < window.length) { if (!await admitWindowGroup(engine, current, key, slot)) break; continue; }
if (window.length >= depth) break;
const start = current.index + current.group!.length + window.reduce((sum, group) => sum + group.length, 0);
if (start >= current.entries.length) break;
@@ -506,18 +507,19 @@ async function admitAhead(engine: BrainEngine, cursor: Cursor, key: string, bulk
assertActive();
return current;
}
-/** Admits window group `slot` when its requests are missing (a failed admission is retried when it becomes the cursor's group). */
-async function admitWindowGroup(engine: BrainEngine, cursor: Cursor, key: string, slot: number): Promise<void> {
+/** Admits window group `slot` when its requests are missing; false when they are still missing (retried on the next pass, or when it becomes the cursor's group). */
+async function admitWindowGroup(engine: BrainEngine, cursor: Cursor, key: string, slot: number): Promise<boolean> {
const members = cursor.window![slot]!;
const principal = cursor.authority.writer.principal;
const admitted = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2 AND request_id=ANY($3::uuid[])',
[principal.kind, principal.id, members.map(member => member.requestId)]);
- if ((admitted[0]?.n ?? 0) >= members.length) return;
+ if ((admitted[0]?.n ?? 0) >= members.length) return true;
const rows = await admitGroup(engine, members, cursor, async tx => {
const [held] = await tx.executeRaw<{ request_id: string | null }>(`SELECT completed_keys->0->'window'->($3::int)->0->>'requestId' AS request_id FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 FOR SHARE`, [OP, key, slot]);
return held?.request_id === members[0]!.requestId;
}).catch(() => null);
if (rows) startPersistenceConsumer(engine, loadConfig() ?? { engine: engine.kind }).wake();
+ return rows !== null;
}
/**
* #5984 bulk: admits the cursor's group, waits for it and advances over the
diff --git a/test/managed-sync-lanes.test.ts b/test/managed-sync-lanes.test.ts
index 99801bcaf4..521a730ad5 100644
--- a/test/managed-sync-lanes.test.ts
+++ b/test/managed-sync-lanes.test.ts
@@ -18,6 +18,7 @@ import { WINDOW_CANCEL_MESSAGE } from '../src/core/persistence/sync-window.ts';
import { acquireShared, 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';
+import { awaitLaneTurn, closeLaneRun, laneOf, openLanes } from '../src/core/persistence/sync-lanes.ts';
const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-lanes-'));
let engine: BrainEngine | undefined;
@@ -80,6 +81,20 @@ test('a lease is shared by lanes; an exclusive writer drains and wounds it and g
expect(leaseDraining(path)).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 () => {
+ 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;
+ const tx = (states: Array<string | null>) => ({ executeRaw: async () => { const next = states.shift(); return next === null || next === undefined ? [] : [{ state: next }]; } }) as never;
+ 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' });
+ await expect(awaitLaneTurn(tx(['running', 'running', 'running']), state, rows, 60)).rejects.toMatchObject({ reason: 'order_timeout' });
+ closeLaneRun('run-turn');
+ expect(laneOf({ worktree_id: 'wt-turn', intent: { lane: 'run-turn' } } as never)).toBeNull();
+});
+
test('lanes publish several groups at once and every page still commits, attributed to its own request, in manifest order', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_BULK_SIZE: '4' }, async () => {
if (!engine) return;
const f = await fixture(engine, notes(80));