Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
managed sync lanes: pipeline the group publication and the page apply (#5984 lane apply diet)
garrytan7a9bafab7fd0
diff --git a/src/core/engine-sql/chunks.ts b/src/core/engine-sql/chunks.tsindex 3041d7ea8f..ba18694bb7 100644--- a/src/core/engine-sql/chunks.ts+++ b/src/core/engine-sql/chunks.ts@@ -41,6 +41,7 @@ import { mapChunkWindowRows, type ChunkWindowOpts, type ChunkWindowPage, type Chimport type { SqlExecutor } from './executor.ts';import type { LegacyUnscopedRead, ScopedRead } from './brands.ts';import { joinFragments, renderFragment, sqlFragment, trustedSql, type SqlFragment } from './fragment.ts';+import { pipelined } from '../page-state/transactions.ts';/** The engine's page-state guards, run on the same (transaction) engine. */export interface ChunkPageGuards {@@ -64,7 +65,7 @@ export async function upsertChunksOnce(guards: ChunkPageGuards,slug: string,chunks: ChunkInput[],- opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string; sealChunkerVersion?: number },+ opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string; sealChunkerVersion?: number; pageId?: 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,@@ -86,10 +87,14 @@ export async function upsertChunksOnce(// every chunk of the page earlier in this transaction, so nothing stale can// remain, and the seal (which also locks the page row and yields its id)// commits only together with the insert below.+ // #5984: a seal whose caller knows the page id (`pageId`, its own write of the page in+ // this transaction) is sent in one pipeline with the insert and checked after both ran.const seal = opts?.sealChunkerVersion;- const pages = (await exec.run<{ id: number }>(seal === undefined- ? sqlFragment`SELECT id FROM pages WHERE slug = ${slug} AND source_id = ${sourceId} FOR UPDATE`- : sqlFragment`UPDATE pages SET chunker_version = ${seal} WHERE slug = ${slug} AND source_id = ${sourceId} RETURNING id`)).rows;+ const sealed = seal !== undefined && opts?.pageId !== undefined && chunks.length > 0 ? opts.pageId : undefined;+ const sealPage = () => exec.run<{ id: number }>(sqlFragment`UPDATE pages SET chunker_version = ${seal} WHERE slug = ${slug} AND source_id = ${sourceId} RETURNING id`);+ const pages = sealed !== undefined ? [{ id: sealed }] : (await (seal === undefined+ ? exec.run<{ id: number }>(sqlFragment`SELECT id FROM pages WHERE slug = ${slug} AND source_id = ${sourceId} FOR UPDATE`)+ : sealPage())).rows;if (pages.length === 0) throw new Error(`Page not found: ${slug} (source=${sourceId})`);const pageId = pages[0].id;@@ -303,7 +308,10 @@ 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.query(text, params);+ if (sealed === undefined) { await exec.query(text, params); return; }+ const [{ rows }] = await pipelined({ kind: exec.dialect }, [sealPage, () => exec.query(text, params)]) as [{ rows: Array<{ id: number }> }];+ if (rows.length === 0) throw new Error(`Page not found: ${slug} (source=${sourceId})`);+ if (Number(rows[0]!.id) !== Number(sealed)) throw new Error(`Page ${slug} (source=${sourceId}) is not the page this transaction wrote`);}export async function getChunks(diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.tsindex 96241aea3f..046c9748a3 100644--- a/src/core/engine-sql/pages.ts+++ b/src/core/engine-sql/pages.ts@@ -119,10 +119,17 @@ export async function putPage(const sourceUri = page.source_uri ?? null;const ingestedVia = page.ingested_via ?? null;const ingestedAt = (sourceKind || sourceUri || ingestedVia) ? new Date() : null;+ // #5984: the contextual retrieval stamp, when the caller passes it, rides in this statement.+ const cr = opts?.contextualRetrieval && opts.contextualRetrieval.mode !== 'none' ? opts.contextualRetrieval : null;+ const crColumns = cr ? sqlFragment`, contextual_retrieval_mode, corpus_generation` : sqlFragment``;+ const crValues = cr ? sqlFragment`, ${cr.mode}, ${cr.corpusGeneration}` : sqlFragment``;+ const crSet = cr ? sqlFragment`+ contextual_retrieval_mode = EXCLUDED.contextual_retrieval_mode,+ corpus_generation = EXCLUDED.corpus_generation,` : sqlFragment``;const { rows } = await exec.run(sqlFragment`- INSERT INTO pages (source_id, slug, type, page_kind, title, compiled_truth, timeline, frontmatter, content_hash, updated_at, effective_date, effective_date_source, import_filename, chunker_version, source_path, source_kind, source_uri, ingested_via, ingested_at)- VALUES (${sourceId}, ${slug}, ${page.type}, ${pageKind}, ${sanitizeText(page.title)}, ${sanitizeText(page.compiled_truth)}, ${sanitizeText(page.timeline || '')}, ${jsonbParam(frontmatter)}, ${hash}, now(), ${effectiveDate}, ${effectiveDateSource}, ${importFilename}, ${chunkerVersion}::smallint, ${sourcePath}, ${sourceKind}, ${sourceUri}, ${ingestedVia}, ${ingestedAt})- ON CONFLICT (source_id, slug) DO UPDATE SET+ INSERT INTO pages (source_id, slug, type, page_kind, title, compiled_truth, timeline, frontmatter, content_hash, updated_at, effective_date, effective_date_source, import_filename, chunker_version, source_path, source_kind, source_uri, ingested_via, ingested_at${crColumns})+ VALUES (${sourceId}, ${slug}, ${page.type}, ${pageKind}, ${sanitizeText(page.title)}, ${sanitizeText(page.compiled_truth)}, ${sanitizeText(page.timeline || '')}, ${jsonbParam(frontmatter)}, ${hash}, now(), ${effectiveDate}, ${effectiveDateSource}, ${importFilename}, ${chunkerVersion}::smallint, ${sourcePath}, ${sourceKind}, ${sourceUri}, ${ingestedVia}, ${ingestedAt}${crValues})+ ON CONFLICT (source_id, slug) DO UPDATE SET${crSet}type = EXCLUDED.type,page_kind = EXCLUDED.page_kind,title = EXCLUDED.title,diff --git a/src/core/engine.ts b/src/core/engine.tsindex 38d2c763f0..5b087d0e26 100644--- a/src/core/engine.ts+++ b/src/core/engine.ts@@ -1168,9 +1168,11 @@ export interface BrainEngine {* 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.+ * sealed at that chunker version after the insert. With `pageId` (the+ * caller's own write of that page in this transaction) the seal and the+ * insert are sent together and the seal's page is checked against it.*/- upsertChunks(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string; sealChunkerVersion?: number } & BatchOpts): Promise<void>;+ upsertChunks(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string; sealChunkerVersion?: number; pageId?: number } & BatchOpts): Promise<void>;/*** Read every chunk for a page. Scope precedence mirrors getPage (#2555):* a federated grant (`sourceIds[]`) wins over scalar `sourceId`; with@@ -2434,6 +2436,8 @@ export interface BrainEngine {slug: string,sourceId: string,aliasNorms: string[],+ /** #5984: `inline` writes in the caller's page transaction, without a savepoint. */+ opts?: { inline?: boolean },): Promise<void>;/**diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex 2cb6b82c14..4fbacb9af2 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -36,6 +36,8 @@ import { isEmbeddingZeroNormError, type EmbeddingZeroNormError } from './ai/embeimport { slugifyPath, slugifyCodePath, isCodeFilePath, hasMalformedPathSegment } from './sync.ts';import type { ChunkInput, Page, PageInput, PageType } from './types.ts';import type { PageSnapshot } from './page-state/types.ts';+import { pipelined } from './page-state/transactions.ts';+import { addPageTags } from './page-state/tags.ts';import { computeEffectiveDate, fallbackCreatedAt, isValidTimeZone } from './effective-date.ts';import { MARKDOWN_CHUNKER_VERSION } from './chunkers/recursive.ts';import { logSlugFallback } from './audit-slug-fallback.ts';@@ -847,9 +849,8 @@ export async function importFromContent(const [timeZone, mentionPolicy] = await Promise.all([loadBrainTimeZone(engine), readMentionPolicy(engine).catch(() => null)]);const applyPrepared = async (tx: BrainEngine, preimage?: PageSnapshot | null) => {if (!opts.coordinated) await assertImportBase(tx, slug, txOpts.sourceId, existing, reused.size > 0);- await assertPreparedFactWithdrawals(tx, txOpts.sourceId, parsed.compiled_truth, parsed.timeline || '', slug);- if (existing) await tx.createVersion(slug, preimage ? { ...txOpts, preimage } : txOpts);-+ // #5984: the canonical writes go out in two pipelined waves of mutually independent statements; the+ // second depends on the first (the page row and its id, the old chunks gone). A failure rolls back the caller's transaction.// v0.29.1 — compute effective_date from frontmatter precedence chain.// Filename comes from importFromFile path (basename) or the slug tail// (put_page MCP op fallback). An undated page falls back to a stable@@ -868,83 +869,85 @@ export async function importFromContent(createdAt: fallbackCreatedAt({ existing, fileTimes: opts.fileTimes, now: nowDate }),});- const written = await tx.putPage(slug, {- type: parsed.type,- title: parsed.title,- compiled_truth: parsed.compiled_truth,- timeline: parsed.timeline || '',- frontmatter: parsed.frontmatter,- content_hash: hash,- effective_date: effectiveDate,- effective_date_source: effectiveDateSource,- import_filename: filenameForChain,- // Preserve the repo-relative path for sync's delete/rename handling.- source_path: opts.sourcePath ?? null,- // v0.39.3.0 provenance write-through (WARN-8). Engine layer applies- // COALESCE-preserve UPDATE so omitting these on a later put_page- // doesn't erase the original ingestion's audit trail.- source_kind: opts.source_kind ?? null,- source_uri: opts.source_uri ?? originUri,- ingested_via: opts.ingested_via ?? null,- // ingested_at is server-stamped at the engine layer when any- // provenance write fires; never client-controlled.- // Empty-overwrite escape hatch only when the caller vouched (file- // import / explicit allow_empty); otherwise the engine guard stays on.- }, opts.allowEmptyOverwrite === true ? { ...txOpts, allowEmptyOverwrite: true } : txOpts);-- // v0.40.3.0: stamp the contextual retrieval state columns alongside- // the page write. updatePageContextualRetrievalState is a narrow- // UPDATE that runs after putPage's INSERT/UPDATE so the row exists.- // Deferred embedders reproduce it: the prepared outbox installs only- // under CAS, and --no-embed drains read it back. Every chunk row is- // replaced below, so no older vector survives under this stamp.- // This stamp certifies no vector: embedding_signature stays deferred.- await tx.updatePageContextualRetrievalState(- slug,- sourceId ?? 'default',- effectiveCRMode,- corpusGeneration,- );-- // Tag reconciliation (A14): frontmatter tags carry tag_source='frontmatter'.- // A frontmatter-owned row whose tag left the frontmatter is deleted; rows- // explicit adds own ('added': add_tag, enrichment, the code importer) and- // legacy NULL rows are never deleted here (#1621: reindex must not wipe- // enrichment). A legacy row still in the frontmatter is adopted. Prepared- // (managed) imports keep the add-only union their canonical file renders.- if (!opts.prepare) {- await tx.executeRaw(`DELETE FROM tags t USING pages p WHERE p.id = t.page_id AND p.source_id = $1 AND p.slug = $2- AND t.tag_source = 'frontmatter' AND NOT (t.tag = ANY($3::text[]))`, [txOpts.sourceId, slug, parsed.tags]);- }- for (const tag of parsed.tags) {- await tx.addTag(slug, tag, opts.prepare ? txOpts : { ...txOpts, tagSource: 'frontmatter' });- }-- // Replace every derived row atomically. Only vectors the A13 reuse gate- // above admitted carry over; a new seal otherwise inherits nothing from an- // older index, whose contextual vector may have included a private sibling.- await tx.deleteChunks(slug, txOpts);- 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, { ...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- // paths stamp too; this covers the inline import/sync path.- if (!opts.noEmbed && !opts.onPostCommitEmbedding && !embeddingDeferred) {- // D9: signature is null when the gateway is unconfigured — skip the- // stamp (a wrong signature is worse than none).- const importSig = currentEmbeddingSignature();- if (importSig) {- await tx.setPageEmbeddingSignature(slug, { sourceId, signature: importSig });+ if (existing && !preimage) await tx.createVersion(slug, txOpts); // reads the page itself, so before the page write+ let written: Page | undefined;+ await pipelined(tx, [+ () => assertPreparedFactWithdrawals(tx, txOpts.sourceId, parsed.compiled_truth, parsed.timeline || '', slug),+ async () => { if (existing && preimage) await tx.createVersion(slug, { ...txOpts, preimage }); },+ async () => {+ written = await tx.putPage(slug, {+ type: parsed.type,+ title: parsed.title,+ compiled_truth: parsed.compiled_truth,+ timeline: parsed.timeline || '',+ frontmatter: parsed.frontmatter,+ content_hash: hash,+ effective_date: effectiveDate,+ effective_date_source: effectiveDateSource,+ import_filename: filenameForChain,+ // Preserve the repo-relative path for sync's delete/rename handling.+ source_path: opts.sourcePath ?? null,+ // v0.39.3.0 provenance write-through (WARN-8). Engine layer applies+ // COALESCE-preserve UPDATE so omitting these on a later put_page+ // doesn't erase the original ingestion's audit trail.+ source_kind: opts.source_kind ?? null,+ source_uri: opts.source_uri ?? originUri,+ ingested_via: opts.ingested_via ?? null,+ // ingested_at is server-stamped at the engine layer when any+ // provenance write fires; never client-controlled.+ // Empty-overwrite escape hatch only when the caller vouched (file+ // import / explicit allow_empty); otherwise the engine guard stays on.+ }, { ...txOpts, ...(opts.allowEmptyOverwrite === true ? { allowEmptyOverwrite: true } : {}), inline: true,+ ...(effectiveCRMode !== 'none' ? { contextualRetrieval: { mode: effectiveCRMode, corpusGeneration } } : {}) });+ // v0.40.3.0: the contextual retrieval state is stamped with the page write (the `none` tier's+ // stamp, which also clears tier vectors, follows it). Deferred embedders reproduce it; every+ // chunk row is replaced below. This stamp certifies no vector: embedding_signature stays deferred.+ if (effectiveCRMode === 'none') await tx.updatePageContextualRetrievalState(slug, sourceId ?? 'default', effectiveCRMode, corpusGeneration);+ },+ // Replace every derived row atomically. Only vectors the A13 reuse gate above admitted carry over; a new+ // seal otherwise inherits nothing from an older index, whose contextual vector may have included a private sibling.+ () => tx.deleteChunks(slug, txOpts),+ // Alias projection and readback share the page commit. A later writer can+ // no longer turn a successful import into a postcommit verification error.+ () => writePageAliases(tx, slug, sourceId ?? 'default', parsed, opts.activePack, mentionPolicy),+ ]);+ const pageId = written && written.deleted_at == null ? written.id : undefined;+ await pipelined(tx, [+ async () => {+ // Tag reconciliation (A14): frontmatter tags carry tag_source='frontmatter'.+ // A frontmatter-owned row whose tag left the frontmatter is deleted; rows+ // explicit adds own ('added': add_tag, enrichment, the code importer) and+ // legacy NULL rows are never deleted here (#1621: reindex must not wipe+ // enrichment). A legacy row still in the frontmatter is adopted. Prepared+ // (managed) imports keep the add-only union their canonical file renders.+ if (!opts.prepare) await tx.executeRaw(`DELETE FROM tags t USING pages p WHERE p.id = t.page_id AND p.source_id = $1 AND p.slug = $2+ AND t.tag_source = 'frontmatter' AND NOT (t.tag = ANY($3::text[]))`, [txOpts.sourceId, slug, parsed.tags]);+ if (pageId !== undefined) return addPageTags(tx, Number(pageId), parsed.tags, opts.prepare ? undefined : 'frontmatter');+ for (const tag of parsed.tags) await tx.addTag(slug, tag, opts.prepare ? txOpts : { ...txOpts, tagSource: 'frontmatter' });+ },+ async () => {+ 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, { ...txOpts, ...(embeddingColumn ? { embeddingColumn } : {}), sealChunkerVersion: MARKDOWN_CHUNKER_VERSION,+ ...(pageId !== undefined ? { pageId: Number(pageId) } : {}) });+ // 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+ // paths stamp too; this covers the inline import/sync path.+ if (!opts.noEmbed && !opts.onPostCommitEmbedding && !embeddingDeferred) {+ // D9: signature is null when the gateway is unconfigured — skip the+ // stamp (a wrong signature is worse than none).+ const importSig = currentEmbeddingSignature();+ if (importSig) await tx.setPageEmbeddingSignature(slug, { sourceId, signature: importSig });+ }+ } else {+ // Seal only the completed, full-body sanitized replacement (the upsert above seals its own); 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]);}- }- } else {- // Seal only the completed, full-body sanitized replacement (the upsert above seals its own); 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]);- }+ },+ ]);if (!opts.coordinated) await sealPageTextProjection(tx, slug, txOpts.sourceId);// v0.19.0 E1 — doc↔impl linking: if this markdown page cites code paths@@ -983,9 +986,6 @@ export async function importFromContent());} catch { /* same reason — silent skip */ }}- // Alias projection and readback share the page commit. A later writer can- // no longer turn a successful import into a postcommit verification error.- await writePageAliases(tx, slug, sourceId ?? 'default', parsed, opts.activePack, mentionPolicy);if (!opts.coordinated) await verifyPageReadable(tx, slug, hash, sourceId, 'importFromContent');await opts.beforeCommit?.(tx, slug);if (opts.onPostCommitEmbedding && !opts.noEmbed && chunks.length > 0) {diff --git a/src/core/mentions/pass.ts b/src/core/mentions/pass.tsindex 8e1081ae7e..8d3753a2f4 100644--- a/src/core/mentions/pass.ts+++ b/src/core/mentions/pass.ts@@ -45,6 +45,7 @@ import {import { linkableTypesFor, loadSourcePack, parseNameList, readMentionPolicy, type MentionPolicy, type PackTypes } from './policy.ts';import { deriveEntityAliases, type DerivedAlias } from './aliases.ts';import { normalizeAliasList } from '../search/alias-normalize.ts';+import { pipelined } from '../page-state/transactions.ts';import { withCoordinatedWrite } from '../persistence/context.ts';import { maintenanceAttribution } from '../persistence/attribution.ts';import { managedPersistenceEnabled } from '../persistence/ownership.ts';@@ -168,8 +169,11 @@ export async function writeDerivedAliases(tx: Pick<BrainEngine, 'executeRaw' | 'export async function writePageAliases(tx: BrainEngine, slug: string, sourceId: string,page: { title: string; type: string; compiled_truth: string; timeline: string; frontmatter: Record<string, unknown> }, pack: unknown,policy: MentionPolicy | null): Promise<void> {- await tx.setPageAliases(slug, sourceId, normalizeAliasList(page.frontmatter.aliases));- await writeDerivedAliases(tx, sourceId, { slug, ...page }, { pack: (pack as PackTypes | undefined) ?? null, policy });+ // #5984: the frontmatter and derived rows are independent; their statements are pipelined, in the caller's transaction.+ await pipelined(tx, [+ () => tx.setPageAliases(slug, sourceId, normalizeAliasList(page.frontmatter.aliases), { inline: true }),+ () => writeDerivedAliases(tx, sourceId, { slug, ...page }, { pack: (pack as PackTypes | undefined) ?? null, policy }),+ ]);}/** Turn the index off for one source: plain mention links, derived aliases, entries and page state go; typed_ner rows stay. */diff --git a/src/core/page-state/guards.ts b/src/core/page-state/guards.tsindex ce8bd581ac..ad2fc40d85 100644--- a/src/core/page-state/guards.ts+++ b/src/core/page-state/guards.ts@@ -1,40 +1,59 @@import type { BrainEngine } from '../engine.ts';import { validateSlug } from '../utils.ts';import type { PageKey } from './types.ts';+import { pipelined } from './transactions.ts';-/** Source locks precede auth/request locks in callers; repeat held locks safely. */-export async function lockPageKeys(engine: Pick<BrainEngine, 'executeRaw'>, keys: readonly PageKey[]): Promise<void> {+/**+ * Source locks precede auth/request locks in callers; repeat held locks safely.+ * #5984: the guard statements are pipelined in the sorted key order. Keys that+ * all carry their source's expected `incarnation` send the source reads in the+ * same pipeline; a source that is missing or was recreated then fails the call+ * after its statements ran, so the caller's transaction must roll back.+ */+export async function lockPageKeys(engine: Pick<BrainEngine, 'executeRaw'> & { kind?: string }, keys: readonly PageKey[]): Promise<void> {const unique = new Map<string, PageKey>();for (const key of keys) {if (!key.sourceId) throw new TypeError('A page guard requires an exact sourceId');const slug = validateSlug(key.slug);- unique.set(JSON.stringify([key.sourceId, slug]), { sourceId: key.sourceId, slug });+ unique.set(JSON.stringify([key.sourceId, slug]), { sourceId: key.sourceId, slug, ...(key.incarnation ? { incarnation: key.incarnation } : {}) });}const ordered = [...unique.values()].sort((a, b) => a.sourceId < b.sourceId ? -1 : a.sourceId > b.sourceId ? 1 : a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0);- const sources = new Map<string, string>();- for (const { sourceId } of ordered) {- if (sources.has(sourceId)) continue;- const rows = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1 FOR SHARE', [sourceId]);+ const expected = new Map<string, string>();+ for (const { sourceId, incarnation } of ordered) if (incarnation && (expected.get(sourceId) ?? incarnation) === incarnation) expected.set(sourceId, incarnation);+ const hinted = ordered.every(key => key.incarnation && expected.get(key.sourceId) === key.incarnation);+ const readSource = (sourceId: string) => engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1 FOR SHARE', [sourceId]).then(rows => {if (!rows.length) throw new Error(`Page source does not exist: ${sourceId}`);- sources.set(sourceId, rows[0].incarnation);+ if (hinted && rows[0]!.incarnation !== expected.get(sourceId)) throw new Error(`Page source was recreated: ${sourceId}`);+ return rows[0]!.incarnation;+ });+ const run = (calls: Array<() => Promise<unknown>>) => pipelined({ kind: engine.kind ?? '' }, calls);+ const sources = new Map<string, string>(hinted ? expected : []);+ const reads: Array<() => Promise<unknown>> = [];+ for (const sourceId of new Set(ordered.map(key => key.sourceId))) {+ if (hinted) reads.push(() => readSource(sourceId));+ else sources.set(sourceId, await readSource(sourceId));}if (ordered.length > 1) {// #5984: many keys in three statements, still created and locked in the sorted key order.const incarnations = ordered.map(key => sources.get(key.sourceId)!), slugs = ordered.map(key => key.slug), sourceIds = ordered.map(key => key.sourceId);- await engine.executeRaw('INSERT INTO page_write_guards(source_incarnation,slug) SELECT i,s FROM unnest($1::uuid[],$2::text[]) WITH ORDINALITY AS k(i,s,n) ORDER BY n ON CONFLICT DO NOTHING', [incarnations, slugs]);- await engine.executeRaw(`SELECT g.slug FROM unnest($1::uuid[],$2::text[]) WITH ORDINALITY AS k(i,s,n)- JOIN page_write_guards g ON g.source_incarnation=k.i AND g.slug=k.s ORDER BY k.n FOR UPDATE OF g`, [incarnations, slugs]);- await engine.executeRaw(`SELECT p.id FROM unnest($1::text[],$2::text[]) WITH ORDINALITY AS k(src,s,n)- JOIN pages p ON p.source_id=k.src AND p.slug=k.s ORDER BY k.n FOR UPDATE OF p`, [sourceIds, slugs]);+ await run([...reads,+ () => engine.executeRaw('INSERT INTO page_write_guards(source_incarnation,slug) SELECT i,s FROM unnest($1::uuid[],$2::text[]) WITH ORDINALITY AS k(i,s,n) ORDER BY n ON CONFLICT DO NOTHING', [incarnations, slugs]),+ () => engine.executeRaw(`SELECT g.slug FROM unnest($1::uuid[],$2::text[]) WITH ORDINALITY AS k(i,s,n)+ JOIN page_write_guards g ON g.source_incarnation=k.i AND g.slug=k.s ORDER BY k.n FOR UPDATE OF g`, [incarnations, slugs]),+ () => engine.executeRaw(`SELECT p.id FROM unnest($1::text[],$2::text[]) WITH ORDINALITY AS k(src,s,n)+ JOIN pages p ON p.source_id=k.src AND p.slug=k.s ORDER BY k.n FOR UPDATE OF p`, [sourceIds, slugs]),+ ]);return;}- for (const key of ordered) {+ await run([...reads, ...ordered.flatMap(key => {const params = [sources.get(key.sourceId)!, key.slug];- await engine.executeRaw('INSERT INTO page_write_guards(source_incarnation,slug) VALUES ($1::uuid,$2) ON CONFLICT DO NOTHING', params);- await engine.executeRaw('SELECT slug FROM page_write_guards WHERE source_incarnation=$1::uuid AND slug=$2 FOR UPDATE', params);- // Also fence direct SQL row writers. The guard remains when this row is absent.- await engine.executeRaw('SELECT id FROM pages WHERE source_id=$1 AND slug=$2 FOR UPDATE', [key.sourceId, key.slug]);- }+ return [+ () => engine.executeRaw('INSERT INTO page_write_guards(source_incarnation,slug) VALUES ($1::uuid,$2) ON CONFLICT DO NOTHING', params),+ () => engine.executeRaw('SELECT slug FROM page_write_guards WHERE source_incarnation=$1::uuid AND slug=$2 FOR UPDATE', params),+ // Also fence direct SQL row writers. The guard remains when this row is absent.+ () => engine.executeRaw('SELECT id FROM pages WHERE source_id=$1 AND slug=$2 FOR UPDATE', [key.sourceId, key.slug]),+ ];+ })]);}/**@@ -54,7 +73,7 @@ function holds(held: HeldPageKeys | null, id: string): boolean {return false;}/** lockPageKeys for keys this transaction does not hold yet; invalid keys still reach its checks. */-export async function lockUnheldPageKeys(engine: Pick<BrainEngine, 'executeRaw'>, held: HeldPageKeys, keys: readonly PageKey[]): Promise<void> {+export async function lockUnheldPageKeys(engine: Pick<BrainEngine, 'executeRaw'> & { kind?: string }, held: HeldPageKeys, keys: readonly PageKey[]): Promise<void> {const pending = keys.filter(key => { const id = pageGuardKey(key); return id === null || !holds(held, id); });if (!pending.length) return;await lockPageKeys(engine, pending);diff --git a/src/core/page-state/tags.ts b/src/core/page-state/tags.tsindex 614cb0c340..6dd1b0e38f 100644--- a/src/core/page-state/tags.ts+++ b/src/core/page-state/tags.ts@@ -20,3 +20,18 @@ export async function mutatePageTag(engine: BrainEngine, key: PageKey, tag: stri}});}++/**+ * #5984: addTag for many tags of one page the caller wrote in this transaction+ * (its id from that write, its page guard held): one statement with the same+ * claim rules (an explicit add claims the tag; a frontmatter claim only adopts+ * an unclaimed legacy row).+ */+export async function addPageTags(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number, tags: readonly string[], tagSource?: 'frontmatter'): Promise<void> {+ if (!tags.length) return;+ await engine.executeRaw(tagSource === 'frontmatter'+ ? `INSERT INTO tags(page_id,tag,tag_source) SELECT $1,t,'frontmatter' FROM (SELECT DISTINCT unnest($2::text[]) AS t) u+ ON CONFLICT (page_id,tag) DO UPDATE SET tag_source = 'frontmatter' WHERE tags.tag_source IS NULL`+ : `INSERT INTO tags(page_id,tag,tag_source) SELECT $1,t,'added' FROM (SELECT DISTINCT unnest($2::text[]) AS t) u+ ON CONFLICT (page_id,tag) DO UPDATE SET tag_source = 'added'`, [pageId, [...tags]]);+}diff --git a/src/core/page-state/types.ts b/src/core/page-state/types.tsindex 36f6e731c1..f9e48ca3af 100644--- a/src/core/page-state/types.ts+++ b/src/core/page-state/types.ts@@ -9,9 +9,24 @@ export interface PageMutationPrecondition {export interface PageWriteOptions extends PageMutationPrecondition {sourceId?: string;allowEmptyOverwrite?: boolean;+ /**+ * #5984: inside a page transaction, write in that transaction instead of a+ * savepoint (one round trip less); a failure then aborts the transaction.+ */+ inline?: boolean;+ /**+ * #5984: stamps the page's contextual retrieval state in the same statement,+ * as `updatePageContextualRetrievalState` would right after it. Not for the+ * `none` tier, whose stamp also clears tier vectors.+ */+ contextualRetrieval?: { mode: string; corpusGeneration: string | null };}-export interface PageKey { sourceId: string; slug: string }+export interface PageKey {+ sourceId: string; slug: string;+ /** #5984: the source incarnation the caller already verified; lets a page lock send its source read with the guard statements. */+ incarnation?: string;+}export interface PageSnapshotOptions extends GetPageOpts {/** Exact slug wins; only follow a source-scoped alias when explicitly requested. */resolveAlias?: boolean;diff --git a/src/core/persistence/authority.ts b/src/core/persistence/authority.tsindex 4f9b7a4516..760f5c414d 100644--- a/src/core/persistence/authority.ts+++ b/src/core/persistence/authority.ts@@ -76,6 +76,29 @@ export async function submissionAuthority(ctx: OperationContext, operation: strireturn a;}+/** #5984: one local-writer read per transaction; a FOR SHARE read also answers a plain one. */+function localWriterRow(engine: SqlEngine, id: string, lock: boolean) {+ const key = `local-writer:${id}`;+ return 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${lock ? ' FOR SHARE' : ''}`, [id]));+}+/** #5984: one membership read per source per transaction; a FOR SHARE read also answers a plain one. */+function sourceMembership(engine: SqlEngine, sourceId: string, lock: boolean) {+ return transactionMemo(engine, lock ? [`source-membership:${sourceId}:share`] : [`source-membership:${sourceId}`, `source-membership:${sourceId}:share`],+ () => engine.executeRaw<{ incarnation: string; archived: boolean }>(`SELECT incarnation,archived FROM sources WHERE id=$1${lock ? ' FOR SHARE' : ''}`, [sourceId]));+}+/**+ * #5984: the reads `authorizeStoredRequest` shares across the rows of one+ * transaction (each source's membership, each local writer), as calls a+ * caller pipelines; the rows' own checks then answer them from the memo.+ */+export function storedAuthorizationReads(engine: SqlEngine, rows: readonly WriteRequest[], lock = false): Array<() => Promise<unknown>> {+ const sources = [...new Set(rows.map(row => row.source_id))];+ const writers = [...new Set(rows.flatMap(row => ['local_cli', 'local_stdio'].includes(row.authority?.principal?.kind) ? [row.authority.principal.id] : []))];+ return [...sources.map(id => () => sourceMembership(engine, id, lock)), ...writers.map(id => () => localWriterRow(engine, id, lock))];+}+/** Caller holds source guards first. FOR SHARE serializes publication against revocation. */export async function authorizeWrite(engine: SqlEngine, a: WriteAuthority, operation: string, slug: string, lock = false): Promise<void> {if (a.version !== 1 || !a.principal || !a.sourceId || !a.sourceIncarnation) deny('Missing durable write authority.');@@ -111,10 +134,7 @@ export async function authorizeWrite(engine: SqlEngine, a: WriteAuthority, opera}if (a.principal.kind === 'local_cli' || a.principal.kind === 'local_stdio') {// #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 [row] = await localWriterRow(engine, a.principal.id, lock);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;@@ -128,8 +148,7 @@ export async function authorizeWrite(engine: SqlEngine, a: WriteAuthority, opera/** `pageVisibility: false` is for a caller that checks the target's visibility itself after locking the page. */export async function authorizeStoredRequest(engine: SqlEngine, row: WriteRequest, lock = false, opts: { pageVisibility?: boolean } = {}): Promise<void> {// #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]));+ const [source] = await sourceMembership(engine, row.source_id, lock);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.tsindex ea58e2e5ea..ab5727edb5 100644--- a/src/core/persistence/canonical-projections.ts+++ b/src/core/persistence/canonical-projections.ts@@ -358,14 +358,15 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par() => 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]),];+ // The timeline rows are independent of the fact and take rows, so they ride in the first pipeline.if (factRows.length) {- await pipelined(tx, [expireFacts]);+ await pipelined(tx, [expireFacts, ...timelineRows]);await tx.insertFacts(factRows, { source_id: sourceId }); // gbrain-allow-direct-insert: canonical fence projection shares the journal publication transactionawait pipelined(tx, [...factFields, checkTakes, dropTakes]);- } else await pipelined(tx, [expireFacts, checkTakes, dropTakes]);+ } else await pipelined(tx, [expireFacts, checkTakes, dropTakes, ...timelineRows]);if (takes.length) {await tx.addTakesBatch(takes.map(t => takesPreparation.toCanonicalBatchInput(id, t)));- await pipelined(tx, [...resolveTakes, ...timelineRows]);- } else await pipelined(tx, timelineRows);+ await pipelined(tx, resolveTakes);+ }};}diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex 193b88df4e..f1f7478e84 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -598,7 +598,7 @@ export class PersistenceConsumer {const rows = [row, ...followers];for (const member of rows) this.executing.add(member.id);try {- return await executeClaimedGroup(this.engine, rows, { hostId: this.hostId, lane, prepare: member => this.prepare(this.engine, member, this.config),+ return await executeClaimedGroup(this.engine, rows, { hostId: this.hostId, lane, prepare: (member, engine) => this.prepare(engine, member, this.config),lease: this.leaseTiming(),leftRunning: (work, blocksRoot) => {const settled = this.keepUntilSettled(work);diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.tsindex be05a78c43..16e8e5f847 100644--- a/src/core/persistence/group-publish.ts+++ b/src/core/persistence/group-publish.ts@@ -28,7 +28,7 @@*/import type { BrainEngine } from '../engine.ts';import { OperationError } from '../ops/contract.ts';-import { authorizeStoredRequest } from './authority.ts';+import { authorizeStoredRequest, storedAuthorizationReads } from './authority.ts';import { localHostId } from './identity.ts';import { acquireWorktree, acquireWorktreeShared, getWorktreeBinding, guardOwnership } from './ownership.ts';import { awaitLaneBegin, awaitLaneTurn, LaneAbort, laneApplyBegin, laneClaimed, laneFinished, stepDownLanes, type LaneState } from './sync-lanes.ts';@@ -104,6 +104,45 @@ function groupReads(tx: BrainEngine): BrainEngine {} });}+/**+ * #5984: reads a claimed group's preparation repeats for every member and that+ * publication checks again inside the group transaction (the local writer, the+ * source binding and root, the coordinator switch, the shared skill packs), plus+ * the source's own row. Plain reads only; a locking read is never answered here.+ */+const STABLE_IN_PREPARATION = new Set([+ 'SELECT lane,revoked_at,grant_ceiling FROM persistence_local_writers WHERE id=$1::uuid',+ 'SELECT s.source_id,s.source_incarnation,s.worktree_id,s.relative_path, s.topology_generation::text AS topology_generation,w.owner_host_id,w.owner_epoch::text AS owner_epoch,w.state, h.local_path,h.coordination_path FROM persistence_source_bindings s JOIN persistence_worktrees w ON w.id=s.worktree_id LEFT JOIN persistence_host_bindings h ON h.worktree_id=w.id AND h.host_id=$2::uuid WHERE s.source_id=$1',+ 'SELECT local_path FROM sources WHERE id=$1',+ 'SELECT enabled FROM persistence_brain WHERE singleton=1',+ "SELECT to_regclass('shared_skill_packs') IS NOT NULL AS present",+ 'SELECT p.source_id,p.source_incarnation,s.local_path AS source_root, h.local_path AS worktree_root,b.relative_path FROM shared_skill_packs p JOIN sources s ON s.id=p.source_id AND s.incarnation=p.source_incarnation LEFT JOIN persistence_source_bindings b ON b.source_id=p.source_id AND b.source_incarnation=p.source_incarnation LEFT JOIN persistence_host_bindings h ON h.worktree_id=b.worktree_id AND h.host_id=$1::uuid',+ 'SELECT id, name, local_path, last_commit, last_sync_at, config, created_at, contextual_retrieval_mode, trust_frontmatter_overrides FROM sources WHERE id = $1',+]);+/**+ * #5984: the engine a claimed group's members are prepared with. The reads+ * above and config values (`getConfig`, `getAllConfig`) are answered once for+ * the whole preparation, as if every member were prepared at the same moment;+ * publication re-checks what it relies on under its locks. It lives only for+ * one group's preparation; a failed read is not kept.+ */+function preparationReads(engine: BrainEngine): BrainEngine {+ const reads = new Map<string, Promise<unknown>>();+ const once = <T>(id: string, read: () => Promise<T>): Promise<T> => {+ let value = reads.get(id) as Promise<T> | undefined;+ if (!value) { value = read(); reads.set(id, value); value.catch(() => reads.delete(id)); }+ return value;+ };+ return new Proxy(engine, { get(target, key) {+ if (key === 'executeRaw') return (sql: string, params?: unknown[], opts?: { signal?: AbortSignal }) =>+ STABLE_IN_PREPARATION.has(flat(sql)) && !opts?.signal ? once(JSON.stringify([flat(sql), params ?? null]), () => target.executeRaw(sql, params, opts)) : target.executeRaw(sql, params, opts);+ if (key === 'getConfig') return (name: string) => once(`config:${name}`, () => target.getConfig(name));+ if (key === 'getAllConfig') return () => once('config:*', () => target.getAllConfig()).then(all => ({ ...all }));+ const value = Reflect.get(target, key, target);+ return typeof value === 'function' ? value.bind(target) : value;+ } });+}+/** Test seams around a group's commit and its rollback. */export interface GroupHooks {beforeCommit?(rows: WriteRequest[]): Promise<void>;@@ -156,46 +195,73 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], prtimed.apply?.end(rows.length);if (lane) timed.apply = laneApplyBegin(lane);const tx = groupReads(transaction);- await declareDurablePersistence(tx);- const live = await guardOwnership(tx, head, hostId);- if (String(live?.owner_epoch) !== String(binding.owner_epoch)) throw new OperationError('owner_unavailable', 'Owner epoch changed before publication.', 'Inspect the source owner with gbrain sources writer status; do not claim or transfer the source to push this write.');+ // #5984: the transaction's fixed reads and locks go out as one pipeline, in the order they always took:+ // protocol, ownership guard, page guards, then the members' shared authorization reads (answered from the memo below).+ const owned = async () => {+ const live = await guardOwnership(tx, head, hostId);+ if (String(live?.owner_epoch) !== String(binding.owner_epoch)) throw new OperationError('owner_unavailable', 'Owner epoch changed before publication.', 'Inspect the source owner with gbrain sources writer status; do not claim or transfer the source to push this write.');+ };+ const keys = rows.flatMap((row, i) => [{ sourceId: row.source_id, slug: row.slug, incarnation: row.source_incarnation },+ ...(prepared[i]!.additionalPageKeys ?? []).map(key => key.sourceId === row.source_id ? { ...key, incarnation: row.source_incarnation } : key)]);+ const locked = () => [() => tx.lockPageKeys(keys), ...storedAuthorizationReads(tx, rows, true)];+ let ready: Promise<unknown>;if (recorded.size) {+ await pipelined(tx, [() => declareDurablePersistence(tx), owned]);// A published file needs recovery even if this transaction rolls back; claims are verified first.const members = [...recorded.values()].map(member => member.row);const started = await tx.executeRaw(`UPDATE persistence_requests r SET publication_started=true FROM unnest($1::uuid[],$2::uuid[]) AS t(id,token)WHERE r.id=t.id AND r.execution_token=t.token AND r.state='running' RETURNING r.id`, [members.map(row => row.id), members.map(row => row.execution_token)]);if (started.length !== members.length) throw new OperationError('write_claim_lost', 'Execution claim changed before publication.', 'Another worker holds the request; inspect it rather than resubmitting.');if (await sourceMirrorReadOnly(tx, head.source_id, true)) throw new OperationError('source_changed', 'The source became a read-only mirror after this write was prepared.', 'The members publish one at a time.');- }- await tx.lockPageKeys(rows.flatMap((row, i) => [{ sourceId: row.source_id, slug: row.slug }, ...(prepared[i]!.additionalPageKeys ?? [])]));+ ready = pipelined(tx, locked());+ } else ready = pipelined(tx, [() => declareDurablePersistence(tx), owned, ...locked()]);+ // The coordinated write's settings statement follows that pipeline. When the pipeline fails first, the+ // transaction reports that failure (postgres.js names the cause of a 25P02 abort), not the settings statement's abort.+ ready.catch(() => undefined);const outcomes: Record<string, unknown>[] = [];// One coordinated write for the group; each member is the attributed actor of what it writes.await withCoordinatedWrite(tx, [head.source_id], async () => {+ await ready;+ // The previous member's effects (rows no attribution or page check depends on) go out with the next member's checks.+ let effects: (() => Promise<void>) | null = null;for (let i = 0; i < rows.length; i++) {- const row = rows[i]!, member = prepared[i]!, file = recorded.get(i);- await authorizeStoredRequest(tx, row, true, { pageVisibility: false });- if (!syncMember(row)) await assertKnowledgePublicationAllowed(tx, row, member.file);- const snapshot = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });- await authorizePageVisibility(tx, row.authority, row.slug);- if ((snapshot?.page.id ?? null) !== row.page_id) throw new OperationError('page_identity_changed', 'The accepted page was deleted or recreated.', 'Read the page again and submit a new intent with a new request_id.');- await assertUnboundPublication(tx, row, snapshot?.page.source_path);- 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);+ const row = rows[i]!, member = prepared[i]!, file = recorded.get(i), sync = syncMember(row), previous = effects;+ // #5984: a member's checks and reads are pipelined and run in their usual order, so the first failing one is reported.+ // A sync member validates alongside (read-only checks); a member that publishes a file sets its attribution after the file.+ const [, , , snapshot] = await pipelined(tx, [+ async () => { await previous?.(); },+ () => authorizeStoredRequest(tx, row, true, { pageVisibility: false }),+ async () => { if (!sync) await assertKnowledgePublicationAllowed(tx, row, member.file); },+ async () => {+ const snapshot = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });+ await authorizePageVisibility(tx, row.authority, row.slug);+ if ((snapshot?.page.id ?? null) !== row.page_id) throw new OperationError('page_identity_changed', 'The accepted page was deleted or recreated.', 'Read the page again and submit a new intent with a new request_id.');+ await assertUnboundPublication(tx, row, snapshot?.page.source_path);+ 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.');+ return snapshot;+ },+ async () => { if (sync) await member.validate?.(tx); },+ async () => { if (!file) await setMemberAttribution(tx, requestAttribution(row)); },+ ]) as [unknown, unknown, unknown, Awaited<ReturnType<BrainEngine['readPageSnapshot']>>];+ if (!sync) await member.validate?.(tx);if (file) {if (persistenceFileHash(file.record.path) !== file.record.beforeHash) throw new OperationError('unexpected_file_bytes', 'The canonical file changed during preparation.', 'The members publish one at a time.');await withFilesystemPublication([file.record.root], async () => publishPersistenceFile(member.file!, file.record.staging?.publication?.path));+ await setMemberAttribution(tx, requestAttribution(row));}- await setMemberAttribution(tx, requestAttribution(row));member.postimage = undefined;const outcome = await member.apply(tx, snapshot);await classifyUnboundPage(tx, row);if (member.databaseOnlyReason === 'mirror_read_only') await classifyMirrorPage(tx, row);const final = await publicationPostimage(tx, row, member);decoratePublicationOutcome(row, member, outcome, final, file ? 1 : 0, false);- await recordPublicationFenceTrend(tx, row, outcome);- await queuePublicationEffects(tx, row, final, outcome, member, { deferBatchReconcile: true });+ effects = async () => {+ await recordPublicationFenceTrend(tx, row, outcome);+ await queuePublicationEffects(tx, row, final, outcome, member, { deferBatchReconcile: true });+ };outcomes.push(outcome);}+ await effects?.();}, requestAttribution(head));// #5984 lanes: applied concurrently, committed in manifest order.if (lane) { timed.apply?.turn(); await awaitLaneTurn(tx, lane, rows); timed.apply?.turned(); }@@ -315,7 +381,8 @@ export async function completeGroup(tx: BrainEngine, rows: WriteRequest[], outcoexport interface GroupExecution {/** #5984 lanes: the open lane run this group belongs to in this process. */lane?: LaneState | null;- prepare(row: WriteRequest): Promise<PreparedMutation>;+ /** `engine` answers the members' repeated preparation reads once (see preparationReads). */+ prepare(row: WriteRequest, engine: BrainEngine): Promise<PreparedMutation>;settled(row: WriteRequest): void;hostId: string;hooks?: GroupHooks;@@ -347,12 +414,13 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteRequesif (run.lane) laneClaimed(run.lane, rows);try {const prepared: Array<{ ok: PreparedMutation } | { error: unknown }> = new Array(rows.length);+ const reads = preparationReads(engine);// A put_pages group prepares all of its (at most PAGE_BATCH_GROUP_MAX) pages at once.const width = publicationGroupKey(rows[0]!)?.startsWith('batch:') ? PAGE_BATCH_GROUP_MAX : 4;const preparing = (async () => {for (let start = 0; start < rows.length; start += width) {await Promise.all(rows.slice(start, start + width).map(async (row, offset) => {- try { prepared[start + offset] = { ok: await run.prepare(row) }; } catch (error) { prepared[start + offset] = { error }; }+ try { prepared[start + offset] = { ok: await run.prepare(row, reads) }; } catch (error) { prepared[start + offset] = { error }; }}));}})();diff --git a/src/core/persistence/ownership.ts b/src/core/persistence/ownership.tsindex 8092a77876..7f55a2923c 100644--- a/src/core/persistence/ownership.ts+++ b/src/core/persistence/ownership.ts@@ -9,6 +9,7 @@ import { discoverGitRoot } from '../sync-git.ts';import { cliOptsToProgressOptions, getCliOptions } from '../cli-options.ts';import { createProgress, type ProgressOptions } from '../progress.ts';import { digest, sha256 } from './digest.ts';+import { pipelined } from '../page-state/transactions.ts';import { localHostId, persistenceHome } from './identity.ts';import type { SqlEngine, WriteRequest } from './model.ts';import { acquireNativeLock, tryAcquireNativeLock, type NativeLockHandle } from './native-lock.ts';@@ -181,9 +182,12 @@ export async function probeWorktreeWriter(binding: WorktreeBinding, engine?: Bra}export async function guardOwnership(tx: SqlEngine, row: WriteRequest, hostId: string): Promise<WorktreeBinding | null> {if (!row.worktree_id) return null;- const [owner] = await tx.executeRaw<{ owner_host_id: string; owner_epoch: string | number; state: string }>(- 'SELECT owner_host_id,owner_epoch,state FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE', [row.worktree_id]);- const binding = await getWorktreeBinding(tx, row.source_id, hostId);+ // #5984: both reads in one pipeline (the worktree row is locked first, as before).+ const [[owner], binding] = await pipelined({ kind: (tx as { kind?: string }).kind ?? '' }, [+ () => tx.executeRaw<{ owner_host_id: string; owner_epoch: string | number; state: string }>(+ 'SELECT owner_host_id,owner_epoch,state FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE', [row.worktree_id]),+ () => getWorktreeBinding(tx, row.source_id, hostId),+ ]) as [Array<{ owner_host_id: string; owner_epoch: string | number; state: string }>, WorktreeBinding | null];if (!owner || !binding || binding.worktree_id !== row.worktree_id || binding.source_incarnation !== row.source_incarnation ||owner.owner_host_id !== hostId || owner.state !== 'active' || String(binding.topology_generation) !== String(row.topology_generation)) {throw opError('owner_unavailable', 'The accepted worktree ownership or source topology changed.',diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex ef6da2f984..f80d3f4682 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -101,6 +101,30 @@ function sharedSyncValidation(tx: BrainEngine, key: string, run: () => Promise<{if (!shared) { shared = run(); byKey.set(key, shared); }return shared;}+/**+ * #5984: the source-wide part of sync validation as one pipeline: coordinator switch, configured root,+ * cursor, window predecessor and owner epoch, each checked in that order. The rows stay locked FOR SHARE.+ */+async function sourceSyncChecks(tx: BrainEngine, row: WriteRequest, p: SyncIntent, root: string, after: string | null) {+ const [, , held] = await pipelined(tx, [+ () => assertManagedSyncActive(tx, true),+ async () => {+ const [configuredSource] = await tx.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1 FOR SHARE', [row.source_id]);+ assertConfiguredSyncRoot(root, configuredSource?.local_path ?? null);+ },+ () => readSyncCursorFence(tx, p.cursorKey),+ async () => {+ if (after && !await windowPredecessorAllows(tx, row)) throw syncPublicationRefusal('revision_conflict', 'An earlier page of this sync did not commit.', row, p,+ `Request ${row.request_id} was admitted ahead of request ${after} of the same sync run, which did not commit, so this page must not publish after it.`);+ },+ async () => {+ const current = await getWorktreeBinding(tx, row.source_id);+ if (!current || String(current.owner_epoch) !== p.ownerEpoch) throw syncPublicationRefusal('owner_unavailable', 'The accepted sync owner epoch changed.', row, p,+ `The owner epoch of ${row.source_id} changed after this sync was admitted. Do not claim or transfer the source to repair content.`, true);+ },+ ]) as [unknown, unknown, Awaited<ReturnType<typeof readSyncCursorFence>>];+ return held ?? null;+}/*** Read-only: the receipt itself for the local CLI writer's own request;* another principal's request is inspected on the owner instead.@@ -266,33 +290,31 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write`Page ${moved.slug}, which this file was renamed from, changed or was deleted after the sync was admitted.`);}};+ // #5984: validation's reads are pipelined; each check runs in the order it always did, so the first failing one is reported.const validate = async (tx: BrainEngine) => {const after = windowPredecessor(row);- const cursor = await sharedSyncValidation(tx, `${row.source_id}\0${p.cursorKey}\0${p.ownerEpoch}\0${root}\0${after ?? ''}`, async () => {- await assertManagedSyncActive(tx, true);- const [configuredSource] = await tx.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1 FOR SHARE', [row.source_id]);- assertConfiguredSyncRoot(root, configuredSource?.local_path ?? null);- const held = await readSyncCursorFence(tx, p.cursorKey);- if (after && !await windowPredecessorAllows(tx, row)) throw syncPublicationRefusal('revision_conflict', 'An earlier page of this sync did not commit.', row, p,- `Request ${row.request_id} was admitted ahead of request ${after} of the same sync run, which did not commit, so this page must not publish after it.`);- const current = await getWorktreeBinding(tx, row.source_id);- if (!current || String(current.owner_epoch) !== p.ownerEpoch) throw syncPublicationRefusal('owner_unavailable', 'The accepted sync owner epoch changed.', row, p,- `The owner epoch of ${row.source_id} changed after this sync was admitted. Do not claim or transfer the source to repair content.`, true);- return held ?? null;- });- await validateSyncAuthority(tx, p.syncAuthority, row.slug);- if (cursor && (cursor.run_id !== p.runId || (cursor.request_id !== row.request_id && !cursor.group?.includes(row.request_id)))) throw syncPublicationRefusal('revision_conflict', 'The accepted sync cursor changed before publication.', row, p,- `Another sync run of ${row.source_id} replaced the cursor this request belongs to.`);- if (p.kind !== 'managed_sync_checkpoint') await assertKnowledgePublicationAllowed(tx, row,- p.path === null ? undefined : { root, path: join(root, p.path) });- if (p.path !== null && syncRawHash(root, p.path) !== p.rawHash) throw syncPublicationRefusal('source_changed', 'The imported file changed after sync admission.', row, p,- `The file of ${row.slug} changed on disk after this sync was admitted; review the change and commit it.`);- if (origin && originContext) {- assertSyncEntryOrigin(originContext, origin);- await assertSyncPageOrigin(tx, row.source_id, origin.sourcePath, originPageId, p.kind === 'managed_sync_delete', originScope);- if (moved) await assertSyncPageOrigin(tx, row.source_id, moved.sourcePath, moved.pageId, true, originScope);- await assertRenameSource(tx);- }+ const shared = sharedSyncValidation(tx, `${row.source_id}\0${p.cursorKey}\0${p.ownerEpoch}\0${root}\0${after ?? ''}`, () => sourceSyncChecks(tx, row, p, root, after));+ await pipelined(tx, [+ () => shared,+ () => validateSyncAuthority(tx, p.syncAuthority, row.slug),+ async () => {+ const cursor = await shared;+ if (cursor && (cursor.run_id !== p.runId || (cursor.request_id !== row.request_id && !cursor.group?.includes(row.request_id)))) throw syncPublicationRefusal('revision_conflict', 'The accepted sync cursor changed before publication.', row, p,+ `Another sync run of ${row.source_id} replaced the cursor this request belongs to.`);+ },+ async () => { if (p.kind !== 'managed_sync_checkpoint') await assertKnowledgePublicationAllowed(tx, row, p.path === null ? undefined : { root, path: join(root, p.path) }); },+ async () => {+ if (p.path !== null && syncRawHash(root, p.path) !== p.rawHash) throw syncPublicationRefusal('source_changed', 'The imported file changed after sync admission.', row, p,+ `The file of ${row.slug} changed on disk after this sync was admitted; review the change and commit it.`);+ },+ async () => {+ if (!origin || !originContext) return;+ assertSyncEntryOrigin(originContext, origin);+ await assertSyncPageOrigin(tx, row.source_id, origin.sourcePath, originPageId, p.kind === 'managed_sync_delete', originScope);+ },+ async () => { if (origin && originContext && moved) await assertSyncPageOrigin(tx, row.source_id, moved.sourcePath, moved.pageId, true, originScope); },+ async () => { if (origin && originContext) await assertRenameSource(tx); },+ ]);if (p.companyApproval) {const [source] = await tx.executeRaw<{ config: unknown }>('SELECT config FROM sources WHERE id=$1', [row.source_id]);const policy = companyBrainProfile(source?.config);@@ -480,16 +502,17 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write}// A moved page is versioned from its own (rename source) read.await applied.apply(tx, renamed ? undefined : preimage);- // 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]);+ // Hash no-ops still repair a missing physical origin under the same guard (a page write records it itself).+ if (applied.noop) 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]);// #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);+ // The projections, the text seal, the hold and the provenance touch separate rows; their pipelines run together.await pipelined(tx, [+ async () => { if (!applied.noop || p.companyApproval) await project(tx, final?.page.id); },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!,diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 9a4156b3bd..9c9c9783a2 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -1216,14 +1216,15 @@ export class PGLiteEngine implements BrainEngine {async putPage(slug: string, page: PageInput, opts?: PageWriteOptions): Promise<Page> {slug = validateSlug(slug);- return this.transaction(async tx => {+ const write = async (tx: BrainEngine) => {const sourceId = opts?.sourceId ?? 'default';await tx.lockPageKeys([{ sourceId, slug }]);if (opts?.expectedRevision !== undefined || opts?.force !== undefined) {assertPageRevision(await tx.readPageSnapshot(slug, { sourceId, includeDeleted: true }), opts);}return pagesImpl.putPage((tx as PGLiteEngine).engineSql, slug, page, opts, (s, src) => tx.getPage(s, { sourceId: src }));- });+ };+ return opts?.inline && this._pageTransaction ? write(this) : this.transaction(write);}async deletePage(slug: string, opts?: { sourceId?: string }): Promise<void> {@@ -1759,13 +1760,13 @@ 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; sealChunkerVersion?: number } & BatchOpts): Promise<void> {+ async upsertChunks(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string; sealChunkerVersion?: number; pageId?: 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; sealChunkerVersion?: number }): Promise<void> {+ private async _upsertChunksOnce(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string; sealChunkerVersion?: number; pageId?: number }): Promise<void> {return chunksImpl.upsertChunksOnce(this.engineSql, {lockPageKeys: (keys) => this.lockPageKeys(keys),readPageSnapshot: (pageSlug, snapshotOpts) => this.readPageSnapshot(pageSlug, snapshotOpts),@@ -2749,7 +2750,8 @@ export class PGLiteEngine implements BrainEngine {return readAliases(this.executeRaw.bind(this), aliasNorms, opts);}- async setPageAliases(slug: string, sourceId: string, aliasNorms: string[]): Promise<void> {+ async setPageAliases(slug: string, sourceId: string, aliasNorms: string[], opts?: { inline?: boolean }): Promise<void> {+ if (opts?.inline && this._pageTransaction) return pagesImpl.setPageAliases(this.engineSql, this, slug, sourceId, aliasNorms);return this.transaction(tx => pagesImpl.setPageAliases((tx as PGLiteEngine).engineSql, tx, slug, sourceId, aliasNorms));}diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 9bbfc2836f..38015df77c 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -742,14 +742,15 @@ export class PostgresEngine implements BrainEngine {async putPage(slug: string, page: PageInput, opts?: PageWriteOptions): Promise<Page> {slug = validateSlug(slug);- return this.transaction(async tx => {+ const write = async (tx: BrainEngine) => {const sourceId = opts?.sourceId ?? 'default';await tx.lockPageKeys([{ sourceId, slug }]);if (opts?.expectedRevision !== undefined || opts?.force !== undefined) {assertPageRevision(await tx.readPageSnapshot(slug, { sourceId, includeDeleted: true }), opts);}return pagesImpl.putPage((tx as PostgresEngine).engineSql, slug, page, opts);- });+ };+ return opts?.inline && this._pageTransaction ? write(this) : this.transaction(write);}async deletePage(slug: string, opts?: { sourceId?: string }): Promise<void> {@@ -1455,13 +1456,13 @@ 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; sealChunkerVersion?: number } & BatchOpts): Promise<void> {+ async upsertChunks(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string; sealChunkerVersion?: number; pageId?: 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; sealChunkerVersion?: number }): Promise<void> {+ private async _upsertChunksOnce(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string; sealChunkerVersion?: number; pageId?: number }): Promise<void> {return chunksImpl.upsertChunksOnce(this.engineSql, {lockPageKeys: (keys) => this.lockPageKeys(keys),readPageSnapshot: (pageSlug, snapshotOpts) => this.readPageSnapshot(pageSlug, snapshotOpts),@@ -2492,7 +2493,8 @@ export class PostgresEngine implements BrainEngine {return readAliases(this.executeRaw.bind(this), aliasNorms, opts);}- async setPageAliases(slug: string, sourceId: string, aliasNorms: string[]): Promise<void> {+ async setPageAliases(slug: string, sourceId: string, aliasNorms: string[], opts?: { inline?: boolean }): Promise<void> {+ if (opts?.inline && this._pageTransaction) return pagesImpl.setPageAliases(this.engineSql, this, slug, sourceId, aliasNorms);return this.transaction(tx => pagesImpl.setPageAliases((tx as PostgresEngine).engineSql, tx, slug, sourceId, aliasNorms));}