Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(sync): #6712 PR 4b parallel scans for the confirm round's proof
garrytan45f67a01e39a
diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.tsindex cfb9b66c44..5a60ae434a 100644--- a/src/core/persistence/fault-points.ts+++ b/src/core/persistence/fault-points.ts@@ -47,6 +47,9 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect// #6712 PR 4b: a taken confirm round about to patch the previous round's origin domain (sync-pass-narrow.ts); a hook that// throws makes it build the domain whole (`confirm.narrow: 'forced'`).| 'sync:level_narrow'+ // #6712 PR 4b: before a confirm round's proof sets its parallel scans (sync-pass-confirm.ts `parallelProof`); a hook that+ // throws makes the server refuse the setting, as a restricted role or a managed host does.+ | 'sync:confirm_parallel'// #6712 PR 4b (#6926): inside the round's last import's publication, before its folded stamp's checks (sync-pass-fold.ts); a hook// that throws models a failed check statement there: the stamp rolls back to its savepoint and the pass stamps by its checkpoint request.| 'sync:pass_fold'diff --git a/src/core/persistence/sync-pass-confirm.ts b/src/core/persistence/sync-pass-confirm.tsindex 643b334192..b9e9dd5c5f 100644--- a/src/core/persistence/sync-pass-confirm.ts+++ b/src/core/persistence/sync-pass-confirm.ts@@ -35,6 +35,7 @@import { GIT_HOLD_OP, GIT_HOLD_RETRY_OP, GIT_HOLD_SUMMARY_OP, SYNC_IMPORT_PROVENANCE_OP } from './sync-holds.ts';import { MANAGED_SYNC_PASS_OP, SYNC_DELETES_WITHHELD_OP, SYNC_ORIGIN_DELETED_OP } from './sync-pass-row.ts';import type { BrainEngine } from '../engine.ts';+import { faultPoint } from './fault-points.ts';type Exec = Pick<BrainEngine, 'executeRaw'>;@@ -79,6 +80,31 @@ const PROOF = `WITH x AS MATERIALIZED (SELECT txid_snapshot_xmin(txid_current_sn(SELECT COALESCE(jsonb_agg(fingerprint), '[]'::jsonb) FROM op_checkpoints WHERE op='${GIT_HOLD_OP}' AND starts_with(fingerprint, $3 || ':')) AS holdsFROM x, pg`;+type ProofRow = { xmin: string; span: number; ops: Record<string, number> | null; holds: string[]; pages: number;+ pages_changed: Array<[string, boolean, string]>; ops_changed: Array<[string, string, string | null, string | null]> };++/**+ * Parallel workers for the proof's two scans (about 420 ms against 820 ms at 600k). A server that refuses a setting (a+ * restricted role, a managed host) raises inside the block, whose handler drops the settings and keeps the transaction.+ */+const parallelSettings = (cost: string) => `DO $$ BEGIN PERFORM set_config('parallel_setup_cost', '${cost}', true), set_config('parallel_tuple_cost', '0', true),+ set_config('min_parallel_table_scan_size', '0', true); EXCEPTION WHEN OTHERS THEN NULL; END $$`;++/**+ * The proof with parallel scans, for the proof alone: the settings are made inside a savepoint the proof then rolls back+ * to, so the statements after it (the round's other reads) run with the transaction's own settings; refused, the proof+ * runs without them. Its statements are issued together, so nothing the caller pipelines lands inside the savepoint. The+ * `sync:confirm_parallel` seam (a hook that throws) sends a value the server refuses.+ */+async function parallelProof(exec: Exec, sourceId: string, params: unknown[]): Promise<ProofRow[]> {+ const refused = await faultPoint('sync:confirm_parallel', { sourceId }).then(() => false, () => true);+ const steps = [exec.executeRaw('SAVEPOINT gbrain_confirm_proof'), exec.executeRaw(parallelSettings(refused ? 'refused' : '0')), exec.executeRaw<ProofRow>(PROOF, params),+ exec.executeRaw('ROLLBACK TO SAVEPOINT gbrain_confirm_proof'), exec.executeRaw('RELEASE SAVEPOINT gbrain_confirm_proof')];+ for (const step of steps) step.catch(() => undefined);+ const [, , proof] = await Promise.all(steps);+ return proof as ProofRow[];+}+/*** What the pass may reuse: the pages it wrote since S1 (`pages`, by id), which of them changed their import record* (`records`), the source's count of pages with an origin, and S2's mark for the next round; or why the full read.@@ -89,14 +115,14 @@ export type ConfirmProof = { ok: true; mark: LevelMark; pages: string[]; records* Proves, in S2 (the round's snapshot), that every change since `base` (S1) to what the level read consumes is the pass's* own write (see the header). The counts still need the reused rows: `countsMatch` checks them after the delta read.*/-export async function proveConfirm(exec: Exec, input: { sourceId: string; incarnation: string; passId: string; base: LevelMark; recorded?: ReadonlySet<number>; postgres: boolean; self?: string }): Promise<ConfirmProof> {+export async function proveConfirm(exec: Exec, input: { sourceId: string; incarnation: string; passId: string; base: LevelMark; recorded?: ReadonlySet<number>; postgres: boolean;+ parallel?: boolean; self?: string }): Promise<ConfirmProof> {const scope = `${input.sourceId}:${input.incarnation}`;+ const params = [input.sourceId, CONFIRM_OPS, scope, input.base.xmin, input.passId, input.self ?? null];// Two plain scans: compiling them (JIT, which the planner's cost picks at 600k) cost more than running them (about 200 ms).const jit = input.postgres ? exec.executeRaw('SET LOCAL jit = off') : Promise.resolve([]);jit.catch(() => undefined);- const [row] = await exec.executeRaw<{ xmin: string; span: number; ops: Record<string, number> | null; holds: string[]; pages: number;- pages_changed: Array<[string, boolean, string]>; ops_changed: Array<[string, string, string | null, string | null]> }>(- PROOF, [input.sourceId, CONFIRM_OPS, scope, input.base.xmin, input.passId, input.self ?? null]);+ const [row] = input.postgres && input.parallel ? await parallelProof(exec, input.sourceId, params) : await exec.executeRaw<ProofRow>(PROOF, params);await jit;const mark: LevelMark = { xmin: row!.xmin, ops: row!.ops ?? {}, holds: row!.holds };if (!(Number(row!.span) >= 0 && Number(row!.span) < 2 ** 31)) return { ok: false, reason: 'xid_span', mark };diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.tsindex 804ee6be7c..4977fc0766 100644--- a/src/core/persistence/sync-pass.ts+++ b/src/core/persistence/sync-pass.ts@@ -899,7 +899,7 @@ async function readRoundSnapshot(engine: BrainEngine, input: { kind: 'postgres'if (reuse) reuse.cache.pages = undefined;const round = (marking: boolean) => withRoundSnapshot(engine, async exec => {const base = marking ? prior?.mark : undefined;- const proof = base ? confirmGuard(timed('confirm', () => proveConfirm(exec, { sourceId, incarnation, passId: reuse!.passId, base, recorded: reuse!.recorded, postgres: kind === 'postgres' }))) : null;+ const proof = base ? confirmGuard(timed('confirm', () => proveConfirm(exec, { sourceId, incarnation, passId: reuse!.passId, base, recorded: reuse!.recorded, postgres: kind === 'postgres', parallel: true }))) : null;const marked = marking && !base ? confirmGuard(readLevelMark(exec, sourceId, incarnation)) : null;// PGLite has no snapshot: the mark (or the proof, the next round's mark) runs before the reads it vouches for.if (kind === 'pglite') await (proof ?? marked)?.catch(() => undefined);@@ -915,7 +915,7 @@ async function readRoundSnapshot(engine: BrainEngine, input: { kind: 'postgres'const [work, markers, passRow] = await others;if (reuse && mark) reuse.cache.pages = { key, mark, table: read!.pages };const confirm = confirmed?.confirm ?? unkeyed;- return { pages: read!.pages, open: work, markers, passRow, statements: read!.statements + work.statements + 2 + (marked ? 1 : proof ? (kind === 'postgres' ? 2 : 1) : 0), ...(confirm ? { confirm } : {}),+ return { pages: read!.pages, open: work, markers, passRow, statements: read!.statements + work.statements + 2 + (marked ? 1 : proof ? (kind === 'postgres' ? 6 : 1) : 0), ...(confirm ? { confirm } : {}),...(confirmed?.read ? { changed: confirmed.changed } : {}) };});if (!reuse || reuse.working) return round(false);diff --git a/test/e2e/sync-pass-confirm-parallel-6712-postgres.test.ts b/test/e2e/sync-pass-confirm-parallel-6712-postgres.test.tsnew file mode 100644index 0000000000..0fb0e9cb1d--- /dev/null+++ b/test/e2e/sync-pass-confirm-parallel-6712-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../sync-pass-confirm-parallel-6712.test.ts'));diff --git a/test/sync-pass-confirm-parallel-6712.test.ts b/test/sync-pass-confirm-parallel-6712.test.tsnew file mode 100644index 0000000000..5b974da657--- /dev/null+++ b/test/sync-pass-confirm-parallel-6712.test.ts@@ -0,0 +1,126 @@+/**+ * #6712 PR 4b: a confirm round's proof (sync-pass-confirm.ts `proveConfirm`) scans `pages` and `op_checkpoints` with+ * parallel workers, its settings scoped to the proof by a savepoint it rolls back to (`parallelProof`).+ *+ * Protects (Postgres, direct and through transaction-mode PgBouncer): the settings hold inside the proof and nowhere else:+ * after it, SHOW in the same transaction and session gives what it gave before; the proof's verdict equals the plain+ * proof's, for an unchanged source and for a foreign page write. A server that refuses the setting (the+ * `sync:confirm_parallel` seam) aborts only the savepoint: the proof runs without the settings, gives the same verdict, and+ * the transaction stays usable; a pass's round 2 still confirms. PGLite never sets them (no savepoint, no seam).+ *+ * PGLite and Postgres here; Postgres also through test/e2e/sync-pass-confirm-parallel-6712-postgres.test.ts.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { mkdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { proveConfirm, readLevelMark, type LevelMark } from '../src/core/persistence/sync-pass-confirm.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { testBackends } from './helpers/test-backends.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';++const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const commit = (root: string, message: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };+const note = (title: string, body: string) => `---\ntype: concept\ntitle: ${title}\n---\n\n${body}\n`;+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };+const setup = ({ root }: { root: string }) => {+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');+ for (const slug of ['a', 'b', 'c']) writeFileSync(join(root, `notes/${slug}.md`), note(`notes/${slug}`, `The committed body of notes/${slug}.`));+ commit(root, 'notes');+};+const SETTINGS = ['parallel_setup_cost', 'parallel_tuple_cost', 'min_parallel_table_scan_size'];+type Exec = Pick<BrainEngine, 'executeRaw'>;+const show = async (exec: Exec) => Object.fromEntries(await Promise.all(SETTINGS.map(async name => [name, (await exec.executeRaw<Record<string, string>>(`SHOW ${name}`))[0]![name]])));+const incarnationOf = async (engine: BrainEngine) => (await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text FROM sources WHERE id='default'"))[0]!.incarnation;++/** Every statement the proof sends, and the settings in effect right after its proof statement (queued behind it). */+function recording(exec: Exec) {+ const sent: string[] = [];+ let during: Promise<Record<string, string>> | null = null;+ const wrapped: Exec = { executeRaw: ((sql: string, params?: unknown[]) => {+ sent.push(sql.trim().split(/\s+/).slice(0, 3).join(' '));+ const result = exec.executeRaw(sql, params);+ if (sql.includes('pages_changed') && !during) { during = show(exec); during.catch(() => undefined); }+ return result;+ }) as Exec['executeRaw'] };+ return { exec: wrapped, sent, during: () => during };+}++/** The proof in a round-like snapshot (repeatable read, read only), parallel and plain, with the settings around it. */+async function proveBoth(engine: BrainEngine, base: LevelMark, incarnation: string) {+ return engine.transaction(async tx => {+ await tx.executeRaw('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');+ const before = await show(tx);+ const input = { sourceId: 'default', incarnation, passId: crypto.randomUUID(), base, postgres: engine.kind === 'postgres' };+ const probe = recording(tx);+ const parallel = await proveConfirm(probe.exec, { ...input, parallel: true });+ const during = await probe.during();+ const after = await show(tx);+ const plain = await proveConfirm(tx, input);+ return { before, during, after, parallel, plain, sent: probe.sent };+ });+}++afterEach(() => installFaultHook(undefined));++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? process.env.DATABASE_URL : undefined;+ const brain = (run: Parameters<typeof managedBrain>[0]) => managedBrain(run, { ...(databaseUrl ? { databaseUrl } : {}), setup });++ describe(`#6712 PR 4b parallel confirm proof (${backend})`, () => {+ if (backend === 'postgres') {+ test('the settings hold for the proof alone, and its verdict equals the plain proof (unchanged, then a foreign page write)', () => brain(async ({ engine }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ const incarnation = await incarnationOf(engine), base = await readLevelMark(engine, 'default', incarnation), session = await show(engine);+ const clean = await proveBoth(engine, base, incarnation);+ expect(clean.during).toEqual({ parallel_setup_cost: '0', parallel_tuple_cost: '0', min_parallel_table_scan_size: '0' });+ expect(clean.after).toEqual(clean.before);+ expect(clean.parallel).toEqual(clean.plain);+ expect(clean.parallel.ok).toBe(true);+ expect(clean.sent).toEqual(['SET LOCAL jit', 'SAVEPOINT gbrain_confirm_proof', 'DO $$ BEGIN', 'WITH x AS', 'ROLLBACK TO SAVEPOINT', 'RELEASE SAVEPOINT gbrain_confirm_proof']);+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw("UPDATE pages SET title='A foreign title.' WHERE source_id='default' AND slug='notes/b'"), TEST_WRITE_ATTRIBUTION));+ const foreign = await proveBoth(engine, base, incarnation);+ expect(foreign.parallel).toEqual(foreign.plain);+ expect(foreign.parallel).toMatchObject({ ok: false, reason: 'foreign_page_write' });+ expect(foreign.after).toEqual(foreign.before);+ expect(await show(engine)).toEqual(session);+ }), 120_000);++ test('a server that refuses the setting: the proof runs without it, gives the same verdict, and the transaction goes on', () => brain(async ({ engine }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ const incarnation = await incarnationOf(engine), base = await readLevelMark(engine, 'default', incarnation);+ let refusals = 0;+ installFaultHook(point => { if (point === 'sync:confirm_parallel') { refusals++; throw new Error('the server refuses the setting'); } });+ const refused = await proveBoth(engine, base, incarnation);+ expect(refusals).toBe(1);+ expect(refused.parallel).toEqual(refused.plain);+ expect(refused.parallel.ok).toBe(true);+ expect(refused.during).toEqual(refused.before);+ expect(refused.after).toEqual(refused.before);+ }), 120_000);+ }++ test('a pass round 2 confirms with the parallel proof, and with a server that refuses it; PGLite never sets it', () => brain(async ({ engine, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ const run = async (refuse: boolean) => {+ const seen = { seam: 0, confirm: null as unknown };+ installFaultHook(async (point, detail) => {+ if (point === 'sync:confirm_parallel') { seen.seam++; if (refuse) throw new Error('the server refuses the setting'); }+ if (point === 'sync:level_read' && detail.round === 2) seen.confirm = detail.level?.confirm ?? null;+ });+ try { return { status: (await performManagedSync(engine, OPTS)).status, ...seen }; } finally { installFaultHook(undefined); }+ };+ writeFileSync(join(root, 'notes/a.md'), note('notes/a', 'A committed change of notes/a.')); commit(root, 'change a');+ const plain = await run(false);+ writeFileSync(join(root, 'notes/b.md'), note('notes/b', 'A committed change of notes/b.')); commit(root, 'change b');+ const refused = await run(true);+ const seam = backend === 'postgres' ? 1 : 0;+ expect(plain).toEqual({ status: 'synced', seam, confirm: { taken: true, reason: null, rows: 1, narrow: 'taken' } });+ expect(refused).toEqual({ status: 'synced', seam, confirm: { taken: true, reason: null, rows: 1, narrow: 'taken' } });+ }), 120_000);+ });+}