Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

WIP: #5984 lane A round-trip diet

garrytan739840447dff
diff --git a/scripts/bench/managed-sync-pipeline-spike.ts b/scripts/bench/managed-sync-pipeline-spike.ts
new file mode 100644
index 0000000000..ced54da61b
--- /dev/null
+++ b/scripts/bench/managed-sync-pipeline-spike.ts
@@ -0,0 +1,157 @@
+#!/usr/bin/env bun
+/**
+ * #5984 Phase 0 pipelining spike. Opt-in, never run in CI. Result:
+ * docs/eval/managed-sync-catchup.md ("Pipelining spike").
+ *
+ * bun scripts/bench/managed-sync-pipeline-spike.ts [--rtt 57] [--out <file.json>] [--keep]
+ *
+ * Inside one gbrain `engine.transaction` on Postgres, issues `tx.executeRaw`
+ * calls without awaiting between them and checks, from the wire trace
+ * (src/core/sql-trace.ts), whether postgres.js sends them on one connection
+ * before the first reply (pipelined) and whether they keep their order. Covers
+ * a pipelined failure (the first error code, and what later statements get),
+ * `prepare: true` vs `prepare: false`, and transaction-mode PgBouncer. Uses
+ * the catch-up bench's Docker Postgres and toxiproxy (loopback only) plus an
+ * `edoburu/pgbouncer` container in front of that Postgres.
+ */
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { spawnSync } from 'node:child_process';
+import { startHarness, round1, type TraceRecord } from './managed-sync-catchup-lib.ts';
+
+function flag(name: string, fallback: string): string {
+ const i = process.argv.indexOf(`--${name}`);
+ return i >= 0 && process.argv[i + 1] ? process.argv[i + 1]! : fallback;
+}
+const RTT = Number(flag('rtt', '57'));
+const KEEP = process.argv.includes('--keep');
+const work = mkdtempSync(join(tmpdir(), 'gbrain-spike-'));
+const TRACE = join(work, 'trace.jsonl');
+process.env.GBRAIN_SQL_TRACE = TRACE;
+process.env.GBRAIN_SQL_TRACE_LABEL = 'spike';
+process.env.GBRAIN_HOME = work;
+
+const PG_PORT = 55432, PROXY_PORT = 55433, API_PORT = 58474, BOUNCER_PORT = 56432, BOUNCER_PROXY_PORT = 56433;
+const harness = await startHarness({ pgPort: PG_PORT, proxyPort: PROXY_PORT, apiPort: API_PORT, keep: KEEP });
+await harness.setRtt(RTT);
+
+function docker(args: string[], allowFail = false): string {
+ const r = spawnSync('docker', args, { encoding: 'utf8' });
+ if (r.status !== 0 && !allowFail) throw new Error(`docker ${args.join(' ')} failed: ${r.stderr || r.stdout}`);
+ return (r.stdout ?? '').trim();
+}
+docker(['rm', '-f', 'gbrain-spike-pgbouncer'], true);
+docker(['run', '-d', '--name', 'gbrain-spike-pgbouncer', '--network', 'host', '-e', `DATABASE_URL=postgres://postgres:[email protected]:${PG_PORT}/postgres`,
+ '-e', `LISTEN_PORT=${BOUNCER_PORT}`, '-e', 'LISTEN_ADDR=127.0.0.1', '-e', 'POOL_MODE=transaction', '-e', 'AUTH_TYPE=scram-sha-256', '-e', 'MAX_PREPARED_STATEMENTS=0', '-e', 'IGNORE_STARTUP_PARAMETERS=extra_float_digits,statement_timeout,idle_in_transaction_session_timeout,lock_timeout,options',
+ 'edoburu/pgbouncer:latest']);
+const api = `http://127.0.0.1:${API_PORT}`;
+await fetch(`${api}/proxies/bouncer-spike`, { method: 'DELETE' });
+await fetch(`${api}/proxies`, { method: 'POST', body: JSON.stringify({ name: 'bouncer-spike', listen: `127.0.0.1:${BOUNCER_PROXY_PORT}`, upstream: `127.0.0.1:${BOUNCER_PORT}`, enabled: true }) });
+for (const stream of ['upstream', 'downstream']) {
+ if (RTT > 0) await fetch(`${api}/proxies/bouncer-spike/toxics`, { method: 'POST', body: JSON.stringify({ name: `lat_${stream}`, type: 'latency', stream, toxicity: 1, attributes: { latency: Math.round(RTT / 2), jitter: 0 } }) });
+}
+
+const { PostgresEngine } = await import('../../src/core/postgres-engine.ts');
+type Engine = InstanceType<typeof PostgresEngine>;
+
+interface CaseResult { name: string; wall_ms: number; records: number; waves: number; describes: number; pipelined: boolean; order_kept?: boolean; errors?: Record<string, string | null>; detail?: unknown }
+
+function traceSince(t0: number): TraceRecord[] {
+ return readFileSync(TRACE, 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l) as TraceRecord).filter(r => r.t >= t0 && r.kind !== 'connect');
+}
+/** Sequential round trips: maximal runs of overlapping records on one connection. */
+function waves(records: TraceRecord[]): number {
+ let n = 0, end = -Infinity, conn = -1;
+ for (const r of [...records].sort((a, b) => a.conn - b.conn || a.t - b.t)) {
+ if (r.conn !== conn || r.t >= end) { n++; end = r.t + r.ms; conn = r.conn; } else end = Math.max(end, r.t + r.ms);
+ }
+ return n;
+}
+
+async function flushTrace(): Promise<void> { await Bun.sleep(1100); }
+
+async function runCase(engine: Engine, name: string, body: (tx: Engine) => Promise<Omit<CaseResult, 'name' | 'wall_ms' | 'records' | 'waves' | 'describes' | 'pipelined'>>): Promise<CaseResult> {
+ await flushTrace();
+ const t0 = performance.timeOrigin + performance.now();
+ const started = performance.now();
+ let extra: Awaited<ReturnType<typeof body>> = {};
+ try { await engine.transaction(async tx => { extra = await body(tx as Engine); }); } catch (error) { extra = { ...extra, detail: { transaction_error: String((error as { code?: string }).code ?? error) } }; }
+ const wall = performance.now() - started;
+ await flushTrace();
+ const records = traceSince(t0).filter(r => !/^(begin|commit|rollback)/i.test(r.sql.trim()));
+ const w = waves(records);
+ return { name, wall_ms: round1(wall), records: records.length, waves: w, describes: records.filter(r => r.kind === 'describe').length, pipelined: w < records.length, ...extra };
+}
+
+async function suite(url: string, label: string): Promise<CaseResult[]> {
+ const engine = new PostgresEngine();
+ await engine.connect({ database_url: url, poolSize: 2 });
+ const out: CaseResult[] = [];
+ try {
+ await engine.executeRaw('CREATE TABLE IF NOT EXISTS spike_pipeline(id serial PRIMARY KEY, label text UNIQUE, v int NOT NULL DEFAULT 0)');
+ await engine.executeRaw('TRUNCATE spike_pipeline RESTART IDENTITY');
+ await engine.executeRaw("INSERT INTO spike_pipeline(label) VALUES ('counter')");
+ for (const warm of [false, true]) {
+ out.push(await runCase(engine, `${label}: 2 statements awaited one by one (${warm ? 'warm' : 'cold'})`, async tx => {
+ await tx.executeRaw("UPDATE spike_pipeline SET v=v+$1 WHERE label='counter'", [1]);
+ await tx.executeRaw("SELECT v FROM spike_pipeline WHERE label=$1", ['counter']);
+ return {};
+ }));
+ out.push(await runCase(engine, `${label}: 2 dependent statements issued without await (${warm ? 'warm' : 'cold'})`, async tx => {
+ const a = tx.executeRaw<{ v: number }>("UPDATE spike_pipeline SET v=v+$1 WHERE label='counter' RETURNING v", [1]);
+ const b = tx.executeRaw<{ v: number }>("SELECT v FROM spike_pipeline WHERE label=$1", ['counter']);
+ const [[ra], [rb]] = await Promise.all([a, b]);
+ return { order_kept: Number(rb!.v) === Number(ra!.v), detail: { update_returned: ra!.v, select_saw: rb!.v } };
+ }));
+ }
+ out.push(await runCase(engine, `${label}: 5 inserts issued without await keep issue order`, async tx => {
+ const labels = Array.from({ length: 5 }, (_, i) => `row-${Date.now()}-${i}`);
+ await Promise.all(labels.map(l => tx.executeRaw('INSERT INTO spike_pipeline(label) VALUES ($1)', [l])));
+ const rows = await tx.executeRaw<{ label: string }>('SELECT label FROM spike_pipeline WHERE label=ANY($1::text[]) ORDER BY id', [labels]);
+ return { order_kept: rows.map(r => r.label).join() === labels.join() };
+ }));
+ out.push(await runCase(engine, `${label}: pipelined failure (unique violation first, then 2 statements)`, async tx => {
+ const settled = await Promise.allSettled([
+ tx.executeRaw("INSERT INTO spike_pipeline(label) VALUES ($1)", ['counter']),
+ tx.executeRaw("UPDATE spike_pipeline SET v=v+$1 WHERE label='counter'", [1]),
+ tx.executeRaw('SELECT v FROM spike_pipeline WHERE label=$1', ['counter']),
+ ]);
+ const code = (s: PromiseSettledResult<unknown>) => s.status === 'rejected' ? String((s.reason as { code?: string }).code ?? s.reason) : null;
+ return { errors: { first: code(settled[0]!), second: code(settled[1]!), third: code(settled[2]!) } };
+ }));
+ out.push(await runCase(engine, `${label}: unparameterized statements issued without await`, async tx => {
+ await Promise.all([tx.executeRaw("SELECT 1 AS a"), tx.executeRaw("SELECT 2 AS b"), tx.executeRaw("SELECT 3 AS c")]);
+ return {};
+ }));
+ out.push(await runCase(engine, `${label}: new statement text each call (varying SQL) issued without await`, async tx => {
+ await Promise.all([1, 2, 3].map(n => tx.executeRaw(`SELECT $1::int + ${n} AS v`, [n])));
+ return {};
+ }));
+ } finally {
+ await engine.executeRaw('DROP TABLE IF EXISTS spike_pipeline').catch(() => undefined);
+ await engine.disconnect();
+ }
+ return out;
+}
+
+const report: Record<string, unknown> = { schema: 'gbrain.bench.pipeline-spike/v1', rtt_ms: RTT, started_at: new Date().toISOString(), suites: {} };
+try {
+ const direct = harness.proxyUrl('postgres');
+ const bouncer = `postgresql://postgres:[email protected]:${BOUNCER_PROXY_PORT}/postgres`;
+ (report.suites as Record<string, unknown>)['postgres prepare=true'] = await suite(direct, 'postgres prepare=true');
+ (report.suites as Record<string, unknown>)['postgres prepare=false'] = await suite(`${direct}?prepare=false`, 'postgres prepare=false');
+ (report.suites as Record<string, unknown>)['pgbouncer transaction mode prepare=false'] = await suite(`${bouncer}?prepare=false`, 'pgbouncer txn prepare=false');
+} finally {
+ report.finished_at = new Date().toISOString();
+ const out = flag('out', join(work, 'spike.json'));
+ writeFileSync(out, JSON.stringify(report, null, 2) + '\n');
+ for (const [suiteName, cases] of Object.entries(report.suites as Record<string, CaseResult[]>)) {
+ console.log(`\n## ${suiteName}\n| case | wall ms | statements | round trips | describes | pipelined | order kept | errors |\n|---|---|---|---|---|---|---|---|`);
+ for (const c of cases) console.log(`| ${c.name.replace(/^[^:]*: /, '')} | ${c.wall_ms} | ${c.records} | ${c.waves} | ${c.describes} | ${c.pipelined} | ${c.order_kept ?? ''} | ${c.errors ? JSON.stringify(c.errors) : ''} |`);
+ }
+ console.log(`\nreport: ${out}`);
+ if (!KEEP) { docker(['rm', '-f', 'gbrain-spike-pgbouncer'], true); rmSync(work, { recursive: true, force: true }); }
+ harness.stop();
+}
+process.exit(0);
diff --git a/src/core/engine-sql/chunks.ts b/src/core/engine-sql/chunks.ts
index f33eef5be7..f2ac3a5ced 100644
--- a/src/core/engine-sql/chunks.ts
+++ b/src/core/engine-sql/chunks.ts
@@ -46,6 +46,8 @@ import { joinFragments, renderFragment, sqlFragment, trustedSql, type SqlFragmen
export interface ChunkPageGuards {
lockPageKeys(keys: readonly PageKey[]): Promise<void>;
readPageSnapshot(slug: string, opts?: PageSnapshotOptions): Promise<PageSnapshot | null>;
+ /** #5984: shares a config read across one page transaction (the engine's `transactionMemo`). */
+ memo?<T>(key: string, read: () => Promise<T>): Promise<T>;
}
/**
@@ -62,8 +64,9 @@ export async function upsertChunksOnce(
guards: ChunkPageGuards,
slug: string,
chunks: ChunkInput[],
- opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string },
+ opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string; sealChunkerVersion?: number },
): Promise<void> {
+ const memo = guards.memo ?? (<T>(_key: string, read: () => Promise<T>) => read());
// Normalize the same way putPage does — pages.slug is stored lowercased,
// so a raw mixed-case slug here would miss the row it just wrote (#430).
slug = validateSlug(slug);
@@ -83,17 +86,26 @@ export async function upsertChunksOnce(
if (pages.length === 0) throw new Error(`Page not found: ${slug} (source=${sourceId})`);
const pageId = pages[0].id;
- // A fragment write cannot certify the full-body fence boundary. Import seals
- // only after its complete replacement succeeds in the same transaction.
- const invalidation = chunkWriteInvalidation(pageId, chunks);
- await exec.unsafe(invalidation.sql, invalidation.params);
-
- // Remove chunks that no longer exist (chunk_index beyond new count)
- const newIndices = chunks.map(c => c.chunk_index);
- if (newIndices.length > 0) {
- await exec.run(sqlFragment`DELETE FROM content_chunks WHERE page_id = ${pageId} AND chunk_index != ALL(${newIndices})`);
- } else {
- await exec.run(sqlFragment`DELETE FROM content_chunks WHERE page_id = ${pageId}`);
+ // #5984: `sealChunkerVersion` is a complete replacement: the caller deleted
+ // every chunk of the page earlier in this transaction, so nothing stale can
+ // remain, and the page is sealed at that chunker version after the insert.
+ const seal = opts?.sealChunkerVersion;
+ if (seal === undefined) {
+ // A fragment write cannot certify the full-body fence boundary. Import seals
+ // only after its complete replacement succeeds in the same transaction.
+ const invalidation = chunkWriteInvalidation(pageId, chunks);
+ await exec.unsafe(invalidation.sql, invalidation.params);
+
+ // Remove chunks that no longer exist (chunk_index beyond new count)
+ const newIndices = chunks.map(c => c.chunk_index);
+ if (newIndices.length > 0) {
+ await exec.run(sqlFragment`DELETE FROM content_chunks WHERE page_id = ${pageId} AND chunk_index != ALL(${newIndices})`);
+ } else {
+ await exec.run(sqlFragment`DELETE FROM content_chunks WHERE page_id = ${pageId}`);
+ return;
+ }
+ } else if (chunks.length === 0) {
+ await exec.run(sqlFragment`UPDATE pages SET chunker_version = ${seal} WHERE id = ${pageId}`);
return;
}
@@ -127,7 +139,8 @@ export async function upsertChunksOnce(
let searchEmbeddingColumn: string | null = null;
let embeddingColumnsJson: string | null = null;
try {
- const cfgRows = (await exec.run<{ key: string; value: string }>(sqlFragment`SELECT key, value FROM config WHERE key IN ('search_embedding_column', 'embedding_columns')`)).rows;
+ const cfgRows = await memo('config:embedding-columns', async () =>
+ (await exec.run<{ key: string; value: string }>(sqlFragment`SELECT key, value FROM config WHERE key IN ('search_embedding_column', 'embedding_columns')`)).rows);
for (const r of cfgRows) {
if (r.key === 'search_embedding_column') searchEmbeddingColumn = r.value;
else if (r.key === 'embedding_columns') embeddingColumnsJson = r.value;
@@ -145,8 +158,6 @@ export async function upsertChunksOnce(
// later text rewrite that keeps the vector is detectable as content
// drift (invalidateContentDriftEmbeddings). NULL when no embedding lands.
const cols = `(page_id, chunk_index, chunk_text, chunk_source, ${writeColId}, model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image)`;
- const rows: SqlFragment[] = [];
-
let resolvedModel: string | null = null;
try {
// Keep the gateway lazy so module-load failure remains inside this soft
@@ -156,7 +167,8 @@ export async function upsertChunksOnce(
} catch {}
if (!resolvedModel) {
try {
- const cfg = (await exec.run<{ value?: string }>(sqlFragment`SELECT value FROM config WHERE key = 'embedding_model'`)).rows;
+ const cfg = await memo('config:embedding-model', async () =>
+ (await exec.run<{ value?: string }>(sqlFragment`SELECT value FROM config WHERE key = 'embedding_model'`)).rows);
resolvedModel = cfg[0]?.value ?? null;
} catch {}
}
@@ -166,33 +178,33 @@ export async function upsertChunksOnce(
}
if (!resolvedModel) resolvedModel = 'unconfigured';
- for (const chunk of chunks) {
- const embeddingStr = chunk.embedding
- ? '[' + Array.from(chunk.embedding).join(',') + ']'
- : null;
- const embeddingImageStr = chunk.embedding_image
- ? '[' + Array.from(chunk.embedding_image).join(',') + ']'
- : null;
- const parentPath = chunk.parent_symbol_path && chunk.parent_symbol_path.length > 0
- ? chunk.parent_symbol_path
- : null;
- const modality = chunk.modality ?? 'text';
- // Already normalized before the seal snapshot. Both storage and the
- // embedded_text_hash input must use those same canonical bytes.
- const sanitizedChunkText = chunk.chunk_text;
-
- const embeddingPh = embeddingStr ? sqlFragment`${embeddingStr}${trustedSql(writeCast)}` : sqlFragment`NULL`;
- const embeddedAtPh = trustedSql(embeddingStr ? 'now()' : 'NULL');
- const embeddingImagePh = embeddingImageStr ? sqlFragment`${embeddingImageStr}::vector` : sqlFragment`NULL`;
- // #4246: hash in SQL (not JS) so stamp + drift comparison share ONE
- // md5 implementation. Binds chunk_text a second time.
- const embeddedTextHashPh = embeddingStr ? sqlFragment`md5(${sanitizedChunkText})` : sqlFragment`NULL`;
- // #5553: embedding-input provenance travels only with the vector it describes.
- const embeddingInputHash = embeddingStr ? chunk.embedding_input_hash ?? null : null;
- const embeddingInputHashPh = embeddingInputHash ? sqlFragment`${embeddingInputHash}` : sqlFragment`NULL`;
-
- rows.push(sqlFragment`(${pageId}, ${chunk.chunk_index}, ${sanitizedChunkText}, ${chunk.chunk_source}, ${embeddingPh}, ${chunk.model || resolvedModel}, ${chunk.token_count || null}, ${embeddedAtPh}, ${embeddedTextHashPh}, ${embeddingInputHashPh}, ${chunk.language || null}, ${chunk.symbol_name || null}, ${chunk.symbol_type || null}, ${chunk.start_line ?? null}, ${chunk.end_line ?? null}, ${parentPath}::text[], ${chunk.doc_comment || null}, ${chunk.symbol_name_qualified || null}, ${modality}, ${embeddingImagePh})`);
- }
+ // #5984: one statement text per brain whatever the chunk count (the rows bind as one
+ // JSON document), so a prepared connection pays no describe round trip per page.
+ const incoming = chunks.map(chunk => {
+ const embedding = chunk.embedding ? '[' + Array.from(chunk.embedding).join(',') + ']' : null;
+ return {
+ chunk_index: chunk.chunk_index,
+ // Already normalized before the seal snapshot. Both storage and the
+ // embedded_text_hash input must use those same canonical bytes.
+ chunk_text: chunk.chunk_text,
+ chunk_source: chunk.chunk_source ?? null,
+ embedding,
+ model: chunk.model || resolvedModel,
+ token_count: chunk.token_count || null,
+ // #5553: embedding-input provenance travels only with the vector it describes.
+ embedding_input_hash: embedding ? chunk.embedding_input_hash ?? null : null,
+ language: chunk.language || null,
+ symbol_name: chunk.symbol_name || null,
+ symbol_type: chunk.symbol_type || null,
+ start_line: chunk.start_line ?? null,
+ end_line: chunk.end_line ?? null,
+ parent_symbol_path: chunk.parent_symbol_path && chunk.parent_symbol_path.length > 0 ? chunk.parent_symbol_path : null,
+ doc_comment: chunk.doc_comment || null,
+ symbol_name_qualified: chunk.symbol_name_qualified || null,
+ modality: chunk.modality ?? 'text',
+ embedding_image: chunk.embedding_image ? '[' + Array.from(chunk.embedding_image).join(',') + ']' : null,
+ };
+ });
// Single statement upsert: preserves existing embeddings via COALESCE when new value is NULL.
// CONSISTENCY: when chunk_text changes and no new embedding is supplied, BOTH embedding AND
@@ -225,9 +237,18 @@ export async function upsertChunksOnce(
// relabeled preserved (older-model) vectors with the current gateway model on every
// partial re-embed, corrupting provenance without changing the vector.
//
- // Master's raw path (it was `unsafe` on both engines). No bind batching:
- // master PGLite never split this statement.
- const { text, params } = renderFragment(sqlFragment`INSERT INTO content_chunks ${trustedSql(cols)} VALUES ${joinFragments(rows, ', ')}
+ // #4246: embedded_text_hash is md5(chunk_text) in SQL (not JS) so stamp + drift
+ // comparison share ONE md5 implementation; it, embedded_at and the input hash
+ // are set only when the row carries a vector.
+ const { text, params } = renderFragment(sqlFragment`INSERT INTO content_chunks ${trustedSql(cols)}
+ SELECT ${pageId}::int, c.chunk_index, c.chunk_text, c.chunk_source, c.embedding${trustedSql(writeCast)}, c.model, c.token_count,
+ CASE WHEN c.embedding IS NULL THEN NULL ELSE now() END,
+ CASE WHEN c.embedding IS NULL THEN NULL ELSE md5(c.chunk_text) END,
+ c.embedding_input_hash, c.language, c.symbol_name, c.symbol_type, c.start_line, c.end_line,
+ c.parent_symbol_path, c.doc_comment, c.symbol_name_qualified, c.modality, c.embedding_image::vector
+ FROM jsonb_to_recordset(${JSON.stringify(incoming)}::text::jsonb) AS c(chunk_index int, chunk_text text, chunk_source text,
+ embedding text, model text, token_count int, embedding_input_hash text, language text, symbol_name text, symbol_type text,
+ start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text, modality text, embedding_image text)
ON CONFLICT (page_id, chunk_index) DO UPDATE SET
chunk_text = EXCLUDED.chunk_text,
chunk_source = EXCLUDED.chunk_source,
@@ -282,7 +303,8 @@ export async function upsertChunksOnce(
symbol_name_qualified = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name_qualified ELSE COALESCE(EXCLUDED.symbol_name_qualified, content_chunks.symbol_name_qualified) END,
modality = EXCLUDED.modality,
embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image)`);
- await exec.unsafe(text, params);
+ await exec.query(text, params);
+ if (seal !== undefined) await exec.run(sqlFragment`UPDATE pages SET chunker_version = ${seal} WHERE id = ${pageId}`);
}
export async function getChunks(
diff --git a/src/core/engine.ts b/src/core/engine.ts
index f946f3a2dd..b162753872 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -1151,8 +1151,11 @@ export interface BrainEngine {
* resolveWriteColumnFromConfigRows — the same registry the read side
* searches — falling back to the legacy `embedding`::vector column on
* pre-registry brains. `embedding_image` routing is unaffected.
+ * `sealChunkerVersion` (#5984): the caller deleted every chunk of the page
+ * earlier in this transaction; the stale-row work is skipped and the page is
+ * sealed at that chunker version after the insert.
*/
- upsertChunks(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string } & BatchOpts): Promise<void>;
+ upsertChunks(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string; sealChunkerVersion?: number } & BatchOpts): Promise<void>;
/**
* Read every chunk for a page. Scope precedence mirrors getPage (#2555):
* a federated grant (`sourceIds[]`) wins over scalar `sourceId`; with
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index b15c1ac1be..74a9ee1d8b 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -224,6 +224,14 @@ export async function importFromContent(
opts: {
/** Coordinator seam: prepare without publishing, then commit under its guarded transaction. */
prepare?: (prepared: import('./persistence/prepared-import.ts').PreparedContentImport) => Promise<ImportResult>;
+ /**
+ * #5984, with `prepare`: the publication coordinator proves the page's base
+ * revision under its page guard before apply, and the caller reads the page
+ * once after apply, seals its text projection from that read and checks the
+ * read-back against `contentHash`. apply then skips its own base re-read,
+ * text-projection seal and read-back.
+ */
+ coordinated?: boolean;
/** Internal canonical metadata, after protected-body overlays and before hashing. */
prepareFrontmatter?: (page: ParsedPage) => void;
noEmbed?: boolean;
@@ -823,7 +831,7 @@ export async function importFromContent(
let persistedProjection: ProjectionSnapshot | null = null;
const timeZone = await loadBrainTimeZone(engine);
const applyPrepared = async (tx: BrainEngine) => {
- await assertImportBase(tx, slug, txOpts.sourceId, existing);
+ if (!opts.coordinated) await assertImportBase(tx, slug, txOpts.sourceId, existing);
await assertPreparedFactWithdrawals(tx, txOpts.sourceId, parsed.compiled_truth, parsed.timeline || '', slug);
if (existing) await tx.createVersion(slug, txOpts);
@@ -904,7 +912,9 @@ export async function importFromContent(
if (chunks.length > 0) {
const embeddingColumn = await stampEmbeddingInputs(tx, chunks, null,
{ title: parsed.title, tier: effectiveCRMode === 'title' ? 'title' : 'none', corpusGeneration });
- await tx.upsertChunks(slug, chunks, embeddingColumn ? { ...txOpts, embeddingColumn } : txOpts);
+ // A complete replacement of the chunks deleted above: the full-body seal
+ // (`chunker_version`) is stamped by the same upsert, after its insert.
+ await tx.upsertChunks(slug, chunks, { ...txOpts, ...(embeddingColumn ? { embeddingColumn } : {}), sealChunkerVersion: MARKDOWN_CHUNKER_VERSION });
// v0.41.31: stamp embedding provenance when this import actually
// embedded (not --no-embed), so a later model/dims swap is detectable
// as stale via embed --stale. The deferred/backfill + per-slug embed
@@ -920,12 +930,12 @@ export async function importFromContent(
} else {
// Content is empty — delete stale chunks so they don't ghost in search results
await tx.deleteChunks(slug, txOpts);
+ // Seal only the completed, full-body sanitized replacement. A body-only
+ // write or a failed transaction must never certify old stored fragments.
+ await tx.executeRaw('UPDATE pages SET chunker_version = $1 WHERE source_id = $2 AND slug = $3',
+ [MARKDOWN_CHUNKER_VERSION, txOpts.sourceId, slug]);
}
- // Seal only the completed, full-body sanitized replacement. A body-only
- // write or a failed transaction must never certify old stored fragments.
- await tx.executeRaw('UPDATE pages SET chunker_version = $1 WHERE source_id = $2 AND slug = $3',
- [MARKDOWN_CHUNKER_VERSION, txOpts.sourceId, slug]);
- await sealPageTextProjection(tx, slug, txOpts.sourceId);
+ if (!opts.coordinated) await sealPageTextProjection(tx, slug, txOpts.sourceId);
// v0.19.0 E1 — doc↔impl linking: if this markdown page cites code paths
// (e.g. 'src/core/sync.ts:42'), create bidirectional edges to the code
@@ -966,7 +976,7 @@ export async function importFromContent(
// Alias projection and readback share the page commit. A later writer can
// no longer turn a successful import into a postcommit verification error.
await tx.setPageAliases(slug, sourceId ?? 'default', normalizeAliasList(parsed.frontmatter.aliases));
- await verifyPageReadable(tx, slug, hash, sourceId, 'importFromContent');
+ if (!opts.coordinated) await verifyPageReadable(tx, slug, hash, sourceId, 'importFromContent');
await opts.beforeCommit?.(tx, slug);
if (opts.onPostCommitEmbedding && !opts.noEmbed && chunks.length > 0) {
// Capture the complete installed projection before releasing the page
@@ -976,7 +986,7 @@ export async function importFromContent(
};
if (opts.prepare) return opts.prepare({
slug, parsedPage, observedRevision: (existing as (typeof existing & { knowledge_revision?: string }) | null)?.knowledge_revision ?? null,
- noop: false, result: { slug, status: 'imported', chunks: chunks.length, parsedPage,
+ noop: false, contentHash: hash, result: { slug, status: 'imported', chunks: chunks.length, parsedPage,
...(pageQuarantined ? { quarantined: true } : {}), ...(pageFlagged ? { flagged: true, flag_reason: pageFlagReason } : {}) },
validate: tx => assertPreparedFactWithdrawals(tx, txOpts.sourceId, parsed.compiled_truth, parsed.timeline || '', slug),
apply: applyPrepared,
@@ -1036,14 +1046,16 @@ export async function importFromContent(
* This is the write-then-verify guard on the sync/write path: a write is not
* "done" until it is readable back.
*/
-async function verifyPageReadable(
+export async function verifyPageReadable(
engine: BrainEngine,
slug: string,
expectedHash: string,
sourceId: string | undefined,
caller: string,
+ /** The caller's own read of the live page after the write (null: not found); read here when omitted. */
+ read?: Pick<Page, 'content_hash'> | null,
): Promise<void> {
- const readBack = await engine.getPage(slug, { sourceId: sourceId ?? 'default' });
+ const readBack = read !== undefined ? read : await engine.getPage(slug, { sourceId: sourceId ?? 'default' });
if (!readBack) {
// Log to ingest_log before throwing so the failure is durable and
// agent-inspectable, not just a transient stderr message.
diff --git a/src/core/page-state/transactions.ts b/src/core/page-state/transactions.ts
index 8fd17ec6e2..f6672e2ef3 100644
--- a/src/core/page-state/transactions.ts
+++ b/src/core/page-state/transactions.ts
@@ -47,3 +47,45 @@ export function composablePgliteTransaction(handle: Transaction, state = { next:
},
}) as unknown as PGlite;
}
+
+const memos = new WeakMap<object, Map<string, Promise<unknown>>>();
+/**
+ * #5984: a read every statement of one page transaction may share (the
+ * embedding config rows, the local writer, source membership). The first key
+ * stores the read; later keys are entries that also satisfy it (a `FOR SHARE`
+ * read satisfies a plain one). Outside a page transaction the read runs every
+ * time. A rejected read is not kept.
+ */
+export function transactionMemo<T>(tx: object, keys: string | readonly string[], read: () => Promise<T>): Promise<T> {
+ if ((tx as { _pageTransaction?: boolean })._pageTransaction !== true) return read();
+ const [key, ...alternatives] = typeof keys === 'string' ? [keys] : keys;
+ let byKey = memos.get(tx);
+ if (!byKey) { byKey = new Map(); memos.set(tx, byKey); }
+ const hit = [key!, ...alternatives].map(k => byKey!.get(k)).find(Boolean);
+ if (hit) return hit as Promise<T>;
+ const stored = read();
+ byKey.set(key!, stored);
+ stored.catch(() => byKey!.delete(key!));
+ return stored;
+}
+
+/**
+ * #5984: issues one transaction's statements back to back without awaiting
+ * between them, so postgres.js pipelines those already prepared on the
+ * transaction's connection (docs/eval/managed-sync-catchup.md, "Pipelining
+ * spike": order kept, later statements of a failed pipeline fail with 25P02).
+ * Each call must send its statement synchronously (`executeRaw`, engine-sql
+ * `run`), so call order is send order. The first failure in call order is
+ * thrown. PGLite runs the calls one at a time.
+ */
+export async function pipelined(engine: { kind: string }, calls: ReadonlyArray<() => Promise<unknown>>): Promise<unknown[]> {
+ if (engine.kind !== 'postgres') {
+ const results: unknown[] = [];
+ for (const call of calls) results.push(await call());
+ return results;
+ }
+ const settled = await Promise.allSettled(calls.map(call => { try { return call(); } catch (error) { return Promise.reject(error); } }));
+ const failed = settled.find(s => s.status === 'rejected') as PromiseRejectedResult | undefined;
+ if (failed) throw failed.reason;
+ return settled.map(s => (s as PromiseFulfilledResult<unknown>).value);
+}
diff --git a/src/core/persistence/authority.ts b/src/core/persistence/authority.ts
index 9508ff8e8b..f9411fc3d9 100644
--- a/src/core/persistence/authority.ts
+++ b/src/core/persistence/authority.ts
@@ -10,6 +10,7 @@ import { authSourcesFromGrant, grantFromTokenRow } from '../grants/model.ts';
import { readLocalWriter, currentVerifiedLocalWriter, verifyLocalWriter, type LocalGrant } from './identity.ts';
import type { Principal, SqlEngine, WriteAuthority, WriteRequest } from './model.ts';
import { authorizePageVisibility, excludesPrivateWrites } from './page-visibility.ts';
+import { transactionMemo } from '../page-state/transactions.ts';
function deny(message: string): never { throw new OperationError('permission_denied', message, 'Inspect the current writer registration and source/operation grants.'); }
function strings(value: unknown): value is string[] { return Array.isArray(value) && value.every(v => typeof v === 'string'); }
@@ -92,8 +93,11 @@ export async function authorizeWrite(engine: SqlEngine, a: WriteAuthority, opera
return;
}
if (a.principal.kind === 'local_cli' || a.principal.kind === 'local_stdio') {
- const [row] = await engine.executeRaw<{ lane: string; revoked_at: unknown; grant_ceiling: LocalGrant }>(
- `SELECT lane,revoked_at,grant_ceiling FROM persistence_local_writers WHERE id=$1::uuid${suffix}`, [a.principal.id]);
+ // #5984: one local-writer read per transaction; a FOR SHARE read also answers a plain one.
+ const key = `local-writer:${a.principal.id}`;
+ const [row] = await transactionMemo(engine, lock ? [`${key}:share`] : [key, `${key}:share`],
+ () => engine.executeRaw<{ lane: string; revoked_at: unknown; grant_ceiling: LocalGrant }>(
+ `SELECT lane,revoked_at,grant_ceiling FROM persistence_local_writers WHERE id=$1::uuid${suffix}`, [a.principal.id]));
const lane = a.principal.kind === 'local_cli' ? 'cli' : 'stdio';
if (!row || row.revoked_at != null || row.lane !== lane || a.remote !== (lane === 'stdio')) deny('The local writer is revoked or its trust lane changed.');
const g = row.grant_ceiling;
@@ -105,8 +109,9 @@ export async function authorizeWrite(engine: SqlEngine, a: WriteAuthority, opera
deny('Application authority is unavailable through submitted write requests.');
}
export async function authorizeStoredRequest(engine: SqlEngine, row: WriteRequest, lock = false): Promise<void> {
- const [source] = await engine.executeRaw<{ incarnation: string; archived: boolean }>(
- `SELECT incarnation,archived FROM sources WHERE id=$1${lock ? ' FOR SHARE' : ''}`, [row.source_id]);
+ // #5984: one membership read per source per transaction; a FOR SHARE read also answers a plain one.
+ const [source] = await transactionMemo(engine, lock ? [`source-membership:${row.source_id}:share`] : [`source-membership:${row.source_id}`, `source-membership:${row.source_id}:share`],
+ () => engine.executeRaw<{ incarnation: string; archived: boolean }>(`SELECT incarnation,archived FROM sources WHERE id=$1${lock ? ' FOR SHARE' : ''}`, [row.source_id]));
if (!source || source.archived || source.incarnation !== row.source_incarnation) {
throw opError('source_changed', 'The accepted source is no longer active.',
`Source ${row.source_id} was archived, removed, or recreated after request ${row.request_id} was accepted, so it will not be applied. Check the source's writer status; a new write must target the current source.`,
diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.ts
index 8232785f6d..6aacc20865 100644
--- a/src/core/persistence/canonical-projections.ts
+++ b/src/core/persistence/canonical-projections.ts
@@ -1,6 +1,7 @@
import type { BrainEngine } from '../engine.ts';
import type { ParsedPage } from '../import-file.ts';
import type { PageSnapshot } from '../page-state/types.ts';
+import { pipelined } from '../page-state/transactions.ts';
import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence } from '../facts-fence.ts';
import { TAKES_FENCE_BEGIN, TAKES_FENCE_END, parseTakesFence } from '../takes-fence.ts';
import { extractFactsFromFenceText } from '../facts/extract-from-fence.ts';
@@ -249,7 +250,7 @@ function takeCollision(): OperationError {
* what this writer actually edited.
*/
export async function prepareCanonicalProjections(engine: BrainEngine, page: ParsedPage, slug: string, sourceId: string,
- prior: PageSnapshot | null, writer: ProjectionWriter): Promise<(tx: BrainEngine) => Promise<void>> {
+ prior: PageSnapshot | null, writer: ProjectionWriter): Promise<(tx: BrainEngine, pageId?: number) => Promise<void>> {
const { factRows, takes } = compileCanonicalProjections(page, slug, sourceId);
const { timeline, exactIncoming, pinned } = classifyTimeline(prior ? await storedTimeline(engine, prior.page.id) : [],
page, prior?.page ?? null, slug, writer);
@@ -265,49 +266,58 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par
JOIN jsonb_to_recordset($2::text::jsonb) AS n(row_num integer,claim text,kind text,holder text) ON n.row_num=k.row_num
WHERE k.page_id=$1 AND (k.claim,k.kind,k.holder) IS DISTINCT FROM (n.claim,n.kind,n.holder) LIMIT 1`, [pageId, newTakes])).length > 0;
if (prior && await collides(engine, prior.page.id)) throw takeCollision();
- return async tx=>{
- const snapshot=await tx.readPageSnapshot(slug,{sourceId});
- if (!snapshot) return;
+ // #5984: `pageId` is the caller's own read of the page in this transaction. The
+ // statements are issued as pipelines; an engine call that sends more than one
+ // statement (insertFacts, addTakesBatch) ends one, so order is kept.
+ return async (tx, pageId) => {
+ const id = pageId ?? (await tx.readPageSnapshot(slug, { sourceId }))?.page.id;
+ if (id == null) return;
// Fact IDs in permanent receipts remain meaningful when a canonical row is
// removed/replaced. Expire and detach its row position instead of deleting it.
// Conversation-extractor rows share the page coordinate without a fence
// (#1928, as in the extract_facts reconcile); their replay owns them. A
// fence row that takes one of their row numbers wins that position.
- const incoming=JSON.stringify(factRows.map(f=>({row_num:f.row_num,fact:f.fact,visibility:f.visibility})));
- await tx.executeRaw(`UPDATE facts f SET expired_at=COALESCE(expired_at,now()),row_num=NULL
+ const incoming = JSON.stringify(factRows.map(f => ({ row_num: f.row_num, fact: f.fact, visibility: f.visibility })));
+ const expireFacts = () => tx.executeRaw(`UPDATE facts f SET expired_at=COALESCE(expired_at,now()),row_num=NULL
WHERE source_id=$1 AND source_markdown_slug=$2 AND row_num IS NOT NULL
AND (COALESCE(f.source,'') NOT LIKE 'cli:extract-conversation-facts%'
OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num=f.row_num))
AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer,fact text,visibility text)
- WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility)`,[sourceId,slug,incoming]);
- if (factRows.length) {
- await tx.insertFacts(factRows,{source_id:sourceId}); // gbrain-allow-direct-insert: canonical fence projection shares the journal publication transaction
- for (const fact of factRows) await tx.executeRaw(`UPDATE facts SET kind=$4,notability=$5,context=$6,
+ WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility)`, [sourceId, slug, incoming]);
+ const factFields = factRows.map(fact => () => tx.executeRaw(`UPDATE facts SET kind=$4,notability=$5,context=$6,
valid_from=COALESCE($7::timestamptz,valid_from),valid_until=$8::timestamptz,expired_at=$9::timestamptz,
source=$10,confidence=$11,claim_metric=$12,claim_value=$13,claim_unit=$14,claim_period=$15
WHERE source_id=$1 AND source_markdown_slug=$2 AND row_num=$3`,
- [sourceId,slug,fact.row_num,fact.kind,fact.notability,fact.context,fact.valid_from?.toISOString()??null,
- fact.valid_until?.toISOString()??null,fact.expired_at?.toISOString()??null,fact.source,fact.confidence,
- fact.claim_metric??null,fact.claim_value??null,fact.claim_unit??null,fact.claim_period??null]);
- }
- const pageId=snapshot.page.id;
- if (await collides(tx,pageId)) throw takeCollision();
- await tx.executeRaw('DELETE FROM takes WHERE page_id=$1 AND row_num=ANY($2::integer[])',[pageId,takeRowsGone]);
- if (takes.length) await tx.addTakesBatch(takes.map(t=>takesPreparation.toCanonicalBatchInput(pageId,t)));
+ [sourceId, slug, fact.row_num, fact.kind, fact.notability, fact.context, fact.valid_from?.toISOString() ?? null,
+ fact.valid_until?.toISOString() ?? null, fact.expired_at?.toISOString() ?? null, fact.source, fact.confidence,
+ fact.claim_metric ?? null, fact.claim_value ?? null, fact.claim_unit ?? null, fact.claim_period ?? null]));
+ const checkTakes = async () => { if (await collides(tx, id)) throw takeCollision(); };
+ const dropTakes = () => tx.executeRaw('DELETE FROM takes WHERE page_id=$1 AND row_num=ANY($2::integer[])', [id, takeRowsGone]);
// Full canonical versions include resolution fields; a revert restores those
// fields from Markdown too, without the ordinary immutable-resolution API.
- for (const take of takes) await tx.executeRaw(`UPDATE takes SET resolved_at=$3::timestamptz,
+ const resolveTakes = takes.map(take => () => tx.executeRaw(`UPDATE takes SET resolved_at=$3::timestamptz,
resolved_quality=$4,resolved_outcome=$5,resolved_source=$6,resolved_value=$7,resolved_unit=$8,resolved_by=$9
- WHERE page_id=$1 AND row_num=$2`,[pageId,take.rowNum,take.resolvedAt??null,take.resolvedQuality??null,
- take.resolvedQuality==='correct'?true:take.resolvedQuality==='incorrect'?false:null,
- take.resolvedEvidence??null,take.resolvedValue??null,take.resolvedUnit??null,take.resolvedBy??null]);
- // Event-page references have a different canonical origin and remain intact.
- await tx.executeRaw(`DELETE FROM timeline_entries t USING jsonb_to_recordset($2::text::jsonb) AS d(id integer,date date,source text,summary text,detail text)
- WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=d.id AND t.date=d.date AND t.source=d.source
- AND t.summary=d.summary AND t.detail=d.detail`,[pageId,deletions]);
- // New rows carry their Markdown detail on insert; pinned rows refresh only from their preimage.
- for (const entry of timeline.values()) await tx.addTimelineEntry(slug,entry,{sourceId});
- await tx.executeRaw(`UPDATE timeline_entries t SET detail=r.next FROM jsonb_to_recordset($2::text::jsonb) AS r(id integer,detail text,next text)
- WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=r.id AND t.detail=r.detail`,[pageId,refreshes]);
+ WHERE page_id=$1 AND row_num=$2`, [id, take.rowNum, take.resolvedAt ?? null, take.resolvedQuality ?? null,
+ take.resolvedQuality === 'correct' ? true : take.resolvedQuality === 'incorrect' ? false : null,
+ take.resolvedEvidence ?? null, take.resolvedValue ?? null, take.resolvedUnit ?? null, take.resolvedBy ?? null]));
+ // Event-page references have a different canonical origin and remain intact;
+ // new rows carry their Markdown detail on insert, pinned rows refresh only from their preimage.
+ const timelineRows = [
+ () => tx.executeRaw(`DELETE FROM timeline_entries t USING jsonb_to_recordset($2::text::jsonb) AS d(id integer,date date,source text,summary text,detail text)
+ WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=d.id AND t.date=d.date AND t.source=d.source
+ AND t.summary=d.summary AND t.detail=d.detail`, [id, deletions]),
+ ...[...timeline.values()].map(entry => () => tx.addTimelineEntry(slug, entry, { sourceId })),
+ () => tx.executeRaw(`UPDATE timeline_entries t SET detail=r.next FROM jsonb_to_recordset($2::text::jsonb) AS r(id integer,detail text,next text)
+ WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=r.id AND t.detail=r.detail`, [id, refreshes]),
+ ];
+ if (factRows.length) {
+ await pipelined(tx, [expireFacts]);
+ await tx.insertFacts(factRows, { source_id: sourceId }); // gbrain-allow-direct-insert: canonical fence projection shares the journal publication transaction
+ await pipelined(tx, [...factFields, checkTakes, dropTakes]);
+ } else await pipelined(tx, [expireFacts, checkTakes, dropTakes]);
+ if (takes.length) {
+ await tx.addTakesBatch(takes.map(t => takesPreparation.toCanonicalBatchInput(id, t)));
+ await pipelined(tx, [...resolveTakes, ...timelineRows]);
+ } else await pipelined(tx, timelineRows);
};
}
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 930258c21e..3eab73369b 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -1,6 +1,7 @@
import { existsSync, mkdirSync, readFileSync, statSync, unlinkSync } from 'node:fs';
import { dirname } from 'node:path';
import type { BrainEngine } from '../engine.ts';
+import type { PageSnapshot } from '../page-state/types.ts';
import { OperationError, opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import type { Action } from '../agent-output.ts';
@@ -43,6 +44,12 @@ interface PreparedMutationBase {
databaseOnlyReason?: 'db_only' | 'unbound_source' | 'mirror_read_only';
/** Must perform only transaction-composable database work. */
apply(tx: BrainEngine): Promise<Record<string, unknown>>;
+ /**
+ * #5984: set by apply to its own read of the page (including deleted rows)
+ * after its last write to the page; the publisher takes the receipt revision
+ * and effects from it instead of reading the page again.
+ */
+ postimage?: PageSnapshot | null;
validate?(tx: BrainEngine): Promise<void>;
}
/** A page file target; `publishMode` (Google pages) is the exact mode it publishes with, and its created directories get 0700. */
@@ -123,6 +130,16 @@ export async function finishUnpublishedFailure(engine: BrainEngine, row: WriteRe
return engine.transaction(tx => completeWrite(tx, row, conflictCode(failure.code) ? 'conflict' : 'failed', {}, failure));
}
+/**
+ * #5984: the page after apply, for the receipt revision and effects: apply's own
+ * read when it kept one and nothing reclassified the page since, else a fresh read.
+ */
+export async function publicationPostimage(tx: BrainEngine, row: WriteRequest, prepared: PreparedMutation): Promise<PageSnapshot | null> {
+ const reclassified = row.authority.databaseOnlyReason === 'unbound_source' || prepared.databaseOnlyReason === 'mirror_read_only';
+ if (prepared.postimage !== undefined && !reclassified) return prepared.postimage;
+ return tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
+}
+
/** The receipt fields every committed publication carries: revision, persistence mode and write-through. */
export function decoratePublicationOutcome(row: WriteRequest, prepared: PreparedMutation, outcome: Record<string, unknown>,
final: { revision: string } | null, fileCount: number, skill: boolean): void {
@@ -292,10 +309,11 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
});
await hooks.boundary?.('after_publication', row);
}
+ prepared.postimage = undefined;
const outcome = await withCoordinatedWrite(tx, [row.source_id], () => prepared.apply(tx), requestAttribution(row));
if (!skill) await classifyUnboundPage(tx, row);
if (prepared.databaseOnlyReason === 'mirror_read_only') await classifyMirrorPage(tx, row);
- const final = skill ? null : await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
+ const final = skill ? null : await publicationPostimage(tx, row, prepared);
decoratePublicationOutcome(row, prepared, outcome, final, files.length, skill);
await queuePublicationEffects(tx, row, final, outcome, prepared);
await hooks.boundary?.('before_commit', row);
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index 6a511010d1..02928c69ce 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -25,7 +25,7 @@ import { OperationError } from '../ops/contract.ts';
import { authorizeStoredRequest } from './authority.ts';
import { localHostId } from './identity.ts';
import { acquireWorktree, getWorktreeBinding, guardOwnership } from './ownership.ts';
-import { completeWrite, getWriteRequestById, lockCounters, releaseUnpublishedClaim, renewGroupClaims } from './journal.ts';
+import { completeWrite, ENSURE_COUNTERS_SQL, getWriteRequestById, LOCK_COUNTERS_SQL, releaseUnpublishedClaim, renewGroupClaims } from './journal.ts';
import { principalKey, requestPrincipal, type WriteRequest } from './model.ts';
import { setMemberAttribution, withCoordinatedWrite } from './context.ts';
import { requestAttribution } from './attribution.ts';
@@ -34,7 +34,10 @@ import { queuePublicationEffects } from './effect-journal.ts';
import { assertUnboundPublication, classifyUnboundPage } from './unbound-source.ts';
import { declarePersistenceProtocol } from './protocol.ts';
import { classifyMirrorPage } from './mirror-read-only.ts';
-import { decoratePublicationOutcome, finishUnpublishedFailure, publishMutation, type PreparedMutation } from './coordinator.ts';
+import { decoratePublicationOutcome, finishUnpublishedFailure, publicationPostimage, publishMutation, type PreparedMutation } from './coordinator.ts';
+import { pipelined } from '../page-state/transactions.ts';
+import { jsonBytes } from './digest.ts';
+import { writerStamp } from './writer-versions.ts';
/** Whether a prepared member can share a group transaction. */
export function groupable(row: WriteRequest, prepared: PreparedMutation): boolean {
@@ -75,25 +78,17 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
if ((snapshot?.revision ?? null) !== member.observedRevision) throw new OperationError('revision_conflict', 'The page changed during preparation.', 'Read its current revision and submit the updated intent with a new request_id.');
await member.validate?.(tx);
await setMemberAttribution(tx, requestAttribution(row));
+ member.postimage = undefined;
const outcome = await member.apply(tx);
await classifyUnboundPage(tx, row);
if (member.databaseOnlyReason === 'mirror_read_only') await classifyMirrorPage(tx, row);
- const final = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
+ const final = await publicationPostimage(tx, row, member);
decoratePublicationOutcome(row, member, outcome, final, 0, false);
await queuePublicationEffects(tx, row, final, outcome, member);
outcomes.push(outcome);
}
}, requestAttribution(head));
- await lockCounters(tx, ['brain', ...new Set(rows.map(row => principalKey(requestPrincipal(row)))), `worktree:${head.worktree_id}`]);
- const current = await tx.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=ANY($1::uuid[]) ORDER BY sequence FOR UPDATE', [rows.map(row => row.id)]);
- const byId = new Map(current.map(row => [row.id, row]));
- const done: WriteRequest[] = [];
- for (let i = 0; i < rows.length; i++) {
- const locked = byId.get(rows[i]!.id);
- if (!locked || locked.execution_token !== rows[i]!.execution_token || locked.state !== 'running') throw new OperationError('write_claim_lost', 'Execution claim changed before publication.', 'Another worker holds the request; inspect it rather than resubmitting.');
- done.push(await completeWrite(tx, locked, 'committed', outcomes[i]!, undefined, locked));
- }
- return done;
+ return completeGroup(tx, rows, outcomes);
});
} catch {
return null;
@@ -103,6 +98,52 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
}
}
+/**
+ * #5984: completes every member's request row in one statement. Each member's
+ * queued effect bytes are read (and missing counter rows created) before the
+ * counters are locked; then the counter lock (`brain`, each principal,
+ * `worktree:<id>`, the order every completion uses) and one UPDATE that checks
+ * each member's claim (`execution_token`, `state='running'`) and terminal
+ * reservation, completes the rows and decrements the counters, are pipelined.
+ * If the UPDATE returns fewer rows than the group, this throws so the
+ * transaction rolls back; the group then takes the single path, where
+ * completeWrite reports each member's exact error code. JSON binds as text.
+ */
+export async function completeGroup(tx: BrainEngine, rows: WriteRequest[], outcomes: Record<string, unknown>[]): Promise<WriteRequest[]> {
+ const ids = rows.map(row => row.id);
+ const keys = [...new Set(['brain', ...rows.map(row => principalKey(requestPrincipal(row))), `worktree:${rows[0]!.worktree_id}`])].sort();
+ const [effects] = await pipelined(tx, [
+ () => tx.executeRaw<{ request_id: string; bytes: string }>(`SELECT request_id::text AS request_id,SUM(octet_length(data::text)+octet_length(kind)+1024)::text AS bytes
+ FROM persistence_effects WHERE request_id=ANY($1::uuid[]) GROUP BY request_id`, [ids]),
+ () => tx.executeRaw(ENSURE_COUNTERS_SQL, [keys]),
+ ]) as [Array<{ request_id: string; bytes: string }>];
+ const effectBytes = new Map(effects.map(e => [e.request_id, Number(e.bytes)]));
+ const stamp = writerStamp();
+ const [, completed] = await pipelined(tx, [
+ () => tx.executeRaw(LOCK_COUNTERS_SQL, [keys]),
+ () => tx.executeRaw<WriteRequest & { principal_key: string }>(`WITH m AS (
+ SELECT * FROM unnest($1::uuid[],$2::uuid[],$3::text[],$4::bigint[],$5::text[]) AS m(id,token,outcome,need,principal_key)
+ ), done AS (
+ UPDATE persistence_requests r SET state='committed',outcome=m.outcome::jsonb,error_code=NULL,error_message=NULL,
+ completed_at=now(),updated_at=now(),claim_expires_at=NULL,blocked_reason=NULL,
+ consumer_version=$6,consumer_host_id=$7::uuid,published_at=now()
+ FROM m WHERE r.id=m.id AND r.execution_token=m.token AND r.state='running' AND m.need<=r.terminal_reservation
+ RETURNING r.*,m.principal_key
+ ), released AS (
+ UPDATE persistence_counters c SET outstanding_count=c.outstanding_count-d.n,intent_bytes=c.intent_bytes-d.bytes
+ FROM (SELECT k.key,count(*) AS n,SUM(done.intent_bytes) AS bytes FROM done CROSS JOIN LATERAL (VALUES ('brain'),(done.principal_key)) AS k(key) GROUP BY k.key) d
+ WHERE c.key=d.key
+ )
+ SELECT * FROM done`, [ids, rows.map(row => row.execution_token), outcomes.map(outcome => JSON.stringify(outcome)),
+ rows.map((row, i) => jsonBytes(outcomes[i]) + jsonBytes(row.authority) + 1024 + (effectBytes.get(row.id) ?? 0)),
+ rows.map(row => principalKey(requestPrincipal(row))), stamp.version, stamp.hostId]),
+ ]) as [unknown, Array<WriteRequest & { principal_key: string }>];
+ if (completed.length !== rows.length) throw new OperationError('write_claim_lost', 'A group member failed its claim or terminal-reservation check before publication.',
+ 'The group rolls back and its members publish one at a time, where each member reports its own outcome; inspect the requests rather than resubmitting.');
+ const byId = new Map(completed.map(({ principal_key: _key, ...row }) => [row.id, row as WriteRequest]));
+ return rows.map(row => byId.get(row.id)!);
+}
+
export interface GroupExecution {
prepare(row: WriteRequest): Promise<PreparedMutation>;
settled(row: WriteRequest): void;
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index b9d7c214cd..a892b384c7 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -88,10 +88,14 @@ export async function assertLifetimeIdHeadroom(engine: SqlEngine, principal: Pri
}
}
/** Creates and locks the counter rows in key order: two statements for any number of keys (#5984 round-trip diet). */
+/** Creates missing counter rows; takes no lock on existing ones. Keys sorted. */
+export const ENSURE_COUNTERS_SQL = 'INSERT INTO persistence_counters(key) SELECT k FROM unnest($1::text[]) WITH ORDINALITY AS u(k,n) ORDER BY n ON CONFLICT DO NOTHING';
+/** Locks counter rows in one global order (deadlock avoidance). */
+export const LOCK_COUNTERS_SQL = 'SELECT * FROM persistence_counters WHERE key=ANY($1::text[]) ORDER BY key COLLATE "C" FOR UPDATE';
export async function lockCounters(tx: SqlEngine, keys: string[]): Promise<Counter[]> {
const sorted = [...new Set(keys)].sort();
- await tx.executeRaw('INSERT INTO persistence_counters(key) SELECT k FROM unnest($1::text[]) WITH ORDINALITY AS u(k,n) ORDER BY n ON CONFLICT DO NOTHING', [sorted]);
- return tx.executeRaw<Counter>('SELECT * FROM persistence_counters WHERE key=ANY($1::text[]) ORDER BY key COLLATE "C" FOR UPDATE', [sorted]);
+ await tx.executeRaw(ENSURE_COUNTERS_SQL, [sorted]);
+ return tx.executeRaw<Counter>(LOCK_COUNTERS_SQL, [sorted]);
}
export async function getWriteRequest(engine: SqlEngine, principal: Principal, requestId: string): Promise<WriteRequest | null> {
const [row] = await engine.executeRaw<WriteRequest>(
diff --git a/src/core/persistence/prepared-import.ts b/src/core/persistence/prepared-import.ts
index 1f915f58bb..6e22a470a6 100644
--- a/src/core/persistence/prepared-import.ts
+++ b/src/core/persistence/prepared-import.ts
@@ -7,6 +7,8 @@ export interface PreparedContentImport {
parsedPage: ParsedPage;
observedRevision: string | null;
noop: boolean;
+ /** The imported content hash, when apply writes the page (`coordinated` callers verify their read-back against it). */
+ contentHash?: string;
result: ImportResult;
validate(tx: BrainEngine): Promise<void>;
apply(tx: BrainEngine): Promise<void>;
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index b70e98956d..9be43a4e59 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -6,7 +6,7 @@ import type { Page } from '../types.ts';
import { OperationError, opError, type OpErrorOpts } from '../ops/contract.ts';
import type { Action } from '../agent-output.ts';
import type { RegistryCode } from '../error-registry.ts';
-import { importFromContent, importCodeFile } from '../import-file.ts';
+import { importFromContent, importCodeFile, verifyPageReadable } from '../import-file.ts';
import { screenImportContent, type ContentRefusal, type ImportScreenResult, type ImportSanityConfig } from '../import-screen.ts';
import { ContentSanityBlockError } from '../content-sanity.ts';
import { parseMarkdown, resolveParsedSubtype, serializePageToMarkdown, type ParseOpts } from '../markdown.ts';
@@ -15,6 +15,7 @@ import { SOURCE_CONFIG_OBJECT_SQL } from '../source-config-sql.ts';
import { sameCanonicalImport } from '../page-state/import-guard.ts';
import { assertPageRevision } from '../page-state/types.ts';
import { sealPageTextProjection } from '../page-state/projections.ts';
+import { pipelined } from '../page-state/transactions.ts';
import { prepareCanonicalProjections } from './canonical-projections.ts';
import { digest, sha256 } from './digest.ts';
import { preserveProtectedTakes } from './protected-takes.ts';
@@ -371,7 +372,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
}
}
let prepared: PreparedContentImport | undefined;
- const importOptions = { ...source, noEmbed: true, remote: row.authority.remote, activePack,
+ const importOptions = { ...source, noEmbed: true, remote: row.authority.remote, activePack, coordinated: true,
filename: basename(p.sourcePath).replace(/\.mdx?$/i, ''), sourcePath: p.sourcePath, allowEmptyOverwrite: true };
const result = await importFromContent(engine, renamed?.slug ?? row.slug, importContent, { ...importOptions,
prepare: async value => { prepared = value; return value.result; } }).catch(error => {
@@ -408,7 +409,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
`The canonical correction for ${row.slug} would overwrite newer working-tree bytes; preserve the local edit and commit it.`);
// A rename projects against the moved page (same id), so its pinned timeline rows carry over.
const project = await prepareCanonicalProjections(engine, ready.parsedPage, row.slug, row.source_id, base, p.companyApproval ? 'immutable' : 'file');
- return { observedRevision: snapshot?.revision ?? null,
+ const preparedImport: PreparedMutation = { observedRevision: snapshot?.revision ?? null,
// Tells the #5470 screen the content is unchanged; publication still queues its effects.
contentUnchanged: ready.noop && !moved && !writeback,
...(renamed ? { additionalPageKeys: [{ sourceId: row.source_id, slug: renamed.slug }] } : {}),
@@ -434,14 +435,23 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
await applied.apply(tx);
// Hash no-ops still repair a missing physical origin under the same guard.
await tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2 AND source_path IS DISTINCT FROM $3', [row.source_id, row.slug, p.sourcePath]);
- if (!applied.noop || p.companyApproval) await project(tx);
- if (!applied.noop) await sealPageTextProjection(tx, row.slug, row.source_id);
- await releaseHold(tx);
- const [page] = await tx.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', [row.source_id, row.slug]);
- if (page) await recordSyncImportProvenance(tx, { source_id: row.source_id, incarnation: row.source_incarnation, page_id: Number(page.id), origin: p.sourcePath!,
- raw_sha256: sha256(p.content!), ...(p.blobOid ? { blob_oid: p.blobOid } : {}), gbrain_version: VERSION, ...(recovery?.length ? { recovery } : {}) });
+ // #5984: the one read of the page after its last page write (the projections
+ // below and the seal leave its revision unchanged): read-back check, projection
+ // target, seal input, receipt revision and effects.
+ const final = await tx.readPageSnapshot(row.slug, { ...source, includeDeleted: true });
+ const live = final && final.page.deleted_at == null ? final : null;
+ if (!applied.noop) await verifyPageReadable(tx, row.slug, applied.contentHash!, row.source_id, 'managed sync', live?.page ?? null);
+ if (!applied.noop || p.companyApproval) await project(tx, final?.page.id);
+ await pipelined(tx, [
+ async () => { if (!applied.noop && live) await sealPageTextProjection(tx, row.slug, row.source_id, live); },
+ () => releaseHold(tx),
+ async () => { if (final) await recordSyncImportProvenance(tx, { source_id: row.source_id, incarnation: row.source_incarnation, page_id: Number(final.page.id), origin: p.sourcePath!,
+ raw_sha256: sha256(p.content!), ...(p.blobOid ? { blob_oid: p.blobOid } : {}), gbrain_version: VERSION, ...(recovery?.length ? { recovery } : {}) }); },
+ ]);
+ preparedImport.postimage = final;
return { status: moved ? 'renamed' : applied.noop ? 'skipped' : snapshot ? 'updated' : 'created', slug: row.slug, source_id: row.source_id,
chunks: applied.result.chunks, noop: applied.noop && !moved, imported_file: true, ...(moved ? { renamed_from: moved.slug } : {}),
...(recovery?.length ? { recovered_frontmatter: true } : {}), ...(commentValue ? { comment_value: true } : {}) };
} };
+ return preparedImport;
}
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 138e0e292e..542ca25b60 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -8,7 +8,7 @@ import { lockUnheldPageKeys, withHeldPageKeys, type HeldPageKeys } from './page-
import { readPageSnapshot as readCanonicalPageSnapshot } from './page-state/snapshot.ts';
import { createPageVersion } from './page-state/versions.ts';
import { moveSlugBindings, recordRenameAlias } from './page-state/rename-alias.ts';
-import { composablePgliteTransaction } from './page-state/transactions.ts';
+import { composablePgliteTransaction, transactionMemo } from './page-state/transactions.ts';
import { dropRowTypeArrayParsers, PgliteStatementCache } from './pglite-statements.ts';
import { snapshotSchemaInputs } from './snapshot-schema-inputs.ts';
import type { PageReadScope } from './types.ts';
@@ -1706,16 +1706,17 @@ export class PGLiteEngine implements BrainEngine {
// Chunks SQL lives once in ./engine-sql/chunks.ts (refactor wave 1, W1-extended).
// The engine keeps the retry + transaction wrapper, the RLS scope
// transaction and the source-scope / active-column resolution.
- async upsertChunks(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string } & BatchOpts): Promise<void> {
+ async upsertChunks(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string; sealChunkerVersion?: number } & BatchOpts): Promise<void> {
if (this._chunkWritesInTransaction) return this._upsertChunksOnce(slug, chunks, opts);
return this.batchRetry(opts?.auditSite ?? 'upsertChunks', opts?.signal,
() => this.transaction(tx => (tx as PGLiteEngine)._upsertChunksOnce(slug, chunks, opts)), chunks.length);
}
- private async _upsertChunksOnce(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string }): Promise<void> {
+ private async _upsertChunksOnce(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string; sealChunkerVersion?: number }): Promise<void> {
return chunksImpl.upsertChunksOnce(this.engineSql, {
lockPageKeys: (keys) => this.lockPageKeys(keys),
readPageSnapshot: (pageSlug, snapshotOpts) => this.readPageSnapshot(pageSlug, snapshotOpts),
+ memo: (key, read) => transactionMemo(this, key, read),
}, slug, chunks, opts);
}
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index dcf4cff626..dba7590796 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -7,7 +7,7 @@ import { lockUnheldPageKeys, withHeldPageKeys, type HeldPageKeys } from './page-
import { readPageSnapshot as readCanonicalPageSnapshot } from './page-state/snapshot.ts';
import { createPageVersion } from './page-state/versions.ts';
import { moveSlugBindings, recordRenameAlias } from './page-state/rename-alias.ts';
-import { composablePostgresTransaction } from './page-state/transactions.ts';
+import { composablePostgresTransaction, transactionMemo } from './page-state/transactions.ts';
import type { PageReadScope } from './types.ts';
import type { PageReadPolicy } from './types.ts';
import { readRelationalFanout, readAliases, readBacklinkCounts, readAdjacencyBoosts, readContentFlags, readExtractionStates, readEffectiveDates, readSalienceScores } from './search/read-enrichment.ts';
@@ -1444,16 +1444,17 @@ export class PostgresEngine implements BrainEngine {
// Chunks SQL lives once in ./engine-sql/chunks.ts (refactor wave 1, W1-extended).
// The engine keeps the retry + transaction wrapper, the RLS scope
// transaction and the source-scope / active-column resolution.
- async upsertChunks(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string } & BatchOpts): Promise<void> {
+ async upsertChunks(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string; sealChunkerVersion?: number } & BatchOpts): Promise<void> {
if (this._chunkWritesInTransaction) return this._upsertChunksOnce(slug, chunks, opts);
return this.batchRetry(opts?.auditSite ?? 'upsertChunks', opts?.signal,
() => this.transaction(tx => (tx as PostgresEngine)._upsertChunksOnce(slug, chunks, opts)), chunks.length);
}
- private async _upsertChunksOnce(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string }): Promise<void> {
+ private async _upsertChunksOnce(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string; sealChunkerVersion?: number }): Promise<void> {
return chunksImpl.upsertChunksOnce(this.engineSql, {
lockPageKeys: (keys) => this.lockPageKeys(keys),
readPageSnapshot: (pageSlug, snapshotOpts) => this.readPageSnapshot(pageSlug, snapshotOpts),
+ memo: (key, read) => transactionMemo(this, key, read),
}, slug, chunks, opts);
}