Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): a lane drain waits for consumer claims in flight before it reports; test(atoms): settle embedding effects before compaction
garrytan68a22e77499f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2017c550aa..0256d6fb79 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,22 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.60.96.0] - 2026-10-06++**A lane catch-up that stops on a failed page now settles every later page before it reports, and two flaky test families are fixed.**++`gbrain sync --drain` with lanes could report `blocked` while one group after the failed page was still claimed and `running`. The consumer cancelled that group a moment later, and no page after the failure was ever published. But an agent that read the receipts right after the drain returned could see a request still in flight. The drain now waits for that claim too, so every page after the failure reads `cancelled` when it reports.++### Itemized changes++- **Lane drain report (#6153, #6189).** A lane group head was counted as a lane task only after its claim query returned. The drain's close (`closeLaneRun`) could see zero tasks during that query and return while the head it had just claimed was `running`. Each consumer claim that can take a lane row now counts from before its query until its task is counted, on both the lane path and the FIFO path, and the close waits for claims in flight as well as tasks. Forced probe: with a 500 ms pause between the claim and the task count, `test/managed-sync-lanes.test.ts` › "a failed page under lanes stops the run" failed 8 of 8 runs before and passed 8 of 8 after. A new unit test pins the close waiting for a claim in flight.+- **Managed atom compaction tests (#6167, #6168).** The `success` scenarios stopped the persistence consumer while a committed atom's embedding effect was still running. Stopping requeues the effect, and compaction keeps a receipt whose effect is unfinished, so compaction returned 2 instead of 3, and the leftover receipt made the next test return one too many. The helper now waits for the source's effects to settle before it stops the consumer. Forced probe: a 400 ms pause in the embedding effect failed both `success` cases on PostgreSQL and PGLite before the fix and passed after. No assertion changed.+- **#6129** was fixed by #6130 and hasn't recurred on master since.++## To take advantage of v0.60.96.0++Nothing to do. `gbrain sync --drain` picks up the fix after `gbrain upgrade`.+## [0.60.95.0] - 2026-10-06**The full Ubicloud test gate finishes in about five and a half minutes instead of ten to fifteen, and the embedding-migration bad-flag test stops timing out.**diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex 70f3afcb9f..8167ca34a4 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -9,7 +9,7 @@ import { refreshManagedFilesystemRoots } from './filesystem-guard.ts';import { PROJECTION_RETRY_READY_SQL, rebuildPendingPageProjections } from '../page-state/projections.ts';import { publicationConcurrency } from './pool-capacity.ts';import { cancelOrphanedWindowGroup } from './sync-window.ts';-import { laneOf, laneRoots, laneTask } from './sync-lanes.ts';+import { laneClaim, laneOf, laneRoots, laneTask } from './sync-lanes.ts';import { runPersistenceEffects } from './effects.ts';import { PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';import { isWriteErrorCode } from './types.ts';@@ -357,16 +357,19 @@ export class PersistenceConsumer {const concurrency = this.opts.concurrency ?? 2;const attemptedRoots = new Set([...this.activeRoots, ...this.laneTasks.keys(), ...this.rootRetryAfter.keys()]);while (!this.stopping && this.active.size - this.laneTaskCount() < concurrency) {- const row = await this.phase('claim', () => claimNextWrite(this.engine, this.hostId, 30_000, [...attemptedRoots]));- if (!row) break;- if (this.stopping) { await releaseUnpublishedClaim(this.engine, row, 'consumer_stopping'); break; }- const key = row.worktree_id ?? `db:${row.source_incarnation}`;- attemptedRoots.add(key);- // #5984 lanes: the FIFO head of an open lane run runs as the run's first lane.- if (laneOf(row)) { this.startLaneTask(row, key); continue; }- if (this.activeRoots.has(key)) { await releaseUnpublishedClaim(this.engine, row, 'writer_busy'); break; }- this.activeRoots.add(key);- this.track(row, () => this.activeRoots.delete(key), key);+ const claimed = laneClaim();+ try {+ const row = await this.phase('claim', () => claimNextWrite(this.engine, this.hostId, 30_000, [...attemptedRoots]));+ if (!row) break;+ if (this.stopping) { await releaseUnpublishedClaim(this.engine, row, 'consumer_stopping'); break; }+ const key = row.worktree_id ?? `db:${row.source_incarnation}`;+ attemptedRoots.add(key);+ // #5984 lanes: the FIFO head of an open lane run runs as the run's first lane.+ if (laneOf(row)) { this.startLaneTask(row, key); continue; }+ if (this.activeRoots.has(key)) { await releaseUnpublishedClaim(this.engine, row, 'writer_busy'); break; }+ this.activeRoots.add(key);+ this.track(row, () => this.activeRoots.delete(key), key);+ } finally { claimed(); }}await this.claimLanes();}@@ -375,9 +378,12 @@ export class PersistenceConsumer {for (const { worktreeId, run, capacity } of laneRoots()) {if (this.rootRetryAfter.has(worktreeId) || this.activeRoots.has(worktreeId)) continue;while (!this.stopping && (this.laneTasks.get(worktreeId) ?? 0) < capacity) {- const row = await this.phase('claim', () => claimNextLaneHead(this.engine, this.hostId, worktreeId, run));- if (!row) break;- this.startLaneTask(row, worktreeId);+ const claimed = laneClaim();+ try {+ const row = await this.phase('claim', () => claimNextLaneHead(this.engine, this.hostId, worktreeId, run));+ if (!row) break;+ this.startLaneTask(row, worktreeId);+ } finally { claimed(); }}}}diff --git a/src/core/persistence/sync-lanes.ts b/src/core/persistence/sync-lanes.tsindex bbd1d21be4..e07d7bed95 100644--- a/src/core/persistence/sync-lanes.ts+++ b/src/core/persistence/sync-lanes.ts@@ -28,6 +28,7 @@ export interface LaneState extends LanePolicy { coordinationPath: string | null;/** Lane tasks this process runs for the run, from the head's claim until the task settles; `closing` stops new claims. */tasks: number; closing: boolean }const policies = new Map<string, LaneState>();+let claiming = 0;/** The drain's lane policy for a worktree; replaces any earlier one. */export function openLanes(worktreeId: string, run: string, lanes: number, coordinationPath: string | null): void {@@ -35,16 +36,26 @@ export function openLanes(worktreeId: string, run: string, lanes: number, coordi}/*** Ends a drain's lane run on every worktree it opened: no new lane claims, then waits (up to `maxMs`) for the- * lane tasks already running to settle, so a drain never reports while one of its groups is still publishing- * or aborting. Its unclaimed groups go back to the FIFO claim.+ * consumer claims in flight and the lane tasks already running to settle, so a drain never reports while one of+ * its groups is still publishing or aborting. Its unclaimed groups go back to the FIFO claim.*/export async function closeLaneRun(run: string, maxMs = 90_000): Promise<void> {const open = [...policies].filter(([, state]) => state.run === run);for (const [, state] of open) state.closing = true;const started = Date.now();- while (open.some(([, state]) => state.tasks > 0) && Date.now() - started < maxMs) await sleep(20);+ while ((claiming > 0 || open.some(([, state]) => state.tasks > 0)) && Date.now() - started < maxMs) await sleep(20);for (const [worktreeId, state] of open) if (policies.get(worktreeId) === state) policies.delete(worktreeId);}+/**+ * Counts a consumer claim that can take a lane row, from before its claim query until the claimed head's lane+ * task is counted; returns the release. A head claimed while its run closes is already running before its task+ * counts, so without this the drain could report before that head settles.+ */+export function laneClaim(): () => void {+ claiming++;+ let released = false;+ return () => { if (!released) { released = true; claiming--; } };+}/** Counts a lane task from its head's claim until it settles; returns the release. */export function laneTask(state: LaneState): () => void {state.tasks++;diff --git a/test/helpers/managed-atom-compaction.ts b/test/helpers/managed-atom-compaction.tsindex b300496fd1..53e3324328 100644--- a/test/helpers/managed-atom-compaction.ts+++ b/test/helpers/managed-atom-compaction.ts@@ -15,6 +15,7 @@ import type { WriteRequest } from '../../src/core/persistence/model.ts';import { disposePersistenceConsumer, waitForWrite } from '../../src/core/persistence/service.ts';import { sha256 } from '../../src/core/persistence/digest.ts';import { withEnv } from './with-env.ts';+import { waitFor } from './wait-for.ts';export const atomCompactionCases = ['all_failed', 'mixed_all', 'completion_only', 'failed_child_only', 'committed_child_only', 'changed_target', 'success', 'malformed'] as const;export const atomCompactionActions = ['resume', 'retry'] as const;@@ -61,6 +62,12 @@ export async function exerciseAtomCompaction(engine: BrainEngine, scenario: typeexpect(accepted).toHaveLength(scenario === 'malformed' ? 1 : 3);const completion = await waitForWrite(observedEngine, accepted.at(-1)!, { engine: engine.kind });expect(completion.state).toBe(['success', 'malformed'].includes(scenario) ? 'committed' : 'conflict');+ // A committed atom still has its embedding effect running. Stopping the+ // consumer requeues it, and compaction retains a receipt whose effect is+ // unfinished, so settle the source's effects before stopping.+ await waitFor(async () => (await engine.executeRaw(+ "SELECT 1 FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE r.source_id=$1 AND e.state IN ('queued','running')", [sourceId])).length === 0,+ { label: `${engine.kind}: ${scenario} ${action} atom effects settled` });await disposePersistenceConsumer(observedEngine);const originals = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE source_id=$1 ORDER BY sequence', [sourceId]);if (scenario !== 'malformed') expect(originals.map(row => row.state)).toEqual(scenario === 'success' ? ['committed', 'committed', 'committed'] :diff --git a/test/managed-sync-lanes.test.ts b/test/managed-sync-lanes.test.tsindex 05d9ae9a42..0c7054f433 100644--- a/test/managed-sync-lanes.test.ts+++ b/test/managed-sync-lanes.test.ts@@ -18,7 +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, laneRoots, laneTask, openLanes } from '../src/core/persistence/sync-lanes.ts';+import { awaitLaneTurn, closeLaneRun, laneClaim, laneOf, laneRoots, laneTask, openLanes } from '../src/core/persistence/sync-lanes.ts';const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-lanes-'));let engine: BrainEngine | undefined;@@ -147,6 +147,23 @@ test('closing a lane run stops new lane claims and waits for the lane tasks stilexpect(laneOf({ worktree_id: 'wt-close', intent: { lane: 'run-close' } } as never)).toBeNull();});+test('closing a lane run waits for a claim still in flight to count its lane task', async () => {+ openLanes('wt-claim', 'run-claim', 4, null);+ const state = laneOf({ worktree_id: 'wt-claim', intent: { lane: 'run-claim' } } as never)!;+ const claimed = laneClaim();+ let closed = false;+ const closing = closeLaneRun('run-claim').then(() => { closed = true; });+ await new Promise(resolve => setTimeout(resolve, 100));+ expect(closed).toBe(false);+ const release = laneTask(state);+ claimed();+ await new Promise(resolve => setTimeout(resolve, 100));+ expect(closed).toBe(false);+ release();+ await closing;+ expect(laneOf({ worktree_id: 'wt-claim', intent: { lane: 'run-claim' } } 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));