Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): mark a lane group begun inside its transaction so lanes BEGIN in manifest order
garrytane20a13146b06
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f9d2313832..f3a836734f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,7 @@ identifiers and attribution are available in the pre-removal Git revision- **`insertFacts` inserts in multi-row chunks** (`src/core/engine-sql/facts.ts`), 500 rows per statement, for every caller. Each input's id is mapped back by `(source_markdown_slug, row_num)`: a row the unique index skips stays null, and the first input wins a duplicate row number, as before. The `superseded by #N` pass now reads every target in one statement and writes every link in one more, with the same chain, cycle, int4-overflow and warning rules. Embedded rows keep their `::vector`/`::halfvec` cast, model and text hash. A lone surrogate in free text still lands as U+FFFD.- **Guarded fact renumbers** (`src/core/trust/fence-guard.ts`) move in one statement instead of one per row.- **No false "owner missing" during a long publish** (`src/core/persistence/consumer.ts`, `group-publish.ts`, `claim-lease.ts`). The publish transaction locks its request rows, so a lease renewal from another connection waited on that lock, overran its deadline, and the claim read lapsed. `gbrain sync` then stopped `drain_stalled` with `owner_missing`. Now the consumer commits one renewal before the transaction opens, stamping the claim `publishing` with a lease of the ceiling plus grace, settle and 30 s, and stops renewing until the publish ends. `sync-drain` already waits on a live `publishing` claim and reports `publication_overdue` past the ceiling. Tradeoff: an owner that crashes mid-publish holds its head until that lease ends, not 30 s.+- **Lane groups BEGIN in manifest order** (`sync-lanes.ts`, `group-publish.ts`). A lane group marked itself begun when it stopped waiting, before its BEGIN reached the server, so the next group could BEGIN first and its `published_at` came out of order. This failed `managed-sync-bulk`'s "every page commits in manifest order" on this PR's CI. The mark is now set inside the transaction. `test/sync-lanes-begin-order.test.ts` fails on master and passes here.- **Slow projection log.** A projection that takes 30 s or more prints `[persistence] phase=publication reason=slow_projection source=… slug=… elapsed_ms=… timeline_rows=… fact_rows=… take_rows=… steps=timeline:…,facts:…,…`, so the slow step is named in one line.- **`unexpected_file_bytes` explains itself.** The registry summary said "A canonical skill file mode changed outside publication" and the docs said to run doctor. It now says the file matches neither the recorded prior nor the published bytes, and that the user picks which version to keep. A command that resolves it is a follow-up.- **Tests.** `test/canonical-projection-statements.test.ts` projects a 100-row and a 2,000-row page and allows only one extra statement per extra 500-row chunk (on master: 336 and 6,036; now 15 and 21), on PGLite, and checks every row lands once on PGLite and Postgres. New `insertFacts` cases cover a duplicate row number inside a batch, a 1,203-row batch with duplicates and supersession across chunks, embeddings, and hostile text. `test/e2e/publication-claim-lease-6574-postgres.test.ts` holds a put_pages group inside its open transaction and reads each member from another connection: `running`, `publishing`, leased past the ceiling. It fails on master. The SQL-text goldens for `facts` and `_driver` changed because `insertFacts` now sends one multi-row INSERT per chunk.diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.tsindex c59e258992..888ea3b5bd 100644--- a/src/core/persistence/group-publish.ts+++ b/src/core/persistence/group-publish.ts@@ -185,6 +185,8 @@ export function preparationReads(engine: BrainEngine, imports?: ImportGroupReads/** Test seams around a group's commit and its rollback. */export interface GroupHooks {+ /** Inside the group transaction, once BEGIN has run (a lane prefix marks its original group begun here). */+ began?(): void;beforeCommit?(rows: WriteRequest[]): Promise<void>;/** After a failed group transaction and the restoration of any file it published. */rolledBack?(rows: WriteRequest[]): Promise<void>;@@ -260,8 +262,10 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], prfor (const [i, member] of files) recorded.set(i, member);for (const member of files.values()) await seam('prepared', member.row);}- if (lane) await awaitLaneBegin(lane, rows);+ const markBegun = lane ? await awaitLaneBegin(lane, rows) : null;const done = await transaction(async opened => {+ markBegun?.();+ hooks.began?.();timed.apply?.end(rows.length);if (lane) timed.apply = laneApplyBegin(lane);const tx = groupReads(opened);@@ -664,8 +668,9 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteRequeslet requeued = new Set<string>();if (live.every(({ i }) => 'ok' in prepared[i]!)) {// #6278 lanes: a prefix publishes under the original group's order key, then drops its own begun mark.- if (run.lane && liveRows.length < rows.length) await awaitLaneBegin(run.lane, rows);- const result = await bounded(() => publishGroup(engine, liveRows, live.map(({ i }) => (prepared[i] as { ok: PreparedMutation }).ok), run.hostId, run.hooks, run.lane ?? null));+ const markOriginal = run.lane && liveRows.length < rows.length ? await awaitLaneBegin(run.lane, rows) : null;+ const hooks = markOriginal ? { ...run.hooks, began: () => { markOriginal(); run.hooks?.began?.(); } } : run.hooks;+ const result = await bounded(() => publishGroup(engine, liveRows, live.map(({ i }) => (prepared[i] as { ok: PreparedMutation }).ok), run.hostId, hooks, run.lane ?? null));if (run.lane && liveRows.length < rows.length) run.lane.begun.delete(liveRows.at(-1)!.request_id);if (result.done) { for (const row of result.done) run.settled(row); return true; }requeued = new Set(result.requeued);diff --git a/src/core/persistence/sync-lanes.ts b/src/core/persistence/sync-lanes.tsindex 64d218af48..1021995ca1 100644--- a/src/core/persistence/sync-lanes.ts+++ b/src/core/persistence/sync-lanes.ts@@ -155,13 +155,17 @@ const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));* Lane transactions begin in manifest order: a group whose predecessor this* process claimed but has not begun waits for it, so the oldest unfinished* group always holds a connection first (transaction-mode poolers included).+ * Returns the group's begun mark. The caller sets it inside its transaction,+ * once BEGIN has run, so the next group's BEGIN always comes after this one's+ * (marking before BEGIN let two lanes race it, #6574 CI).*/-export async function awaitLaneBegin(state: LaneState, rows: WriteRequest[], maxMs = 10_000): Promise<void> {+export async function awaitLaneBegin(state: LaneState, rows: WriteRequest[], maxMs = 10_000): Promise<() => void> {const after = predecessorOf(rows);const started = Date.now();while (after && state.claimed.has(after) && !state.begun.has(after) && Date.now() - started < maxMs) await sleep(20);if (after && state.claimed.has(after)) state.overlapped++;- state.begun.add(groupKey(rows));+ const key = groupKey(rows);+ return () => { state.begun.add(key); };}/**diff --git a/test/sync-lanes-begin-order.test.ts b/test/sync-lanes-begin-order.test.tsnew file mode 100644index 0000000000..55f84bb2cf--- /dev/null+++ b/test/sync-lanes-begin-order.test.ts@@ -0,0 +1,35 @@+/**+ * #6574 CI: lane transactions begin in manifest order. A group's begun mark+ * used to be set when it finished waiting, before its BEGIN reached the+ * server, so the next group could BEGIN first and its `now()` (published_at)+ * came out of order (managed-sync-bulk "every page commits in manifest+ * order"). awaitLaneBegin now returns the mark for the caller to set inside+ * its transaction; until then the next group keeps waiting.+ */+import { expect, test } from 'bun:test';+import { awaitLaneBegin, type LaneState } from '../src/core/persistence/sync-lanes.ts';+import type { WriteRequest } from '../src/core/persistence/model.ts';++const lane = (): LaneState => ({ run: 'r', asked: 2, effective: 2, stepDown: null, overlapped: 0, fallbacks: 0, coordinationPath: null,+ claimed: new Set(['first', 'second']), begun: new Set(), tasks: 0, closing: false,+ timing: { open: 0, since: Date.now(), openArea: 0, activeMs: 0, applyMs: 0, appliedMembers: 0, turnWaitMs: 0, transactionMs: 0, recentPerMember: null } });+const group = (id: string, after?: string) => [{ request_id: id, intent: after ? { after } : {} }] as unknown as WriteRequest[];+const settledWithin = (p: Promise<unknown>, ms: number) => Promise.race([p.then(() => true), new Promise(resolve => setTimeout(() => resolve(false), ms))]);++test('the next lane group waits until the group before it marks itself begun, not just until it stops waiting', async () => {+ const state = lane();+ const markFirst = await awaitLaneBegin(state, group('first'));+ expect(state.begun.has('first')).toBe(false);+ const second = awaitLaneBegin(state, group('second', 'first'));+ expect(await settledWithin(second, 120)).toBe(false);+ markFirst();+ expect(await settledWithin(second, 1_000)).toBe(true);+});++test('a predecessor that finished without beginning releases the next group', async () => {+ const state = lane();+ await awaitLaneBegin(state, group('first'));+ const second = awaitLaneBegin(state, group('second', 'first'));+ state.claimed.delete('first');+ expect(await settledWithin(second, 1_000)).toBe(true);+});