Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(refresh): a committed write whose publisher still holds the worktree lock no longer refuses a refresh as recovery_required
garrytan3e20868dbfe5
diff --git a/src/core/persistence/worktree-refresh.ts b/src/core/persistence/worktree-refresh.tsindex 4c7ead167d..731c66f9e7 100644--- a/src/core/persistence/worktree-refresh.ts+++ b/src/core/persistence/worktree-refresh.ts@@ -181,7 +181,7 @@ async function precheck(engine: BrainEngine, git: Git, sourceId: string, fetchTiconst active = await readActiveRefresh(engine, binding.worktree_id);if (active) throw refusal('refresh_in_progress', `Refresh ${active.id} of this worktree is ${active.state}; only one refresh per worktree runs at a time.`,`gbrain sources refresh ${sourceId} --resume`, active.id);- if (binding.state !== 'active' || await worktreeRecoveryPending(engine, binding.worktree_id)) throw refusal('refresh_recovery_required',+ if (binding.state !== 'active' || await worktreeRecoveryPending(engine, binding)) throw refusal('refresh_recovery_required','Publication or topology recovery is pending on this worktree; the checkout must not move until it is recovered.',`gbrain sources writer status ${sourceId}, let the owner finish recovery, then gbrain sources refresh ${sourceId}`);const members = (await engine.executeRaw<{ source_id: string }>('SELECT source_id FROM persistence_source_bindings WHERE worktree_id=$1::uuid ORDER BY source_id',@@ -221,16 +221,27 @@ function dirtyRefusal(sourceId: string, overlap: string[], refreshId?: string):`Commit or discard those paths (check gbrain sources writer status ${sourceId} --json for pending git effects first), then retry gbrain sources refresh ${sourceId}.`, refreshId);}/**- * Recovery no live execution will finish. A recovery record under an unexpired- * running claim is an in-flight publication; the drain step waits for it.+ * Recovery no live execution will finish. A publisher holds the worktree native+ * lock from its claim until it clears its recovery record, and that clear runs+ * 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.+ * Topology recovery always refuses.*/-async function worktreeRecoveryPending(engine: BrainEngine, worktreeId: string): Promise<boolean> {- const [row] = await engine.executeRaw<{ pending: boolean }>(`SELECT EXISTS (SELECT 1 FROM persistence_requests WHERE worktree_id=$1::uuid AND recovery IS NOT NULL+async function worktreeRecoveryPending(engine: BrainEngine, binding: WorktreeBinding): Promise<boolean> {+ const [row] = await engine.executeRaw<{ publication: boolean; topology: boolean }>(`SELECT+ EXISTS (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 NULL- AND NOT (state='running' AND claim_expires_at > now()))- OR EXISTS (SELECT 1 FROM persistence_topology_changes WHERE recovery IS NOT NULL AND recovery->>'worktreeId'=$1::text) AS pending`, [worktreeId]);- return row?.pending === true;+ AND 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;}/** 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 e077190f02..d27870314f 100644--- a/test/persistence-worktree-refresh.test.ts+++ b/test/persistence-worktree-refresh.test.ts@@ -24,6 +24,8 @@ import { operations } from '../src/core/operations.ts';import { runSourcesRefresh } from '../src/commands/sources-refresh.ts';import { claimCoalescedGitEffects, claimPersistenceEffect } from '../src/core/persistence/effect-journal.ts';import { localHostId } from '../src/core/persistence/identity.ts';+import { tryAcquireNativeLock } from '../src/core/persistence/native-lock.ts';+import { getWorktreeBinding } from '../src/core/persistence/ownership.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { runManagedSourceLifecycle } from '../src/core/persistence/source-lifecycle.ts';import { runPersistenceAdministration } from '../src/core/persistence/administration.ts';@@ -289,6 +291,32 @@ test('13b. a publication in flight (recovery under a live claim) is drained, not}}), 120_000);+test('13c. a committed write whose publisher still holds the worktree lock (recovery not yet cleared) is drained, not refused', () => each(async f => {+ // The coordinator commits the receipt (completeWrite) and only then clears the request's recovery record+ // (clearResolvedRecovery), holding the worktree native lock throughout. A refresh whose precheck lands in+ // that window used to refuse refresh_recovery_required; on loaded CI this flaked cases 8 and 13.+ 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]);+ const binding = (await getWorktreeBinding(f.engine, f.alpha))!;+ 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]);+ try {+ // No live owner: the same record left by a crashed publisher is still refused.+ await committedWithRecovery();+ await refusedWith(refreshWorktree(f.engine, f.alpha, { waitDrainMs: 300 }), 'refresh_recovery_required');+ // Live owner: the publisher holds the worktree lock until it clears the record.+ const lock = (await tryAcquireNativeLock(binding.coordination_path!))!;+ expect(lock).not.toBeNull();+ 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;+ expect(result).toMatchObject({ status: 'completed', target_head: target });+ } finally { 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');