Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
sync feeder: pipeline the cursor save, the admission settings and the request insert with its counter update (#5984 Phase 1)
garrytanb1645d414597
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex 50bc90700c..e00812fa29 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -266,7 +266,7 @@ export async function admitWriteGroupInTransaction(tx: BrainEngine, inputs: Writif (Number(row.terminal_bytes) + terminalBytes > limits[`${scope}TerminalBytes`]) throw await cumulativeCapacityError(tx, `${scope} reserved receipt bytes`,row.key, `${scope}TerminalBytes`, Number(row.terminal_bytes), limits[`${scope}TerminalBytes`]);}- const rows = await tx.executeRaw<WriteRequest>(`INSERT INTO persistence_requests+ const [rows] = await pipelined(tx, [() => tx.executeRaw<WriteRequest>(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,page_id,slug,worktree_id,topology_generation,digest,intent,authority,intent_bytes,terminal_reservation,target_kind,protocol_version,admitter_version,admitter_host_id)@@ -276,11 +276,11 @@ export async function admitWriteGroupInTransaction(tx: BrainEngine, inputs: WritRETURNING *`, [first.principal.kind, first.principal.id, first.operation, first.sourceId, first.sourceIncarnation, first.worktreeId ?? null,first.topologyGeneration ?? null, JSON.stringify(first.authority), stamp.version, stamp.hostId,JSON.stringify(fresh.map(item => ({ request_id: item.requestId, page_id: item.input.pageId ?? null, slug: item.input.slug, digest: item.fingerprint,- intent: item.input.intent, intent_bytes: item.bytes, terminal_reservation: item.terminalBytes })))]);- for (const row of rows) priors.set(row.request_id, row);- await tx.executeRaw(`UPDATE persistence_counters SET outstanding_count=outstanding_count+$4,+ intent: item.input.intent, intent_bytes: item.bytes, terminal_reservation: item.terminalBytes })))]),+ () => tx.executeRaw(`UPDATE persistence_counters SET outstanding_count=outstanding_count+$4,intent_bytes=intent_bytes+$2,lifetime_ids=lifetime_ids+$4,terminal_bytes=terminal_bytes+$3 WHERE key=ANY($1::text[])`,- [counters.map(c => c.key), bytes, terminalBytes, fresh.length]);+ [counters.map(c => c.key), bytes, terminalBytes, fresh.length])]) as [WriteRequest[]];+ for (const row of rows) priors.set(row.request_id, row);}return items.map(item => priors.get(item.requestId)!);}diff --git a/src/core/persistence/sync-group.ts b/src/core/persistence/sync-group.tsindex f36c1649fd..1cb3f16f22 100644--- a/src/core/persistence/sync-group.ts+++ b/src/core/persistence/sync-group.ts@@ -18,6 +18,7 @@ import { admitWriteGroupInTransaction } from './journal.ts';import { retryWriteAdmission } from './admission-retry.ts';import { wouldWaiveEntry, type WaiverCursor, type WaiverEntry } from './sync-waivers.ts';import type { WriteRequest } from './model.ts';+import { pipelined } from '../page-state/transactions.ts';import type { SyncIntent } from './sync-prepare.ts';import type { SyncAuthority } from './sync-authority.ts';@@ -132,12 +133,15 @@ export async function admitGroup(engine: BrainEngine, members: WaiverEntry[], cucursorHolds: (tx: BrainEngine) => Promise<boolean>): Promise<WriteRequest[] | null> {const head = members[0]!;return retryWriteAdmission(head.requestId, remaining => engine.transaction(async tx => {- await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout',$1,true),set_config('statement_timeout',$2,true)",- [`${Math.min(1000, remaining)}ms`, `${remaining}ms`]);- const rows = await admitWriteGroupInTransaction(tx, members.map(member => ({ requestId: member.requestId, operation: 'submit_job',- sourceId: cursor.sourceId, sourceIncarnation: cursor.incarnation, slug: member.slug, pageId: member.pageId,- worktreeId: cursor.binding.worktree_id, topologyGeneration: cursor.binding.topology_generation,- principal: cursor.authority.writer.principal, authority: cursor.authority.writer, callerIntent: member.intent, intent: member.intent })));+ // The settings go out with the admission's first burst of checks, ahead of them.+ const [, rows] = await pipelined(tx, [+ () => tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout',$1,true),set_config('statement_timeout',$2,true)",+ [`${Math.min(1000, remaining)}ms`, `${remaining}ms`]),+ () => admitWriteGroupInTransaction(tx, members.map(member => ({ requestId: member.requestId, operation: 'submit_job',+ sourceId: cursor.sourceId, sourceIncarnation: cursor.incarnation, slug: member.slug, pageId: member.pageId,+ worktreeId: cursor.binding.worktree_id, topologyGeneration: cursor.binding.topology_generation,+ principal: cursor.authority.writer.principal, authority: cursor.authority.writer, callerIntent: member.intent, intent: member.intent }))),+ ]) as [unknown, WriteRequest[]];if (!await cursorHolds(tx)) throw new GroupMoved();return rows;})).catch(error => { if (error instanceof GroupMoved) return null; throw error; });diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 6da6789743..4181c8e4b3 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -124,6 +124,11 @@ async function saveCursor(engine: BrainEngine, key: string, before: Cursor | nulinTx?: (tx: BrainEngine) => Promise<unknown>): Promise<Cursor> {const saved = await engine.transaction(async tx => {assertActive?.();+ if (!requireIdle) {+ const current = await writeCursor(tx, key, before, next, inTx, true);+ assertActive?.();+ return current;+ }await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");if (requireIdle) {await tx.executeRaw('SELECT id FROM persistence_worktrees WHERE id=$1::uuid FOR UPDATE', [next.binding.worktree_id]);@@ -142,20 +147,26 @@ async function saveCursor(engine: BrainEngine, key: string, before: Cursor | nulreturn saved;}/** Compare-and-swap inside the caller's transaction; a lost swap returns the cursor that won. */-async function writeCursor(tx: BrainEngine, key: string, before: Cursor | null, next: Cursor, inTx?: (tx: BrainEngine) => Promise<unknown>): Promise<Cursor> {+async function writeCursor(tx: BrainEngine, key: string, before: Cursor | null, next: Cursor, inTx?: (tx: BrainEngine) => Promise<unknown>, synchronous = false): Promise<Cursor> {if (before === null) {+ if (synchronous) await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb) ON CONFLICT DO NOTHING`, [`${OP}-manifest`, next.runId, JSON.stringify(next.entries)]);await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb) ON CONFLICT DO NOTHING`, [OP, key, JSON.stringify([header(next)])]);} else {- const saved = await tx.executeRaw(`UPDATE op_checkpoints SET completed_keys=$4::text::jsonb,updated_at=now()- WHERE op=$1 AND fingerprint=$2 AND completed_keys=$3::text::jsonb RETURNING fingerprint`, [OP, key, JSON.stringify([header(before)]), JSON.stringify([header(next)])]);- await tx.executeRaw('UPDATE op_checkpoints SET updated_at=now() WHERE op=$1 AND fingerprint=$2', [`${OP}-manifest`, next.runId]);+ // #5984: the settings, the compare-and-swap and the manifest touch go out together; a won swap is the saved cursor.+ const [, saved] = await pipelined(tx, [+ () => synchronous ? tx.executeRaw("SELECT set_config('synchronous_commit','on',true)") : Promise.resolve([]),+ () => tx.executeRaw(`UPDATE op_checkpoints SET completed_keys=$4::text::jsonb,updated_at=now()+ WHERE op=$1 AND fingerprint=$2 AND completed_keys=$3::text::jsonb RETURNING fingerprint`, [OP, key, JSON.stringify([header(before)]), JSON.stringify([header(next)])]),+ () => tx.executeRaw('UPDATE op_checkpoints SET updated_at=now() WHERE op=$1 AND fingerprint=$2', [`${OP}-manifest`, next.runId]),+ ]) as [unknown, unknown[]];// #5988: a hold write or clear commits with the cursor step that passes its entry, never without it.if (saved.length) await inTx?.(tx);// #6188 (E33): the run's fences_normalized total commits with the cursor step that counts it, so the trend never differs from the cursor.const fences = next.counts.fences;if (saved.length && fences?.count && fences.count !== before.counts.fences?.count) await recordSyncRunTrend(tx, { sourceId: next.sourceId, runId: next.runId,day: new Date().toISOString().slice(0, 10), count: fences.count, byClass: fences.by_class, writers: fences.dirs });+ if (saved.length) return next;}return currentCursor(tx, key, next);}