Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(#6007): fewer database round trips per published write; put_pages admits through the group admission

garrytanf238377e88fd
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index a6ae453fbe..096e1d2d47 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -26,7 +26,7 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers
- `src/core/persistence/admission-retry.ts` — bounded retries for database-confirmed admission transaction aborts. Each retry reuses the UUID and normalized intent, rechecks guarded authority and reserves quota only on commitment. Standalone journal admission uses 100ms lock waits within the five-second retry budget to retain queue position behind short counter transactions; backoff occurs after rollback releases the connection so counter contention leaves pool capacity for reads. Ambiguous connection/commit errors are never classified as confirmed rollback. Real counter-lock, sustained-queue progress, read-capacity and after-insert rollback tests live in `test/persistence-journal.test.ts`. Withdrawal retries wrap its whole source-exclusive transaction with its existing lock policy; `admitWriteInTransaction` never backs off inside an existing unit of work. `test/persistence-withdrawal-retry.test.ts` verifies guard release, complete rollback and bounded contention.
-- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `CLAIMABLE_WRITE_SQL` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms per page). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`.
+- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write first and runs its due root refresh plus recovery and expiry scans after the claim, while the claimed write prepares (scans run at most once per poll interval on these ticks; the claim predicate already excludes recovering roots); explicit, timer and idle-probe ticks always scan before claiming. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `CLAIMABLE_WRITE_SQL` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms per page). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`.
- `src/core/persistence/health.ts` — pure advisory age/reason/action policy shared by receipts and trusted diagnostics. The nested public contract is optional, validated and explicitly allowlisted; thresholds are 30/120 seconds and polls 1/5/30 seconds. The journal batches at most 100 authorized receipts into one projected root query with a 500ms caller budget, retaining one in-flight query per engine until settlement. Database-only pending lookups use a partial source-incarnation/sequence index shared by both engines. Synchronous service reads coalesce only for the same request ID, retain at most four unresolved reads per engine until settlement, and permit cancellation only by the read's initiating waiter or shutdown. No health observation changes authority or durable state. Real authenticated legacy/OAuth recovery and the synthetic three-client import live in `test/e2e/persistence-http-liveness.test.ts`.
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index bbfed08f5c..fa4cd41c47 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -47,7 +47,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/ops/sources.ts` — `sources_remove` is confined to the caller's WRITE authority via `assertSourceInCallerWriteScope(ctx, id)` (context.ts): an untrusted caller may hard-remove only its own write source; a federated read grant naming a source does not make it removable; any other id answers `OperationError('not_found', 'Unknown source: <id>')`, byte-identical to a nonexistent source so the error is not an existence oracle. `sources_status` keeps the read-scope helper (`assertSourceInCallerScope`), so a federated grant can still diagnose a source it cannot remove. Trusted local CLI keeps the full operator view. Over HTTP every client carries a write source (registration default `default`) and its own `oauth_clients.source_id` row FK-RESTRICTs removing that source, so hard removal is effectively an operator action (`gbrain sources remove`); a source a remote `sources_admin` caller just created via `sources_add` stays outside its authority until the operator rescopes the client. There is no `sources_archive` op — archive lives in the CLI (`gbrain sources archive`). Pinned by `test/sources-mcp.test.ts` (federated-read-only id → not_found while status still answers; write-source id → removed; unbound → any; local → any; `remote: undefined` fail-closed) and `test/e2e/sources-remote-mcp.test.ts` (real server: not_found before AND after a read-grant widen; operator CLI completes; rescoping `--source` moves the authority).
-- `src/core/page-state/` — Canonical page concurrency foundation shared by both engines. `schema.ts` (migration 150) adds source incarnation UUIDs, logical page revisions, text-projection revisions, and persistent guards for absent pages. `guards.ts` locks sorted sources then page identities in an existing transaction; callers lock sources before authority/request/fact rows. `snapshot.ts` reads page/tags/withdrawals in one MVCC statement and applies withdrawals using database-normalized text. `transactions.ts` makes helper transaction APIs compose through savepoints. `versions.ts` records the complete canonical snapshot; `rename-alias.ts` records `slug_aliases(old -> new)` inside both engines' `updateSlug` transaction, repoints aliases that named the old slug and drops one spelled like the new slug; `moveSlugBindings` moves the page's facts (`entity_slug`, `source_markdown_slug`) and `page_aliases` in the same transaction, letting a purged page's leftovers at the new slug yield (`test/rename-slug-alias.test.ts`); `materialize.ts` persists only verified canonical overlay bytes without another logical revision. `types.ts` defines revision preconditions: missing revision is create-only, explicit force overwrites. Plain legacy `putPage` calls keep compatibility until their owning operation adopts the managed write protocol. `projection-schema.ts` (migration 153) invalidates unverified prior projections once and queues durable work; `projections.ts` rebuilds Markdown without a worktree/provider and installs only matching canonical revisions. Embedding installs also compare exact chunk identities/text. Source importers seal code/image projections; all read arms hide unsealed projections.
+- `src/core/page-state/` — Canonical page concurrency foundation shared by both engines. `schema.ts` (migration 150) adds source incarnation UUIDs, logical page revisions, text-projection revisions, and persistent guards for absent pages. `guards.ts` locks sorted sources then page identities in an existing transaction, in three statements for any key set (sources share-locked in key order before any guard row is inserted, then guards, then pages rows); a transaction or savepoint never re-acquires a key it holds, which covers absent pages because the only pages INSERT runs after `putPage` takes the same guard (`test/e2e/page-guards-postgres.test.ts`); callers lock sources before authority/request/fact rows. `snapshot.ts` reads page/tags/withdrawals in one MVCC statement and applies withdrawals using database-normalized text. `transactions.ts` makes helper transaction APIs compose through savepoints. `versions.ts` records the complete canonical snapshot; `rename-alias.ts` records `slug_aliases(old -> new)` inside both engines' `updateSlug` transaction, repoints aliases that named the old slug and drops one spelled like the new slug; `moveSlugBindings` moves the page's facts (`entity_slug`, `source_markdown_slug`) and `page_aliases` in the same transaction, letting a purged page's leftovers at the new slug yield (`test/rename-slug-alias.test.ts`); `materialize.ts` persists only verified canonical overlay bytes without another logical revision. `types.ts` defines revision preconditions: missing revision is create-only, explicit force overwrites. Plain legacy `putPage` calls keep compatibility until their owning operation adopts the managed write protocol. `projection-schema.ts` (migration 153) invalidates unverified prior projections once and queues durable work; `projections.ts` rebuilds Markdown without a worktree/provider and installs only matching canonical revisions. Embedding installs also compare exact chunk identities/text. Source importers seal code/image projections; all read arms hide unsealed projections.
- `src/core/page-state/projections.ts` — captures canonical revision, source incarnation, page identity, the complete raw chunk inventory and resolved indexing inputs before preparing derived work. Embedding reads require a current text seal; healing/rebuild capture can explicitly include unsealed pages. Projection installation compares its originating seal, chunk identities/text/source/completion state, chunker version and indexing context (including stored corpus generation) under the page guard before replacing any row. A same-revision re-chunk may replace the snapshot it actually captured; a delayed older installation cannot discard newer chunks or vectors. Rebuild also rechecks its queued job before capture so a completed job from an old listing stays completed. Chunkless healing sanitizes complete body/timeline fences before splitting, preserving withdrawn history in direct page reads while excluding it from retrieval. Tests: `page-projection-origin.test.ts`, `page-projection-vector-preservation.test.ts` (PGLite and isolated Postgres), `embed-stale-chunkless-pages.serial.test.ts` (public healing entry). Shared `markdown-chunks.ts` and `code-chunks.ts` preserve fenced code and source-language metadata. A preserving rebuild keeps a vector only when its `content_chunks.embedding_input_hash` (`src/core/embedding-input-hash.ts`) equals one recomputed from the current page, or, with no recorded hash, when the page is non-contextual and the legacy model/text-hash checks pass; a contextual chunk without provenance is nulled once. `installPageEmbeddings` records the hash in the vector's UPDATE (the plain re-embed tier by default, or the caller's `built` tier and corpus generation), and `stampEmbeddingInputs` does the same for full imports. `resealSafeChunks` re-seals a page below the safe-chunk fence from its unchanged body with no canonical write; `projectionBelowSafeFence` is its predicate. Tests add `projection-embedding-input-hash.test.ts` and `safe-chunk-reseal.test.ts`. It replaces outgoing code edges without deleting incoming edges to retained chunks and clears backfill watermarks. Failed jobs rotate with a retained diagnostic; successful drain refreshes planner statistics. `rebuildPendingPageProjections(engine, limit, { deadlineMs, now, notAfter, retryCooldown, onFailure })` (#5401) checks an injectable clock between pages, bounds a run to rows queued at or before its start (`notAfter`, cast from text in SQL so microseconds survive the driver), applies the 30 s `rebuild_failed` cooldown for the resident, and treats a lock or snapshot error as that page's failure instead of aborting the batch; `projectionBacklog` returns counts only (pending, failed, oldest age) for the drain command and the resident's `projection_status` IPC reply.
- `src/core/page-state/credential-reseal.ts` + `src/core/schema-migrations/v189-pages-credential-projection-pending.ts` + `src/commands/doctor/checks/credential-projection.ts` — the targeted re-chunk of pages indexed before the credential-safe projection. Schema migration v187 (on the first connect after upgrade) sets `text_projection_revision = NULL` on every live markdown/code page whose `compiled_truth` or `timeline` matches `-----(BEGIN|END) [A-Z ]*PRIVATE KEY-----` and upserts a `page_projection_jobs` row (reason `credential_projection`), so the current-text-projection seal withholds their old chunks from every retrieval path, local and remote (code-walk `hydrateChunks` in `search/two-pass.ts` applies the same filter). The marker literal is frozen as shipped. `credentialProjectionPending(engine, sourceIds?)` counts pending pages in active sources as `rebuildable` and `kept` (code pages with no `frontmatter.file` or `source_path`, which wait for their importer). `resealCredentialProjections` re-seals each rebuildable page from its unchanged body through `resealSafeChunks` (the `repair safe-chunks` installer), one page per transaction, with no page write, journal admission or provider call; vectors of unchanged chunk text are kept and re-chunked key chunks wait for `gbrain embed --stale`; a revision conflict counts as superseded, a failure prints the retry command and leaves the page withheld. The doctor check `credential_projection_pending` (a `WAVE_CHECKS` entry, `resolution: 'operator'`, brain category) reports `pages_pending` and `kept_pages` and warns while either is non-zero, naming `gbrain apply-migrations --yes --no-autopilot-install` (no provider calls), then `gbrain embed --stale`, and the re-import for kept code pages; a read error is `warn` with unknown health.
diff --git a/src/core/page-state/guards.ts b/src/core/page-state/guards.ts
index 1ff388223d..3cb362335a 100644
--- a/src/core/page-state/guards.ts
+++ b/src/core/page-state/guards.ts
@@ -2,57 +2,69 @@ import type { BrainEngine } from '../engine.ts';
import { validateSlug } from '../utils.ts';
import type { PageKey } from './types.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> {
+type SqlExecutor = Pick<BrainEngine, 'executeRaw'>;
+const keyId = (sourceId: string, slug: string) => JSON.stringify([sourceId, slug]);
+
+function orderedPageKeys(keys: readonly PageKey[]): PageKey[] {
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 });
- }
- 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]);
- if (!rows.length) throw new Error(`Page source does not exist: ${sourceId}`);
- sources.set(sourceId, rows[0].incarnation);
- }
- 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]);
- return;
- }
- for (const key of ordered) {
- 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]);
+ unique.set(keyId(key.sourceId, slug), { sourceId: key.sourceId, slug });
}
+ return [...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);
+}
+
+/**
+ * Locks sorted sources (FOR SHARE), then the sorted page guards, then the
+ * sorted pages rows, in three statements for any number of keys (#6007).
+ */
+async function lockOrderedPageKeys(engine: SqlExecutor, ordered: readonly PageKey[]): Promise<void> {
+ if (!ordered.length) return;
+ const sourceIds = [...new Set(ordered.map(key => key.sourceId))];
+ // Every source row is share-locked, in key order, before the first guard
+ // row is inserted: the insert is gated on reading the whole locked set.
+ const sources = await engine.executeRaw<{ id: string; incarnation: string }>(`WITH s AS MATERIALIZED (
+ SELECT src.id,src.incarnation FROM unnest($1::text[]) WITH ORDINALITY AS u(id,n) JOIN sources src ON src.id=u.id ORDER BY u.n FOR SHARE OF src),
+ created AS (INSERT INTO page_write_guards(source_incarnation,slug)
+ SELECT s.incarnation,k.s FROM unnest($2::text[],$3::text[]) WITH ORDINALITY AS k(src,s,n) JOIN s ON s.id=k.src
+ WHERE (SELECT count(*) FROM s)=cardinality($1::text[]) ORDER BY k.n ON CONFLICT DO NOTHING)
+ SELECT id,incarnation FROM s`, [sourceIds, ordered.map(key => key.sourceId), ordered.map(key => key.slug)]);
+ const incarnations = new Map(sources.map(row => [row.id, row.incarnation]));
+ const missing = sourceIds.find(id => !incarnations.has(id));
+ if (missing !== undefined) throw new Error(`Page source does not exist: ${missing}`);
+ 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`,
+ [ordered.map(key => incarnations.get(key.sourceId)!), ordered.map(key => key.slug)]);
+ // Also fence direct SQL row writers. The guard remains when this row is absent.
+ 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`, [ordered.map(key => key.sourceId), ordered.map(key => key.slug)]);
+}
+
+/** Source locks precede auth/request locks in callers; repeat held locks safely. */
+export async function lockPageKeys(engine: SqlExecutor, keys: readonly PageKey[]): Promise<void> {
+ await lockOrderedPageKeys(engine, orderedPageKeys(keys));
}
/**
- * Guards a PGLite transaction already holds, chained through its open
- * savepoints. The single PGLite session owns them until the transaction or
- * savepoint ends, so they are not re-acquired.
+ * Guards a transaction already holds, chained through its open savepoints.
+ * The transaction's session owns them until the transaction or savepoint
+ * ends, so they are not re-acquired. That includes a key whose pages row was
+ * absent when it was locked: the only pages INSERT (engine-sql/pages.ts
+ * putPage) runs after both engines' putPage take the same guard, so no other
+ * transaction can create that row while the guard is held.
*/
export interface HeldPageKeys { keys: Set<string>; parent: HeldPageKeys | null }
function pageGuardKey(key: PageKey): string | null {
if (!key.sourceId) return null;
- try { return JSON.stringify([key.sourceId, validateSlug(key.slug)]); } catch { return null; }
+ try { return keyId(key.sourceId, validateSlug(key.slug)); } catch { return null; }
}
function holds(held: HeldPageKeys | null, id: string): boolean {
for (; held; held = held.parent) if (held.keys.has(id)) return true;
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: SqlExecutor, 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/projections.ts b/src/core/page-state/projections.ts
index 8a9dc9d0db..3ebd7eef47 100644
--- a/src/core/page-state/projections.ts
+++ b/src/core/page-state/projections.ts
@@ -217,21 +217,28 @@ export async function installPageEmbeddings(engine: BrainEngine, prepared: Proje
built?.corpusGeneration !== undefined ? built.corpusGeneration : context.corpusGeneration, stored);
// This is deliberately UPDATE-only: a late embed can never replace text,
// chunk identity, metadata, or membership in the installed projection.
+ // #6007: one set-based statement for every chunk with a vector or image;
+ // a repeated chunk index keeps its last entry, as sequential updates would.
+ const updates = new Map<number, { id: number; vector: string | null; image: string | null; model: string | null; chunk_text: string; input_hash: string }>();
for (const chunk of chunks) {
if (!chunk.embedding && !chunk.embedding_image) continue;
const original = byIndex.get(chunk.chunk_index)!;
const vector = chunk.embedding ? `[${Array.from(chunk.embedding).join(',')}]` : null;
- const image = chunk.embedding_image ? `[${Array.from(chunk.embedding_image).join(',')}]` : null;
- await tx.executeRaw(`UPDATE content_chunks SET
- ${quoteIdentifier(column.name)}=CASE WHEN $2::text IS NULL THEN ${quoteIdentifier(column.name)} ELSE $2${vectorCastSuffix(column)} END,
- embedding_image=CASE WHEN $3::text IS NULL THEN embedding_image ELSE $3::vector END,
- embedding_input_hash=CASE WHEN $2::text IS NULL THEN embedding_input_hash ELSE $7 END,
- embedded_at=now(),embedded_text_hash=md5(chunk_text),model=COALESCE($4,model)
- WHERE id=$1 AND page_id=$5 AND chunk_text=$6`,
- // Bind the full provider:model captured before the provider call. Keeping
- // an old label on a new vector prevents provenance-complete migration.
- [original.id, vector, image, chunk.model ?? (vector ? prepared.embeddingModel : null), snapshot.page.id, original.chunk_text,
- embeddingInputHash(provenance, tier, original)]);
+ updates.set(chunk.chunk_index, { id: original.id, vector, image: chunk.embedding_image ? `[${Array.from(chunk.embedding_image).join(',')}]` : null,
+ // Bind the full provider:model captured before the provider call. Keeping
+ // an old label on a new vector prevents provenance-complete migration.
+ model: chunk.model ?? (vector ? prepared.embeddingModel : null) ?? null, chunk_text: original.chunk_text,
+ input_hash: embeddingInputHash(provenance, tier, original) });
+ }
+ if (updates.size) {
+ const target = quoteIdentifier(column.name);
+ await tx.executeRaw(`UPDATE content_chunks c SET
+ ${target}=CASE WHEN u.vector IS NULL THEN c.${target} ELSE u.vector${vectorCastSuffix(column)} END,
+ embedding_image=CASE WHEN u.image IS NULL THEN c.embedding_image ELSE u.image::vector END,
+ embedding_input_hash=CASE WHEN u.vector IS NULL THEN c.embedding_input_hash ELSE u.input_hash END,
+ embedded_at=now(),embedded_text_hash=md5(c.chunk_text),model=COALESCE(u.model,c.model)
+ FROM jsonb_to_recordset($1::text::jsonb) AS u(id bigint,vector text,image text,model text,chunk_text text,input_hash text)
+ WHERE c.id=u.id AND c.page_id=$2 AND c.chunk_text=u.chunk_text`, [JSON.stringify([...updates.values()]), snapshot.page.id]);
}
if (signature) await tx.setPageEmbeddingSignature(slug, { sourceId, signature });
return true;
diff --git a/src/core/persistence/authority.ts b/src/core/persistence/authority.ts
index 9508ff8e8b..0bb61fe541 100644
--- a/src/core/persistence/authority.ts
+++ b/src/core/persistence/authority.ts
@@ -104,7 +104,8 @@ 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> {
+/** `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> {
const [source] = await 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) {
@@ -120,7 +121,7 @@ export async function authorizeStoredRequest(engine: SqlEngine, row: WriteReques
for (const slug of affected) await authorizeWrite(engine, row.authority, row.operation, slug, lock);
}
}
- if (!skillWrite(row.operation)) await authorizePageVisibility(engine, row.authority, row.slug);
+ if (!skillWrite(row.operation) && opts.pageVisibility !== false) await authorizePageVisibility(engine, row.authority, row.slug);
if (row.authority.remote && ['takes_add', 'takes_update', 'takes_resolve', 'takes_supersede'].includes(row.operation)) {
await authorizeStoredTakeHolders(engine, row);
}
@@ -155,11 +156,31 @@ async function authorizeStoredTakeHolders(engine: SqlEngine, row: WriteRequest):
if (row.state === 'committed' && holders.size === 0) deny('The legacy take receipt has no verifiable holder authority.');
for (const holder of holders) await authorizeTakeHolder(engine, row.authority, holder);
}
+/**
+ * #6007: one access check answers identical read-only statements once (the
+ * current and the stored authority read the same writer row and visibility).
+ * The memo lives for that single check and holds no locking reads.
+ */
+function onceReads(engine: BrainEngine): BrainEngine {
+ const reads = new Map<string, Promise<unknown[]>>();
+ return new Proxy(engine, { get(target, key) {
+ if (key === 'executeRaw') return (sql: string, params?: unknown[], opts?: { signal?: AbortSignal }) => {
+ if (/\bFOR (?:SHARE|UPDATE)\b/i.test(sql)) return target.executeRaw(sql, params, opts);
+ const id = JSON.stringify([sql, params ?? null]);
+ let read = reads.get(id);
+ if (!read) { read = target.executeRaw(sql, params, opts); reads.set(id, read); read.catch(() => reads.delete(id)); }
+ return read;
+ };
+ const value = Reflect.get(target, key, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+}
export async function ownRequestAccessible(ctx: OperationContext, row: WriteRequest): Promise<boolean> {
try {
- const auth = await submissionAuthority(ctx, row.operation, row.source_id, row.source_incarnation, row.slug);
+ const engine = onceReads(ctx.engine);
+ const auth = await submissionAuthority({ ...ctx, engine }, row.operation, row.source_id, row.source_incarnation, row.slug);
if (auth.principal.kind !== row.principal_kind || auth.principal.id !== row.principal_id) return false;
- await authorizeStoredRequest(ctx.engine, row);
+ await authorizeStoredRequest(engine, row);
return true;
} catch (error) {
if (error instanceof OperationError && ['permission_denied','source_changed','writer_registration_required','page_not_found'].includes(error.code)) return false;
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index a9e3e56a23..4c8283daba 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -266,11 +266,11 @@ export class PersistenceConsumer {
this.idleDelayMs = this.pollMs;
this.nextDelayMs = this.pollMs;
const scan = !afterProgress || Date.now() - this.lastScan >= this.pollMs;
- if (scan) {
- this.lastScan = Date.now();
- await this.phase('refresh_roots', signal => refreshManagedFilesystemRoots(this.engine,
- this.engine.kind === 'pglite' ? this.config.database_path : undefined, signal));
- }
+ // #6007: a tick after progress claims first and runs its due scans after the claim, while the claimed
+ // write prepares; the claim predicate itself excludes recovering roots, so no claim depends on a scan.
+ const scanAfterClaim = scan && afterProgress;
+ if (scan) this.lastScan = Date.now();
+ if (scan && !scanAfterClaim) await this.refreshRoots();
if (this.stopping) return;
if (scan && !this.topologyWorker) this.topologyWorker = import('./topology-recovery.ts')
.then(({ recoverSourceTopologies }) => recoverSourceTopologies(this.engine, { hostId: this.hostId, limit: 2,
@@ -295,41 +295,11 @@ export class PersistenceConsumer {
// proves that a previous process can no longer be publishing this root.
const now = Date.now();
for (const [root, retryAt] of this.rootRetryAfter) if (retryAt <= now) this.rootRetryAfter.delete(root);
- if (scan) {
- const excluded = [...this.activeRoots, ...this.rootRetryAfter.keys()];
- const recovery = await this.phase('recovery_scan', signal => this.engine.executeRaw<WriteRequest>(`SELECT r.* FROM persistence_requests r
- JOIN persistence_worktrees w ON w.id=r.worktree_id
- WHERE w.owner_host_id=$1::uuid AND r.recovery IS NOT NULL AND NOT(r.worktree_id::text=ANY($2::text[]))
- AND NOT EXISTS (SELECT 1 FROM persistence_requests earlier WHERE earlier.worktree_id=r.worktree_id
- AND earlier.recovery IS NOT NULL AND earlier.sequence<r.sequence)
- ORDER BY r.updated_at,r.sequence LIMIT 16`, [this.hostId, excluded], { signal }));
- for (const row of recovery) {
- const root = row.worktree_id!;
- // Always skip at least the next scheduled poll for an unresolved root.
- // This preserves its FIFO head while allowing the next root into LIMIT 16.
- const delay = Math.max(1000, (this.opts.pollMs ?? 250) * 2);
- this.rootRetryAfter.set(root, Date.now() + delay);
- try {
- const recovered = await this.phase('recovery', () => recoverPublication(this.engine, row.id, this.hostId));
- if (isTerminal(recovered)) this.settled(recovered);
- if (!recovered.recovery) this.rootRetryAfter.delete(root);
- else if (recovered.blocked_reason === 'unexpected_file_bytes') this.rootRetryAfter.set(root, Date.now() + Math.max(delay, 30_000));
- } catch (error) {
- this.rootRetryAfter.set(root, Date.now() + Math.max(delay, 30_000));
- this.report(error);
- }
- }
- await this.phase('expired_claims', signal => this.engine.executeRaw(`WITH expired AS (
- SELECT r.id FROM persistence_requests r WHERE r.state='running' AND r.recovery IS NULL
- AND r.publication_started=false AND r.claim_expires_at<now() AND ${PERSISTENCE_PROTOCOL_PREDICATE}
- AND (r.worktree_id IS NULL OR EXISTS (SELECT 1 FROM persistence_worktrees w WHERE w.id=r.worktree_id AND w.owner_host_id=$1::uuid))
- ORDER BY r.sequence LIMIT 100 FOR UPDATE OF r SKIP LOCKED)
- UPDATE persistence_requests r SET state='queued',execution_token=NULL,claim_expires_at=NULL
- FROM expired WHERE r.id=expired.id`, [this.hostId], { signal }));
- }
+ if (scan && !scanAfterClaim) await this.recoveryScans();
if (publicationConcurrency(this.engine) === 0) {
await this.phase('capacity', signal => this.engine.executeRaw(`UPDATE persistence_requests SET blocked_reason='writer_pool_capacity'
WHERE state='queued' AND blocked_reason IS DISTINCT FROM 'writer_pool_capacity' AND ${PERSISTENCE_PROTOCOL_PREDICATE}`, undefined, { signal }));
+ if (scanAfterClaim) { await this.refreshRoots(); await this.recoveryScans(); }
return;
}
const concurrency = this.opts.concurrency ?? 2;
@@ -350,6 +320,44 @@ export class PersistenceConsumer {
});
this.active.add(task);
}
+ if (scanAfterClaim && !this.stopping) { await this.refreshRoots(); if (!this.stopping) await this.recoveryScans(); }
+ }
+ private async refreshRoots(): Promise<void> {
+ await this.phase('refresh_roots', signal => refreshManagedFilesystemRoots(this.engine,
+ this.engine.kind === 'pglite' ? this.config.database_path : undefined, signal));
+ }
+ /** Recovers this owner's roots with a recovery record, then requeues expired unpublished claims. */
+ private async recoveryScans(): Promise<void> {
+ const excluded = [...this.activeRoots, ...this.rootRetryAfter.keys()];
+ const recovery = await this.phase('recovery_scan', signal => this.engine.executeRaw<WriteRequest>(`SELECT r.* FROM persistence_requests r
+ JOIN persistence_worktrees w ON w.id=r.worktree_id
+ WHERE w.owner_host_id=$1::uuid AND r.recovery IS NOT NULL AND NOT(r.worktree_id::text=ANY($2::text[]))
+ AND NOT EXISTS (SELECT 1 FROM persistence_requests earlier WHERE earlier.worktree_id=r.worktree_id
+ AND earlier.recovery IS NOT NULL AND earlier.sequence<r.sequence)
+ ORDER BY r.updated_at,r.sequence LIMIT 16`, [this.hostId, excluded], { signal }));
+ for (const row of recovery) {
+ const root = row.worktree_id!;
+ // Always skip at least the next scheduled poll for an unresolved root.
+ // This preserves its FIFO head while allowing the next root into LIMIT 16.
+ const delay = Math.max(1000, (this.opts.pollMs ?? 250) * 2);
+ this.rootRetryAfter.set(root, Date.now() + delay);
+ try {
+ const recovered = await this.phase('recovery', () => recoverPublication(this.engine, row.id, this.hostId));
+ if (isTerminal(recovered)) this.settled(recovered);
+ if (!recovered.recovery) this.rootRetryAfter.delete(root);
+ else if (recovered.blocked_reason === 'unexpected_file_bytes') this.rootRetryAfter.set(root, Date.now() + Math.max(delay, 30_000));
+ } catch (error) {
+ this.rootRetryAfter.set(root, Date.now() + Math.max(delay, 30_000));
+ this.report(error);
+ }
+ }
+ await this.phase('expired_claims', signal => this.engine.executeRaw(`WITH expired AS (
+ SELECT r.id FROM persistence_requests r WHERE r.state='running' AND r.recovery IS NULL
+ AND r.publication_started=false AND r.claim_expires_at<now() AND ${PERSISTENCE_PROTOCOL_PREDICATE}
+ AND (r.worktree_id IS NULL OR EXISTS (SELECT 1 FROM persistence_worktrees w WHERE w.id=r.worktree_id AND w.owner_host_id=$1::uuid))
+ ORDER BY r.sequence LIMIT 100 FOR UPDATE OF r SKIP LOCKED)
+ UPDATE persistence_requests r SET state='queued',execution_token=NULL,claim_expires_at=NULL
+ FROM expired WHERE r.id=expired.id`, [this.hostId], { signal }));
}
/** Effects keep pace with publication: full batches continue without waiting for the next tick. */
private async drainEffects(): Promise<void> {
diff --git a/src/core/persistence/context.ts b/src/core/persistence/context.ts
index 6cdd0bbd66..0fabd1a996 100644
--- a/src/core/persistence/context.ts
+++ b/src/core/persistence/context.ts
@@ -17,17 +17,18 @@ async function withTransactionSettings<T>(engine: Pick<BrainEngine, 'executeRaw'
const [row] = await engine.executeRaw<Record<string, string | null>>(
`SELECT ${names.map((name, index) => `current_setting('${name}',true) AS s${index}`).join(',')}`);
const previous = names.map((_, index) => row?.[`s${index}`] ?? '');
- const apply = (values: string[]) => engine.executeRaw(
- `SELECT ${names.map((name, index) => `set_config('${name}',$${index + 1},true)`).join(',')}`, values);
- await apply(next(previous));
+ await applySettings(engine, names, next(previous));
let failed = false;
try { return await fn(); }
catch (error) { failed = true; throw error; }
finally {
- try { await apply(previous); }
+ try { await applySettings(engine, names, previous); }
catch (error) { if (!failed) throw error; }
}
}
+function applySettings(engine: Pick<BrainEngine, 'executeRaw'>, names: readonly string[], values: string[]) {
+ return engine.executeRaw(`SELECT ${names.map((name, index) => `set_config('${name}',$${index + 1},true)`).join(',')}`, values);
+}
/** A nested scope keeps the outer actor: a request publication that calls a derived writer stays attributed to the request. */
const attributionValues = (outer: string[], attribution: WriteAttribution) => outer[1]
? outer : [attribution.requestId ?? '', attribution.principal.kind, attribution.principal.id];
@@ -38,19 +39,35 @@ const attributionValues = (outer: string[], attribution: WriteAttribution) => ou
* content row and page revision written inside (persistence/attribution-schema.ts).
*/
export async function withCoordinatedWrite<T>(engine: BrainEngine, sourceIds: string[], fn: () => Promise<T>, attribution: WriteAttribution): Promise<T> {
- const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1');
- if (!brain) {
+ // #6007: the persistence identity, the enclosing settings and the new settings in one round trip;
+ // nothing is set when the identity row is missing. The OFFSET 0 subquery reads the enclosing values first.
+ const names = ['gbrain.write_sources', ...ATTRIBUTION_SETTINGS];
+ const [brain] = await engine.executeRaw<Record<string, string | null>>(`SELECT b.brain_id,prev.*,
+ CASE WHEN b.brain_id IS NOT NULL THEN concat(set_config('gbrain.write_sources',$1,true),
+ set_config('gbrain.write_request',CASE WHEN prev.s2<>'' THEN prev.s1 ELSE $2 END,true),
+ set_config('gbrain.write_principal_kind',CASE WHEN prev.s2<>'' THEN prev.s2 ELSE $3 END,true),
+ set_config('gbrain.write_principal_id',CASE WHEN prev.s2<>'' THEN prev.s3 ELSE $4 END,true)) END AS applied
+ FROM (SELECT ${names.map((name, index) => `COALESCE(current_setting('${name}',true),'') AS s${index}`).join(',')} OFFSET 0) prev
+ LEFT JOIN persistence_brain b ON b.singleton=1`,
+ [JSON.stringify(sourceIds), attribution.requestId ?? '', attribution.principal.kind, attribution.principal.id]);
+ if (!brain?.brain_id) {
throw opError('writer_not_initialized', 'Persistence identity is missing.',
'This brain has no persistence identity row, so coordinated writes cannot run and nothing was written. List the pending migrations that create it and ask the user to approve applying them.',
{ fix: { argv: ['gbrain', 'apply-migrations', '--dry-run', '--json'], consent: [], actor: 'agent', why: 'Lists the pending migrations without applying them.', requires_exclusive: false } });
}
const context: PublicationContext = { brainId: brain.brain_id, sourceIds: new Set(sourceIds), active: true };
- return withTransactionSettings(engine, ['gbrain.write_sources', ...ATTRIBUTION_SETTINGS],
- ([, ...outer]) => [JSON.stringify(sourceIds), ...attributionValues(outer, attribution)],
- () => publication.run(context, async () => {
+ const previous = names.map((_, index) => brain[`s${index}`] ?? '');
+ let failed = false;
+ try {
+ return await publication.run(context, async () => {
try { return await fn(); }
finally { context.active = false; }
- }));
+ });
+ } catch (error) { failed = true; throw error; }
+ finally {
+ try { await applySettings(engine, names, previous); }
+ catch (error) { if (!failed) throw error; }
+ }
}
/**
* #5984 bulk: inside one coordinated write that publishes several requests,
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 930258c21e..ea65932592 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -25,7 +25,7 @@ import { authorizePageVisibility } from './page-visibility.ts';
import { withNoRepoWriteThroughWarning } from '../write-through.ts';
import { assertUnboundPublication, classifyUnboundPage, unboundWriteWarning } from './unbound-source.ts';
import { assertRecoveryStagingAbsent, cleanupRecoveryStaging, recoveryStagingFile, upgradeRecoveryStaging } from './staging.ts';
-import { assertMutationProtocol, assertSharedSkillPersistence, declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
+import { assertMutationProtocol, assertSharedSkillPersistence, declareDurablePersistence, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
import { assertBundleRecoveryBinding, bundleFileHash, prepareBundleRecovery, publishStagedBundleFile, stageBundleFile, type MutationFile } from './bundle-files.ts';
import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';
import { classifyMirrorPage, sourceMirrorReadOnly } from './mirror-read-only.ts';
@@ -239,14 +239,14 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
await hooks.boundary?.('prepared', row);
}
const done = await engine.transaction(async tx => {
- await declarePersistenceProtocol(tx);
- await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','1s',true),set_config('statement_timeout','5s',true)");
+ await declareDurablePersistence(tx);
const liveBinding = await guardOwnership(tx, row, hostId);
if (prepared.sourceExclusive) await tx.executeRaw('SELECT id FROM sources WHERE id=$1 FOR UPDATE', [row.source_id]);
if (binding && String(liveBinding?.owner_epoch) !== String(binding.owner_epoch)) throw opError('owner_unavailable', 'Owner epoch changed before publication.',
`Source ${row.source_id}'s canonical owner changed (a transfer or re-claim) after request ${row.request_id} was prepared, so this host published nothing for it. Inspect the owner and the request before resubmitting; do not claim or transfer the source to push this write through.`,
{ fix: ownerStatusFix(row.source_id) });
- await authorizeStoredRequest(tx, row, true);
+ // A page target's visibility is checked below, once its page is locked.
+ await authorizeStoredRequest(tx, row, true, { pageVisibility: skill });
await lockCounters(tx, ['brain', principalKey(requestPrincipal(row)), ...(row.worktree_id ? [`worktree:${row.worktree_id}`] : [])]);
const [current] = await tx.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid FOR UPDATE', [row.id]);
if (!current || current.execution_token !== row.execution_token || current.state !== 'running') throw opError('write_claim_lost', 'Execution claim changed before publication.',
@@ -304,7 +304,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
return committed;
});
await hooks.boundary?.('after_commit', done);
- if (recovery) await clearResolvedRecovery(engine, row.id);
+ if (recovery) await clearResolvedRecovery(engine, row.id, done);
return done;
} catch (error) {
if (recovery) {
@@ -353,8 +353,7 @@ export async function recoverPublication(engine: BrainEngine, id: string, hostId
}
if (row.recovery.version === 1 && !row.recovery.staging && !isTerminal(row)) await upgradeRecoveryStaging(engine, 'persistence_requests', id, row.worktree_id!, 'restore');
row = await engine.transaction(async tx => {
- await declarePersistenceProtocol(tx);
- await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','1s',true),set_config('statement_timeout','5s',true)");
+ await declareDurablePersistence(tx);
await tx.executeRaw('SELECT id FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE', [row!.worktree_id]);
await lockCounters(tx, ['brain', principalKey(requestPrincipal(row!)), `worktree:${row!.worktree_id}`]);
const [current] = await tx.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid FOR UPDATE', [id]);
diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.ts
index 1463edb72c..1aa7e3b442 100644
--- a/src/core/persistence/effect-journal.ts
+++ b/src/core/persistence/effect-journal.ts
@@ -26,24 +26,23 @@ export async function queuePublicationEffects(tx: BrainEngine, row: EffectReques
await declarePersistenceProtocol(tx);
const revision = snapshot?.revision;
const data = { slug: row.slug, page_id: snapshot?.page.id };
- const queue = async (kind: EffectKind, extra: Record<string, unknown> = {}) => tx.executeRaw(`INSERT INTO persistence_effects
- (request_id,kind,revision,data,source_id,source_incarnation,worktree_id)
- VALUES($1::uuid,$2,$3::uuid,$4::text::jsonb,$5,$6::uuid,$7::uuid) ON CONFLICT(request_id,kind) DO NOTHING`,
- [row.id, kind, revision ?? null, JSON.stringify({ ...data, ...extra }), row.source_id, row.source_incarnation, row.worktree_id]);
+ // #6007: the effects are inserted together, in queue order, by one statement at the end.
+ const queued: { kind: EffectKind; data: Record<string, unknown> }[] = [];
+ const queue = (kind: EffectKind, extra: Record<string, unknown> = {}) => { queued.push({ kind, data: { ...data, ...extra } }); };
if (prepared?.file && row.worktree_id) {
const [binding] = await tx.executeRaw<{ local_path: string }>(`SELECT h.local_path FROM persistence_host_bindings h
JOIN persistence_worktrees w ON w.id=h.worktree_id AND w.owner_host_id=h.host_id WHERE w.id=$1::uuid`, [row.worktree_id]);
if (!binding?.local_path) throw new OperationError('owner_unavailable', 'Cannot record the canonical Git target without its owner binding.');
- await queue('git', { relative_path: relative(binding.local_path, prepared.file.path).split(sep).join('/'),
+ queue('git', { relative_path: relative(binding.local_path, prepared.file.path).split(sep).join('/'),
expected_hash: prepared.file.content === null ? null : sha256(prepared.file.content) });
if (outcome.persistence && typeof outcome.persistence === 'object') Object.assign(outcome.persistence, { git_state: 'queued' });
}
if (snapshot && !snapshot.page.deleted_at) {
- if (!prepared?.deferEmbedding) await queue('embedding');
+ if (!prepared?.deferEmbedding) queue('embedding');
outcome.embedding_state = await embeddingDisabled(tx) ? 'disabled' : prepared?.deferEmbedding ? 'deferred' : 'queued';
if ((outcome.facts_backstop as { queued?: boolean } | undefined)?.queued) {
if (!(await isFactsExtractionEnabled(tx))) outcome.facts_backstop = { skipped: 'extraction_disabled' };
- else await queue('facts-backstop', { visibility: await resolveDefaultVisibility(tx) });
+ else queue('facts-backstop', { visibility: await resolveDefaultVisibility(tx) });
}
if (row.authority && row.operation && REMOTE_MENTION_OPERATIONS.includes(row.operation)
&& !(row.authority.autoLinkTrusted ?? !row.authority.remote)) {
@@ -58,6 +57,10 @@ export async function queuePublicationEffects(tx: BrainEngine, row: EffectReques
// #5876: the Life Chronicle decision is a ledger row, not an effect; the `chronicle` cycle phase executes it.
await recordChronicleDecision(tx, row, snapshot, outcome);
}
+ if (queued.length) await tx.executeRaw(`INSERT INTO persistence_effects (request_id,kind,revision,data,source_id,source_incarnation,worktree_id)
+ SELECT $1::uuid,t.e->>'kind',$2::uuid,t.e->'data',$3,$4::uuid,$5::uuid FROM jsonb_array_elements($6::text::jsonb) WITH ORDINALITY AS t(e,n)
+ ORDER BY t.n ON CONFLICT(request_id,kind) DO NOTHING`,
+ [row.id, revision ?? null, row.source_id, row.source_incarnation, row.worktree_id, JSON.stringify(queued)]);
}
/**
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index 6a511010d1..f6890a38f8 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -32,7 +32,7 @@ import { requestAttribution } from './attribution.ts';
import { tryAcquirePublicationCapacity } from './pool-capacity.ts';
import { queuePublicationEffects } from './effect-journal.ts';
import { assertUnboundPublication, classifyUnboundPage } from './unbound-source.ts';
-import { declarePersistenceProtocol } from './protocol.ts';
+import { declareDurablePersistence } from './protocol.ts';
import { classifyMirrorPage } from './mirror-read-only.ts';
import { decoratePublicationOutcome, finishUnpublishedFailure, publishMutation, type PreparedMutation } from './coordinator.ts';
@@ -58,8 +58,7 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
releaseCapacity = tryAcquirePublicationCapacity(engine);
if (!releaseCapacity) return null;
return await engine.transaction(async tx => {
- await declarePersistenceProtocol(tx);
- await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','1s',true),set_config('statement_timeout','5s',true)");
+ 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.');
await tx.lockPageKeys(rows.flatMap((row, i) => [{ sourceId: row.source_id, slug: row.slug }, ...(prepared[i]!.additionalPageKeys ?? [])]));
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index e95de896e1..7014eac985 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -13,7 +13,7 @@ import { writerStamp } from './writer-versions.ts';
import { publicFailureDetail } from './publication-failure.ts';
import { catalogueError } from '../error-catalogue.ts';
import { ACTIVE_REFRESH_STATES_SQL, refreshFenceClear } from './worktree-refresh-schema.ts';
-import { assertMutationProtocol, assertSharedSkillPersistence, declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
+import { assertMutationProtocol, assertSharedSkillPersistence, declareDurablePersistence, declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
import {
isTerminal, principalKey, requestPrincipal, recoveryFiles,
type JournalLimits, type Principal, type RecoveryRecord, type RequestState,
@@ -126,125 +126,74 @@ export function assertReplayIntent(row: WriteRequest, expectedDigest: string): W
return row;
}
export async function admitWrite(engine: BrainEngine, input: WriteAdmission, overrides?: Partial<JournalLimits>): Promise<WriteRequest> {
- const { requestIds, apply } = await prepareAdmissions(engine, [input], overrides);
- return admissionTransaction(engine, requestIds[0]!, async tx => (await apply(tx))[0]!);
-}
-/**
- * #6007: admit several writes for one principal, source and worktree in ONE
- * transaction: every new row is accepted or none is, with capacity reserved
- * for the whole set. Rows that already exist replay (identical intent) or
- * refuse with idempotency_conflict.
- */
-export async function admitWrites(engine: BrainEngine, inputs: readonly WriteAdmission[], overrides?: Partial<JournalLimits>,
- opts: { budgetMs?: number; retryLabel?: string } = {}): Promise<WriteRequest[]> {
- const { requestIds, apply } = await prepareAdmissions(engine, inputs, overrides);
- return admissionTransaction(engine, opts.retryLabel ?? requestIds.join(', '), apply, opts.budgetMs);
-}
-function admissionTransaction<T>(engine: BrainEngine, label: string, apply: (tx: BrainEngine) => Promise<T>, budgetMs?: number): Promise<T> {
- return retryWriteAdmission(label, remaining => engine.transaction(async tx => {
- await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout',$1,true),set_config('statement_timeout',$2,true)",
- [`${Math.min(100, remaining)}ms`, `${remaining}ms`]);
+ const { requestId, apply } = await prepareAdmission(engine, input, overrides);
+ return retryWriteAdmission(requestId, remaining => engine.transaction(async tx => {
+ await declareDurablePersistence(tx, `${Math.min(100, remaining)}ms`, `${remaining}ms`);
return apply(tx);
- }), budgetMs);
+ }));
}
/** Caller owns the transaction and retries its entire unit of work after rollback. */
export async function admitWriteInTransaction(tx: BrainEngine, input: WriteAdmission, overrides?: Partial<JournalLimits>): Promise<WriteRequest> {
- return (await (await prepareAdmissions(tx, [input], overrides)).apply(tx))[0]!;
+ return (await prepareAdmission(tx, input, overrides)).apply(tx);
}
-async function prepareAdmissions(engine: BrainEngine, inputs: readonly WriteAdmission[], overrides?: Partial<JournalLimits>) {
- const first = inputs[0];
- if (!first) throw new TypeError('Admission requires at least one write.');
- for (const input of inputs) {
- if (input.sourceId !== first.sourceId || input.sourceIncarnation !== first.sourceIncarnation || (input.worktreeId ?? null) !== (first.worktreeId ?? null)
- || String(input.topologyGeneration ?? '') !== String(first.topologyGeneration ?? '')
- || principalKey(input.principal) !== principalKey(first.principal)) throw new TypeError('A batched admission shares one principal, source and worktree binding.');
- }
+async function prepareAdmission(engine: BrainEngine, input: WriteAdmission, overrides?: Partial<JournalLimits>) {
const limits = await readJournalLimits(engine,overrides);
- const rows = inputs.map(input => {
- const requestId = requireUuid(input.requestId ?? randomUUID());
- const terminalBytes = input.terminalReservation ?? Math.max(16_384,jsonBytes(input.authority)+8192);
- if (!Number.isSafeInteger(terminalBytes) || terminalBytes < 1024) throw new TypeError('Invalid terminal receipt reservation.');
- return { input, requestId, fingerprint: intentDigest(input), bytes: jsonBytes(input.intent) + jsonBytes(input.authority), terminalBytes };
- });
- if (new Set(rows.map(row => row.requestId)).size !== rows.length) throw new TypeError('A batched admission repeats a request_id.');
+ const requestId = requireUuid(input.requestId ?? randomUUID());
+ const fingerprint = intentDigest(input);
+ const bytes = jsonBytes(input.intent) + jsonBytes(input.authority);
+ const terminalBytes = input.terminalReservation ?? Math.max(16_384,jsonBytes(input.authority)+8192);
+ if (!Number.isSafeInteger(terminalBytes) || terminalBytes < 1024) throw new TypeError('Invalid terminal receipt reservation.');
const stamp = writerStamp();
- return { requestIds: rows.map(row => row.requestId), apply: async (tx: BrainEngine): Promise<WriteRequest[]> => {
+ return { requestId, apply: async (tx: BrainEngine): Promise<WriteRequest> => {
await declarePersistenceProtocol(tx);
- for (const { input } of rows) assertMutationProtocol({ target_kind: input.targetKind, protocol_version: input.protocolVersion });
- if (first.worktreeId) {
- await tx.executeRaw('SELECT id FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE', [first.worktreeId]);
- for (const { input } of rows) await assertWorktreeNotRefreshing(tx, input);
- const binding = await tx.executeRaw(`SELECT source_id FROM persistence_source_bindings WHERE source_id=$1
- AND source_incarnation=$2::uuid AND worktree_id=$3::uuid AND topology_generation=$4`,
- [first.sourceId, first.sourceIncarnation, first.worktreeId, first.topologyGeneration]);
- if (!binding.length) throw opError('source_changed', 'The source binding changed during admission.',
- `Source ${first.sourceId}'s worktree binding changed (a claim, transfer or lifecycle change) while this write was being admitted, so nothing was accepted. Check the owner with the command in fix, then submit the write again; reusing the same request_id is safe because nothing was recorded.`,
- { fix: ownerStatusFix(first.sourceId) });
- }
+ assertMutationProtocol({ target_kind: input.targetKind, protocol_version: input.protocolVersion });
+ if (input.worktreeId) await assertWorktreeAdmission(tx, input);
// Source membership is locked before principal/counter/request guards. A
// deleted/recreated source never receives work accepted for its old identity.
const [source] = await tx.executeRaw<{ incarnation: string; archived: boolean }>(
- 'SELECT incarnation,archived FROM sources WHERE id=$1 FOR SHARE', [first.sourceId]);
- if (!source || source.archived || source.incarnation !== first.sourceIncarnation) {
+ 'SELECT incarnation,archived FROM sources WHERE id=$1 FOR SHARE', [input.sourceId]);
+ if (!source || source.archived || source.incarnation !== input.sourceIncarnation) {
throw new OperationError('source_changed', 'The write source is missing, archived, or was replaced.', 'Resolve the source again and submit a new request.');
}
- for (const { input } of rows) await authorizeWrite(tx, input.authority, input.operation, input.slug, true);
- const counters = await lockCounters(tx, ['brain', principalKey(first.principal)]);
- if(first.principal.kind==='local_cli') {
- const topology=await tx.executeRaw<{ request_id: string }>('SELECT request_id FROM persistence_topology_changes WHERE principal_id=$1::uuid AND request_id=ANY($2::uuid[])',
- [first.principal.id, rows.map(row => row.requestId)]);
- if(topology.length) throw lifecycleIdConflict(String(topology[0]!.request_id));
+ await authorizeWrite(tx, input.authority, input.operation, input.slug, true);
+ const counters = await lockCounters(tx, ['brain', principalKey(input.principal)]);
+ if(input.principal.kind==='local_cli') {
+ const topology=await tx.executeRaw('SELECT id FROM persistence_topology_changes WHERE principal_id=$1::uuid AND request_id=$2::uuid',[input.principal.id,requestId]);
+ if(topology.length) throw lifecycleIdConflict(requestId);
}
- const priors = rows.length === 1
- ? [await getWriteRequest(tx, first.principal, rows[0]!.requestId)].filter((row): row is WriteRequest => row !== null)
- : await tx.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2 AND request_id=ANY($3::uuid[])',
- [first.principal.kind, first.principal.id, rows.map(row => row.requestId)]);
- const priorById = new Map(priors.map(row => [String(row.request_id), row]));
- const result: (WriteRequest | null)[] = [];
- const fresh: typeof rows = [];
- for (const row of rows) {
- const prior = priorById.get(row.requestId);
- if (!prior) { result.push(null); fresh.push(row); continue; }
- if ((prior.target_kind ?? 'page') !== (row.input.targetKind ?? 'page') || (prior.protocol_version ?? 1) !== (row.input.protocolVersion ?? 1)) {
+ const prior = await getWriteRequest(tx, input.principal, requestId);
+ if (prior) {
+ if ((prior.target_kind ?? 'page') !== (input.targetKind ?? 'page') || (prior.protocol_version ?? 1) !== (input.protocolVersion ?? 1)) {
throw opError('idempotency_conflict', 'This request_id belongs to a different mutation target or protocol.',
- `Request ID ${row.requestId} was already accepted for a ${prior.target_kind ?? 'page'} write (protocol ${prior.protocol_version ?? 1}), so this ${row.input.targetKind ?? 'page'} write was not admitted. Read the original request${prior.principal_kind === 'local_cli' ? ' with the command in fix' : ' with get_write_request'} if you meant to replay it; otherwise submit this write with a new request_id.`,
+ `Request ID ${requestId} was already accepted for a ${prior.target_kind ?? 'page'} write (protocol ${prior.protocol_version ?? 1}), so this ${input.targetKind ?? 'page'} write was not admitted. Read the original request${prior.principal_kind === 'local_cli' ? ' with the command in fix' : ' with get_write_request'} if you meant to replay it; otherwise submit this write with a new request_id.`,
prior.principal_kind === 'local_cli' ? { fix: requestInspectFix(prior) } : {});
}
- result.push(assertReplayIntent(prior, row.fingerprint));
+ return assertReplayIntent(prior, fingerprint);
}
- if (!fresh.length) return result as WriteRequest[];
- for (const { input } of fresh) if (input.targetKind === 'skill_bundle') await assertSharedSkillPersistence(tx, input.sourceId);
- const count = fresh.length;
- const bytes = fresh.reduce((sum, row) => sum + row.bytes, 0);
- const terminalBytes = fresh.reduce((sum, row) => sum + row.terminalBytes, 0);
+ if (input.targetKind === 'skill_bundle') await assertSharedSkillPersistence(tx, input.sourceId);
for (const row of counters) {
const brain = row.key === 'brain';
- if (Number(row.outstanding_count) + count > (brain ? limits.brainOutstanding : limits.principalOutstanding)) throw capacityError(`${brain ? 'brain' : 'principal'} outstanding requests`);
+ if (Number(row.outstanding_count) + 1 > (brain ? limits.brainOutstanding : limits.principalOutstanding)) throw capacityError(`${brain ? 'brain' : 'principal'} outstanding requests`);
if (Number(row.intent_bytes) + bytes > (brain ? limits.brainIntentBytes : limits.principalIntentBytes)) throw capacityError(`${brain ? 'brain' : 'principal'} intent bytes`);
const scope = brain ? 'brain' : 'principal';
- if (Number(row.lifetime_ids) + count > limits[`${scope}LifetimeIds`]) throw await cumulativeCapacityError(tx, `${scope} permanent request IDs`,
+ if (Number(row.lifetime_ids) + 1 > limits[`${scope}LifetimeIds`]) throw await cumulativeCapacityError(tx, `${scope} permanent request IDs`,
row.key, `${scope}LifetimeIds`, Number(row.lifetime_ids), limits[`${scope}LifetimeIds`]);
if (Number(row.terminal_bytes) + terminalBytes > limits[`${scope}TerminalBytes`]) throw await cumulativeCapacityError(tx, `${scope} reserved receipt bytes`,
row.key, `${scope}TerminalBytes`, Number(row.terminal_bytes), limits[`${scope}TerminalBytes`]);
}
- let next = 0;
- for (const { input, requestId, fingerprint, bytes: rowBytes, terminalBytes: rowTerminal } of fresh) {
- const [inserted] = await tx.executeRaw<WriteRequest>(`INSERT INTO persistence_requests
- (principal_kind,principal_id,request_id,operation,source_id,source_incarnation,page_id,slug,
- worktree_id,topology_generation,digest,intent,authority,intent_bytes,terminal_reservation,target_kind,protocol_version,
- admitter_version,admitter_host_id)
- VALUES($1,$2,$3::uuid,$4,$5,$6::uuid,$7,$8,$9::uuid,$10,$11,$12::text::jsonb,$13::text::jsonb,$14,$15,$16,$17,$18,$19::uuid)
- RETURNING *`, [input.principal.kind, input.principal.id, requestId, input.operation, input.sourceId,
- input.sourceIncarnation, input.pageId ?? null, input.slug, input.worktreeId ?? null, input.topologyGeneration ?? null,
- fingerprint, JSON.stringify(input.intent), JSON.stringify(input.authority), rowBytes, rowTerminal, input.targetKind ?? 'page', input.protocolVersion ?? 1,
- stamp.version, stamp.hostId]);
- while (result[next] !== null) next++;
- result[next++] = inserted!;
- }
- await tx.executeRaw(`UPDATE persistence_counters SET outstanding_count=outstanding_count+$4,
- intent_bytes=intent_bytes+$2,lifetime_ids=lifetime_ids+$4,terminal_bytes=terminal_bytes+$3 WHERE key=ANY($1::text[])`,
- [counters.map(c => c.key), bytes, terminalBytes, count]);
- return result as WriteRequest[];
+ // The request row and its counter reservation in one statement; the counters are already locked.
+ const [row] = await tx.executeRaw<WriteRequest>(`WITH reserved AS (UPDATE persistence_counters SET outstanding_count=outstanding_count+1,
+ intent_bytes=intent_bytes+$14,lifetime_ids=lifetime_ids+1,terminal_bytes=terminal_bytes+$15 WHERE key=ANY($20::text[]))
+ INSERT INTO persistence_requests
+ (principal_kind,principal_id,request_id,operation,source_id,source_incarnation,page_id,slug,
+ worktree_id,topology_generation,digest,intent,authority,intent_bytes,terminal_reservation,target_kind,protocol_version,
+ admitter_version,admitter_host_id)
+ VALUES($1,$2,$3::uuid,$4,$5,$6::uuid,$7,$8,$9::uuid,$10,$11,$12::text::jsonb,$13::text::jsonb,$14,$15,$16,$17,$18,$19::uuid)
+ RETURNING *`, [input.principal.kind, input.principal.id, requestId, input.operation, input.sourceId,
+ input.sourceIncarnation, input.pageId ?? null, input.slug, input.worktreeId ?? null, input.topologyGeneration ?? null,
+ fingerprint, JSON.stringify(input.intent), JSON.stringify(input.authority), bytes, terminalBytes, input.targetKind ?? 'page', input.protocolVersion ?? 1,
+ stamp.version, stamp.hostId, counters.map(c => c.key)]);
+ return row;
} };
}
@@ -269,16 +218,7 @@ export async function admitWriteGroupInTransaction(tx: BrainEngine, inputs: Writ
bytes: jsonBytes(input.intent) + jsonBytes(input.authority), terminalBytes: input.terminalReservation ?? Math.max(16_384, jsonBytes(input.authority) + 8192) }));
await declarePersistenceProtocol(tx);
assertMutationProtocol({ target_kind: 'page', protocol_version: 1 });
- if (first.worktreeId) {
- await tx.executeRaw('SELECT id FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE', [first.worktreeId]);
- await assertWorktreeNotRefreshing(tx, first);
- const binding = await tx.executeRaw(`SELECT source_id FROM persistence_source_bindings WHERE source_id=$1
- AND source_incarnation=$2::uuid AND worktree_id=$3::uuid AND topology_generation=$4`,
- [first.sourceId, first.sourceIncarnation, first.worktreeId, first.topologyGeneration]);
- if (!binding.length) throw opError('source_changed', 'The source binding changed during admission.',
- `Source ${first.sourceId}'s worktree binding changed (a claim, transfer or lifecycle change) while this write was being admitted, so nothing was accepted. Check the owner with the command in fix, then submit the write again; reusing the same request_id is safe because nothing was recorded.`,
- { fix: ownerStatusFix(first.sourceId) });
- }
+ if (first.worktreeId) await assertWorktreeAdmission(tx, first);
const [source] = await tx.executeRaw<{ incarnation: string; archived: boolean }>('SELECT incarnation,archived FROM sources WHERE id=$1 FOR SHARE', [first.sourceId]);
if (!source || source.archived || source.incarnation !== first.sourceIncarnation) {
throw new OperationError('source_changed', 'The write source is missing, archived, or was replaced.', 'Resolve the source again and submit a new request.');
@@ -374,10 +314,26 @@ export async function renewGroupClaims(engine: SqlEngine, rows: WriteRequest[],
* own writes are admitted; a `syncing` refresh whose members all reached the
* target is completed here, so a later cycle sync converges a crashed refresh.
*/
-async function assertWorktreeNotRefreshing(tx: BrainEngine, input: WriteAdmission): Promise<void> {
- const [refresh] = await tx.executeRaw<{ id: string; state: string; source_ids: string[] }>(`SELECT id,state,source_ids FROM persistence_worktree_refreshes
- WHERE worktree_id=$1::uuid AND state IN ${ACTIVE_REFRESH_STATES_SQL}`, [input.worktreeId]);
- if (!refresh) return;
+/**
+ * Share-locks the worktree, then checks its refresh fence and the source
+ * binding (#6007: both read in one statement after the lock; the fence is
+ * judged first, as before).
+ */
+async function assertWorktreeAdmission(tx: BrainEngine, input: WriteAdmission): Promise<void> {
+ await tx.executeRaw('SELECT id FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE', [input.worktreeId]);
+ const [state] = await tx.executeRaw<{ refresh: { id: string; state: string; source_ids: string[] } | string | null; bound: boolean }>(`SELECT
+ (SELECT row_to_json(f) FROM (SELECT id,state,source_ids FROM persistence_worktree_refreshes
+ WHERE worktree_id=$3::uuid AND state IN ${ACTIVE_REFRESH_STATES_SQL} LIMIT 1) f) AS refresh,
+ EXISTS (SELECT 1 FROM persistence_source_bindings WHERE source_id=$1
+ AND source_incarnation=$2::uuid AND worktree_id=$3::uuid AND topology_generation=$4) AS bound`,
+ [input.sourceId, input.sourceIncarnation, input.worktreeId, input.topologyGeneration]);
+ const refresh = typeof state?.refresh === 'string' ? JSON.parse(state.refresh) as { id: string; state: string; source_ids: string[] } : state?.refresh ?? null;
+ if (refresh) await assertWorktreeNotRefreshing(tx, input, refresh);
+ if (!state?.bound) throw opError('source_changed', 'The source binding changed during admission.',
+ `Source ${input.sourceId}'s worktree binding changed (a claim, transfer or lifecycle change) while this write was being admitted, so nothing was accepted. Check the owner with the command in fix, then submit the write again; reusing the same request_id is safe because nothing was recorded.`,
+ { fix: ownerStatusFix(input.sourceId) });
+}
+async function assertWorktreeNotRefreshing(tx: BrainEngine, input: WriteAdmission, refresh: { id: string; state: string; source_ids: string[] }): Promise<void> {
const managedSync = input.operation === 'submit_job' && String(input.intent.kind ?? '').startsWith('managed_sync_');
if (refresh.state === 'syncing' && managedSync) return;
if (refresh.state === 'syncing') {
@@ -424,20 +380,20 @@ export async function hasClaimableWrite(engine: SqlEngine, hostId: string, exclu
return row?.claimable === true;
}
-/** Claims commit before OS-lock waits. An unresolved head blocks its entire root. */
+/**
+ * Claims commit before OS-lock waits. An unresolved head blocks its entire
+ * root. #6007: one autocommit statement on the direct route selects, locks
+ * (skipping locked rows) and claims the head.
+ */
export async function claimNextWrite(engine: BrainEngine, hostId: string, leaseMs = 30_000, excludeRoots: string[] = []): Promise<WriteRequest | null> {
- return engine.transactionDirect(async tx => {
- await declarePersistenceProtocol(tx);
- const [row] = await tx.executeRaw<WriteRequest>(`SELECT r.* FROM persistence_requests r
+ const [claimed] = await engine.executeRawDirect<WriteRequest>(`UPDATE persistence_requests SET state='running',
+ execution_token=$3::uuid,claim_expires_at=now()+($4::double precision*interval '1 millisecond'),
+ updated_at=now(),blocked_reason=NULL
+ WHERE id=(SELECT r.id FROM persistence_requests r
LEFT JOIN persistence_worktrees w ON w.id=r.worktree_id
WHERE ${CLAIMABLE_WRITE_SQL}
- ORDER BY r.sequence LIMIT 1 FOR UPDATE OF r SKIP LOCKED`, [hostId, excludeRoots]);
- if (!row) return null;
- const [claimed] = await tx.executeRaw<WriteRequest>(`UPDATE persistence_requests SET state='running',
- execution_token=$2::uuid,claim_expires_at=now()+($3::double precision*interval '1 millisecond'),
- updated_at=now(),blocked_reason=NULL WHERE id=$1::uuid RETURNING *`, [row.id, randomUUID(), leaseMs]);
- return claimed;
- });
+ ORDER BY r.sequence LIMIT 1 FOR UPDATE OF r SKIP LOCKED) AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING *`, [hostId, excludeRoots, randomUUID(), leaseMs]);
+ return claimed ?? null;
}
export async function renewWriteClaim(engine: SqlEngine, id: string, token: string, leaseMs = 30_000, signal?: AbortSignal): Promise<boolean> {
const rows = await engine.executeRaw(`UPDATE persistence_requests SET
@@ -458,11 +414,19 @@ export async function prepareRecovery(engine: BrainEngine, row: WriteRequest, re
if (!row.worktree_id) throw new TypeError('Filesystem recovery requires a worktree.');
if (bytes > limits.worktreeRecoveryBytes || bytes > limits.brainRecoveryBytes) throw new OperationError('request_too_large', 'This request exceeds the configured recovery capacity.', 'Increase recovery capacity before submitting a new request.');
await engine.transaction(async tx => {
- await declarePersistenceProtocol(tx);
// A crash after rename must never lose the earlier recovery reservation,
// even when the deployment defaults ordinary transactions to async commit.
- await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','1s',true),set_config('statement_timeout','5s',true)");
+ await declareDurablePersistence(tx);
const counters = await lockCounters(tx, ['brain', `worktree:${row.worktree_id}`]);
+ const fits = counters.every(c => Number(c.recovery_bytes) + bytes <= (c.key === 'brain' ? limits.brainRecoveryBytes : limits.worktreeRecoveryBytes));
+ // #6007: the common case records the reservation in one statement; any other state takes the checked path below.
+ if (fits) {
+ const [reserved] = await tx.executeRaw(`WITH recorded AS (UPDATE persistence_requests SET recovery=$3::text::jsonb,recovery_bytes=$4,updated_at=now()
+ WHERE id=$1::uuid AND execution_token=$2::uuid AND state='running' AND recovery IS NULL RETURNING id),
+ reserved AS (UPDATE persistence_counters SET recovery_bytes=recovery_bytes+$4 WHERE key=ANY($5::text[]) AND EXISTS (SELECT 1 FROM recorded))
+ SELECT id FROM recorded`, [row.id, row.execution_token, JSON.stringify(recovery), bytes, counters.map(c => c.key)]);
+ if (reserved) return;
+ }
const [current] = await tx.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid FOR UPDATE', [row.id]);
if (!current || current.execution_token !== row.execution_token || current.state !== 'running') throw opError('write_claim_lost', 'The write execution claim was superseded.',
`Another owner pass claimed request ${row.request_id} in source ${row.source_id} before this pass recorded its recovery, so this pass stopped without publishing; the current claim finishes or recovers it. Inspect the request with the command in fix instead of resubmitting it.`,
@@ -474,9 +438,9 @@ export async function prepareRecovery(engine: BrainEngine, row: WriteRequest, re
return;
}
for (const c of counters) if (Number(c.recovery_bytes) + bytes > (c.key === 'brain' ? limits.brainRecoveryBytes : limits.worktreeRecoveryBytes)) throw capacityError('recovery bytes currently reserved by other requests');
- await tx.executeRaw(`UPDATE persistence_requests SET recovery=$3::text::jsonb,recovery_bytes=$4,updated_at=now()
- WHERE id=$1::uuid AND execution_token=$2::uuid`, [row.id, row.execution_token, JSON.stringify(recovery), bytes]);
- await tx.executeRaw('UPDATE persistence_counters SET recovery_bytes=recovery_bytes+$2 WHERE key=ANY($1::text[])', [counters.map(c => c.key), bytes]);
+ await tx.executeRaw(`WITH reserved AS (UPDATE persistence_counters SET recovery_bytes=recovery_bytes+$4 WHERE key=ANY($5::text[]))
+ UPDATE persistence_requests SET recovery=$3::text::jsonb,recovery_bytes=$4,updated_at=now()
+ WHERE id=$1::uuid AND execution_token=$2::uuid`, [row.id, row.execution_token, JSON.stringify(recovery), bytes, counters.map(c => c.key)]);
});
}
@@ -501,37 +465,55 @@ export async function completeWrite(tx: SqlEngine, row: WriteRequest, state: 'co
if (row.execution_token !== current.execution_token) throw opError('write_claim_lost', 'Write claim changed before completion.',
`Another owner pass claimed request ${row.request_id} in source ${row.source_id} before this pass recorded its outcome, so this pass's completion was discarded; the current claim records the final outcome. Inspect the request with the command in fix instead of resubmitting it.`,
{ fix: requestInspectFix(row) });
- const [effects] = await tx.executeRaw<{bytes:string}>(`SELECT COALESCE(SUM(octet_length(data::text)+octet_length(kind)+1024),0)::text AS bytes
- FROM persistence_effects WHERE request_id=$1::uuid`,[row.id]);
- if (jsonBytes(outcome) + jsonBytes(current.authority) + 1024 + Buffer.byteLength(error?.message ?? '') + (error?.detail ? jsonBytes(error.detail) : 0) + Number(effects.bytes) > Number(current.terminal_reservation)) throw capacityError('terminal result and effects exceed their reserved bounded encoding');
// Only publication stamps the consumer; failures, cancellations and conflicts leave it unset.
const stamp = writerStamp();
- const [done] = await tx.executeRaw<WriteRequest>(`UPDATE persistence_requests SET state=$2,outcome=$3::text::jsonb,
- error_code=$4,error_message=$5,error_detail=COALESCE($8::text::jsonb,error_detail),completed_at=now(),updated_at=now(),claim_expires_at=NULL,blocked_reason=NULL,
- consumer_version=CASE WHEN $2='committed' THEN $6 ELSE consumer_version END,
- consumer_host_id=CASE WHEN $2='committed' THEN $7::uuid ELSE consumer_host_id END,
- published_at=CASE WHEN $2='committed' THEN now() ELSE published_at END
- WHERE id=$1::uuid RETURNING *`, [row.id, state, JSON.stringify(outcome), error?.code ?? null, error?.message ?? null, stamp.version, stamp.hostId,
- error?.detail ? JSON.stringify(error.detail) : null]);
- await tx.executeRaw(`UPDATE persistence_counters SET outstanding_count=outstanding_count-1,intent_bytes=intent_bytes-$2
- WHERE key=ANY($1::text[])`, [['brain', principalKey(requestPrincipal(row))], Number(current.intent_bytes)]);
+ // #6007: one statement sizes the queued effects, checks the terminal reservation, completes the row and
+ // releases its outstanding counters; no row means the encoding exceeds the reservation and nothing changed.
+ const resultBytes = jsonBytes(outcome) + jsonBytes(current.authority) + 1024 + Buffer.byteLength(error?.message ?? '') + (error?.detail ? jsonBytes(error.detail) : 0);
+ const [done] = await tx.executeRaw<WriteRequest>(`WITH effects AS (SELECT COALESCE(SUM(octet_length(data::text)+octet_length(kind)+1024),0) AS bytes
+ FROM persistence_effects WHERE request_id=$1::uuid),
+ done AS (UPDATE persistence_requests SET state=$2,outcome=$3::text::jsonb,
+ error_code=$4,error_message=$5,error_detail=COALESCE($8::text::jsonb,error_detail),completed_at=now(),updated_at=now(),claim_expires_at=NULL,blocked_reason=NULL,
+ consumer_version=CASE WHEN $2='committed' THEN $6 ELSE consumer_version END,
+ consumer_host_id=CASE WHEN $2='committed' THEN $7::uuid ELSE consumer_host_id END,
+ published_at=CASE WHEN $2='committed' THEN now() ELSE published_at END
+ WHERE id=$1::uuid AND $9::bigint+(SELECT bytes FROM effects)<=terminal_reservation RETURNING *),
+ released AS (UPDATE persistence_counters SET outstanding_count=outstanding_count-1,intent_bytes=intent_bytes-$11
+ WHERE key=ANY($10::text[]) AND EXISTS (SELECT 1 FROM done))
+ SELECT * FROM done`, [row.id, state, JSON.stringify(outcome), error?.code ?? null, error?.message ?? null, stamp.version, stamp.hostId,
+ error?.detail ? JSON.stringify(error.detail) : null, resultBytes, ['brain', principalKey(requestPrincipal(row))], Number(current.intent_bytes)]);
+ if (!done) throw capacityError('terminal result and effects exceed their reserved bounded encoding');
// Recovery bytes remain reserved until physical cleanup has been verified.
return done;
}
-export async function clearResolvedRecovery(engine: BrainEngine, id: string): Promise<void> {
- const row = await getWriteRequestById(engine, id);
+/**
+ * `known` is the row a publication just completed, passed while it still
+ * holds the worktree's native lock, so neither its recovery record nor its
+ * staging files can change: its staging is checked first and the record is
+ * cleared in one statement when it is still exactly that record.
+ */
+export async function clearResolvedRecovery(engine: BrainEngine, id: string, known?: WriteRequest): Promise<void> {
+ const row = known ?? await getWriteRequestById(engine, id);
if (!row?.recovery || !isTerminal(row)) return;
+ if (known) for (const file of recoveryFiles(row.recovery)) assertRecoveryStagingAbsent(file);
await engine.transaction(async tx => {
- await declarePersistenceProtocol(tx);
- await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','1s',true),set_config('statement_timeout','5s',true)");
+ await declareDurablePersistence(tx);
const keys = ['brain', ...(row.worktree_id ? [`worktree:${row.worktree_id}`] : [])];
await lockCounters(tx, keys);
+ if (known) {
+ const [cleared] = await tx.executeRaw(`WITH locked AS (SELECT id,recovery_bytes FROM persistence_requests WHERE id=$1::uuid AND recovery=$3::text::jsonb
+ AND state IN ('committed','conflict','failed','cancelled') FOR UPDATE),
+ released AS (UPDATE persistence_counters SET recovery_bytes=recovery_bytes-(SELECT recovery_bytes FROM locked) WHERE key=ANY($2::text[]) AND EXISTS (SELECT 1 FROM locked))
+ UPDATE persistence_requests r SET recovery=NULL,recovery_bytes=0,blocked_reason=NULL FROM locked WHERE r.id=locked.id RETURNING r.id`,
+ [id, keys, JSON.stringify(row.recovery)]);
+ if (cleared) return;
+ }
const [locked] = await tx.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid FOR UPDATE', [id]);
if (!locked?.recovery || !isTerminal(locked)) return;
for (const file of recoveryFiles(locked.recovery)) assertRecoveryStagingAbsent(file);
- await tx.executeRaw('UPDATE persistence_counters SET recovery_bytes=recovery_bytes-$2 WHERE key=ANY($1::text[])', [keys, Number(locked.recovery_bytes)]);
- await tx.executeRaw('UPDATE persistence_requests SET recovery=NULL,recovery_bytes=0,blocked_reason=NULL WHERE id=$1::uuid', [id]);
+ await tx.executeRaw(`WITH released AS (UPDATE persistence_counters SET recovery_bytes=recovery_bytes-$3 WHERE key=ANY($2::text[]))
+ UPDATE persistence_requests SET recovery=NULL,recovery_bytes=0,blocked_reason=NULL WHERE id=$1::uuid`, [id, keys, Number(locked.recovery_bytes)]);
});
}
export async function markRecovering(engine: SqlEngine, row: WriteRequest, reason: string, failure?: {code:string;message:string;detail?:unknown}): Promise<void> {
diff --git a/src/core/persistence/page-batch.ts b/src/core/persistence/page-batch.ts
index ba0c79b66a..be1cd0313e 100644
--- a/src/core/persistence/page-batch.ts
+++ b/src/core/persistence/page-batch.ts
@@ -12,7 +12,10 @@
*/
import type { OperationContext } from '../ops/contract.ts';
import { OperationError, opError } from '../ops/contract.ts';
-import { admitWrites, type WriteAdmission } from './journal.ts';
+import { admitWriteGroupInTransaction, type WriteAdmission } from './journal.ts';
+import { retryWriteAdmission } from './admission-retry.ts';
+import { declareDurablePersistence } from './protocol.ts';
+import { digest } from './digest.ts';
import { queueLinksReconcile } from './effect-journal.ts';
import { pageBatchChildRequestId, pageBatchChildRequestIds } from './page-batch-id.ts';
@@ -132,6 +135,28 @@ function batchReceipt(ctx: OperationContext, batchId: string, sourceId: string,
...(retryAfterMs !== null ? { retry_after_ms: retryAfterMs } : {}), next, links, pages };
}
+/**
+ * Every new page of the batch in ONE transaction, so capacity is reserved for
+ * all of them or none. Pages whose stored authority differs (for example one
+ * page is database-only) are admitted as separate groups inside it.
+ */
+async function admitBatch(ctx: OperationContext, batchId: string, admissions: WriteAdmission[]): Promise<WriteRequest[]> {
+ const groups = new Map<string, number[]>();
+ admissions.forEach((admission, index) => {
+ const key = digest(admission.authority);
+ groups.set(key, [...(groups.get(key) ?? []), index]);
+ });
+ return retryWriteAdmission(`batch ${batchId}`, remaining => ctx.engine.transaction(async tx => {
+ await declareDurablePersistence(tx, `${Math.min(1000, remaining)}ms`, `${remaining}ms`);
+ const rows: WriteRequest[] = new Array(admissions.length);
+ for (const indexes of groups.values()) {
+ const admitted = await admitWriteGroupInTransaction(tx, indexes.map(index => admissions[index]!));
+ indexes.forEach((index, position) => { rows[index] = admitted[position]!; });
+ }
+ return rows;
+ }), BATCH_ADMISSION_BUDGET_MS);
+}
+
async function prepareAll(ctx: OperationContext, batchId: string, sourceId: string, pages: BatchPage[]) {
const prepared: (Awaited<ReturnType<typeof preparePageAdmission>> | OperationError)[] = new Array(pages.length);
const prepareOne = async (index: number) => {
@@ -206,8 +231,7 @@ export async function submitPageBatch(ctx: OperationContext, params: Record<stri
if (admissions.length) {
let admitted: WriteRequest[];
try {
- admitted = await admitWrites(ctx.engine, admissions.map(entry => entry.admission), undefined,
- { budgetMs: BATCH_ADMISSION_BUDGET_MS, retryLabel: `batch ${batchId}` });
+ admitted = await admitBatch(ctx, batchId, admissions.map(entry => entry.admission));
} catch (error) {
if (error instanceof OperationError && error.code === 'queue_capacity') {
throw new OperationError('queue_capacity', `${error.message} No page of batch ${batchId} was admitted (it needs ${admissions.length} new write slots).`,
diff --git a/src/core/persistence/protocol.ts b/src/core/persistence/protocol.ts
index aac5d9bd6f..413758748c 100644
--- a/src/core/persistence/protocol.ts
+++ b/src/core/persistence/protocol.ts
@@ -10,6 +10,17 @@ export async function declarePersistenceProtocol(tx: SqlEngine): Promise<void> {
if (inTransaction) declared.add(tx);
}
+/**
+ * #6007: the protocol declaration plus the durable-write settings (synchronous
+ * commit, lock and statement timeouts) in one round trip. Later
+ * `declarePersistenceProtocol` calls on the same transaction engine are free.
+ */
+export async function declareDurablePersistence(tx: SqlEngine, lockTimeout = '1s', statementTimeout = '5s'): Promise<void> {
+ await tx.executeRaw(`SELECT set_config('gbrain.persistence_protocol','2',true),set_config('synchronous_commit','on',true),
+ set_config('lock_timeout',$1,true),set_config('statement_timeout',$2,true)`, [lockTimeout, statementTimeout]);
+ if ((tx as { _pageTransaction?: boolean })._pageTransaction === true) declared.add(tx);
+}
+
export const PERSISTENCE_PROTOCOL_PREDICATE = "set_config('gbrain.persistence_protocol','2',true)='2'";
export function assertMutationProtocol(row: Pick<WriteRequest, 'target_kind' | 'protocol_version'>): void {
diff --git a/src/core/shared-skills/knowledge-guard.ts b/src/core/shared-skills/knowledge-guard.ts
index 543b8dcc8f..1e28a0ab8e 100644
--- a/src/core/shared-skills/knowledge-guard.ts
+++ b/src/core/shared-skills/knowledge-guard.ts
@@ -28,11 +28,22 @@ function reject(): never {
}
const packsInTransaction = new WeakMap<object, Promise<PackRoot[]>>();
+/** Engines (the connection owner, not a transaction view of it) whose schema has shared_skill_packs; migrations never drop it. */
+const packTablePresent = new WeakSet<object>();
+function connectionOwner(engine: object): object {
+ let owner = engine;
+ while (Object.hasOwn(owner, '_pageTransaction') && (owner as { _pageTransaction?: boolean })._pageTransaction === true) owner = Object.getPrototypeOf(owner);
+ return owner;
+}
/** The shared skillpack roots; #5984: read once per transaction engine. */
function sharedPacks(engine: SqlEngine): Promise<PackRoot[]> {
const read = async () => {
- const [schema] = await engine.executeRaw<{ present: boolean }>("SELECT to_regclass('shared_skill_packs') IS NOT NULL AS present");
- if (!schema?.present) return [];
+ const owner = connectionOwner(engine);
+ if (!packTablePresent.has(owner)) {
+ const [schema] = await engine.executeRaw<{ present: boolean }>("SELECT to_regclass('shared_skill_packs') IS NOT NULL AS present");
+ if (!schema?.present) return [];
+ packTablePresent.add(owner);
+ }
return engine.executeRaw<PackRoot>(`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
diff --git a/test/e2e/page-guards-postgres.test.ts b/test/e2e/page-guards-postgres.test.ts
new file mode 100644
index 0000000000..15fb118cde
--- /dev/null
+++ b/test/e2e/page-guards-postgres.test.ts
@@ -0,0 +1,175 @@
+/**
+ * #6007: set-based page guards and counter locks on real Postgres, with
+ * concurrent transactions on separate pooled connections. lockPageKeys takes
+ * the source share locks, the guard rows and the pages rows in three
+ * statements; a transaction (and its savepoints) never re-acquires a key it
+ * holds; lockCounters creates and locks a counter set in one statement.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { hasDatabase } from './helpers.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { lockCounters } from '../../src/core/persistence/journal.ts';
+
+const d = hasDatabase() ? describe : describe.skip;
+const A = 'guard-src-a', B = 'guard-src-b';
+const page = { type: 'note' as const, title: 'Guard fixture', compiled_truth: 'Synthetic guarded body.', timeline: '', frontmatter: {} };
+
+/** Resolves true when the promise settles within the window, false while it is still blocked. */
+const settlesWithin = (promise: Promise<unknown>, ms = 400) =>
+ Promise.race([promise.then(() => true, () => true), Bun.sleep(ms).then(() => false)]);
+/** A transaction held open until `release` resolves. */
+function holdTransaction(engine: BrainEngine, body: (tx: BrainEngine) => Promise<void>) {
+ let release!: () => void;
+ let ready!: () => void;
+ const released = new Promise<void>(resolve => { release = resolve; });
+ const entered = new Promise<void>(resolve => { ready = resolve; });
+ const done = engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('lock_timeout','15s',true)");
+ await body(tx);
+ ready();
+ await released;
+ });
+ done.catch(() => ready());
+ return { entered, release, done };
+}
+
+d('#6007 set-based page guards on Postgres', () => {
+ let engine: PostgresEngine;
+ let close: () => Promise<void>;
+ beforeAll(async () => {
+ ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ for (const id of [A, B]) await engine.executeRaw('INSERT INTO sources(id,name) VALUES ($1,$1)', [id]);
+ await engine.putPage('present', page, { sourceId: A });
+ }, 120_000);
+ afterAll(async () => { await close(); });
+
+ test('a missing source refuses with the same error and creates no guard rows', async () => {
+ const before = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM page_write_guards');
+ await expect(engine.transaction(tx => tx.lockPageKeys([{ sourceId: A, slug: 'fresh-one' }, { sourceId: 'guard-src-missing', slug: 'x' }])))
+ .rejects.toThrow('Page source does not exist: guard-src-missing');
+ expect(await engine.executeRaw('SELECT count(*)::int AS n FROM page_write_guards')).toEqual(before);
+ });
+
+ test('a guard on an absent page blocks another transaction from creating that page until it ends', async () => {
+ const holder = holdTransaction(engine, tx => tx.lockPageKeys([{ sourceId: A, slug: 'absent-page' }]));
+ await holder.entered;
+ const writer = engine.putPage('absent-page', page, { sourceId: A });
+ expect(await settlesWithin(writer)).toBe(false);
+ expect(await engine.executeRaw("SELECT id FROM pages WHERE source_id=$1 AND slug='absent-page'", [A])).toEqual([]);
+ holder.release();
+ await holder.done;
+ await writer;
+ expect((await engine.executeRaw("SELECT id FROM pages WHERE source_id=$1 AND slug='absent-page'", [A])).length).toBe(1);
+ });
+
+ test('an existing pages row is locked against direct SQL writers', async () => {
+ const holder = holdTransaction(engine, tx => tx.lockPageKeys([{ sourceId: A, slug: 'present' }]));
+ await holder.entered;
+ const direct = engine.executeRaw("UPDATE pages SET frontmatter='{}'::jsonb WHERE source_id=$1 AND slug='present'", [A]);
+ expect(await settlesWithin(direct)).toBe(false);
+ holder.release();
+ await holder.done;
+ await direct;
+ });
+
+ test('a rolled-back savepoint releases its new guard and forgets it; the outer transaction locks it again', async () => {
+ const key = { sourceId: B, slug: 'savepoint-rollback' };
+ const holder = holdTransaction(engine, async tx => {
+ await expect(tx.transaction(async child => { await child.lockPageKeys([key]); throw new Error('child rollback'); })).rejects.toThrow('child rollback');
+ // Released by the savepoint rollback: another transaction takes it at once.
+ expect(await settlesWithin(engine.transaction(other => other.lockPageKeys([key])))).toBe(true);
+ // Not remembered as held: this call locks it for real.
+ await tx.lockPageKeys([key]);
+ });
+ await holder.entered;
+ const contender = engine.transaction(other => other.lockPageKeys([key]));
+ expect(await settlesWithin(contender)).toBe(false);
+ holder.release();
+ await holder.done;
+ await contender;
+ });
+
+ test('a released savepoint keeps its guard for the outer transaction until commit', async () => {
+ const key = { sourceId: B, slug: 'savepoint-release' };
+ const holder = holdTransaction(engine, async tx => {
+ await tx.transaction(child => child.lockPageKeys([key]));
+ await tx.lockPageKeys([key]);
+ });
+ await holder.entered;
+ const contender = engine.transaction(other => other.lockPageKeys([key]));
+ expect(await settlesWithin(contender)).toBe(false);
+ holder.release();
+ await holder.done;
+ await contender;
+ });
+
+ test('an outer rollback releases every guard it took', async () => {
+ const keys = [{ sourceId: A, slug: 'outer-1' }, { sourceId: B, slug: 'outer-2' }];
+ await expect(engine.transaction(async tx => { await tx.lockPageKeys(keys); throw new Error('outer rollback'); })).rejects.toThrow('outer rollback');
+ expect(await settlesWithin(engine.transaction(tx => tx.lockPageKeys(keys)))).toBe(true);
+ });
+
+ test('pooled transactions keep separate held sets', async () => {
+ const key = { sourceId: A, slug: 'pooled' };
+ const first = holdTransaction(engine, tx => tx.lockPageKeys([key]));
+ await first.entered;
+ const second = engine.transaction(tx => tx.lockPageKeys([key]));
+ expect(await settlesWithin(second)).toBe(false);
+ first.release();
+ await first.done;
+ await second;
+ });
+
+ test('concurrent overlapping multi-source key sets in any input order never deadlock', async () => {
+ const all = [A, B].flatMap(sourceId => ['k1', 'k2', 'k3', 'present'].map(slug => ({ sourceId, slug })));
+ const shuffled = (seed: number) => [...all].sort((x, y) => ((x.slug.charCodeAt(1) * 31 + x.sourceId.length * seed) % 7) - ((y.slug.charCodeAt(1) * 31 + y.sourceId.length * seed) % 7));
+ const results = await Promise.allSettled(Array.from({ length: 12 }, (_, i) => engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('lock_timeout','10s',true)");
+ const keys = shuffled(i + 1).slice(i % 3, i % 3 + 5);
+ await tx.lockPageKeys(keys);
+ await Bun.sleep(5);
+ // Held keys are not re-acquired, so repeating a subset in another order is free of lock waits.
+ await tx.lockPageKeys([...keys].reverse().slice(1));
+ })));
+ expect(results.filter(r => r.status === 'rejected').map(r => String((r as PromiseRejectedResult).reason))).toEqual([]);
+ });
+});
+
+d('#6007 one-statement counter locks on Postgres', () => {
+ let engine: PostgresEngine;
+ let close: () => Promise<void>;
+ beforeAll(async () => { ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!)); }, 120_000);
+ afterAll(async () => { await close(); });
+
+ test('simultaneous first creation of overlapping counter sets creates each row once and serializes every holder', async () => {
+ const keySets = Array.from({ length: 10 }, (_, i) => ['brain', `counter:${i % 3}`, `counter:${(i + 1) % 4}`, 'counter:shared'].reverse());
+ const returned = await Promise.all(keySets.map(keys => engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('lock_timeout','10s',true)");
+ const rows = await lockCounters(tx, keys);
+ await tx.executeRaw('UPDATE persistence_counters SET outstanding_count=outstanding_count+1 WHERE key=ANY($1::text[])', [rows.map(row => row.key)]);
+ return rows.map(row => row.key);
+ })));
+ for (const [i, keys] of returned.entries()) expect(keys).toEqual([...new Set(keySets[i]!)].sort());
+ const counts = Object.fromEntries((await engine.executeRaw<{ key: string; n: number }>(
+ 'SELECT key,outstanding_count::int AS n FROM persistence_counters ORDER BY key')).map(row => [row.key, row.n]));
+ const expected: Record<string, number> = {};
+ for (const keys of keySets) for (const key of new Set(keys)) expected[key] = (expected[key] ?? 0) + 1;
+ expect(counts).toEqual(expected);
+ });
+
+ test('a counter row already locked by another transaction is waited for, then returned current', async () => {
+ await engine.transaction(tx => lockCounters(tx, ['counter:wait']));
+ const holder = holdTransaction(engine, async tx => {
+ await lockCounters(tx, ['counter:wait']);
+ await tx.executeRaw("UPDATE persistence_counters SET outstanding_count=41 WHERE key='counter:wait'");
+ });
+ await holder.entered;
+ const waiter = engine.transaction(tx => lockCounters(tx, ['counter:wait', 'brain']));
+ expect(await settlesWithin(waiter)).toBe(false);
+ holder.release();
+ await holder.done;
+ expect((await waiter).map(row => [row.key, Number(row.outstanding_count)])).toEqual([['brain', expect.any(Number)], ['counter:wait', 41]]);
+ });
+});
diff --git a/test/e2e/persistence-statement-budget.test.ts b/test/e2e/persistence-statement-budget.test.ts
new file mode 100644
index 0000000000..53a37dbc15
--- /dev/null
+++ b/test/e2e/persistence-statement-budget.test.ts
@@ -0,0 +1,196 @@
+/**
+ * #6007: SQL statements one remote put_page of a new ~60 KB page issues on
+ * Postgres, per phase of the coordinated write path, counted at the socket by
+ * the env-gated wire trace (src/core/sql-trace.ts). Each round trip is one
+ * record; `execute` and `simple` records are statements, `describe` records
+ * are the extra round trip a statement pays the first time a pooled
+ * connection prepares it (reported, not budgeted: which connection runs a
+ * statement is not deterministic).
+ *
+ * Phases come from the transaction each statement runs in (begin..commit on
+ * one connection, labelled by its signature statement) and, for statements
+ * outside a transaction, from known consumer-scan and effect statements or
+ * the statement's position between the transactions.
+ */
+import { describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { randomUUID } from 'node:crypto';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { hasDatabase } from './helpers.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { dispatchToolCall } from '../../src/mcp/dispatch.ts';
+import { claimWorktree } from '../../src/core/persistence/ownership.ts';
+import { registerLocalWriter, withVerifiedLocalRegistration, type LocalRegistration } from '../../src/core/persistence/identity.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';
+
+interface TraceRecord { t: number; ms: number; conn: number; kind: string; sql: string }
+type Phase = 'admission' | 'claim' | 'prepare' | 'recovery_record' | 'publication' | 'completion' | 'consumer_scan' | 'wait_poll' | 'effects' | 'other';
+const CRITICAL: Phase[] = ['admission', 'claim', 'prepare', 'recovery_record', 'publication', 'completion'];
+
+/**
+ * Per-phase statement budgets, about 10% above the measured counts (#6007
+ * measured admission 25, claim 2, prepare 19, recovery record 6, publication
+ * 52, completion 6: 110 on the critical path, and an 8-statement receipt; the
+ * code before #6007 measured 29, 9, 21, 9, 61, 10: 139, and 10).
+ */
+const BUDGET: Record<string, number> = {
+ admission: 28, claim: 3, prepare: 21, recovery_record: 7, publication: 57, completion: 7, critical_path: 121, receipt: 9,
+};
+
+const SCAN = [
+ /^SELECT \( EXISTS/, /^SELECT EXISTS \(SELECT 1 FROM persistence_requests r/, /FROM persistence_brain WHERE singleton=1/,
+ /persistence_host_bindings h JOIN persistence_source_bindings/, /r\.recovery IS NOT NULL AND NOT\(r\.worktree_id/,
+ /FROM persistence_effects e JOIN persistence_worktrees w ON w\.id=e\.worktree_id WHERE e\.recovery IS NOT NULL/,
+ /FROM persistence_topology_changes c/, /FROM persistence_worktree_refreshes f JOIN/, /^WITH expired AS/, /page_projection_jobs/,
+];
+const statementKinds = new Set(['execute', 'simple']);
+const flat = (sql: string) => sql.replace(/\s+/g, ' ').trim();
+
+function classify(records: TraceRecord[]) {
+ const sorted = records.filter(r => r.kind !== 'connect').sort((a, b) => a.t - b.t);
+ const open = new Map<number, TraceRecord[]>();
+ const groups: { records: TraceRecord[]; begin: number; end: number }[] = [];
+ const standalone: TraceRecord[] = [];
+ for (const record of sorted) {
+ const text = flat(record.sql).toLowerCase();
+ const group = open.get(record.conn);
+ if (text === 'begin' && record.kind === 'simple') { open.set(record.conn, [record]); continue; }
+ if (!group) { standalone.push(record); continue; }
+ group.push(record);
+ if (text === 'commit' || text === 'rollback') {
+ open.delete(record.conn);
+ groups.push({ records: group, begin: group[0]!.t, end: record.t });
+ }
+ }
+ for (const group of open.values()) groups.push({ records: group, begin: group[0]!.t, end: group[group.length - 1]!.t });
+ const labelled = groups.map(group => {
+ const text = group.records.map(r => flat(r.sql)).join('\n');
+ let phase: Phase = 'other';
+ if (/INSERT INTO persistence_requests/.test(text)) phase = 'admission';
+ else if (/SET publication_started=true|UPDATE persistence_requests SET state=\$2,outcome/.test(text)) phase = 'publication';
+ else if (/UPDATE persistence_requests SET recovery=\$3/.test(text)) phase = 'recovery_record';
+ else if (/UPDATE persistence_requests (r )?SET recovery=NULL/.test(text)) phase = 'completion';
+ else if (/FROM persistence_requests r LEFT JOIN persistence_worktrees w ON w\.id=r\.worktree_id WHERE r\.state='queued'/.test(text)) phase = 'claim';
+ else if (/persistence_effects/.test(text)) phase = 'effects';
+ return { ...group, phase };
+ });
+ const anchor = (phase: Phase, edge: 'begin' | 'end') => {
+ const found = labelled.filter(group => group.phase === phase);
+ return found.length ? (edge === 'begin' ? Math.min(...found.map(g => g.begin)) : Math.max(...found.map(g => g.end))) : undefined;
+ };
+ const admissionBegin = anchor('admission', 'begin') ?? Infinity;
+ const claimEnd = labelled.filter(g => g.phase === 'claim' && /SET state='running'/.test(g.records.map(r => r.sql).join('\n'))).map(g => g.end)[0]
+ ?? standalone.find(r => /^UPDATE persistence_requests SET state='running'/.test(flat(r.sql)) && statementKinds.has(r.kind))?.t
+ ?? anchor('claim', 'end') ?? Infinity;
+ const publicationBegin = anchor('publication', 'begin') ?? Infinity;
+ const publicationEnd = anchor('publication', 'end') ?? Infinity;
+ const phaseOf = (record: TraceRecord): Phase => {
+ const text = flat(record.sql);
+ if (SCAN.some(pattern => pattern.test(text))) return 'consumer_scan';
+ if (/^SELECT state,error_code,error_message,completed_at,updated_at,blocked_reason,outcome FROM persistence_requests/.test(text)) return 'wait_poll';
+ if (/^UPDATE persistence_requests SET state='running'/.test(text) || /FOR UPDATE OF r SKIP LOCKED\) RETURNING/.test(text)) return 'claim';
+ if (/persistence_effects/.test(text) && record.t > publicationEnd) return 'effects';
+ if (record.t < admissionBegin) return 'admission';
+ if (record.t > claimEnd && record.t < publicationBegin) return 'prepare';
+ if (record.t > publicationEnd) return /^SELECT \* FROM persistence_requests WHERE id=\$1::uuid$/.test(text) ? 'completion' : 'effects';
+ return 'other';
+ };
+ const counts = new Map<string, { statements: number; describes: number }>();
+ const add = (phase: string, record: TraceRecord) => {
+ const entry = counts.get(phase) ?? { statements: 0, describes: 0 };
+ if (statementKinds.has(record.kind)) entry.statements++; else if (record.kind === 'describe') entry.describes++;
+ counts.set(phase, entry);
+ };
+ for (const group of labelled) {
+ // A transaction that starts after the publication commit and is not the completion belongs to post-commit effects.
+ const phase = group.phase === 'other' && group.begin > publicationEnd ? 'effects' : group.phase;
+ for (const record of group.records) add(phase, record);
+ }
+ for (const record of standalone) add(phaseOf(record), record);
+ const result: Record<string, { statements: number; describes: number }> = Object.fromEntries(counts);
+ result.critical_path = CRITICAL.reduce((sum, phase) => ({
+ statements: sum.statements + (counts.get(phase)?.statements ?? 0), describes: sum.describes + (counts.get(phase)?.describes ?? 0),
+ }), { statements: 0, describes: 0 });
+ return result;
+}
+
+const d = hasDatabase() ? describe : describe.skip;
+d('#6007 put_page statement budget (Postgres)', () => {
+ test('one remote put_page of a new 60 KB page stays within its per-phase statement budget', async () => {
+ const fixtureDir = mkdtempSync(join(tmpdir(), 'gbrain-statement-budget-'));
+ const trace = join(fixtureDir, 'trace.jsonl');
+ const root = join(fixtureDir, 'brain'); mkdirSync(root);
+ _resetWriteThroughCacheForTest();
+ await withEnv({ GBRAIN_SQL_TRACE: trace, GBRAIN_SQL_TRACE_LABEL: 'statement-budget', GBRAIN_HOME: join(fixtureDir, 'home') }, async () => {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ const engine: PostgresEngine = pg.engine;
+ try {
+ await engine.setConfig('sync.repo_path', root);
+ await claimWorktree(engine, 'default', root);
+ const registration: LocalRegistration = await registerLocalWriter(engine, 'stdio', {
+ sourceIds: ['default'], operations: null, scopes: ['read', 'write'], slugPrefixes: ['notes'],
+ });
+ const dispatch = async (name: string, params: Record<string, unknown>) => {
+ const response = await withVerifiedLocalRegistration(engine, registration, () => dispatchToolCall(engine, name, params, {
+ remote: true, config: { engine: 'postgres', embedding_disabled: true }, sourceId: 'default',
+ auth: { token: 'fixture', clientId: 'fixture-client', scopes: ['read', 'write'], sourceId: 'default', boundSlugPrefixes: ['notes'] },
+ logger: { info() {}, warn() {}, error() {} },
+ }));
+ return JSON.parse((response.content[0] as { text: string }).text) as Record<string, unknown>;
+ };
+ const body = Array.from({ length: 600 }, (_, i) => `Paragraph ${i}: ${'measured canonical text '.repeat(4)}`).join('\n\n');
+ expect(Buffer.byteLength(body)).toBeGreaterThan(55_000);
+ const settle = async () => {
+ for (let i = 0; i < 200; i++) {
+ const [row] = await engine.executeRaw<{ n: number }>(
+ "SELECT count(*)::int AS n FROM persistence_effects WHERE state IN ('queued','running')");
+ if (row!.n === 0) break;
+ await Bun.sleep(25);
+ }
+ await Bun.sleep(400);
+ };
+ const now = () => performance.timeOrigin + performance.now();
+ const measured: { put: Record<string, { statements: number; describes: number }>; receipt: { statements: number; describes: number } }[] = [];
+ const windows: { put: [number, number]; receipt: [number, number] }[] = [];
+ for (let i = 0; i < 5; i++) {
+ await settle();
+ const requestId = randomUUID();
+ const started = now();
+ const result = await dispatch('put_page', { slug: `notes/budget-${i}`, content: `---\ntitle: Budget ${i}\ntype: note\n---\n\n${body}`, request_id: requestId });
+ const finished = now();
+ expect(result.state).toBe('committed');
+ await settle();
+ const receiptStart = now();
+ const receipt = await dispatch('get_write_request', { request_id: requestId });
+ const receiptEnd = now();
+ expect(receipt.state).toBe('committed');
+ windows.push({ put: [started, finished], receipt: [receiptStart, receiptEnd] });
+ }
+ await Bun.sleep(1300);
+ const records = readFileSync(trace, 'utf8').trim().split('\n').map(line => JSON.parse(line) as TraceRecord);
+ // The first two writes warm the pool's prepared statements; the last three are measured.
+ for (const window of windows.slice(2)) {
+ const inWindow = (range: [number, number]) => records.filter(r => r.t >= range[0] && r.t <= range[1]);
+ const receiptRecords = inWindow(window.receipt).filter(r => r.kind !== 'connect' && !SCAN.some(p => p.test(flat(r.sql))) && !/persistence_effects e/.test(r.sql));
+ measured.push({ put: classify(inWindow(window.put)), receipt: {
+ statements: receiptRecords.filter(r => statementKinds.has(r.kind)).length, describes: receiptRecords.filter(r => r.kind === 'describe').length } });
+ }
+ console.log(`[statement-budget] ${JSON.stringify(measured.map(m => ({ ...Object.fromEntries(Object.entries(m.put).map(([k, v]) => [k, `${v.statements}+${v.describes}d`])), receipt: `${m.receipt.statements}+${m.receipt.describes}d` })))}`);
+ for (const m of measured) {
+ for (const [phase, budget] of Object.entries(BUDGET)) {
+ const value = phase === 'receipt' ? m.receipt.statements : m.put[phase]?.statements ?? 0;
+ expect({ phase, statements: value }).toEqual({ phase, statements: Math.min(value, budget) });
+ }
+ }
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await pg.close();
+ }
+ });
+ rmSync(fixtureDir, { recursive: true, force: true });
+ }, 120_000);
+});
diff --git a/test/page-embedding-install-batch.test.ts b/test/page-embedding-install-batch.test.ts
new file mode 100644
index 0000000000..1d3b1cfc56
--- /dev/null
+++ b/test/page-embedding-install-batch.test.ts
@@ -0,0 +1,102 @@
+/**
+ * #6007: installPageEmbeddings writes every chunk's vector, image, model,
+ * input hash and embedded stamps in one set-based UPDATE. Each case pins the
+ * per-chunk semantics the old one-UPDATE-per-chunk loop had, on PGLite and
+ * (with DATABASE_URL) an isolated Postgres database.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { installPageEmbeddings, installPageProjection, preparePageProjection, readProjectionSnapshot } from '../src/core/page-state/projections.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const sourceId = 'embedding-batch-test';
+const slug = 'batch-page';
+const vector = (head: number) => { const v = new Float32Array(1536); v[0] = head; v[1] = -0.5; return v; };
+const text = (v: Float32Array) => `[${Array.from(v).join(',')}]`;
+const image = new Float32Array(1024); image[0] = 0.75;
+
+interface Row { chunk_index: number; chunk_text: string; embedding: string | null; embedding_image: string | null; model: string;
+ embedded_at: string | null; embedded_text_hash: string | null; embedding_input_hash: string | null; text_md5: string }
+
+for (const kind of testBackends()) {
+ describe(`set-based embedding install (${kind})`, () => {
+ let engine: BrainEngine;
+ let closePostgres: (() => Promise<void>) | undefined;
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close: closePostgres } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }
+ }, 120_000);
+ beforeEach(async () => {
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES ($1,$1)', [sourceId]);
+ await engine.putPage(slug, { type: 'note', title: 'Batch fixture', compiled_truth: 'Synthetic body for batched vectors.',
+ timeline: '2026-01-02: Synthetic event.', frontmatter: {} }, { sourceId });
+ await seal();
+ });
+ afterEach(async () => { await engine.executeRaw('DELETE FROM sources WHERE id=$1', [sourceId]); });
+ afterAll(async () => { if (kind === 'pglite') await engine.disconnect(); await closePostgres?.(); });
+
+ const rows = async () => engine.executeRaw<Row>(`SELECT cc.chunk_index,cc.chunk_text,cc.embedding::text AS embedding,cc.embedding_image::text AS embedding_image,
+ cc.model,cc.embedded_at::text AS embedded_at,cc.embedded_text_hash,cc.embedding_input_hash,md5(cc.chunk_text) AS text_md5
+ FROM content_chunks cc JOIN pages p ON p.id=cc.page_id WHERE p.source_id=$1 AND p.slug=$2 ORDER BY cc.chunk_index`, [sourceId, slug]);
+ const seal = async () => {
+ const prepared = (await readProjectionSnapshot(engine, slug, sourceId, { allowUnsealed: true }))!;
+ await installPageProjection(engine, prepared, (await preparePageProjection(prepared)).chunks, { seal: true });
+ };
+ const capture = async () => {
+ const prepared = (await readProjectionSnapshot(engine, slug, sourceId))!;
+ const { chunks } = await preparePageProjection(prepared);
+ return { prepared, chunks };
+ };
+
+ test('a partially refused batch writes only the chunks that came back and leaves the others untouched', async () => {
+ const { prepared, chunks } = await capture();
+ expect(chunks.length).toBeGreaterThanOrEqual(2);
+ const before = await rows();
+ expect(await installPageEmbeddings(engine, prepared, chunks.map((c, i) => i === 0 ? { ...c, embedding: vector(0.25) } : c))).toBe(true);
+ const after = await rows();
+ expect(after[0]!.embedding).toBe(text(vector(0.25)));
+ expect(after[0]!.embedded_text_hash).toBe(after[0]!.text_md5);
+ expect(after[0]!.embedded_at).not.toBeNull();
+ expect(after[0]!.embedding_input_hash).toMatch(/^[0-9a-f]{64}$/);
+ expect(after[0]!.model).toBe(prepared.embeddingModel!);
+ expect(after.slice(1)).toEqual(before.slice(1));
+ });
+
+ test('an image-only chunk keeps its text vector, input hash and model and gains the image and stamps', async () => {
+ const { prepared, chunks } = await capture();
+ expect(await installPageEmbeddings(engine, prepared, chunks.map(c => ({ ...c, embedding: vector(0.5), model: 'test:text-model' })))).toBe(true);
+ const withText = await rows();
+ const again = await capture();
+ expect(await installPageEmbeddings(engine, again.prepared, again.chunks.map((c, i) => i === 1 ? { ...c, embedding_image: image } : c))).toBe(true);
+ const after = await rows();
+ expect(after[0]).toEqual(withText[0]!);
+ expect(after[1]!.embedding).toBe(withText[1]!.embedding);
+ expect(after[1]!.embedding_input_hash).toBe(withText[1]!.embedding_input_hash);
+ expect(after[1]!.model).toBe('test:text-model');
+ expect(after[1]!.embedding_image).toBe(text(image));
+ expect(after[1]!.embedded_text_hash).toBe(after[1]!.text_md5);
+ });
+
+ test('every chunk in one call gets its own vector, model and input hash', async () => {
+ const { prepared, chunks } = await capture();
+ expect(await installPageEmbeddings(engine, prepared, chunks.map((c, i) => ({ ...c, embedding: vector(0.125 * (i + 1)), model: `test:model-${i}` })))).toBe(true);
+ const after = await rows();
+ expect(after.map(r => r.embedding)).toEqual(chunks.map((_, i) => text(vector(0.125 * (i + 1)))));
+ expect(after.map(r => r.model)).toEqual(chunks.map((_, i) => `test:model-${i}`));
+ expect(new Set(after.map(r => r.embedding_input_hash)).size).toBe(after.length);
+ for (const row of after) expect(row.embedded_text_hash).toBe(row.text_md5);
+ });
+
+ test('a delayed install against a changed page writes nothing', async () => {
+ const { prepared, chunks } = await capture();
+ await engine.putPage(slug, { type: 'note', title: 'Batch fixture', compiled_truth: 'A newer body replaced the captured one.',
+ timeline: '2026-01-02: Synthetic event.', frontmatter: {} }, { sourceId });
+ await seal();
+ const before = await rows();
+ expect(await installPageEmbeddings(engine, prepared, chunks.map(c => ({ ...c, embedding: vector(0.9) })))).toBe(false);
+ expect(await rows()).toEqual(before);
+ });
+ });
+}