Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): an abandoned lane preparation bars its worktree from claims (F4)
garrytan1be77d9ac18c
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex a39ff2787f..4824af23be 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1020,6 +1020,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: 'TBD', text: 'A managed `gbrain import` or `gbrain sync` of a new page over 4 MiB stored in segments now replies when the write commits, before its search index is built, instead of waiting for that build (which on a loaded host outlasted the 30 s import wait and replied `write_pending`). The import result and the write\'s receipt say `searchable: "pending"` and `projection: "pending"`; the import result also carries the `request_id`, `searchable_retry_after_ms` and `searchable_fix`. Read the receipt again (`gbrain write-request -- <request_id>`, `get_write_request`) at that interval until it says `searchable: true`; search finds the page from then on. The build no longer holds up the source\'s next write either. A new page up to 4 MiB, and an edit of a page stored in segments, is still searchable when its import replies (`searchable: true`). A `put_page` of a new page over 4 MiB, whose receipt already said `searchable: "pending"`, now also replies at commit instead of after the build.' },// Wave B follow-ups lane F3 (#7122 remote append_page mention links). `since` is stamped at the merge slot.{ since: 'TBD', text: 'A remote `append_page` to the body of a page now adds plain `mentions` links (link source `mcp-remote-mention`) for the `[[wikilinks]]`, markdown links and page paths in the appended text, to existing pages the writer can see inside its grant, as a remote `put_page` does. The post-commit pass reads only the appended text, never the rest of a large page, and never removes a link. `gbrain config set mcp.remote_auto_links off` turns it off.' },+ // Wave B follow-ups lane F4 (an abandoned lane preparation bars its worktree). `since` is stamped at the merge slot.+ { since: 'TBD', text: 'During a managed sync that publishes in lanes, a page whose preparation ran past its budget is no longer claimed and prepared again by another lane while the abandoned preparation still runs; that worktree now waits for it, as a sync without lanes always did, until it settles or `persistence.preparation_ceiling_ms` passes. A foreground write to that worktree waits the same way meanwhile. The page keeps its `preparation_deadline` reason until it is claimed again.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex 04360771c5..ad3b31883a 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -189,6 +189,8 @@ export class PersistenceConsumer implements PersistenceConsumerLike {private besideLanes = new Set<string>();/** #5984 lanes: running lane tasks per worktree. */private laneTasks = new Map<string, number>();+ /** #6278: roots an abandoned preparation still holds, by the number of holds; nothing on them is claimed until each settles or passes the ceiling. */+ private barredRoots = new Map<string, number>();private foregroundCounts = new Map<string, number>();/** #5984 Phase 4.5: the newest sequence when this process last claimed a head of each lane run (one head per foreground commit). */private laneHeadSeen = new Map<string, string>();@@ -306,7 +308,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {*/private async hasWork(): Promise<boolean> {const now = Date.now();- const excluded = [...this.activeRoots, ...[...this.rootRetryAfter].filter(([, at]) => at > now).map(([root]) => root)];+ const excluded = [...this.activeRoots, ...this.barredRoots.keys(), ...[...this.rootRetryAfter].filter(([, at]) => at > now).map(([root]) => root)];for (const [id, at] of this.topologyRetryAfter) if (at <= now) this.topologyRetryAfter.delete(id);const retryingTopologies = [...this.topologyRetryAfter.keys()];// On the direct route the probe needs no reserved pool lane: the direct pool is small and keeps its connections.@@ -622,7 +624,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {const concurrency = this.opts.concurrency ?? 2;// #5984: on a root whose lane groups run here, only a foreground write is claimed, to publish beside them.const laneRootKeys = [...this.laneTasks.keys()];- const attemptedRoots = new Set([...this.activeRoots, ...this.rootRetryAfter.keys()]);+ const attemptedRoots = new Set([...this.activeRoots, ...this.barredRoots.keys(), ...this.rootRetryAfter.keys()]);while (!this.stopping && this.active.size - this.laneTaskCount() < concurrency) {const claimed = laneClaim();try {@@ -675,7 +677,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {/** #5984 lanes: claims the next group heads of every open lane run in this process, up to its effective lane count. */private async claimLanes(): Promise<void> {for (const { worktreeId, run, capacity } of laneRoots()) {- if (this.rootRetryAfter.has(worktreeId) || this.activeRoots.has(worktreeId) && !this.besideLanes.has(worktreeId)) continue;+ if (this.rootRetryAfter.has(worktreeId) || this.barredRoots.has(worktreeId) || this.activeRoots.has(worktreeId) && !this.besideLanes.has(worktreeId)) continue;while (!this.stopping && (this.laneTasks.get(worktreeId) ?? 0) < capacity) {const claimed = laneClaim();try {@@ -704,9 +706,16 @@ export class PersistenceConsumer implements PersistenceConsumerLike {if (!progressed) this.rootRetryAfter.set(key, Date.now() + (root.retryAfterMs ?? this.opts.pollMs ?? 250));else { this.progressWake = true; this.publishedSinceMaintenance++; }this.active.delete(task);- // The slot is free now; the root (or lane slot) waits for an abandoned preparation so nothing on it overtakes that work.- if (root.until) void root.until.then(() => { done(); this.schedule(0); });- else done();+ // The slot is free now; the root waits for an abandoned preparation so nothing on it overtakes that work. A lane task frees+ // only its own lane slot, so the root is barred from claims too: another lane would claim the abandoned member again.+ if (root.until) {+ this.barredRoots.set(key, (this.barredRoots.get(key) ?? 0) + 1);+ void root.until.then(() => {+ const holds = (this.barredRoots.get(key) ?? 1) - 1;+ if (holds > 0) this.barredRoots.set(key, holds); else this.barredRoots.delete(key);+ done(); this.schedule(0);+ });+ } else done();this.schedule(progressed ? 0 : this.opts.pollMs ?? 250);});this.active.add(task);diff --git a/test/e2e/persistence-group-deadline-postgres.test.ts b/test/e2e/persistence-group-deadline-postgres.test.tsindex aaa4837f91..ec5e6a2235 100644--- a/test/e2e/persistence-group-deadline-postgres.test.ts+++ b/test/e2e/persistence-group-deadline-postgres.test.ts@@ -223,6 +223,47 @@ describe.skipIf(!hasDatabase())('grouped preparation deadlines (Postgres, #6278)} finally { release.resolve(); await consumer.stop(); await closeLaneRun(run, 1_000); }}), 90_000);+ // F4: the laneFallback case above flaked when another lane slot claimed the group again while the expired member's+ // abandoned preparation still ran, prepared it a second time and laneFallback released it `group_member_waiting`.+ test('under lanes, an abandoned member bars its root: no lane claims it again while it runs, and it commits once it settles', () => withBrain(async ({ engine, config, sources }) => {+ const run = randomUUID();+ const worktreeId = sources[0]!.binding.worktree_id;+ const predecessor = await admitWrite(engine, admission(config, sources[1]!, 'lanes/predecessor', 'predecessor body'));+ await engine.executeRaw(`UPDATE persistence_requests SET worktree_id=NULL,source_id=$2,source_incarnation=$3::uuid WHERE id=$1::uuid`, [predecessor.id, 'group-deadline-other', sources[1]!.incarnation]);+ const rows = await admitGroup(engine, config, sources[0]!, 'lanes-barred', 3, 'ordered', { lane: run, after: predecessor.request_id });+ openLanes(worktreeId, run, 2, null);+ const release = Promise.withResolvers<void>();+ const attempts = new Map<string, number>();+ const consumer = new PersistenceConsumer(engine, { engine: 'postgres' }, hangingPreparer(sources, new Set([rows[2]!.id]), release.promise, attempts),+ { hostId: config.hostId, concurrency: 1, pollMs: 50, renewalIntervalMs: 20, phaseMs: 2_000, preparationMs: 80,+ preparationBudgets: { maxAttempts: 5, ceilingMs: 60_000 }, onError: () => {} });+ const internals = consumer as unknown as { rootRetryAfter: Map<string, number>; active: Set<Promise<void>>; tick: (afterProgress?: boolean) => Promise<void> };+ let ticks = 0;+ const tick = internals.tick.bind(consumer);+ internals.tick = afterProgress => tick(afterProgress).finally(() => { ticks++; });+ const predecessorRoot = `db:${sources[1]!.incarnation}`;+ try {+ internals.rootRetryAfter.set(predecessorRoot, Date.now() + 60_000);+ consumer.start();+ await waitFor(async () => (await getWriteRequestById(engine, rows[2]!.id))?.blocked_reason === 'preparation_deadline', { timeoutMs: 15_000 });+ await waitFor(async () => (await stateOf(engine, rows.slice(0, 2))).every(s => s.state === 'queued'), { timeoutMs: 15_000, label: 'laneFallback releases the live prefix' });+ // Hold the read until three more claim cycles ran and nothing they claimed is still running.+ const from = ticks;+ await waitFor(() => ticks >= from + 3 && internals.active.size === 0, { timeoutMs: 15_000, label: 'three more claim cycles' });+ expect(attempts.get(rows[2]!.id)).toBe(1);+ expect(await stateOf(engine, rows)).toEqual([+ { state: 'queued', reason: 'group_member_waiting', attempts: 0, error: null },+ { state: 'queued', reason: 'group_member_waiting', attempts: 0, error: null },+ { state: 'queued', reason: 'preparation_deadline', attempts: 1, error: null },+ ]);+ // Once it settles and the predecessor runs, the group is claimed again and commits on a fresh preparation.+ release.resolve();+ internals.rootRetryAfter.delete(predecessorRoot);+ for (const row of rows) await waitFor(async () => (await getWriteRequestById(engine, row.id))?.state === 'committed', { timeoutMs: 20_000, label: `${row.slug} commits after the retry` });+ expect(attempts.get(rows[2]!.id)).toBe(2);+ } finally { release.resolve(); await consumer.stop(); await closeLaneRun(run, 1_000); }+ }), 90_000);+test('the expired-claim sweep charges only the members whose dispatch was marked (the kill case)', () => withBrain(async ({ engine, config, sources }) => {const rows = await admitGroup(engine, config, sources[0]!, 'kill', 6, 'ordered');const release = Promise.withResolvers<void>();