Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(refresh): recheck recovery under the worktree lock so a publisher finishing mid-probe is not refused; harden 13c
garrytan382fa73f68a7
diff --git a/src/core/persistence/worktree-refresh.ts b/src/core/persistence/worktree-refresh.tsindex 731c66f9e7..861a00fd36 100644--- a/src/core/persistence/worktree-refresh.ts+++ b/src/core/persistence/worktree-refresh.ts@@ -226,22 +226,25 @@ function dirtyRefusal(sourceId: string, overlap: string[], refreshId?: string):* after the receipt commits (coordinator `completeWrite`, then* `clearResolvedRecovery`). So a request or effect record is in flight, and left* to the drain step, while it is under an unexpired running claim or while the- * worktree lock is held; only a record no live process can finish refuses.+ * worktree lock is held; only a record still present while this probe holds+ * that lock (no live process can finish it) refuses.* Topology recovery always refuses.*/async function worktreeRecoveryPending(engine: BrainEngine, binding: WorktreeBinding): Promise<boolean> {- const [row] = await engine.executeRaw<{ publication: boolean; topology: boolean }>(`SELECT+ const probe = async () => (await engine.executeRaw<{ publication: boolean; topology: boolean }>(`SELECTEXISTS (SELECT 1 FROM persistence_requests WHERE worktree_id=$1::uuid AND recovery IS NOT NULLAND NOT (state='running' AND claim_expires_at > now()))OR EXISTS (SELECT 1 FROM persistence_effects WHERE worktree_id=$1::uuid AND recovery IS NOT NULLAND NOT (state='running' AND claim_expires_at > now())) AS publication,- EXISTS (SELECT 1 FROM persistence_topology_changes WHERE recovery IS NOT NULL AND recovery->>'worktreeId'=$1::text) AS topology`, [binding.worktree_id]);- if (row?.topology === true) return true;- if (row?.publication !== true || !binding.coordination_path) return row?.publication === true;- const probe = await tryAcquireNativeLock(binding.coordination_path);- if (!probe) return false;- await probe.release();- return true;+ EXISTS (SELECT 1 FROM persistence_topology_changes WHERE recovery IS NOT NULL AND recovery->>'worktreeId'=$1::text) AS topology`, [binding.worktree_id]))[0];+ const first = await probe();+ if (first?.topology === true) return true;+ if (first?.publication !== true || !binding.coordination_path) return first?.publication === true;+ const lock = await tryAcquireNativeLock(binding.coordination_path);+ if (!lock) return false;+ // Holding the lock, no publisher is mid-flight: a record that is still here has no live owner.+ try { const held = await probe(); return held?.publication === true || held?.topology === true; }+ finally { await lock.release(); }}/** Never wait on a sync: an unexhausted cursor names its own resume command. */async function assertNoUnfinishedSync(engine: BrainEngine, members: string[]): Promise<void> {diff --git a/test/persistence-worktree-refresh.test.ts b/test/persistence-worktree-refresh.test.tsindex d27870314f..ef133f3d41 100644--- a/test/persistence-worktree-refresh.test.ts+++ b/test/persistence-worktree-refresh.test.ts@@ -300,6 +300,14 @@ test('13c. a committed write whose publisher still holds the worktree lock (recoconst [request] = await f.engine.executeRaw<{ id: string }>('SELECT id::text FROM persistence_requests WHERE source_id=$1 AND worktree_id IS NOT NULL ORDER BY sequence DESC LIMIT 1', [f.alpha]);const binding = (await getWorktreeBinding(f.engine, f.alpha))!;+ // Let the seed's Git effect finish, then stop the resident consumer so its recovery scan cannot settle the planted record.+ for (let i = 0; i < 100; i++) {+ const [busy] = await f.engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM persistence_effects+ WHERE worktree_id=$1::uuid AND kind IN ('git','withdrawal-mirror') AND state IN ('queued','running')`, [f.worktreeId]);+ if (Number(busy.n) === 0) break;+ await new Promise(resolve => setTimeout(resolve, 100));+ }+ await disposePersistenceConsumer(f.engine);const committedWithRecovery = () => f.engine.executeRaw(`UPDATE persistence_requests SET recovery='{"version":1}'::jsonb, claim_expires_at=NULL WHERE id=$1::uuid AND state='committed'`, [request.id]);const clear = () => f.engine.executeRaw('UPDATE persistence_requests SET recovery=NULL WHERE id=$1::uuid', [request.id]);@@ -310,6 +318,7 @@ test('13c. a committed write whose publisher still holds the worktree lock (reco// Live owner: the publisher holds the worktree lock until it clears the record.const lock = (await tryAcquireNativeLock(binding.coordination_path!))!;expect(lock).not.toBeNull();+ await committedWithRecovery();const publisherFinishes = new Promise<void>(resolve => setTimeout(() => { void clear().then(() => lock.release()).then(resolve); }, 400));const result = await refreshWorktree(f.engine, f.alpha, { waitDrainMs: 10_000 });await publisherFinishes;@@ -317,6 +326,39 @@ test('13c. a committed write whose publisher still holds the worktree lock (reco} finally { await clear(); }}), 120_000);+test('13d. a publisher that clears its record and releases the lock between the precheck probe and its lock attempt is not refused', () => each(async f => {+ // TOCTOU on 13c's fix: the precheck sees the record, then the publisher finishes before the lock probe.+ const target = f.push('alpha/two.md', page('Alpha two', 'Upstream.'));+ await f.put(f.alpha, 'notes/seed', page('Seed', 'Has a worktree request.'));+ const [request] = await f.engine.executeRaw<{ id: string }>(+ 'SELECT id::text FROM persistence_requests WHERE source_id=$1 AND worktree_id IS NOT NULL ORDER BY sequence DESC LIMIT 1', [f.alpha]);+ for (let i = 0; i < 100; i++) {+ const [busy] = await f.engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM persistence_effects+ WHERE worktree_id=$1::uuid AND kind IN ('git','withdrawal-mirror') AND state IN ('queued','running')`, [f.worktreeId]);+ if (Number(busy.n) === 0) break;+ await new Promise(resolve => setTimeout(resolve, 100));+ }+ await disposePersistenceConsumer(f.engine);+ const clear = () => f.engine.executeRaw('UPDATE persistence_requests SET recovery=NULL WHERE id=$1::uuid', [request.id]);+ await f.engine.executeRaw(`UPDATE persistence_requests SET recovery='{"version":1}'::jsonb, claim_expires_at=NULL WHERE id=$1::uuid AND state='committed'`, [request.id]);+ const engine = f.engine as BrainEngine & { executeRaw: BrainEngine['executeRaw'] };+ const original = engine.executeRaw;+ let finished = false;+ // Intercept only the precheck's first recovery probe, then hand the engine back untouched.+ engine.executeRaw = (async (sql: string, params?: unknown[], opts?: unknown) => {+ if (finished || !sql.includes('AS publication')) return original.call(engine, sql, params as never, opts as never);+ finished = true;+ engine.executeRaw = original;+ const rows = await original.call(engine, sql, params as never, opts as never);+ await clear();+ return rows;+ }) as BrainEngine['executeRaw'];+ try {+ expect(await refreshWorktree(f.engine, f.alpha, { waitDrainMs: 10_000 })).toMatchObject({ status: 'completed', target_head: target });+ expect(finished).toBe(true);+ } finally { engine.executeRaw = original; await clear(); }+}), 120_000);+test('admission completes a syncing refresh whose members all reached the target, and refuses while one lags', () => each(async f => {const target = f.push('alpha/two.md', page('Alpha two', 'Upstream.'));expect((await refreshWorktree(f.engine, f.alpha)).status).toBe('completed');