Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
put_page fast path: group of one, pre-admission cache, own-admission claim, reserved-connection publication, apply diet, switches (#5984 Phase 4.1-4.4)
garrytan52b8ae10c59a
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex d82622755a..67cf99f652 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -28,6 +28,8 @@ 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/switches.ts` + `preadmit-cache.ts` + `config-snapshot.ts` — the single-write fast path for foreground page writes on Postgres. `switches.ts` reads every write-path kill switch (`persistence.single_write_group` / `GBRAIN_SINGLE_WRITE_GROUP`, `persistence.preadmit_cache` / `GBRAIN_PREADMIT_CACHE`, `sync.waive_batch` / `GBRAIN_SYNC_WAIVE_BATCH`; on by default, `0`/`false` off, env over config) in one `SELECT key,value FROM config WHERE key = ANY(...)` per engine, kept 5 s; read-through views name their engine (`VIEWED_ENGINE`) to share it. With `single_write_group` on: the consumer publishes an eligible single page write (put_page, capture, edit/delete/restore/revert without an internal `intent.kind` or group key) as a group of one through `publishGroup` (`publishSingleWrite`; its intent carries no group marker, its effects queue without `deferBatchReconcile`, and a group that does not commit falls back to `publishMutation`, reclaiming a claim its file restoration released); PGLite and refused shapes keep `publishMutation`. The waiter's own wake (`wake(true)`) claims without the periodic scans (recovery records still block the claim through `CLAIMABLE_WRITE_SQL`); preparation reads the config table once (`config-snapshot.ts`) and sends its independent reads together; the coordinated (`coordinated: true`) put_page apply reuses the publisher's locked read as the import base, pipelines its follow-up statements and reads the page once after its last write for the read-back check, seal, core notice and receipt. Publication, the own admission and the recovery transactions run on the consumer's reserved lane (`onLane`: the idle-probe connection, taken while two other pool connections stay free and kept across writes), so their prepared statements stay warm; the waiter is told of the commit before the recovery record is cleared. `preadmit-cache.ts` (with `preadmit_cache` on, Postgres) answers the brain id, source row, worktree binding and local-writer reads of `submitPageMutation` from a per-engine cache (30 s, keyed by brain id; absences never cached); admission rechecks each under lock and the brain id against its protocol statement, and a refusal the cache could explain (`source_changed`, `permission_denied`, a changed brain) drops the cache and runs the whole preparation once more uncached. Pinned by `test/e2e/single-write-fast-path-postgres.test.ts` (switches, cache rechecks, replay, restoration after a failure past the file rename, the recovery-blocked direct claim) and `test/single-write-group-parity.test.ts` + `test/e2e/single-write-group-parity-postgres.test.ts` (row-for-row parity with the switches off); measured by `scripts/bench/foreground-put-page.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 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 the first full tick releases claims last written before this process started (`releaseAbandonedClaims` in `effect-journal.ts`: running effects and unpublished requests without a recovery record), since the datastore admits one process and those owners have exited; Postgres keeps lease expiry (requests 30 s, effects 2 minutes). 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`. With `requestsOnly` (engine graduation's drain) the effect, projection, topology and maintenance workers never start; claim, recovery, expired-claim and publication run as usual and `stop()` remains the barrier. Both the single route and the grouped/lane route (`executeClaimedGroup` in `group-publish.ts`) prepare under a claim lease (`claim-lease.ts`: a renewal every `renewalIntervalMs`, default 10 s, each bounded by `phaseMs`); the claim is lost the first time a renewal says it is gone, throws or overruns, and `whileHeld` stops waiting on the preparation at that moment (the single route also aborts it). The claims still ours are released unpublished with `claim_lost` (token-fenced, so a consumer that took one over keeps it); the abandoned preparation is never published and keeps its root or lane slot until it settles, while the consumer slot frees at once. Renewals are never awaited on the way out: `stop()` drains abandoned preparations and in-flight renewals before engine close. Tests: `test/persistence-claim-lease.test.ts`, `test/persistence-consumer-scheduling.test.ts`, `test/e2e/persistence-consumer-claim-loss.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.mdindex f574908563..7003180f07 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -57,7 +57,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/page-state/version-types.ts` — complete canonical version contract with nullable legacy fields, re-exported by `types.ts` for existing callers. `page-state/versions.ts` records deletion, timeline, tags and originating revision in the page publication transaction.-- `src/core/postgres-engine/` + `src/core/pglite-engine/` — per-engine module directories for code that is genuinely dialect-specific. Migrated storage domains (the `migrated` rows of `scripts/engine-sql-baseline.tsv`) do not live here: their SQL exists once in `src/core/engine-sql/` (see that entry in engines-2.md). What remains: `pglite-engine/checkpoint-guard.ts`, `pglite-engine/code-edges.ts` (PGLite's `getEdgesByChunk`, whose master SQL behaves differently from Postgres's: one UNION ALL under a shared LIMIT; listed in `docs/designs/refactor-wave-1/w1-inventory.md`), `postgres-engine/cancellation.ts`, `postgres-engine/init-schema-lock.ts` and `postgres-engine/search-settings.ts` (search transactions run with `jit = off`); the forward-reference bootstrap lives once in `engine-sql/bootstrap.ts` for both engines. Façades import these modules statically (engine-live no-runtime-dynamic-import rule) and keep their full public surface.+- `src/core/postgres-engine/` + `src/core/pglite-engine/` — per-engine module directories for code that is genuinely dialect-specific. Migrated storage domains (the `migrated` rows of `scripts/engine-sql-baseline.tsv`) do not live here: their SQL exists once in `src/core/engine-sql/` (see that entry in engines-2.md). What remains: `pglite-engine/checkpoint-guard.ts`, `pglite-engine/code-edges.ts` (PGLite's `getEdgesByChunk`, whose master SQL behaves differently from Postgres's: one UNION ALL under a shared LIMIT; listed in `docs/designs/refactor-wave-1/w1-inventory.md`), `postgres-engine/cancellation.ts`, `postgres-engine/init-schema-lock.ts` and `postgres-engine/search-settings.ts` (search transactions run with `jit = off`), `postgres-engine/reserved-transactions.ts` (`withReservedConnection` lends its connection a `transaction()`; BEGIN and SAVEPOINT go out with the statements after them, and a COMMIT answered with ROLLBACK throws); the forward-reference bootstrap lives once in `engine-sql/bootstrap.ts` for both engines. Façades import these modules statically (engine-live no-runtime-dynamic-import rule) and keep their full public surface.- `src/core/progressive-batch/` — shared ramp-up + cost-cap + verification primitive (trial 10 → ramp 100 → ramp 500 → full, with verification at each stage), with verifier+policy injection (callers describe HOW TO MEASURE SUCCESS, not WHEN TO WAIT FOR CTRL-C). Modules: `types.ts` (Stage, StageVerdict, AbortReason, discriminated `Verifier` union `OutputCountVerifier | IdempotentMutationVerifier | NoopVerifier`, Policy, StageReport), `orchestrator.ts` (`runProgressiveBatch(items, verifier, policy, runner)` — reads `getCurrentBudgetTracker()` ahead of `Policy.maxCostUsd` fail-closed; null both ways triggers `abort_cost_cap reason='no_budget_safety_net'`), `audit.ts` (ISO-week JSONL at `~/.gbrain/audit/progressive-batch-YYYY-Www.jsonl` via the shared `audit-writer` primitive), `stage-report.ts` (ASCII formatter for the default `Policy.onStageReport`). Env knobs: `GBRAIN_PROGRESSIVE_BATCH_DISABLED=1`, `GBRAIN_PROGRESSIVE_BATCH_AUTO=1` (skip Ctrl-C grace), `GBRAIN_PROGRESSIVE_BATCH_STAGES=10,100,500`. Sites that "jump straight to full" stay that way by default; ramp is opt-in per-site via `Policy.interactiveAbortMs > 0`. Pinned by `test/progressive-batch/orchestrator.test.ts` (35 cases, every verdict path).diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.mdindex f565e22d28..929a522d5d 100644--- a/docs/architecture/key-files/google-and-loops-continued.md+++ b/docs/architecture/key-files/google-and-loops-continued.md@@ -17,7 +17,7 @@- **`src/core/persistence/sync-discovery.ts`** + **`sync-origin.ts`** — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision snapshots. Reserved skillpack paths (`skills/` at any depth and `skillpack.json`, `src/core/skill-reserved-paths.ts`) never enter discovery: the shared skill publisher owns them and `managedImportContent` refuses them, so a seeded pack cannot block a sync. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Under `source-root` mode a stored `<scope>/<path>` origin (the Git-root form older write-through minted from the slug, recognized because `<path>` names the page slug) is accepted as `<path>` at discovery, freeze, preparation and the page-origin query, and an import rewrites it in place; when both readings name existing files the stored origin refuses with `detail: ambiguous_source_path`. A genuine origin mismatch refuses with `detail: sync_origin_mismatch` and the filled paths. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Deleting a file that no page records as its origin (for example a skipped slug twin) while its slug's page keeps another origin commits an explicit no-op receipt (`unownedDeletion`, outcome reason `unowned_deleted_path`) that preserves that live page or tombstone; freeze and publication re-prove that no page owns the path and that the file is still absent. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten. Active Git holds of the source are re-screened when their blob or working bytes changed, the file left, a `sources retry-held` request names them, the hold predates the current `RECOVERY_VERSION`, or the code is `frontmatter_slug_conflict`, `file_too_large`, `rename_held` or `parser_regression`; holds of now-excluded paths are released at the checkpoint. A held rename destination (or a held path renamed again) carries the hold's `renameFrom` when the old page is unchanged, else `renameHeld` (held as `rename_held` / `rename_source_changed`), and a full walk never deletes an origin a hold's `rename_from` names. Imports whose origin has no page claim their slug together: a live page whose own file is still in the tree keeps the slug, otherwise the file named like the slug (else the first path) wins, and the losers leave the manifest and are reported as `slugCollisions` (the library path's `slug_collision` skip) instead of failing the run. A winner whose slug is held by a page with a vanished or deleted origin takes that page over (`renameFrom`, same slug). A Git-detected rename to an unoccupied slug becomes one import carrying `renameFrom` in place of a delete plus a create. Origins for one slug that differ only by case or separator spelling refuse, except a case-only respelling whose old file the same sync removes. Code files keep exact per-origin identity. On Windows a path containing `:` is reported in `SyncDiscovery.fileRefusals` (code `colon_slug_windows_write_through`, with its filled `gbrain sync --source <id> --no-pull` hint) and kept out of the run and its origin checks, so one such file no longer fails the whole sync (#5032).- **`src/core/persistence/sync-drain.ts`** — #5984: drains a managed sync in one invocation. `runDrain` re-enters the single-pass `performManagedSync` (which keeps returning `partial / writer_pending | writer_yield`) until the cursor is done, the caller's signal stops it, a strict registered run deadline is about 15 s away (`forward-progress.ts` `registerRunDeadline`, set by `cli.ts` when it arms the sync watchdog), a writer head needs intervention (`recovery_required`, `owner_unavailable`, unexpected bytes), or the no-progress detector sees the awaited request and its worktree head unchanged for 30 s and 3 passes with nothing claimable here. It retries only `worktree_refreshing` (its `retry_after_ms`), `database_contention`, connection errors and statement timeouts (3 attempts). Every page commit notes forward progress, so the progress-aware watchdog never stops a progressing drain. The result carries `drain: { outcome: synced | resumable | blocked, stop_reason, written, waived, remaining, rate_pages_per_min, eta_seconds, stall }`; `drainNext` builds `next` for the CLI from the shared `syncResumeCommand` (`sync-reconcile.ts`). The CLI (`sync/run.ts` single source, `--all`, `--watch`) sets `SyncOpts.drain`; the PGLite owner delegate uses `runDrain` over IPC; jobs, serve, the cycle, `sync-administration.ts` and `worktree-refresh.ts` keep their own loops. `readManagedSyncBacklog` reads unfinished cursors' `progress` window (stamped by `sync-run.ts` on each advance, reset per drain) for `gbrain doctor` (`managed_sync_backlog`) and `sources status`. Tests: `test/sync-drain.test.ts`, `test/managed-sync-drain.test.ts`.-- **`src/core/persistence/sync-group.ts`** + **`group-publish.ts`** — #5984 bulk publication for draining managed Postgres syncs. `sync-group.ts` resolves bulk settings (`--no-bulk` > `GBRAIN_SYNC_BULK` > `sync.bulk` > on; `sync.bulk_size` 16, `sync.bulk_max_txn_ms` 15 s; PGLite off), sizes the next group from the last group's admission-to-commit time per member, freezes followers (four at a time, stopping at a rename, company plan, overtaken entry or one the waiver would take) and admits a group in one transaction (`admitWriteGroupInTransaction`, which keeps one request row, ID and digest per page and replays priors). `sync-run.ts` keeps the head in `pending` and all members in the cursor's `group` (members carry `intent.group` = the head's request ID), waits for the last member and advances over the committed prefix; a terminal failure becomes the single pending entry, a still-pending member returns `writer_pending`. Any caller finishes an existing group; only a drain forms one. The consumer claims a head's directly following queued members (`claimGroupFollowers`, never past an unfinished non-member) and `executeClaimedGroup` prepares four at a time, then `publishGroup` publishes them in one transaction: one worktree lock, ownership guard and coordinated write (each member set as the attributed actor with `setMemberAttribution`), per-member authorization, preimage read, sync validation (its source-wide part shared per transaction), apply (which reads the postimage the receipt and effects use), effects and receipt; `completeGroup` then reads every member's effect bytes, and pipelines the counter lock with one `UPDATE ... FROM unnest(...) RETURNING` that checks each member's claim and terminal reservation and releases the counters (a short `RETURNING` throws, so the single path reports each member's own code). Any failure rolls the group back; members then publish singly, later members are cancelled after a terminal failure or released after a requeue. Sync validation accepts a group member through the cursor's `group`. #6007: the pages of one `put_pages` batch (`intent.page_batch.id`; the group key is `journal.ts` `publicationGroupKey`) also publish as groups of at most `PAGE_BATCH_GROUP_MAX` (8) pages, prepared all at once, files included: one transaction records every member's recovery record (`prepareRecoveries`) before any file is touched, the publication transaction marks the members `publication_started`, publishes each member's file before its apply and re-arms the batch's mention links once after every member completes (`reconcileFinishedBatch`), and one transaction clears the records after commit (`clearResolvedRecoveries`). Within that transaction the source's local path, the owner's host binding and config values are read once per group (source membership and the writer registration are already memoized per transaction by `transactionMemo`). On failure every file the group published is restored by `recoverPublication`, which requeues those claims; the fallback claims them back in order (`reclaimReleasedWrite`) and publishes the members singly, and a batch member's failure never cancels its siblings. Tests: `test/managed-sync-bulk.test.ts`, `test/e2e/put-pages-group-postgres.test.ts`.+- **`src/core/persistence/sync-group.ts`** + **`group-publish.ts`** — #5984 bulk publication for draining managed Postgres syncs. `sync-group.ts` resolves bulk settings (`--no-bulk` > `GBRAIN_SYNC_BULK` > `sync.bulk` > on; `sync.bulk_size` 16, `sync.bulk_max_txn_ms` 15 s; PGLite off), sizes the next group from the last group's admission-to-commit time per member, freezes followers (four at a time, stopping at a rename, company plan, overtaken entry or one the waiver would take) and admits a group in one transaction (`admitWriteGroupInTransaction`, which keeps one request row, ID and digest per page and replays priors). `sync-run.ts` keeps the head in `pending` and all members in the cursor's `group` (members carry `intent.group` = the head's request ID), waits for the last member and advances over the committed prefix; a terminal failure becomes the single pending entry, a still-pending member returns `writer_pending`. Any caller finishes an existing group; only a drain forms one. The consumer claims a head's directly following queued members (`claimGroupFollowers`, never past an unfinished non-member) and `executeClaimedGroup` prepares four at a time, then `publishGroup` publishes them in one transaction: one worktree lock, ownership guard and coordinated write (each member set as the attributed actor with `setMemberAttribution`), per-member authorization, preimage read, sync validation (its source-wide part shared per transaction), apply (which reads the postimage the receipt and effects use), effects and receipt; `completeGroup` then reads every member's effect bytes, and pipelines the counter lock with one `UPDATE ... FROM unnest(...) RETURNING` that checks each member's claim and terminal reservation and releases the counters (a short `RETURNING` throws, so the single path reports each member's own code). Any failure rolls the group back; members then publish singly, later members are cancelled after a terminal failure or released after a requeue. Sync validation accepts a group member through the cursor's `group`. #6007: the pages of one `put_pages` batch (`intent.page_batch.id`; the group key is `journal.ts` `publicationGroupKey`) also publish as groups of at most `PAGE_BATCH_GROUP_MAX` (8) pages, prepared all at once, files included: one transaction records every member's recovery record (`prepareRecoveries`) before any file is touched, the publication transaction marks the members `publication_started`, publishes each member's file before its apply and re-arms the batch's mention links once after every member completes (`reconcileFinishedBatch`), and one transaction clears the records after commit (`clearResolvedRecoveries`). A single foreground page write publishes here too, as a group of one (core-persistence.md, `switches.ts` entry). Within that transaction the source's local path, the owner's host binding and config values are read once per group (source membership and the writer registration are already memoized per transaction by `transactionMemo`). On failure every file the group published is restored by `recoverPublication`, which requeues those claims; the fallback claims them back in order (`reclaimReleasedWrite`) and publishes the members singly, and a batch member's failure never cancels its siblings. Tests: `test/managed-sync-bulk.test.ts`, `test/e2e/put-pages-group-postgres.test.ts`.- **`src/core/persistence/sync-window.ts`** — #5984 admit-ahead for draining managed Postgres syncs. While the cursor's `group` publishes, `admitAhead` (`sync-run.ts`) freezes and admits the next group and records it in the cursor's `window` (at most one group), so the consumer claims it as soon as the publishing group commits under the unchanged per-worktree FIFO claim. Window members name the previous group's last request in `intent.after`. `cancelOrphanedWindowGroup` runs before the consumer prepares a claimed group: a window group whose predecessor did not commit is cancelled (`WINDOW_CANCEL_MESSAGE`), never published after a failed page. Publication validation (`sync-prepare.ts`) re-checks the predecessor once per transaction and reads the cursor `FOR KEY SHARE`, accepting `pending`, `group` and `window` members, so the drain's cursor saves never wait for the publishing group. After a failed page the drain cancels the window's queued members (`cancelWindow`) and drops the window; resume re-freezes those entries. Nothing is admitted ahead while foreground writes are recent (one was queued on the worktree in the last minute, `FOREGROUND_RECENT_MS`) or when the next entry is not groupable. Older binaries refuse a window member they did not admit (cursor membership), so a mixed-version drain fails closed instead of publishing twice; finish a drain before downgrading.- **`src/core/persistence/sync-lanes.ts`** + **`worktree-lease.ts`** — #5984 lanes. The drain opens a lane policy for its worktree (`openLanes`, keyed by a per-drain run id that lane groups carry as `intent.lane`; `closeLaneRun` at drain end stops new lane claims and waits up to 90 s for the lane tasks still running, counted from the head's claim by `laneTask`; the drain then cancels its run's still-queued rows whose predecessor ended without committing, `cancelOrphanedLaneRows` in sync-window.ts, so a blocked drain never reports while one of its groups is still publishing, aborting or released). While it is open, this process's consumer claims the next admitted lane group head out of FIFO order (`claimNextLaneHead` in journal.ts: every earlier request claimed, any unfinished one a running request of the same run) up to the effective lane count (`laneRoots`), and runs it as a lane (`executeClaimedGroup` with `lane`). Lane publications share the worktree's native lock in this process (`acquireWorktreeShared` / `worktree-lease.ts`; one lane acquires the lock while lanes arriving meanwhile wait and join, and a lease stays registered until its lock is released); every exclusive `acquireWorktree` first yields the lease (marks it draining and wounded, waits up to its budget), and a lease drains for new claims after `LEASE_TURN_MS` of continuous holding. Lane transactions begin in manifest order (`awaitLaneBegin`) and commit in manifest order (`awaitLaneTurn`, inside the transaction before the counters: the predecessor `intent.after` must be committed; a failed one cancels the group, a requeued or unadmitted one releases it, a wounded lease or 60 s rolls it back). Publication validation accepts a lane group whose predecessor is still queued or running (`windowPredecessorAllows`). `laneFallback` in group-publish.ts cancels, releases or falls back to the single path, and a lock or statement timeout steps the lane count down (`stepDownLanes`). Lane settings (`--lanes`/`--no-lanes` > `GBRAIN_SYNC_LANES` > `sync.lanes` > 6, clamped to the pool's long-hold capacity minus 3) resolve in `resolveBulkSettings` (sync-group.ts); with lanes the drain keeps twice the lane count of groups admitted ahead (`admitAhead`).- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. A completed discovery that finds nothing to do (`up_to_date`) stamps only `sources.last_sync_at`, inside `withCoordinatedWrite` and guarded by source id and incarnation, so a quiet managed source stays fresh in doctor and a run that outlived a re-added source stamps nothing; dry runs and partial runs do not stamp. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`. A resume adopts the stored options for every option the caller did not set explicitly (`SyncOpts.explicitProcessing`: CLI flags, wire flags, job params; autopilot and the cycle set none); an explicit conflict refuses with `detail: cursor_processing_options_conflict`, the stored options and the exact resume command. Callers that omit `explicitProcessing` stay strict. Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts, also when the run has a recorded failure and its pending write already committed before the cursor advanced; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol. `freezeEntry` checks a rename's source page (id, revision, origin) as well as its target slug, and a committed rename counts in `renamed`. #5522: a new-file entry (`pageId: null`) whose origin another cursor of the source has since imported is re-frozen against that page when it is live, holds exactly that origin at the entry's slug in the cursor's incarnation, and the sync preparer finds its content unchanged; otherwise the origin refusal stands, and the manifest is never rewritten. #5751: the working-tree screen passes the kernel waivers for working-tree entries and counts them into `legacySkips` (printed by `sync-diagnostics.ts` with `gbrain repair contextual-mode`). A terminal `checkpoint_validation_timeout` receipt gets its hint from `checkpoint-validation.ts`. Content holds (#5988, `sync-screen.ts`): `freezeEntry` screens each import (company-profile cursors and `sync.holds=fail` excepted); a refused file becomes a hold written in the same transaction as the cursor step (`saveCursor`'s `inTx`), with no request admitted, and an over-bound pinned blob is held by size before it is read. A cursor whose pending request failed with a content refusal (`isContentRefusal`, old message shapes included) converts in place with its stored options: held, or re-frozen once per distinct bytes (`converted`), so a refusal the screen misses stays blocked without minting receipts. #6188: a failed fence refusal (`fenceReceiptLocation`: the durable `error_detail.fence`, the message, or an older release's message) holds the same bytes even when the screen admits them (`prepareTimeFenceHold`, reason `prepare_time`); a compacted `invalid_params` / `take_row_collision` receipt converts only when the re-screen holds. A page request of the run that fails with a fence refusal is held in the same invocation at the terminal-failure branch (single path and a bulk group's failed member) after the source's other requests settle within the run's wait budget, else the run returns `partial`; it is converted once, gets no failure-ledger row and is logged as a conversion. `sync.holds=fail` and company-profile cursors keep blocking with the typed refusal. Results carry this run's holds, the outstanding total, escalation, `converted_from_failed` and `recovered_frontmatter` (`buildHoldReport`); dry runs list `would_hold` / `screen_skipped`. After the checkpoint commits (and unless `noExtract`), the owner derives links for the source's stale pages through `links-maintenance.ts`, so a PGLite-delegated sync and a Postgres sync take the same path; the result carries `links`, and an extraction failure leaves pages stale without failing the committed sync.diff --git a/scripts/bench/foreground-put-page.ts b/scripts/bench/foreground-put-page.tsnew file mode 100644index 0000000000..11e470eb79--- /dev/null+++ b/scripts/bench/foreground-put-page.ts@@ -0,0 +1,237 @@+#!/usr/bin/env bun+/**+ * Idle foreground put_page latency at a set round trip. Opt-in, never run in CI.+ *+ * bun scripts/bench/foreground-put-page.ts [--rtt 57] [--writes 30] [--warmup 2] [--label <name>] [--out <file.json>]+ * [--database-url <admin url>] [--pg-port 55432] [--proxy-port 55433] [--api-port 58474] [--keep]+ *+ * Reuses the managed-sync-catchup harness (Docker pgvector Postgres behind a+ * toxiproxy with `--rtt` ms of round trip). Builds a managed source with a few+ * pages, then one long-lived writer process submits put_page through+ * `submitPageMutation` one at a time (closed loop, 1 s floor), each writing a+ * markdown file, with no sync running. Every round trip of the writer is traced+ * (GBRAIN_SQL_TRACE), and each write is split into spans: pre-admission,+ * admission, claim, preparation, recovery record, publication transaction and+ * completion, with statements, sequential waves and describe round trips per+ * span. Environment switches (GBRAIN_SINGLE_WRITE_GROUP, GBRAIN_PREADMIT_CACHE)+ * pass through to the writer.+ */+import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join, resolve } from 'node:path';+import { execFileSync } from 'node:child_process';+import { randomBytes } from 'node:crypto';+import postgres from '#postgres';+import { flatSql, measureRtt, pct, readTrace, round1, startHarness, type Harness, type TraceRecord } from './managed-sync-catchup-lib.ts';+import { cost, transactions, type Txn } from './managed-sync-catchup-phases.ts';++const REPO = resolve(import.meta.dir, '../..');+const CLI = join(REPO, 'src/cli.ts');+const SOURCE = 'bench';+function flag(name: string, fallback: string): string {+ const i = process.argv.indexOf(`--${name}`);+ return i >= 0 && process.argv[i + 1] ? process.argv[i + 1]! : fallback;+}+function gitDescribe(): string {+ try { return execFileSync('git', ['-C', REPO, 'rev-parse', '--abbrev-ref', 'HEAD'], { encoding: 'utf8' }).trim() + '@' + execFileSync('git', ['-C', REPO, 'rev-parse', '--short', 'HEAD'], { encoding: 'utf8' }).trim(); }+ catch { return 'unknown'; }+}+const log = (msg: string) => console.error(`[fg-put ${new Date().toISOString().slice(11, 19)}] ${msg}`);++interface WriteResult { start: number; end: number; ms: number; ok: boolean; state: string; mode?: string }++if (flag('worker', '')) await runWorker();++const RTT = Number(flag('rtt', '57'));+const WRITES = Number(flag('writes', '30'));+const WARMUP = Number(flag('warmup', '2'));+const LABEL = flag('label', gitDescribe());+const OUT = resolve(flag('out', join(REPO, '.context', 'bench', `foreground-put-page-${LABEL.replace(/[^\w.-]/g, '_')}-${Date.now()}.json`)));+const KEEP = process.argv.includes('--keep');+const work = mkdtempSync(join(tmpdir(), 'gbrain-fgput-'));+const created: string[] = [];+let harness: Harness;++function git(root: string, ...args: string[]): string {+ return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+}+function childEnv(home: string, extra: Record<string, string | undefined> = {}): Record<string, string | undefined> {+ const env: Record<string, string | undefined> = { ...process.env };+ for (const key of Object.keys(env)) if (/_API_KEY$|_API_TOKEN$|^DATABASE_URL$|^GBRAIN_DATABASE_URL$|^OPENAI_BASE_URL$/.test(key)) delete env[key];+ return { ...env, GBRAIN_HOME: home, GBRAIN_NO_BANNER: '1', GBRAIN_BACKUP_CHECK: '0', GBRAIN_SKILLS_DIR: join(home, 'skills'), NO_COLOR: '1', ...extra };+}+async function cli(home: string, args: string[]): Promise<Record<string, unknown> | null> {+ const child = Bun.spawn([process.execPath, CLI, ...args], { cwd: home, env: childEnv(home), stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });+ const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);+ if (code !== 0) throw new Error(`gbrain ${args.join(' ')} exited ${code}\nstdout: ${stdout.slice(-1500)}\nstderr: ${stderr.slice(-1500)}`);+ try { return JSON.parse(stdout); } catch { return null; }+}+function writeConfig(home: string, url: string): void {+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ mkdirSync(join(home, 'skills'), { recursive: true });+ writeFileSync(join(home, 'skills', 'RESOLVER.md'), '# Bench fixture skills\n');+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'postgres', database_url: url, self_upgrade: { mode: 'off' }, embedding_disabled: true }, null, 2) + '\n');+}+async function admin<T>(fn: (sql: ReturnType<typeof postgres>) => Promise<T>, db = 'postgres'): Promise<T> {+ const sql = postgres(harness.directUrl(db), { max: 1, onnotice: () => {} });+ try { return await fn(sql); } finally { await sql.end(); }+}++async function setup(): Promise<{ home: string; db: string; trace: string }> {+ const db = `gbrain_fgput_${randomBytes(4).toString('hex')}`;+ await admin(sql => sql.unsafe(`CREATE DATABASE ${db}`));+ created.push(db);+ const home = mkdtempSync(join(work, 'home-'));+ writeConfig(home, harness.directUrl(db));+ process.env.GBRAIN_HOME = home;+ const { PostgresEngine } = await import('../../src/core/postgres-engine.ts');+ const engine = new PostgresEngine();+ await engine.connect({ database_url: harness.directUrl(db), poolSize: 2 });+ await engine.initSchema();+ await engine.disconnect();+ const root = join(home, `repo-${SOURCE}`);+ mkdirSync(join(root, 'notes'), { recursive: true });+ git(root, 'init', '-q');+ writeFileSync(join(root, 'README.md'), '# Bench source\n');+ for (let i = 0; i < 5; i++) writeFileSync(join(root, 'notes', `seed-${i}.md`), `---\ntitle: Seed ${i}\n---\nSeed page ${i}.\n`);+ git(root, 'add', '-A');+ git(root, '-c', 'user.name=Bench Example', '-c', '[email protected]', 'commit', '-qm', 'seed');+ await cli(home, ['sources', 'add', SOURCE, '--path', root, '--no-federated']);+ await cli(home, ['sync', '--source', SOURCE, '--no-pull', '--no-embed', '--json']);+ let state = (await cli(home, ['sources', 'writer', 'status', '--json']))!.admin_state as string;+ await cli(home, ['sources', 'writer', 'claim', SOURCE, '--path', root, '--admin-intent', 'writer_claim', '--expected-state', state, '--json']);+ state = (await cli(home, ['sources', 'writer', 'status', '--json']))!.admin_state as string;+ const activated = await cli(home, ['sources', 'writer', 'activate', '--confirm-quiesced', '--admin-intent', 'writer_activate', '--expected-state', state, '--json']);+ if (activated?.enabled !== true) throw new Error(`activation did not enable managed persistence: ${JSON.stringify(activated)}`);+ writeConfig(home, harness.proxyUrl(db));+ return { home, db, trace: join(home, 'sql-trace.jsonl') };+}++async function runWorker(): Promise<never> {+ const { loadConfig, toEngineConfig } = await import('../../src/core/config.ts');+ const { createEngine } = await import('../../src/core/engine-factory.ts');+ const config = loadConfig()!;+ const engine = await createEngine(toEngineConfig(config));+ await engine.connect(toEngineConfig(config));+ const { disposePersistenceConsumer } = await import('../../src/core/persistence/service.ts');+ const { submitPageMutation } = await import('../../src/core/persistence/page-mutations.ts');+ const total = Number(process.env.BENCH_WRITES);+ const results: WriteResult[] = [];+ const logger = { info() {}, warn() {}, error() {} };+ for (let i = 0; i < total; i++) {+ const start = performance.timeOrigin + performance.now();+ let state = 'error', ok = false;+ try {+ const out = await submitPageMutation({ engine, config, remote: false, dryRun: false, sourceId: process.env.BENCH_SOURCE, logger } as unknown as Parameters<typeof submitPageMutation>[0],+ { operation: 'put_page', params: { slug: `notes/fg-${process.pid}-${i}`, content: `---\ntitle: Foreground ${i}\n---\nForeground write ${i}, idle.\n` }, waitMs: 30_000 });+ state = String((out as { state?: string; status?: string }).state ?? (out as { status?: string }).status ?? '');+ ok = state === 'committed';+ } catch (error) { state = String((error as { code?: string; message?: string }).code ?? (error as Error).message).slice(0, 200); }+ const end = performance.timeOrigin + performance.now();+ results.push({ start, end, ms: round1(end - start), ok, state });+ await Bun.sleep(Math.max(0, 1000 - (end - start)));+ }+ writeFileSync(process.env.BENCH_RESULTS!, JSON.stringify(results));+ await disposePersistenceConsumer(engine);+ await engine.disconnect();+ process.exit(0);+}++const RECOVERY = /^(?:WITH recorded AS \(UPDATE persistence_requests (?:r )?SET recovery=|UPDATE persistence_requests SET recovery=)/;+const ADMISSION = /INSERT INTO persistence_requests\b/;+const CLAIM = /^UPDATE persistence_requests (?:r )?SET state='running'/;+const COMPLETION = /^WITH effects AS \(SELECT COALESCE|UPDATE persistence_requests r SET state='committed'/;+const SPANS = ['pre_admission', 'admission', 'claim', 'preparation', 'recovery_record', 'publication_txn', 'completion'] as const;+type Span = typeof SPANS[number];++/** Splits each write into spans from the writer's own transactions. */+function spans(records: TraceRecord[], writes: WriteResult[]): Array<Record<Span, { ms: number; statements: number; waves: number; describes: number }> & { total_ms: number; publication_kind: string }> {+ const { txns } = transactions(records);+ const has = (re: RegExp) => (t: Txn) => t.records.some(r => re.test(flatSql(r.sql)));+ return writes.flatMap(w => {+ const inside = txns.filter(t => t.start >= w.start && t.start < w.end);+ const admission = inside.find(has(ADMISSION));+ const claim = admission && inside.find(t => has(CLAIM)(t) && t.start >= admission.end);+ const recovery = claim && inside.find(t => has(RECOVERY)(t) && t.start >= claim.end);+ const publication = claim && inside.find(t => has(COMPLETION)(t) && t.committed && t.start >= (recovery?.end ?? claim.end));+ if (!admission || !claim || !publication) return [];+ const bounds: Record<Span, [number, number]> = {+ pre_admission: [w.start, admission.start], admission: [admission.start, admission.end], claim: [admission.end, claim.end],+ preparation: [claim.end, recovery?.start ?? publication.start], recovery_record: recovery ? [recovery.start, publication.start] : [publication.start, publication.start],+ publication_txn: [publication.start, publication.end], completion: [publication.end, w.end],+ };+ const out = { total_ms: round1(w.end - w.start), publication_kind: publication.records.some(r => /SET state='committed'/.test(r.sql)) ? 'group' : 'single' } as ReturnType<typeof spans>[number];+ for (const span of SPANS) {+ const [from, to] = bounds[span];+ out[span] = { ms: round1(to - from), ...cost(records.filter(r => r.t >= from && r.t < to)) };+ }+ return [out];+ });+}++function summarize(records: TraceRecord[], measured: WriteResult[]): Record<string, unknown> {+ const split = spans(records, measured);+ const ms = measured.map(w => w.ms);+ return {+ writes: { count: measured.length, failures: measured.filter(w => !w.ok).length, states: [...new Set(measured.map(w => w.state))],+ p50_ms: pct(ms, 50), p95_ms: pct(ms, 95), max_ms: pct(ms, 100), all_ms: ms, raw: measured },+ spans_found: split.length,+ publication_kinds: Object.fromEntries([...new Set(split.map(s => s.publication_kind))].map(k => [k, split.filter(s => s.publication_kind === k).length])),+ spans: Object.fromEntries(SPANS.map(span => [span, {+ ms_p50: pct(split.map(s => s[span].ms), 50), ms_p95: pct(split.map(s => s[span].ms), 95),+ statements_p50: pct(split.map(s => s[span].statements), 50), waves_p50: pct(split.map(s => s[span].waves), 50), describes_p50: pct(split.map(s => s[span].describes), 50),+ }])),+ };+}+function printSummary(summary: Record<string, unknown>): void {+ const writes = summary.writes as { p50_ms: number; p95_ms: number; count: number; failures: number };+ log(`p50 ${writes.p50_ms} ms, p95 ${writes.p95_ms} ms over ${writes.count} writes (${writes.failures} failed); publication ${JSON.stringify(summary.publication_kinds)}`);+ for (const span of SPANS) { const s = (summary.spans as Record<string, Record<string, unknown>>)[span]!; log(` ${span.padEnd(16)} p50 ${s.ms_p50} ms (p95 ${s.ms_p95}) stmts ${s.statements_p50} waves ${s.waves_p50} describes ${s.describes_p50}`); }+}++const analyze = flag('analyze', '');+if (analyze) {+ const prior = JSON.parse(readFileSync(analyze, 'utf8')) as { trace: string; writes: { raw: WriteResult[] } };+ const summary = summarize(readTrace(prior.trace, r => r.label.startsWith('foreground')), prior.writes.raw);+ printSummary(summary);+ console.log(JSON.stringify(summary.spans, null, 2));+ process.exit(0);+}++harness = await startHarness({ pgPort: Number(flag('pg-port', '55432')), proxyPort: Number(flag('proxy-port', '55433')), apiPort: Number(flag('api-port', '58474')),+ adminUrl: process.argv.includes('--database-url') ? flag('database-url', '') : undefined, keep: KEEP });+const report: Record<string, unknown> = { schema: 'gbrain.bench.foreground-put-page/v1', label: LABEL, commit: gitDescribe(), started_at: new Date().toISOString(),+ params: { rtt_ms: RTT, writes: WRITES, warmup: WARMUP, switches: Object.fromEntries(Object.entries(process.env).filter(([k]) => /^GBRAIN_(SINGLE_WRITE_GROUP|PREADMIT_CACHE|PREPARE)$/.test(k))) },+ rerun: `bun scripts/bench/foreground-put-page.ts ${process.argv.slice(2).join(' ')}` };+try {+ log('setting up the managed source');+ const row = await setup();+ await harness.setRtt(RTT);+ report.measured_rtt_ms = round1(await measureRtt(harness.proxyUrl(row.db)));+ log(`measured RTT ${report.measured_rtt_ms} ms; writing ${WRITES + WARMUP} pages`);+ const results = join(row.home, 'results.json');+ const child = Bun.spawn([process.execPath, import.meta.path, '--worker', '1'], { cwd: row.home, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe',+ env: childEnv(row.home, { GBRAIN_SQL_TRACE: row.trace, GBRAIN_SQL_TRACE_LABEL: 'foreground', BENCH_SOURCE: SOURCE, BENCH_RESULTS: results, BENCH_WRITES: String(WRITES + WARMUP) }) });+ const [stderr] = await Promise.all([new Response(child.stderr).text(), child.exited]);+ if (!existsSync(results)) throw new Error(`writer wrote no results: ${stderr.slice(-2000)}`);+ const all = JSON.parse(readFileSync(results, 'utf8')) as WriteResult[];+ const measured = all.slice(WARMUP);+ const records = readTrace(row.trace, r => r.label.startsWith('foreground'));+ Object.assign(report, summarize(records, measured));+ mkdirSync(dirname(OUT), { recursive: true });+ copyFileSync(row.trace, OUT.replace(/\.json$/, '') + '.trace.jsonl');+ report.trace = OUT.replace(/\.json$/, '') + '.trace.jsonl';+ report.writer_stderr_tail = stderr.slice(-1000);+ printSummary(report);+} finally {+ report.finished_at = new Date().toISOString();+ mkdirSync(dirname(OUT), { recursive: true });+ writeFileSync(OUT, JSON.stringify(report, null, 2) + '\n');+ log(`report: ${OUT}`);+ if (!KEEP) {+ for (const datname of created) await admin(sql => sql.unsafe(`DROP DATABASE IF EXISTS ${datname} WITH (FORCE)`)).catch(() => undefined);+ rmSync(work, { recursive: true, force: true });+ }+ harness.stop();+}+process.exit(0);diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex b90543741b..1272e6a792 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -21,7 +21,7 @@ src/core/import-file.ts 2200 ratchet +2: pre-publication withdrawal validation;src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullablesrc/core/operations.ts 340 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area rowsrc/core/pglite-engine.ts 2996 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows)-src/core/postgres-engine.ts 2941 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts)+src/core/postgres-engine.ts 2942 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +1 Phase 4.4: import of postgres-engine/reserved-transactions.ts (the reserved connection lends its single-write lane a transaction; logic in that module)src/core/search/hybrid.ts 1615 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget optssrc/core/types.ts 2232 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields)src/core/minions/queue.ts 2528 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts)diff --git a/src/core/config.ts b/src/core/config.tsindex 2af92f6751..0ed0f276e6 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1651,7 +1651,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['sync.bulk','sync.bulk_size','sync.bulk_max_txn_ms',- 'sync.lanes',+ 'sync.lanes', 'sync.waive_batch', 'persistence.single_write_group', 'persistence.preadmit_cache', // the last three: write-path kill switches (persistence/switches.ts)// Persisted indexing scope (comma/newline-separated glob list; trailing '/'// normalizes to a '/**' subtree glob). Read best-effort at the top of// performSyncInner and UNIONED with any per-call --exclude so internaldiff --git a/src/core/derived-links.ts b/src/core/derived-links.tsindex f5354cc481..77872f4d47 100644--- a/src/core/derived-links.ts+++ b/src/core/derived-links.ts@@ -1,5 +1,6 @@import type { BrainEngine, LinkBatchInput } from './engine.ts';-import { assertPageRevision } from './page-state/types.ts';+import { assertPageRevision, type PageSnapshot } from './page-state/types.ts';+import { pipelined } from './page-state/transactions.ts';import { executeRawJsonb } from './sql-query.ts';import { sanitizeForJsonb } from './batch-rows.ts';import { replaceWantedLinks, type WantedLinksReplacement } from './wanted-links-store.ts';@@ -12,6 +13,12 @@ export interface DerivedLinkOrigin {sourceId: string;expectedRevision: string;sourceIncarnation: string;+ /**+ * The caller's own read of the origin (live rows only) in the transaction this+ * replacement nests in, taken under that transaction's guard of every key the+ * replacement locks and after its last write to the origin; skips the re-read.+ */+ snapshot?: PageSnapshot | null;}export interface DerivedLinkReplacementOptions {@@ -21,6 +28,8 @@ export interface DerivedLinkReplacementOptions {expectedEndpoints?: Array<{ slug: string; sourceId: string; revision: string }>;/** The origin's unresolved authored references, replaced in the same transaction (wanted pages). */wanted?: WantedLinksReplacement;+ /** The caller installed the pack relation semantics already (links-preparation.ts `primeSemantics`). */+ semanticsPrimed?: boolean;}export class DerivedLinkRepairRequiredError extends Error {@@ -84,42 +93,54 @@ export async function replaceDerivedLinks(}const rows = [...unique.values()];return engine.transaction(async tx => {- await primeRelationSemantics(tx);- await tx.lockPageKeys([{ sourceId: origin.sourceId, slug: origin.slug }, ...rows.flatMap(row => [- { sourceId: row.from_source_id!, slug: row.from_slug }, { sourceId: row.to_source_id!, slug: row.to_slug },- ])]);- const snapshot = await tx.readPageSnapshot(origin.slug, { sourceId: origin.sourceId });+ await pipelined(tx, [+ async () => { if (!opts.semanticsPrimed) await primeRelationSemantics(tx); },+ () => tx.lockPageKeys([{ sourceId: origin.sourceId, slug: origin.slug }, ...rows.flatMap(row => [+ { sourceId: row.from_source_id!, slug: row.from_slug }, { sourceId: row.to_source_id!, slug: row.to_slug },+ ])]),+ ]);+ const snapshot = origin.snapshot !== undefined ? origin.snapshot : await tx.readPageSnapshot(origin.slug, { sourceId: origin.sourceId });assertPageRevision(snapshot, { expectedRevision: origin.expectedRevision });if (!snapshot || snapshot.sourceIncarnation !== origin.sourceIncarnation || snapshot.page.deleted_at) {throw new Error('Derived link origin changed or was deleted');}const id = snapshot.page.id;- if (opts.wanted) await replaceWantedLinks(tx, { pageId: id, sourceId: origin.sourceId }, opts.wanted);+ // The wanted-page replacement and every read the checks below need are sent together, then judged in order.// Temporal evidence (tense, dated transitions, relationship state) is part// of the same derived projection: captured before, replaced after.- const temporalKeysBefore = await relationshipKeysForOrigin(tx, Number(id));- const withTemporal = async (result: { created: number; removed: number }) => {- await applyTemporalEvidence(tx, snapshot.page, rows, temporalKeysBefore, { inlineRanges: await effectiveRangesEnabled(tx) });- return result;- };- if (opts.includeFrontmatter !== false && !opts.preserveExisting) {- const ambiguous = await tx.executeRaw(`SELECT 1 FROM links WHERE link_source='frontmatter'- AND origin_page_id IS NULL AND (from_page_id=$1 OR to_page_id=$1) LIMIT 1`, [id]);- if (ambiguous.length) throw new DerivedLinkRepairRequiredError();- }- const missing = await executeRawJsonb(tx, `SELECT 1 FROM jsonb_to_recordset(($1::jsonb)->'rows')+ type Existing = { id: number; from_slug: string; to_slug: string; from_source_id: string; to_source_id: string; link_type: string;+ link_source: string | null; origin_slug: string | null; origin_source_id: string | null; context: string; origin_field: string | null };+ const [, temporalKeysBefore, ambiguous, missing, changed, existing, inlineRanges] = await pipelined(tx, [+ async () => { if (opts.wanted) await replaceWantedLinks(tx, { pageId: id, sourceId: origin.sourceId }, opts.wanted); },+ () => relationshipKeysForOrigin(tx, Number(id)),+ () => opts.includeFrontmatter !== false && !opts.preserveExisting ? tx.executeRaw(`SELECT 1 FROM links WHERE link_source='frontmatter'+ AND origin_page_id IS NULL AND (from_page_id=$1 OR to_page_id=$1) LIMIT 1`, [id]) : Promise.resolve([]),+ () => executeRawJsonb(tx, `SELECT 1 FROM jsonb_to_recordset(($1::jsonb)->'rows')AS v(from_slug text, to_slug text, from_source_id text, to_source_id text)LEFT JOIN pages f ON f.slug=v.from_slug AND f.source_id=v.from_source_id AND f.deleted_at IS NULLLEFT JOIN pages t ON t.slug=v.to_slug AND t.source_id=v.to_source_id AND t.deleted_at IS NULL- WHERE f.id IS NULL OR t.id IS NULL LIMIT 1`, [], [{ rows }]);- if (missing.length) throw new DerivedLinkEndpointChangedError('A derived link endpoint changed or was deleted');- if (opts.expectedEndpoints?.length) {- const changed = await executeRawJsonb(tx, `SELECT 1 FROM jsonb_to_recordset(($1::jsonb)->'rows')+ WHERE f.id IS NULL OR t.id IS NULL LIMIT 1`, [], [{ rows }]),+ () => opts.expectedEndpoints?.length ? executeRawJsonb(tx, `SELECT 1 FROM jsonb_to_recordset(($1::jsonb)->'rows')AS v(slug text, "sourceId" text, revision text)LEFT JOIN pages p ON p.slug=v.slug AND p.source_id=v."sourceId" AND p.deleted_at IS NULL- WHERE p.id IS NULL OR p.knowledge_revision::text <> v.revision LIMIT 1`, [], [{ rows: opts.expectedEndpoints }]);- if (changed.length) throw new DerivedLinkEndpointChangedError('A derived link endpoint changed after type resolution');- }+ WHERE p.id IS NULL OR p.knowledge_revision::text <> v.revision LIMIT 1`, [], [{ rows: opts.expectedEndpoints }]) : Promise.resolve([]),+ () => opts.preserveExisting ? tx.executeRaw<Existing>(`SELECT l.id, f.slug from_slug, t.slug to_slug,+ f.source_id from_source_id, t.source_id to_source_id, l.link_type, l.link_source,+ o.slug origin_slug, o.source_id origin_source_id, l.context, l.origin_field+ FROM links l JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_id+ LEFT JOIN pages o ON o.id=l.origin_page_id+ WHERE (l.link_source=ANY($2::text[]) OR ($3::boolean AND l.link_source IS NULL))+ AND (l.origin_page_id=$1 OR (l.origin_page_id IS NULL AND l.from_page_id=$1+ AND (l.link_source IN ('markdown','wikilink-resolved') OR l.link_source IS NULL)))`, [id, producers, opts.includeLegacyNullProducer !== false]) : Promise.resolve([]),+ () => effectiveRangesEnabled(tx),+ ]) as [unknown, Awaited<ReturnType<typeof relationshipKeysForOrigin>>, unknown[], unknown[], unknown[], Existing[], boolean];+ const withTemporal = async (result: { created: number; removed: number }) => {+ await applyTemporalEvidence(tx, snapshot.page, rows, temporalKeysBefore, { inlineRanges });+ return result;+ };+ if (ambiguous.length) throw new DerivedLinkRepairRequiredError();+ if (missing.length) throw new DerivedLinkEndpointChangedError('A derived link endpoint changed or was deleted');+ if (changed.length) throw new DerivedLinkEndpointChangedError('A derived link endpoint changed after type resolution');const reversed = rows.filter(row => row.link_type === 'attended' && row.origin_slug&& row.to_slug === origin.slug && row.to_source_id === origin.sourceId&& (row.from_slug !== origin.slug || row.from_source_id !== origin.sourceId));@@ -135,16 +156,6 @@ export async function replaceDerivedLinks(if (invalid.length) throw new TypeError('Canonical attendance requires person endpoints');}if (opts.preserveExisting) {- const existing = await tx.executeRaw<{ id: number; from_slug: string; to_slug: string;- from_source_id: string; to_source_id: string; link_type: string; link_source: string | null;- origin_slug: string | null; origin_source_id: string | null; context: string; origin_field: string | null }>(`SELECT l.id, f.slug from_slug, t.slug to_slug,- f.source_id from_source_id, t.source_id to_source_id, l.link_type, l.link_source,- o.slug origin_slug, o.source_id origin_source_id, l.context, l.origin_field- FROM links l JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_id- LEFT JOIN pages o ON o.id=l.origin_page_id- WHERE (l.link_source=ANY($2::text[]) OR ($3::boolean AND l.link_source IS NULL))- AND (l.origin_page_id=$1 OR (l.origin_page_id IS NULL AND l.from_page_id=$1- AND (l.link_source IN ('markdown','wikilink-resolved') OR l.link_source IS NULL)))`, [id, producers, opts.includeLegacyNullProducer !== false]);const identity = (row: Pick<LinkBatchInput, 'from_source_id' | 'from_slug' | 'to_source_id' | 'to_slug' | 'link_type'>& { link_source?: string | null; origin_slug?: string | null }) => JSON.stringify([row.from_source_id, row.from_slug,row.to_source_id, row.to_slug, row.link_type ?? '', row.link_source ?? 'markdown', row.origin_slug ?? null]);diff --git a/src/core/engine-sql/chunks.ts b/src/core/engine-sql/chunks.tsindex 3041d7ea8f..47c93a2d01 100644--- a/src/core/engine-sql/chunks.ts+++ b/src/core/engine-sql/chunks.ts@@ -87,6 +87,21 @@ export async function upsertChunksOnce(// remain, and the seal (which also locks the page row and yields its id)// commits only together with the insert below.const seal = opts?.sealChunkerVersion;+ // The config reads the insert below needs go out with the page lookup (one round trip on Postgres).+ let gatewayModel: string | null = null;+ try {+ // Keep the gateway lazy so module-load failure remains inside this soft+ // fallback boundary; eager evaluation would bypass the config-row fallback.+ const gw = await import('../ai/gateway.ts'); // engine-dynamic-import-ok+ gatewayModel = gw.getEmbeddingModelProvenance();+ } catch {}+ const writesRows = chunks.length > 0;+ const columnRows = writesRows && !opts?.embeddingColumn ? memo('config:embedding-columns', async () =>+ (await exec.run<{ key: string; value: string }>(sqlFragment`SELECT key, value FROM config WHERE key IN ('search_embedding_column', 'embedding_columns')`)).rows)+ .then(rows => rows, () => null) : undefined;+ const modelRows = writesRows && !gatewayModel ? memo('config:embedding-model', async () =>+ (await exec.run<{ value?: string }>(sqlFragment`SELECT value FROM config WHERE key = 'embedding_model'`)).rows)+ .then(rows => rows, () => null) : undefined;const pages = (await exec.run<{ id: number }>(seal === undefined? sqlFragment`SELECT id FROM pages WHERE slug = ${slug} AND source_id = ${sourceId} FOR UPDATE`: sqlFragment`UPDATE pages SET chunker_version = ${seal} WHERE slug = ${slug} AND source_id = ${sourceId} RETURNING id`)).rows;@@ -138,15 +153,10 @@ export async function upsertChunksOnce(} else {let searchEmbeddingColumn: string | null = null;let embeddingColumnsJson: string | null = null;- try {- const cfgRows = await memo('config:embedding-columns', async () =>- (await exec.run<{ key: string; value: string }>(sqlFragment`SELECT key, value FROM config WHERE key IN ('search_embedding_column', 'embedding_columns')`)).rows);- for (const r of cfgRows) {- if (r.key === 'search_embedding_column') searchEmbeddingColumn = r.value;- else if (r.key === 'embedding_columns') embeddingColumnsJson = r.value;- }- } catch {- // config table unreadable — legacy column via the resolver default.+ // A null read (config table unreadable) leaves the legacy column via the resolver default.+ for (const r of await columnRows ?? []) {+ if (r.key === 'search_embedding_column') searchEmbeddingColumn = r.value;+ else if (r.key === 'embedding_columns') embeddingColumnsJson = r.value;}writeCol = resolveWriteColumnFromConfigRows({ searchEmbeddingColumn, embeddingColumnsJson });}@@ -158,20 +168,8 @@ export async function upsertChunksOnce(// later text rewrite that keeps the vector is detectable as content// drift (invalidateContentDriftEmbeddings). NULL when no embedding lands.const cols = `(page_id, chunk_index, chunk_text, chunk_source, ${writeColId}, model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image)`;- let resolvedModel: string | null = null;- try {- // Keep the gateway lazy so module-load failure remains inside this soft- // fallback boundary; eager evaluation would bypass the config-row fallback.- const gw = await import('../ai/gateway.ts'); // engine-dynamic-import-ok- resolvedModel = gw.getEmbeddingModelProvenance();- } catch {}- if (!resolvedModel) {- try {- const cfg = await memo('config:embedding-model', async () =>- (await exec.run<{ value?: string }>(sqlFragment`SELECT value FROM config WHERE key = 'embedding_model'`)).rows);- resolvedModel = cfg[0]?.value ?? null;- } catch {}- }+ let resolvedModel: string | null = gatewayModel;+ if (!resolvedModel) resolvedModel = (await modelRows)?.[0]?.value ?? null;resolvedModel = writeCol.embeddingModel || resolvedModel;if (!resolvedModel && chunks.some(chunk => chunk.embedding && !chunk.model)) {throw new Error('Embedding model provenance is unknown. Supply an explicit chunk model or run gbrain migrate embeddings --status before an explicit migration.');diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex 2cb6b82c14..34a9c74405 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -61,6 +61,7 @@ import { decorateEmbeddingDimError } from './embedding-dim-check.ts';import { resolveImportContextualMode } from './import-contextual-mode.ts';import { runGuardrails } from './guardrails.ts';import { parseFactsFence, renderFactsTable, restoreHiddenFactRows, factsGapWarning, replaceOrInsertFactsFence } from './facts-fence.ts';+import { pipelined } from './page-state/transactions.ts';/*** #2044 / #4548: row-level, visibility-aware fence merge for one page@@ -242,6 +243,8 @@ export async function importFromContent(prepare?: (prepared: import('./persistence/prepared-import.ts').PreparedContentImport) => Promise<ImportResult>;/** #5984, with `prepare`: the coordinator proves the base revision under its page guard, and the caller seals the text projection and checks the read-back (`contentHash`) from its own read after apply; apply skips all three. */coordinated?: boolean;+ /** With `coordinated`: the caller's own read of this page (deleted rows included) just before, reused as the import base. */+ existingSnapshot?: import('./page-state/types.ts').PageSnapshot | null;/** Internal canonical metadata, after protected-body overlays and before hashing. */prepareFrontmatter?: (page: ParsedPage) => void;noEmbed?: boolean;@@ -558,7 +561,7 @@ export async function importFromContent(// engine.putPage defaults to 'default' when sourceId is unset, so the read// mirrors that default instead of matching the slug in ANY source (the// unscoped-check/scoped-write bug class).- const existingSnapshot = opts.prepare ? await engine.readPageSnapshot(slug, { sourceId: sourceId ?? 'default', includeDeleted: true }) : null;+ const existingSnapshot = !opts.prepare ? null : opts.coordinated && opts.existingSnapshot !== undefined ? opts.existingSnapshot : await engine.readPageSnapshot(slug, { sourceId: sourceId ?? 'default', includeDeleted: true });const existing = opts.prepare ? existingSnapshot?.page ?? null : await engine.getPage(slug, { sourceId: sourceId ?? 'default', includeDeleted: true });if (existing) stabilizeSafetyAssessments(parsed.frontmatter, existing.frontmatter);@@ -899,31 +902,25 @@ export async function importFromContent(// under CAS, and --no-embed drains read it back. Every chunk row is// replaced below, so no older vector survives under this stamp.// This stamp certifies no vector: embedding_signature stays deferred.- await tx.updatePageContextualRetrievalState(- slug,- sourceId ?? 'default',- effectiveCRMode,- corpusGeneration,- );-- // Tag reconciliation (A14): frontmatter tags carry tag_source='frontmatter'.- // A frontmatter-owned row whose tag left the frontmatter is deleted; rows- // explicit adds own ('added': add_tag, enrichment, the code importer) and- // legacy NULL rows are never deleted here (#1621: reindex must not wipe- // enrichment). A legacy row still in the frontmatter is adopted. Prepared- // (managed) imports keep the add-only union their canonical file renders.- if (!opts.prepare) {- await tx.executeRaw(`DELETE FROM tags t USING pages p WHERE p.id = t.page_id AND p.source_id = $1 AND p.slug = $2- AND t.tag_source = 'frontmatter' AND NOT (t.tag = ANY($3::text[]))`, [txOpts.sourceId, slug, parsed.tags]);- }- for (const tag of parsed.tags) {- await tx.addTag(slug, tag, opts.prepare ? txOpts : { ...txOpts, tagSource: 'frontmatter' });- }-- // Replace every derived row atomically. Only vectors the A13 reuse gate- // above admitted carry over; a new seal otherwise inherits nothing from an- // older index, whose contextual vector may have included a private sibling.- await tx.deleteChunks(slug, txOpts);+ // The stamp, the tag reconciliation and the chunk delete touch independent rows: sent together.+ await pipelined(tx, [+ () => tx.updatePageContextualRetrievalState(slug, sourceId ?? 'default', effectiveCRMode, corpusGeneration),+ // Tag reconciliation (A14): frontmatter tags carry tag_source='frontmatter'.+ // A frontmatter-owned row whose tag left the frontmatter is deleted; rows+ // explicit adds own ('added': add_tag, enrichment, the code importer) and+ // legacy NULL rows are never deleted here (#1621: reindex must not wipe+ // enrichment). A legacy row still in the frontmatter is adopted. Prepared+ // (managed) imports keep the add-only union their canonical file renders.+ async () => {+ if (!opts.prepare) await tx.executeRaw(`DELETE FROM tags t USING pages p WHERE p.id = t.page_id AND p.source_id = $1 AND p.slug = $2+ AND t.tag_source = 'frontmatter' AND NOT (t.tag = ANY($3::text[]))`, [txOpts.sourceId, slug, parsed.tags]);+ for (const tag of parsed.tags) await tx.addTag(slug, tag, opts.prepare ? txOpts : { ...txOpts, tagSource: 'frontmatter' });+ },+ // Replace every derived row atomically. Only vectors the A13 reuse gate+ // above admitted carry over; a new seal otherwise inherits nothing from an+ // older index, whose contextual vector may have included a private sibling.+ () => tx.deleteChunks(slug, txOpts),+ ]);if (chunks.length > 0) {const embeddingColumn = await stampEmbeddingInputs(tx, chunks, null,{ title: parsed.title, tier: effectiveCRMode === 'title' ? 'title' : 'none', corpusGeneration });diff --git a/src/core/link-temporal-apply.ts b/src/core/link-temporal-apply.tsindex 1f2980663b..b2a1b18465 100644--- a/src/core/link-temporal-apply.ts+++ b/src/core/link-temporal-apply.ts@@ -20,6 +20,7 @@ import { deriveTemporalEvidence, rowKey, type TemporalEvidence } from './link-teimport { refreshRelationships, type RelationshipKey } from './link-relationships.ts';import { temporalLinkTypes } from './link-validity.ts';import { inlineTransitions } from './link-effective.ts';+import { pipelined } from './page-state/transactions.ts';type Tx = Pick<BrainEngine, 'executeRaw'>;@@ -67,8 +68,8 @@ export async function applyTemporalEvidence(from_source_id: r.from_source_id ?? sourceId, to_source_id: r.to_source_id ?? sourceId,tense: evidence.tense.get(rowKey(r)) === 'past' ? 'past' : null,}));- if (tenseRows.length) {- await executeRawJsonb(tx,+ // The tense update, the transition replacement, the target check and the after-read are sent together, in this order.+ const tense = tenseRows.length ? () => executeRawJsonb(tx,`UPDATE links l SET assertion_tense = v.tenseFROM jsonb_to_recordset(($2::jsonb)->'rows') AS v(from_slug text, to_slug text, link_type text, link_source text,from_source_id text, to_source_id text, tense text)@@ -77,13 +78,8 @@ export async function applyTemporalEvidence(WHERE l.from_page_id = f.id AND l.to_page_id = t.id AND l.link_type = v.link_type AND l.link_source = v.link_sourceAND (l.origin_page_id = $1 OR (l.origin_page_id IS NULL AND l.from_page_id = $1))AND l.assertion_tense IS DISTINCT FROM v.tense`,- [pageId], [{ rows: tenseRows }]);- }-- await tx.executeRaw(`DELETE FROM link_transitions WHERE origin_page_id = $1 AND producer = ANY($2::text[])`, [pageId, DERIVED_PRODUCERS]);- let inserted: RelationshipKey[] = [];- if (transitions.length) {- inserted = await executeRawJsonb<RelationshipKey>(tx,+ [pageId], [{ rows: tenseRows }]) : async () => undefined;+ const insert = transitions.length ? () => executeRawJsonb<RelationshipKey>(tx,`INSERT INTO link_transitions (source_id, from_page_id, to_page_id, link_type, kind, occurred_on, date_precision, producer, origin_page_id, line_hash)SELECT $2, f.id, t.id, v.link_type, v.kind, v.occurred_on::date, v.date_precision, v.producer, $1, v.line_hashFROM jsonb_to_recordset(($3::jsonb)->'rows') AS v(from_slug text, to_slug text, link_type text, kind text,@@ -92,20 +88,25 @@ export async function applyTemporalEvidence(JOIN pages t ON t.slug = v.to_slug AND t.source_id = $2 AND t.deleted_at IS NULLON CONFLICT DO NOTHINGRETURNING from_page_id, to_page_id, link_type`,- [pageId, sourceId], [{ rows: transitions }]);- }+ [pageId, sourceId], [{ rows: transitions }]) : async () => [] as RelationshipKey[];const unmatched = [...evidence.unmatched, ...inline.unmatched];const explicitTargets = [...new Set(evidence.transitions.filter(t => t.producer === 'explicit' || t.producer === 'dream').map(t => t.to_slug))];+ const [, , inserted, liveTargets, keysAfter] = await pipelined(tx, [+ tense,+ () => tx.executeRaw(`DELETE FROM link_transitions WHERE origin_page_id = $1 AND producer = ANY($2::text[])`, [pageId, DERIVED_PRODUCERS]),+ insert,+ () => explicitTargets.length ? tx.executeRaw<{ slug: string }>(+ `SELECT slug FROM pages WHERE source_id = $1 AND slug = ANY($2::text[]) AND deleted_at IS NULL`, [sourceId, explicitTargets]) : Promise.resolve([]),+ () => relationshipKeysForOrigin(tx, pageId),+ ]) as [unknown, unknown, RelationshipKey[], Array<{ slug: string }>, RelationshipKey[]];if (explicitTargets.length) {- const live = new Set((await tx.executeRaw<{ slug: string }>(- `SELECT slug FROM pages WHERE source_id = $1 AND slug = ANY($2::text[]) AND deleted_at IS NULL`, [sourceId, explicitTargets])).map(r => r.slug));+ const live = new Set(liveTargets.map(r => r.slug));for (const t of evidence.transitions) {if ((t.producer === 'explicit' || t.producer === 'dream') && !live.has(t.to_slug)) {unmatched.push({ line: `${t.kind === 'start' ? 'Started' : 'Ended'} ${t.link_type} [[${t.to_slug}]]`, reason: 'no_target' });}}}- const keysAfter = await relationshipKeysForOrigin(tx, pageId);const refreshed = await refreshRelationships(tx, [...keysBefore, ...keysAfter]);return { transitions: inserted.length, refreshed, unmatched };}diff --git a/src/core/mentions/pass.ts b/src/core/mentions/pass.tsindex 8e1081ae7e..586bde2f74 100644--- a/src/core/mentions/pass.ts+++ b/src/core/mentions/pass.ts@@ -37,6 +37,7 @@import { createHash } from 'node:crypto';import type { BrainEngine, LinkBatchInput } from '../engine.ts';+import { pipelined } from '../page-state/transactions.ts';import { isCrossSourceLinksEnabled } from '../link-extraction.ts';import {buildGazetteer, findMentionedEntities, gazetteerEntryKeys, tokenizeTitle,@@ -168,8 +169,11 @@ export async function writeDerivedAliases(tx: Pick<BrainEngine, 'executeRaw' | 'export async function writePageAliases(tx: BrainEngine, slug: string, sourceId: string,page: { title: string; type: string; compiled_truth: string; timeline: string; frontmatter: Record<string, unknown> }, pack: unknown,policy: MentionPolicy | null): Promise<void> {- await tx.setPageAliases(slug, sourceId, normalizeAliasList(page.frontmatter.aliases));- await writeDerivedAliases(tx, sourceId, { slug, ...page }, { pack: (pack as PackTypes | undefined) ?? null, policy });+ // Frontmatter and derived rows are disjoint (by origin): both replacements are sent together.+ await pipelined(tx, [+ () => tx.setPageAliases(slug, sourceId, normalizeAliasList(page.frontmatter.aliases)),+ () => writeDerivedAliases(tx, sourceId, { slug, ...page }, { pack: (pack as PackTypes | undefined) ?? null, policy }),+ ]);}/** Turn the index off for one source: plain mention links, derived aliases, entries and page state go; typed_ner rows stay. */diff --git a/src/core/page-state/guards.ts b/src/core/page-state/guards.tsindex ce8bd581ac..3eb5b66580 100644--- a/src/core/page-state/guards.ts+++ b/src/core/page-state/guards.ts@@ -1,6 +1,7 @@import type { BrainEngine } from '../engine.ts';import { validateSlug } from '../utils.ts';import type { PageKey } from './types.ts';+import { pipelined } from './transactions.ts';/** Source locks precede auth/request locks in callers; repeat held locks safely. */export async function lockPageKeys(engine: Pick<BrainEngine, 'executeRaw'>, keys: readonly PageKey[]): Promise<void> {@@ -12,8 +13,24 @@ export async function lockPageKeys(engine: Pick<BrainEngine, 'executeRaw'>, keys}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 sourceIds = [...new Set(ordered.map(key => key.sourceId))];+ // One source key (the common case): its share lock and the guard statements are sent together; the+ // guards take the incarnation from the locked row, and a missing source is reported before anything else.+ if (sourceIds.length === 1 && ordered.length === 1) {+ const key = ordered[0]!;+ await pipelined(engine, [+ async () => {+ const rows = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1 FOR SHARE', [key.sourceId]);+ if (!rows.length) throw new Error(`Page source does not exist: ${key.sourceId}`);+ },+ () => engine.executeRaw('INSERT INTO page_write_guards(source_incarnation,slug) SELECT incarnation,$2 FROM sources WHERE id=$1 ON CONFLICT DO NOTHING', [key.sourceId, key.slug]),+ () => engine.executeRaw('SELECT g.slug FROM page_write_guards g JOIN sources s ON s.incarnation=g.source_incarnation WHERE s.id=$1 AND g.slug=$2 FOR UPDATE OF g', [key.sourceId, key.slug]),+ // Also fence direct SQL row writers. The guard remains when this row is absent.+ () => engine.executeRaw('SELECT id FROM pages WHERE source_id=$1 AND slug=$2 FOR UPDATE', [key.sourceId, key.slug]),+ ]);+ return;+ }+ for (const sourceId of sourceIds) {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);@@ -21,19 +38,24 @@ export async function lockPageKeys(engine: Pick<BrainEngine, 'executeRaw'>, keysif (ordered.length > 1) {// #5984: many keys in three statements, still created and locked in the sorted key order.const incarnations = ordered.map(key => sources.get(key.sourceId)!), slugs = ordered.map(key => key.slug), sourceIds = ordered.map(key => key.sourceId);- await engine.executeRaw('INSERT INTO page_write_guards(source_incarnation,slug) SELECT i,s FROM unnest($1::uuid[],$2::text[]) WITH ORDINALITY AS k(i,s,n) ORDER BY n ON CONFLICT DO NOTHING', [incarnations, slugs]);- await engine.executeRaw(`SELECT g.slug FROM unnest($1::uuid[],$2::text[]) WITH ORDINALITY AS k(i,s,n)- JOIN page_write_guards g ON g.source_incarnation=k.i AND g.slug=k.s ORDER BY k.n FOR UPDATE OF g`, [incarnations, slugs]);- await engine.executeRaw(`SELECT p.id FROM unnest($1::text[],$2::text[]) WITH ORDINALITY AS k(src,s,n)- JOIN pages p ON p.source_id=k.src AND p.slug=k.s ORDER BY k.n FOR UPDATE OF p`, [sourceIds, slugs]);+ await pipelined(engine, [+ () => engine.executeRaw('INSERT INTO page_write_guards(source_incarnation,slug) SELECT i,s FROM unnest($1::uuid[],$2::text[]) WITH ORDINALITY AS k(i,s,n) ORDER BY n ON CONFLICT DO NOTHING', [incarnations, slugs]),+ () => engine.executeRaw(`SELECT g.slug FROM unnest($1::uuid[],$2::text[]) WITH ORDINALITY AS k(i,s,n)+ JOIN page_write_guards g ON g.source_incarnation=k.i AND g.slug=k.s ORDER BY k.n FOR UPDATE OF g`, [incarnations, slugs]),+ () => engine.executeRaw(`SELECT p.id FROM unnest($1::text[],$2::text[]) WITH ORDINALITY AS k(src,s,n)+ JOIN pages p ON p.source_id=k.src AND p.slug=k.s ORDER BY k.n FOR UPDATE OF p`, [sourceIds, slugs]),+ ]);return;}+ // The three statements of a key are sent together (#5984 pipelining); the server still runs them in this order.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]);+ await pipelined(engine, [+ () => engine.executeRaw('INSERT INTO page_write_guards(source_incarnation,slug) VALUES ($1::uuid,$2) ON CONFLICT DO NOTHING', params),+ () => engine.executeRaw('SELECT slug FROM page_write_guards WHERE source_incarnation=$1::uuid AND slug=$2 FOR UPDATE', params),+ // Also fence direct SQL row writers. The guard remains when this row is absent.+ () => engine.executeRaw('SELECT id FROM pages WHERE source_id=$1 AND slug=$2 FOR UPDATE', [key.sourceId, key.slug]),+ ]);}}diff --git a/src/core/page-state/transactions.ts b/src/core/page-state/transactions.tsindex a9fbc3beed..b5c4211b15 100644--- a/src/core/page-state/transactions.ts+++ b/src/core/page-state/transactions.ts@@ -78,8 +78,8 @@ export function transactionMemo<T>(tx: object, keys: string | readonly string[],* calls' first. The first failure in call order that is not a 25P02 abort is* thrown (the 25P02 itself when that is all there is). PGLite runs the calls one at a time.*/-export async function pipelined(engine: { kind: string }, calls: ReadonlyArray<() => Promise<unknown>>): Promise<unknown[]> {- if (engine.kind !== 'postgres') {+export async function pipelined(engine: object, calls: ReadonlyArray<() => Promise<unknown>>): Promise<unknown[]> {+ if ((engine as { kind?: unknown }).kind !== 'postgres') {const results: unknown[] = [];for (const call of calls) results.push(await call());return results;diff --git a/src/core/persistence/authority.ts b/src/core/persistence/authority.tsindex 4f9b7a4516..b4b2d9d825 100644--- a/src/core/persistence/authority.ts+++ b/src/core/persistence/authority.ts@@ -10,7 +10,7 @@ import { authSourcesFromGrant, grantFromTokenRow } from '../grants/model.ts';import { readLocalWriter, currentVerifiedLocalWriter, verifyLocalWriter, type LocalGrant } from './identity.ts';import type { Principal, SqlEngine, WriteAuthority, WriteRequest } from './model.ts';import { authorizePageVisibility, excludesPrivateWrites } from './page-visibility.ts';-import { transactionMemo } from '../page-state/transactions.ts';+import { pipelined, transactionMemo } from '../page-state/transactions.ts';function deny(message: string): never { throw new OperationError('permission_denied', message, 'Inspect the current writer registration and source/operation grants.'); }function strings(value: unknown): value is string[] { return Array.isArray(value) && value.every(v => typeof v === 'string'); }@@ -128,14 +128,19 @@ export async function authorizeWrite(engine: SqlEngine, a: WriteAuthority, opera/** `pageVisibility: false` is for a caller that checks the target's visibility itself after locking the page. */export async function authorizeStoredRequest(engine: SqlEngine, row: WriteRequest, lock = false, opts: { pageVisibility?: boolean } = {}): Promise<void> {// #5984: one membership read per source per transaction; a FOR SHARE read also answers a plain one.- const [source] = await transactionMemo(engine, lock ? [`source-membership:${row.source_id}:share`] : [`source-membership:${row.source_id}`, `source-membership:${row.source_id}:share`],- () => engine.executeRaw<{ incarnation: string; archived: boolean }>(`SELECT incarnation,archived FROM sources WHERE id=$1${lock ? ' FOR SHARE' : ''}`, [row.source_id]));- if (!source || source.archived || source.incarnation !== row.source_incarnation) {- throw opError('source_changed', 'The accepted source is no longer active.',- `Source ${row.source_id} was archived, removed, or recreated after request ${row.request_id} was accepted, so it will not be applied. Check the source's writer status; a new write must target the current source.`,- { fix: readFix(`Shows source ${row.source_id}'s current registration and requests, read-only.`, { argv: ['gbrain', 'sources', 'writer', 'status', '--source', row.source_id, '--json'] }) });- }- await authorizeWrite(engine, row.authority, row.operation, row.slug, lock);+ // The source lock and the writer check are sent together in lock order; a source refusal is reported first.+ await pipelined(engine, [+ async () => {+ const [source] = await transactionMemo(engine, lock ? [`source-membership:${row.source_id}:share`] : [`source-membership:${row.source_id}`, `source-membership:${row.source_id}:share`],+ () => engine.executeRaw<{ incarnation: string; archived: boolean }>(`SELECT incarnation,archived FROM sources WHERE id=$1${lock ? ' FOR SHARE' : ''}`, [row.source_id]));+ if (!source || source.archived || source.incarnation !== row.source_incarnation) {+ throw opError('source_changed', 'The accepted source is no longer active.',+ `Source ${row.source_id} was archived, removed, or recreated after request ${row.request_id} was accepted, so it will not be applied. Check the source's writer status; a new write must target the current source.`,+ { fix: readFix(`Shows source ${row.source_id}'s current registration and requests, read-only.`, { argv: ['gbrain', 'sources', 'writer', 'status', '--source', row.source_id, '--json'] }) });+ }+ },+ () => authorizeWrite(engine, row.authority, row.operation, row.slug, lock),+ ]);if (skillWrite(row.operation)) {const affected = (row.authority as WriteAuthority & { skillSlugsUsed?: unknown }).skillSlugsUsed;if (affected !== undefined) {diff --git a/src/core/persistence/config-snapshot.ts b/src/core/persistence/config-snapshot.tsnew file mode 100644index 0000000000..089438b57f--- /dev/null+++ b/src/core/persistence/config-snapshot.ts@@ -0,0 +1,31 @@+/**+ * One read of the brain config for a single write's preparation (Phase 4.3).+ * Preparation runs outside every lock and reads a dozen config keys one+ * round trip at a time; this view answers `getConfig` and the equivalent+ * `SELECT value FROM config WHERE key=$1` from one `SELECT key,value FROM+ * config` taken when preparation starts, as one batch's shared reads do+ * (page-mutations.ts `batchSharedReads`). Every other call reaches the engine+ * unchanged (`getAllConfig` answers from the same read). Publication reads its config again inside its transaction.+ */+import type { BrainEngine } from '../engine.ts';+import { VIEWED_ENGINE } from './switches.ts';++const KEY_READ = 'SELECT value FROM config WHERE key=$1';+const flat = (sql: string) => sql.replace(/\s+/g, ' ').trim();++export async function preparationConfigView(engine: BrainEngine): Promise<BrainEngine> {+ const rows = await engine.executeRaw<{ key: string; value: string }>('SELECT key,value FROM config');+ const values = new Map(rows.map(row => [row.key, row.value]));+ const value = (key: string) => values.has(key) ? values.get(key)! : null;+ return new Proxy(engine, { get(target, key) {+ if (key === VIEWED_ENGINE) return target;+ if (key === 'getConfig') return async (name: string) => value(name);+ if (key === 'getAllConfig') return async () => Object.fromEntries(values);+ if (key === 'executeRaw') return (sql: string, params?: unknown[], opts?: { signal?: AbortSignal }) =>+ flat(sql) === KEY_READ && typeof params?.[0] === 'string'+ ? Promise.resolve(values.has(params[0]) ? [{ value: values.get(params[0]) }] : [])+ : target.executeRaw(sql, params, opts);+ const member = Reflect.get(target, key, target);+ return typeof member === 'function' ? member.bind(target) : member;+ } });+}diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex 193b88df4e..1da5ab2cac 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -1,9 +1,10 @@import type { BrainEngine, ReservedConnection } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import { CLAIMABLE_WRITE_SQL, claimGroupFollowers, claimNextLaneHead, claimNextWrite, publicationGroupKey, compactWriteReceipts, hasClaimableWrite, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, vacuumPersistenceQueues } from './journal.ts';-import { finishUnpublishedFailure, publishMutation, recoverPublication, type PreparedMutation } from './coordinator.ts';+import { finishUnpublishedFailure, recoverPublication, type PreparedMutation } from './coordinator.ts';import { localHostId } from './identity.ts';-import { executeClaimedGroup, PAGE_BATCH_GROUP_MAX } from './group-publish.ts';+import { executeClaimedGroup, PAGE_BATCH_GROUP_MAX, publishSingleWrite, singleWrite } from './group-publish.ts';+import { preparationConfigView } from './config-snapshot.ts';import { CLAIM_LOST, DEFAULT_CLAIM_LEASE_TIMING, endLostLease, startClaimLease, type ClaimLeaseTiming } from './claim-lease.ts';import { isTerminal, type WriteRequest } from './model.ts';import { refreshManagedFilesystemRoots } from './filesystem-guard.ts';@@ -15,12 +16,15 @@ import { runPersistenceEffects } from './effects.ts';import { PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';import { isWriteErrorCode } from './types.ts';import { redactConnectionInfo } from '../audit/redact-connection-info.ts';+import { OperationError } from '../ops/contract.ts';+import type { ReservedTransactions } from '../postgres-engine/reserved-transactions.ts';import { AsyncLocalStorage } from 'node:async_hooks';import { monitorEventLoopDelay, type IntervalHistogram } from 'node:perf_hooks';import { maybeRefreshPlannerStats } from '../planner-stats.ts';import { refreshFenceClear } from './worktree-refresh-schema.ts';import { faultPoint } from './fault-points.ts';import { releaseAbandonedClaims } from './effect-journal.ts';+import { writeSwitchOn } from './switches.ts';type PhaseObservation = { name: string; started_at: string; deadline_exceeded: boolean; attempt: number; first_conn_ms?: number };/** #5373: set by a task that abandons a still-running preparation after losing its claim; its root is freed only once `until` settles. */@@ -57,6 +61,8 @@ export async function runResidentProjectionInvocation(engine: BrainEngine, hostI}const PARKED_WORKER: Promise<void> = Promise.resolve();+/** `onLane`'s answer when the lane cannot be lent: the caller runs on the pool instead. */+export const LANE_BUSY = Symbol('gbrain.laneBusy');export type PrepareMutation = (engine: BrainEngine, row: WriteRequest, config: GBrainConfig, signal?: AbortSignal) => Promise<PreparedMutation>;export class PersistenceConsumer {@@ -71,6 +77,8 @@ export class PersistenceConsumer {private topologyRetryAfter = new Map<string, number>();private idleLane: { conn: ReservedConnection; release: () => Promise<void> } | undefined;private idleLaneRetryAt = 0;+ /** Phase 4.4: a single write is publishing on the idle lane's connection. */+ private laneInUse = false;private active = new Set<Promise<void>>();/** #5373: preparations and renewals that outlived their claim; stop() drains them before the engine closes. */private outlived = new Set<Promise<void>>();@@ -88,6 +96,8 @@ export class PersistenceConsumer {private maintenanceVolume = 50;private lastScan = 0;private progressWake = false;+ /** Phase 4.3: this process admitted a write since the last tick; that tick claims before any scan. */+ private ownAdmission = false;private lastError: { code: string; at: string; phase?: string } | undefined;private abort = new AbortController();private phaseObservation: PhaseObservation | undefined;@@ -124,9 +134,15 @@ export class PersistenceConsumer {/*** Work admitted by this process: tick now instead of waiting out the idle* backoff. Like a completed publication, it claims at once and leaves scans- * to at most one pass per poll interval.+ * to at most one pass per poll interval. `ownAdmission` (the waiter of a+ * write this process just admitted) makes that tick skip the scans and+ * claim directly; the scans keep their own cadence, and recovery records+ * still block the claim (CLAIMABLE_WRITE_SQL).*/- wake(): void { this.progressWake = true; this.idleDelayMs = this.pollMs; this.schedule(0); }+ wake(ownAdmission = false): void {+ if (ownAdmission) this.ownAdmission = true;+ this.progressWake = true; this.idleDelayMs = this.pollMs; this.schedule(0);+ }private get pollMs(): number { return this.opts.pollMs ?? 250; }private get idleMaxMs(): number { return Math.max(this.pollMs, this.opts.idleMaxMs ?? 5000); }private schedule(ms: number): void {@@ -196,12 +212,14 @@ export class PersistenceConsumer {* permit fall back to pooled probes. The lane always comes from the ordinary* pool, never the direct/session route, whose clients are scarcer (#5233).*/- private async acquireIdleLane(signal?: AbortSignal): Promise<ReservedConnection | undefined> {+ private async acquireIdleLane(signal?: AbortSignal, forPublication = false): Promise<ReservedConnection | undefined> {if (this.idleLane) return this.idleLane.conn;if (this.engine.kind !== 'postgres' || this.stopping || Date.now() < this.idleLaneRetryAt) return undefined;const pool = (this.engine as { getPoolDiagnostics?: () => { poolMax: number | null; tracked: Record<string, number> } | null }).getPoolDiagnostics?.();// Only reserve from an otherwise idle pool: a saturated pool falls back to a cancellable pooled probe.- if (!pool?.poolMax || pool.poolMax < 3 || Object.values(pool.tracked).some(count => count > 0)) return undefined;+ // A single write's publication (Phase 4.4) also reserves it while at least two other connections stay free.+ const inUse = Object.values(pool?.tracked ?? {}).reduce((sum, count) => sum + Math.max(0, count), 0);+ if (!pool?.poolMax || pool.poolMax < 3 || (forPublication ? pool.poolMax - inUse < 3 : inUse > 0)) return undefined;const held = Promise.withResolvers<void>();const reserved = Promise.withResolvers<ReservedConnection>();const done = this.engine.withReservedConnection(async conn => { reserved.resolve(conn); await held.promise; }, { route: 'ordinary' })@@ -223,10 +241,50 @@ export class PersistenceConsumer {} finally { signal?.removeEventListener('abort', onAbort); }}private async releaseIdleLane(): Promise<void> {+ if (this.laneInUse) return;const lane = this.idleLane;this.idleLane = undefined;await lane?.release();}+ /**+ * Phase 4.4: publishes a single write. On Postgres, with the+ * `single_write_group` switch on, its group-of-one transaction runs on the+ * idle lane's reserved connection (taken while at least two other pool+ * connections stay free, and kept across single-write ticks), so its prepared+ * statements survive the pool's idle timeout and stay warm from one+ * foreground write to the next; without the lane it publishes on the pool.+ */+ private async publishSingle(row: WriteRequest, prepared: PreparedMutation): Promise<{ done: WriteRequest; settled: boolean }> {+ // A waiter learns of the commit before the recovery record is cleared (the clear still runs under the worktree lock).+ let settled = false;+ const hooks = { committed: (rows: WriteRequest[]) => { settled = true; this.settled(rows[0]!); } };+ const published = await this.onLane(transaction => publishSingleWrite(this.engine, row, prepared, this.hostId, hooks, transaction));+ const done = published === LANE_BUSY ? await publishSingleWrite(this.engine, row, prepared, this.hostId, hooks) : published;+ return { done, settled: settled && done.state === 'committed' };+ }+ /**+ * Phase 4.4: runs `run` with transactions on the warm lane connection (the+ * single-write publication's, also lent to this process's own single-write+ * admission), or returns LANE_BUSY without running it when the lane is in+ * use, unavailable, or the `single_write_group` switch is off. A failure+ * that may have broken the connection (not a refusal or an SQL error the+ * transaction rolled back) gives the lane up for a minute.+ */+ async onLane<T>(run: (transaction: <R>(fn: (tx: BrainEngine) => Promise<R>) => Promise<R>) => Promise<T>): Promise<T | typeof LANE_BUSY> {+ if (this.engine.kind !== 'postgres' || this.stopping || this.laneInUse || !await writeSwitchOn(this.engine, 'single_write_group').catch(() => true)) return LANE_BUSY;+ const conn = await this.acquireIdleLane(undefined, true) as (ReservedConnection & Partial<ReservedTransactions>) | undefined;+ if (!conn?.transaction || this.laneInUse) return LANE_BUSY;+ this.laneInUse = true;+ try {+ return await run(fn => conn.transaction!(fn));+ } catch (error) {+ const code = (error as { code?: unknown } | null)?.code;+ if (!(error instanceof OperationError) && !(typeof code === 'string' && /^[0-9A-Z]{5}$/.test(code)) && this.idleLane?.conn === conn) {+ this.laneInUse = false; await this.releaseIdleLane(); this.idleLaneRetryAt = Date.now() + 60_000;+ }+ throw error;+ } finally { this.laneInUse = false; }+ }private async probeQuery<T>(lane: ReservedConnection | undefined, sql: string, params: unknown[], signal?: AbortSignal): Promise<T[]> {if (!lane) return this.engine.executeRaw<T>(sql, params, { signal });const query = lane.executeRaw<T>(sql, params);@@ -287,10 +345,13 @@ export class PersistenceConsumer {return;}}- await this.releaseIdleLane();+ // Lane runs size themselves to the pool's long-hold budget; a single write keeps its warm lane.+ if (laneRoots().length || this.engine.kind !== 'postgres' || !await writeSwitchOn(this.engine, 'single_write_group').catch(() => true)) await this.releaseIdleLane();this.idleDelayMs = this.pollMs;this.nextDelayMs = this.pollMs;- const scan = !afterProgress || Date.now() - this.lastScan >= this.pollMs;+ const direct = afterProgress && this.ownAdmission && await writeSwitchOn(this.engine, 'single_write_group').catch(() => true);+ this.ownAdmission = false;+ const scan = !direct && (!afterProgress || Date.now() - this.lastScan >= this.pollMs);if (scan) {this.lastScan = Date.now();await this.phase('refresh_roots', signal => refreshManagedFilesystemRoots(this.engine,@@ -537,7 +598,10 @@ export class PersistenceConsumer {this.leaseTiming(), () => abort.abort({ code: 'claim_lost' }));const releaseReason = () => !lease.held ? 'claim_lost' : observation.deadline_exceeded ? 'preparation_deadline' : 'consumer_stopping';try {- const preparation = this.prepare(this.engine, row, this.config, bounded ? abort.signal : undefined);+ // Phase 4.3: a single page write prepares against one config read instead of one per key.+ const preparation = (async () => this.prepare(this.engine.kind === 'postgres' && singleWrite(row)+ && await writeSwitchOn(this.engine, 'single_write_group').catch(() => true) ? await preparationConfigView(this.engine) : this.engine,+ row, this.config, bounded ? abort.signal : undefined))();const prepared = await lease.whileHeld(preparation);if (prepared === CLAIM_LOST) {root.until = this.keepUntilSettled(preparation);@@ -557,12 +621,12 @@ export class PersistenceConsumer {this.preparing.delete(row.id);preparationActive = false;await faultPoint('consumer:prepared', { requestId: row.request_id, sourceId: row.source_id, operation: row.operation });- const done = await publishMutation(this.engine, row, prepared, this.hostId);+ const { done, settled } = await this.publishSingle(row, prepared);if (done.state === 'failed') this.log('publication', done.error_code ?? 'storage_error', done.error_message ?? undefined);if (done.state === 'committed' && row.worktree_id && !String(row.intent?.kind).startsWith('managed_sync_')) {this.foregroundCounts.set(row.worktree_id, this.foregroundCompletions(row.worktree_id) + 1);}- return this.settled(done);+ return settled ? isTerminal(done) : this.settled(done);} catch (error) {if (preparationActive && bounded && performance.now() >= deadline) observation.deadline_exceeded = true;if (preparationActive && (abort.signal.aborted || observation.deadline_exceeded)) {@@ -621,6 +685,7 @@ export class PersistenceConsumer {await this.tickPromise;await this.releaseIdleLane();await Promise.allSettled([...this.active]);+ await this.releaseIdleLane();while (this.outlived.size) await Promise.all([...this.outlived]);await this.projectionWorker;await this.effectsWorker;diff --git a/src/core/persistence/graduation-schema.ts b/src/core/persistence/graduation-schema.tsindex da8c76cbfd..b4460d75b7 100644--- a/src/core/persistence/graduation-schema.ts+++ b/src/core/persistence/graduation-schema.ts@@ -74,8 +74,17 @@ function parseJson<T>(value: unknown): T | null {return value as T;}+/** Engines (their root, never a transaction clone) whose database is known to have the table; an absence is never kept. */+const tablePresent = new WeakSet<object>();+function rootEngine(engine: object): object {+ let root = engine;+ while (Object.hasOwn(root, '_pageTransaction')) root = Object.getPrototypeOf(root);+ return root;+}export async function graduationTablePresent(engine: BrainEngine): Promise<boolean> {+ if (tablePresent.has(rootEngine(engine))) return true;const [row] = await engine.executeRaw<{ present: boolean }>(`SELECT to_regclass('persistence_graduation') IS NOT NULL AS present`);+ if (row?.present === true) tablePresent.add(rootEngine(engine));return row?.present === true;}diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.tsindex be05a78c43..a8430fdad5 100644--- a/src/core/persistence/group-publish.ts+++ b/src/core/persistence/group-publish.ts@@ -25,6 +25,11 @@* failure is attributed to its own page and no later member overtakes it.* A member with a skill bundle or a source-exclusive checkpoint, or whose* file changed since preparation, takes the single path.+ *+ * Phase 4.1: an eligible single page write (`publishSingleWrite`) also+ * publishes here, as a group of one, on Postgres. Its intent carries no group+ * marker, so its request identity and replay are unchanged; when the group+ * does not commit it takes `publishMutation` like any other member.*/import type { BrainEngine } from '../engine.ts';import { OperationError } from '../ops/contract.ts';@@ -52,8 +57,13 @@ import { decoratePublicationOutcome, finishUnpublishedFailure, pageRecoveryRecorpublishPersistenceFile, recoverPublication, type PreparedMutation } from './coordinator.ts';import { pipelined } from '../page-state/transactions.ts';import { jsonBytes } from './digest.ts';+import { readJournalLimits } from './limits.ts';+import type { JournalLimits } from './model.ts';import { writerStamp } from './writer-versions.ts';import { recordPublicationFenceTrend } from '../fence-repair/census-store.ts';+import { faultPoint, type PublicationBoundary } from './fault-points.ts';+import { assertMutationProtocol } from './protocol.ts';+import { writeSwitchOn } from './switches.ts';/** A `put_pages` group publishes at most this many pages per transaction, so one commit stays a few seconds long. */export const PAGE_BATCH_GROUP_MAX = 8;@@ -62,11 +72,17 @@ function syncMember(row: WriteRequest): boolean {return row.operation === 'submit_job' && (row.intent?.kind === 'managed_sync_import' || row.intent?.kind === 'managed_sync_delete');}+/** Single page writes that may publish as a group of one (Phase 4.1); owner-internal kinds keep the single path. */+const SINGLE_GROUP_OPERATIONS = new Set(['put_page', 'capture', 'edit_page', 'delete_page', 'restore_page', 'revert_version']);+export function singleWrite(row: Pick<WriteRequest, 'operation' | 'intent'>): boolean {+ return SINGLE_GROUP_OPERATIONS.has(row.operation) && !row.intent?.kind && publicationGroupKey(row) === null;+}+/** Whether a prepared member can share a group transaction. */export function groupable(row: WriteRequest, prepared: PreparedMutation): boolean {if ((row.target_kind ?? 'page') !== 'page' || prepared.target === 'skill_bundle' || prepared.sourceExclusive || prepared.exclusiveSources?.length) return false;if (syncMember(row)) return !prepared.file && typeof prepared.validate === 'function';- return publicationGroupKey(row)?.startsWith('batch:') === true;+ return publicationGroupKey(row)?.startsWith('batch:') === true || singleWrite(row);}const flat = (sql: string) => sql.replace(/\s+/g, ' ').trim();@@ -77,9 +93,10 @@ const flat = (sql: string) => sql.replace(/\s+/g, ' ').trim();* the owner's host binding (its worktree row is held FOR SHARE by the* ownership guard). Nothing in a page publication writes them.*/+const HOST_BINDING_SQL = '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';const STABLE_IN_GROUP = new Set(['SELECT local_path FROM sources WHERE id=$1 AND incarnation=$2::uuid',- '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',+ HOST_BINDING_SQL,]);/*** #6007: the group transaction seen through a per-transaction read snapshot.@@ -109,6 +126,8 @@ export interface GroupHooks {beforeCommit?(rows: WriteRequest[]): Promise<void>;/** After a failed group transaction and the restoration of any file it published. */rolledBack?(rows: WriteRequest[]): Promise<void>;+ /** Right after the commit, before the recovery records are cleared: the committed rows, for waiters. */+ committed?(rows: WriteRequest[]): void;}/**@@ -116,11 +135,15 @@ export interface GroupHooks {* not commit; `requeued` lists members whose claims the file restoration* released, which the caller may claim again while it holds the worktree.*/+/** Runs one transaction: `engine.transaction`, or a reserved connection's (Phase 4.4). */+export type TransactionRunner = <T>(fn: (tx: BrainEngine) => Promise<T>) => Promise<T>;+export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], prepared: PreparedMutation[], hostId = localHostId(),- hooks: GroupHooks = {}, lane: LaneState | null = null): Promise<{ done: WriteRequest[] | null; requeued: string[]; reason?: GroupFailure }> {+ hooks: GroupHooks = {}, lane: LaneState | null = null, transaction: TransactionRunner = fn => engine.transaction(fn)): Promise<{ done: WriteRequest[] | null; requeued: string[]; reason?: GroupFailure }> {const head = rows[0];const none: { done: null; requeued: string[]; reason?: GroupFailure } = { done: null, requeued: [] };- if (!head?.worktree_id || rows.some((row, i) => row.worktree_id !== head.worktree_id || row.source_id !== head.source_id || !groupable(row, prepared[i]!))) return none;+ if (!head?.worktree_id || rows.some((row, i) => row.worktree_id !== head.worktree_id || row.source_id !== head.source_id || !groupable(row, prepared[i]!)+ || rows.length > 1 && singleWrite(row))) return none;const binding = await getWorktreeBinding(engine, head.source_id, hostId);if (!binding || binding.owner_host_id !== hostId || !binding.local_path) return none;// #5984 lanes: lane groups share this process's native lock; everything else takes it exclusively.@@ -132,8 +155,12 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], prlet committed = false;const timed: { apply: ReturnType<typeof laneApplyBegin> | null } = { apply: null };try {- const blocked = await engine.executeRaw(`SELECT 1 FROM persistence_requests WHERE worktree_id=$1::uuid AND NOT (id=ANY($2::uuid[])) AND recovery IS NOT NULL- UNION ALL SELECT 1 FROM persistence_effects WHERE worktree_id=$1::uuid AND recovery IS NOT NULL LIMIT 1`, [head.worktree_id, rows.map(row => row.id)]);+ // The recovery check and the journal limits the recovery record is sized against go out together.+ const [blocked, limits] = await pipelined(engine, [+ () => engine.executeRaw(`SELECT 1 FROM persistence_requests WHERE worktree_id=$1::uuid AND NOT (id=ANY($2::uuid[])) AND recovery IS NOT NULL+ UNION ALL SELECT 1 FROM persistence_effects WHERE worktree_id=$1::uuid AND recovery IS NOT NULL LIMIT 1`, [head.worktree_id, rows.map(row => row.id)]),+ () => prepared.some(member => member.file && !member.noop) ? readJournalLimits(engine) : Promise.resolve(undefined),+ ]) as [unknown[], JournalLimits | undefined];if (blocked.length) return none;releaseCapacity = tryAcquirePublicationCapacity(engine, lane ? lane.effective + 1 : undefined);if (!releaseCapacity) return { ...none, reason: 'busy' };@@ -148,34 +175,47 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], prfiles.set(i, member);}if (files.size) {- await prepareRecoveries(engine, [...files.values()]);+ await prepareRecoveries(engine, [...files.values()], transaction, limits);for (const [i, member] of files) recorded.set(i, member);+ for (const member of files.values()) await seam('prepared', member.row);}if (lane) await awaitLaneBegin(lane, rows);- const done = await engine.transaction(async transaction => {+ const done = await transaction(async opened => {timed.apply?.end(rows.length);if (lane) timed.apply = laneApplyBegin(lane);- const tx = groupReads(transaction);- await declareDurablePersistence(tx);- const live = await guardOwnership(tx, head, hostId);- if (String(live?.owner_epoch) !== String(binding.owner_epoch)) throw new OperationError('owner_unavailable', 'Owner epoch changed before publication.', 'Inspect the source owner with gbrain sources writer status; do not claim or transfer the source to push this write.');- if (recorded.size) {+ const tx = groupReads(opened);+ // The guards are sent together and judged in order; any failure rolls the whole transaction back.+ const members = [...recorded.values()].map(member => member.row);+ const [, live, started, readOnly] = await pipelined(tx, [+ () => declareDurablePersistence(tx),+ () => guardOwnership(tx, head, hostId),// A published file needs recovery even if this transaction rolls back; claims are verified first.- const members = [...recorded.values()].map(member => member.row);- const started = await tx.executeRaw(`UPDATE persistence_requests r SET publication_started=true FROM unnest($1::uuid[],$2::uuid[]) AS t(id,token)- WHERE r.id=t.id AND r.execution_token=t.token AND r.state='running' RETURNING r.id`, [members.map(row => row.id), members.map(row => row.execution_token)]);- if (started.length !== members.length) throw new OperationError('write_claim_lost', 'Execution claim changed before publication.', 'Another worker holds the request; inspect it rather than resubmitting.');- if (await sourceMirrorReadOnly(tx, head.source_id, true)) throw new OperationError('source_changed', 'The source became a read-only mirror after this write was prepared.', 'The members publish one at a time.');- }- await tx.lockPageKeys(rows.flatMap((row, i) => [{ sourceId: row.source_id, slug: row.slug }, ...(prepared[i]!.additionalPageKeys ?? [])]));+ () => members.length ? tx.executeRaw(`UPDATE persistence_requests r SET publication_started=true FROM unnest($1::uuid[],$2::uuid[]) AS t(id,token)+ WHERE r.id=t.id AND r.execution_token=t.token AND r.state='running' RETURNING r.id`, [members.map(row => row.id), members.map(row => row.execution_token)]) : Promise.resolve([]),+ () => prepared.some(member => member.file) ? sourceMirrorReadOnly(tx, head.source_id, true) : Promise.resolve(false),+ () => tx.lockPageKeys(rows.flatMap((row, i) => [{ sourceId: row.source_id, slug: row.slug }, ...(prepared[i]!.additionalPageKeys ?? [])])),+ // The owner's host binding every file member's Git effect records (a STABLE_IN_GROUP read), fetched with the guards.+ () => prepared.some(member => member.file && !member.noop) ? tx.executeRaw(HOST_BINDING_SQL, [head.worktree_id]) : Promise.resolve([]),+ ]) as [unknown, Awaited<ReturnType<typeof guardOwnership>>, unknown[], boolean, unknown, unknown];+ 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.');+ if (started.length !== members.length) throw new OperationError('write_claim_lost', 'Execution claim changed before publication.', 'Another worker holds the request; inspect it rather than resubmitting.');+ // A file target prepared before the source became a read-only mirror is never published (as in publishMutation, noop included).+ if (readOnly) throw new OperationError('source_changed', 'The source became a read-only mirror after this write was prepared.', 'The members publish one at a time.');const outcomes: Record<string, unknown>[] = [];+ // A member's lead (authorization, knowledge guard, its locked read) only reads; the first member's+ // is sent ahead of the coordinated-write settings statement, the others in turn.+ const lead = (i: number) => pipelined(tx, [+ () => authorizeStoredRequest(tx, rows[i]!, true, { pageVisibility: false }),+ async () => { if (!syncMember(rows[i]!)) await assertKnowledgePublicationAllowed(tx, rows[i]!, prepared[i]!.file); },+ () => tx.readPageSnapshot(rows[i]!.slug, { sourceId: rows[i]!.source_id, includeDeleted: true }),+ ]) as Promise<[unknown, unknown, Awaited<ReturnType<BrainEngine['readPageSnapshot']>>]>;+ const first = lead(0);+ first.catch(() => undefined);// One coordinated write for the group; each member is the attributed actor of what it writes.await withCoordinatedWrite(tx, [head.source_id], async () => {for (let i = 0; i < rows.length; i++) {const row = rows[i]!, member = prepared[i]!, file = recorded.get(i);- await authorizeStoredRequest(tx, row, true, { pageVisibility: false });- if (!syncMember(row)) await assertKnowledgePublicationAllowed(tx, row, member.file);- const snapshot = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });+ const [, , snapshot] = await (i === 0 ? first : lead(i));await authorizePageVisibility(tx, row.authority, row.slug);if ((snapshot?.page.id ?? null) !== row.page_id) throw new OperationError('page_identity_changed', 'The accepted page was deleted or recreated.', 'Read the page again and submit a new intent with a new request_id.');await assertUnboundPublication(tx, row, snapshot?.page.source_path);@@ -183,9 +223,12 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], prawait member.validate?.(tx);if (file) {if (persistenceFileHash(file.record.path) !== file.record.beforeHash) throw new OperationError('unexpected_file_bytes', 'The canonical file changed during preparation.', 'The members publish one at a time.');+ await seam('before_publication', row);await withFilesystemPublication([file.record.root], async () => publishPersistenceFile(member.file!, file.record.staging?.publication?.path));+ await seam('after_publication', row);}- await setMemberAttribution(tx, requestAttribution(row));+ // A group of one is already attributed to its only member by the coordinated write.+ if (rows.length > 1) await setMemberAttribution(tx, requestAttribution(row));member.postimage = undefined;const outcome = await member.apply(tx, snapshot);await classifyUnboundPage(tx, row);@@ -193,7 +236,7 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], prconst final = await publicationPostimage(tx, row, member);decoratePublicationOutcome(row, member, outcome, final, file ? 1 : 0, false);await recordPublicationFenceTrend(tx, row, outcome);- await queuePublicationEffects(tx, row, final, outcome, member, { deferBatchReconcile: true });+ await queuePublicationEffects(tx, row, final, outcome, member, singleWrite(row) ? {} : { deferBatchReconcile: true });outcomes.push(outcome);}}, requestAttribution(head));@@ -204,11 +247,14 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], prconst last = rows[rows.length - 1]!;if (publicationGroupKey(last)?.startsWith('batch:') && queuesMentionLinks(last)) await reconcileFinishedBatch(tx, last);await hooks.beforeCommit?.(rows);+ for (const row of rows) await seam('before_commit', row);return done;});committed = true;+ for (const row of done) await seam('after_commit', row);+ hooks.committed?.(done);if (recorded.size) {- try { await clearResolvedRecoveries(engine, done); }+ try { await clearResolvedRecoveries(engine, done, transaction); }catch {// The ordinary recovery pass finishes cleanup of a committed receipt, or blocks its worktree on unexpected bytes.for (const row of done) if (row.recovery) {@@ -237,6 +283,37 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr}}+/** The publication crash seams (fault-points.ts) a member passes, named as in publishMutation. */+function seam(name: PublicationBoundary, row: WriteRequest): Promise<void> {+ return faultPoint(`publication:${name}`, { requestId: row.request_id, sourceId: row.source_id, operation: row.operation });+}++/**+ * Phase 4.1: publishes one claimed single page write as a group of one when+ * it qualifies (Postgres, a page target the group path accepts, the+ * `single_write_group` switch on), otherwise, or when that group does not+ * commit, through `publishMutation`. A claim the group's file restoration+ * released is taken back first; a request the group left recovering or that+ * another worker now holds is returned as it stands.+ */+export async function publishSingleWrite(engine: BrainEngine, row: WriteRequest, prepared: PreparedMutation, hostId = localHostId(), hooks: GroupHooks = {},+ transaction?: TransactionRunner): Promise<WriteRequest> {+ if (engine.kind !== 'postgres' || !singleWrite(row) || !groupable(row, prepared) || !await writeSwitchOn(engine, 'single_write_group').catch(() => true)) {+ return publishMutation(engine, row, prepared, hostId);+ }+ try { assertMutationProtocol(row); } catch { return publishMutation(engine, row, prepared, hostId); }+ const result = await publishGroup(engine, [row], [prepared], hostId, hooks, null, transaction);+ if (result.done) return result.done[0]!;+ let current = await getWriteRequestById(engine, row.id);+ if (current?.state === 'queued' && result.requeued.includes(row.id)) {+ const reclaimed = await reclaimReleasedWrite(engine, row.id);+ if (!reclaimed) return current;+ current = reclaimed;+ } else if (!current || current.execution_token !== row.execution_token) return current ?? row;+ if (current.state !== 'running' || current.recovery) return current;+ return publishMutation(engine, current, prepared, hostId);+}+/** Why a group transaction did not commit, for the lane fallback and step-down. */export type GroupFailure = 'busy' | 'predecessor_failed' | 'predecessor_requeued' | 'wounded' | 'order_timeout' | 'lock_timeout' | 'statement_timeout' | 'failed';function groupFailure(error: unknown): GroupFailure {@@ -267,12 +344,12 @@ async function laneFallback(engine: BrainEngine, rows: WriteRequest[], reason: G}/**- * #5984: completes every member's request row in one statement. Each member's- * queued effect bytes are read (and missing counter rows created) before the- * counters are locked; then the counter lock (`brain`, each principal,- * `worktree:<id>`, the order every completion uses) and one UPDATE that checks- * each member's claim (`execution_token`, `state='running'`) and terminal- * reservation, completes the rows and decrements the counters, are pipelined.+ * #5984: completes every member's request row in one statement. Missing+ * counter rows are created, then the counter lock (`brain`, each principal,+ * `worktree:<id>`, the order every completion uses) and one UPDATE that sizes+ * each member's queued effects, checks its claim (`execution_token`,+ * `state='running'`) and terminal reservation, completes the rows and+ * decrements the counters: three statements sent together, one round trip.* If the UPDATE returns fewer rows than the group, this throws so the* transaction rolls back; the group then takes the single path, where* completeWrite reports each member's exact error code. JSON binds as text.@@ -280,22 +357,20 @@ async function laneFallback(engine: BrainEngine, rows: WriteRequest[], reason: Gexport async function completeGroup(tx: BrainEngine, rows: WriteRequest[], outcomes: Record<string, unknown>[]): Promise<WriteRequest[]> {const ids = rows.map(row => row.id);const keys = [...new Set(['brain', ...rows.map(row => principalKey(requestPrincipal(row))), `worktree:${rows[0]!.worktree_id}`])].sort();- const [effects] = await pipelined(tx, [- () => tx.executeRaw<{ request_id: string; bytes: string }>(`SELECT request_id::text AS request_id,SUM(octet_length(data::text)+octet_length(kind)+1024)::text AS bytes- FROM persistence_effects WHERE request_id=ANY($1::uuid[]) GROUP BY request_id`, [ids]),- () => tx.executeRaw(ENSURE_COUNTERS_SQL, [keys]),- ]) as [Array<{ request_id: string; bytes: string }>];- const effectBytes = new Map(effects.map(e => [e.request_id, Number(e.bytes)]));const stamp = writerStamp();- const [, completed] = await pipelined(tx, [+ const [, , completed] = await pipelined(tx, [+ () => tx.executeRaw(ENSURE_COUNTERS_SQL, [keys]),() => tx.executeRaw(LOCK_COUNTERS_SQL, [keys]),() => tx.executeRaw<WriteRequest & { principal_key: string }>(`WITH m AS (SELECT * FROM unnest($1::uuid[],$2::uuid[],$3::text[],$4::bigint[],$5::text[]) AS m(id,token,outcome,need,principal_key)+ ), e AS (+ SELECT request_id,SUM(octet_length(data::text)+octet_length(kind)+1024) AS bytes FROM persistence_effects WHERE request_id=ANY($1::uuid[]) GROUP BY request_id), done AS (UPDATE persistence_requests r SET state='committed',outcome=m.outcome::jsonb,error_code=NULL,error_message=NULL,completed_at=now(),updated_at=now(),claim_expires_at=NULL,blocked_reason=NULL,consumer_version=$6,consumer_host_id=$7::uuid,published_at=now()- FROM m WHERE r.id=m.id AND r.execution_token=m.token AND r.state='running' AND m.need<=r.terminal_reservation+ FROM m LEFT JOIN e ON e.request_id=m.id+ WHERE r.id=m.id AND r.execution_token=m.token AND r.state='running' AND m.need+COALESCE(e.bytes,0)<=r.terminal_reservationRETURNING r.*,m.principal_key), released AS (UPDATE persistence_counters c SET outstanding_count=c.outstanding_count-d.n,intent_bytes=c.intent_bytes-d.bytes@@ -303,9 +378,9 @@ export async function completeGroup(tx: BrainEngine, rows: WriteRequest[], outcoWHERE c.key=d.key)SELECT * FROM done`, [ids, rows.map(row => row.execution_token), outcomes.map(outcome => JSON.stringify(outcome)),- rows.map((row, i) => jsonBytes(outcomes[i]) + jsonBytes(row.authority) + 1024 + (effectBytes.get(row.id) ?? 0)),+ rows.map((row, i) => jsonBytes(outcomes[i]) + jsonBytes(row.authority) + 1024),rows.map(row => principalKey(requestPrincipal(row))), stamp.version, stamp.hostId]),- ]) as [unknown, Array<WriteRequest & { principal_key: string }>];+ ]) as [unknown, unknown, Array<WriteRequest & { principal_key: string }>];if (completed.length !== rows.length) throw new OperationError('write_claim_lost', 'A group member failed its claim or terminal-reservation check before publication.','The group rolls back and its members publish one at a time, where each member reports its own outcome; inspect the requests rather than resubmitting.');const byId = new Map(completed.map(({ principal_key: _key, ...row }) => [row.id, row as WriteRequest]));diff --git a/src/core/persistence/identity.ts b/src/core/persistence/identity.tsindex 63bebc74a0..a7c5fb2214 100644--- a/src/core/persistence/identity.ts+++ b/src/core/persistence/identity.ts@@ -93,7 +93,8 @@ async function ensureLocalWriter(engine: BrainEngine, lane: 'cli' | 'stdio', gra'SELECT revoked_at,credential_hash,lane FROM persistence_local_writers WHERE id=$1::uuid', [local.id]);if (existing?.revoked_at != null) throw new OperationError('permission_denied', 'This local writer registration was revoked.', 'Explicitly register a new writer to authorize future work.');if (existing && (existing.lane !== lane || existing.credential_hash !== sha256(local.credential))) throw credentialMismatch(path, local.id, lane);- await engine.executeRaw(`INSERT INTO persistence_local_writers(id,lane,credential_hash,grant_ceiling)+ // A registered writer is left as it is (the insert would conflict and do nothing).+ if (!existing) await engine.executeRaw(`INSERT INTO persistence_local_writers(id,lane,credential_hash,grant_ceiling)VALUES($1::uuid,$2,$3,$4::text::jsonb) ON CONFLICT(id) DO NOTHING`, [local.id, lane, sha256(local.credential), JSON.stringify(grant)]);return local;}diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex e00812fa29..c8b7b962bc 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -8,6 +8,8 @@ import { digest, jsonBytes, requireUuid } from './digest.ts';import { authorizeWrite } from './authority.ts';import { journalLimitKey, oneYearCapacity, readJournalLimits, readReceiptRetentionDays } from './limits.ts';import { retryWriteAdmission } from './admission-retry.ts';+import { PreadmitBrainChanged } from './preadmit-cache.ts';+import { pipelined } from '../page-state/transactions.ts';import { writeHealth, type WriteHealthFacts } from './health.ts';import { writerStamp } from './writer-versions.ts';import { publicFailureDetail } from './publication-failure.ts';@@ -15,7 +17,6 @@ import { catalogueError } from '../error-catalogue.ts';import { ACTIVE_REFRESH_STATES_SQL, refreshFenceClear } from './worktree-refresh-schema.ts';import { assertMutationProtocol, assertSharedSkillPersistence, declareDurablePersistence, declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';import { assertGraduationAdmission } from './graduation-custody.ts';-import { pipelined } from '../page-state/transactions.ts';import {isTerminal, principalKey, requestPrincipal, recoveryFiles,type JournalLimits, type Principal, type RecoveryRecord, type RequestState,@@ -39,6 +40,8 @@ export interface WriteAdmission {intent: Record<string, unknown>;authority: WriteAuthority;terminalReservation?: number;+ /** Phase 4.2: the brain the cached pre-admission reads came from; admission under another brain throws PreadmitBrainChanged. */+ brainId?: string;}interface Counter {key: string; outstanding_count: number | string; intent_bytes: number | string;@@ -96,8 +99,12 @@ export const ENSURE_COUNTERS_SQL = 'INSERT INTO persistence_counters(key) SELECTexport const LOCK_COUNTERS_SQL = 'SELECT * FROM persistence_counters WHERE key=ANY($1::text[]) ORDER BY key COLLATE "C" FOR UPDATE';export async function lockCounters(tx: SqlEngine, keys: string[]): Promise<Counter[]> {const sorted = [...new Set(keys)].sort();- await tx.executeRaw(ENSURE_COUNTERS_SQL, [sorted]);- return tx.executeRaw<Counter>(LOCK_COUNTERS_SQL, [sorted]);+ // Sent together; the server creates the rows before it locks them.+ const [, locked] = await pipelined(tx, [+ () => tx.executeRaw(ENSURE_COUNTERS_SQL, [sorted]),+ () => tx.executeRaw<Counter>(LOCK_COUNTERS_SQL, [sorted]),+ ]) as [unknown, Counter[]];+ return locked;}export async function getWriteRequest(engine: SqlEngine, principal: Principal, requestId: string): Promise<WriteRequest | null> {const [row] = await engine.executeRaw<WriteRequest>(@@ -131,10 +138,12 @@ export function assertReplayIntent(row: WriteRequest, expectedDigest: string): W'This request_id was already accepted with different intent.', 'Replay the original request, or allocate a new request_id for a new intent.');return row;}-export async function admitWrite(engine: BrainEngine, input: WriteAdmission, overrides?: Partial<JournalLimits>): Promise<WriteRequest> {+export async function admitWrite(engine: BrainEngine, input: WriteAdmission, overrides?: Partial<JournalLimits>,+ transaction: <T>(fn: (tx: BrainEngine) => Promise<T>) => Promise<T> = fn => engine.transaction(fn)): Promise<WriteRequest> {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 retryWriteAdmission(requestId, remaining => transaction(async tx => {+ const brain = await declareDurablePersistence(tx, `${Math.min(100, remaining)}ms`, `${remaining}ms`);+ if (input.brainId !== undefined && brain !== input.brainId) throw new PreadmitBrainChanged();return apply(tx);}));}@@ -152,23 +161,28 @@ async function prepareAdmission(engine: BrainEngine, input: WriteAdmission, overconst stamp = writerStamp();return { requestId, apply: async (tx: BrainEngine): Promise<WriteRequest> => {await declarePersistenceProtocol(tx);- await assertGraduationAdmission(tx);- 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', [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.');- }- 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 prior = await getWriteRequest(tx, input.principal, requestId);+ // The guards are sent together in lock order (worktree, source, writer, counters) and judged in+ // that order: the first refusal in this list is the one reported, as when they ran one by one.+ const [, , , , , counters, topology, prior] = await pipelined(tx, [+ () => assertGraduationAdmission(tx),+ async () => assertMutationProtocol({ target_kind: input.targetKind, protocol_version: input.protocolVersion }),+ async () => { 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.+ async () => {+ const [source] = await tx.executeRaw<{ incarnation: string; archived: boolean }>(+ '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.');+ }+ },+ () => authorizeWrite(tx, input.authority, input.operation, input.slug, true),+ () => lockCounters(tx, ['brain', principalKey(input.principal)]),+ () => input.principal.kind === 'local_cli' ? tx.executeRaw('SELECT id FROM persistence_topology_changes WHERE principal_id=$1::uuid AND request_id=$2::uuid', [input.principal.id, requestId])+ : Promise.resolve([]),+ () => getWriteRequest(tx, input.principal, requestId),+ ]) as [unknown, unknown, unknown, unknown, unknown, Counter[], unknown[], WriteRequest | null];+ if (topology.length) throw lifecycleIdConflict(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.',@@ -346,13 +360,16 @@ export async function renewGroupClaims(engine: SqlEngine, rows: WriteRequest[],* 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+ // Sent together: the server takes the share lock before it reads the fence and the binding.+ const [, [state]] = await pipelined(tx, [+ () => tx.executeRaw('SELECT id FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE', [input.worktreeId]),+ () => 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_refreshesWHERE 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=$1AND source_incarnation=$2::uuid AND worktree_id=$3::uuid AND topology_generation=$4) AS bound`,- [input.sourceId, input.sourceIncarnation, input.worktreeId, input.topologyGeneration]);+ [input.sourceId, input.sourceIncarnation, input.worktreeId, input.topologyGeneration]),+ ]) as [unknown, Array<{ refresh: { id: string; state: string; source_ids: string[] } | string | null; bound: boolean }>];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.',@@ -409,11 +426,14 @@ export async function hasClaimableWrite(engine: SqlEngine, hostId: string, exclu/** Claims commit before OS-lock waits. An unresolved head blocks its entire root. */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+ // The protocol declaration and the FIFO head read are sent together.+ const [, [row]] = await pipelined(tx, [+ () => declarePersistenceProtocol(tx),+ () => tx.executeRaw<WriteRequest>(`SELECT r.* FROM persistence_requests rLEFT JOIN persistence_worktrees w ON w.id=r.worktree_idWHERE ${CLAIMABLE_WRITE_SQL}- ORDER BY r.sequence LIMIT 1 FOR UPDATE OF r SKIP LOCKED`, [hostId, excludeRoots]);+ ORDER BY r.sequence LIMIT 1 FOR UPDATE OF r SKIP LOCKED`, [hostId, excludeRoots]),+ ]) as [unknown, WriteRequest[]];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'),@@ -507,18 +527,18 @@ export async function prepareRecovery(engine: BrainEngine, row: WriteRequest, re* whose claim moved, or that already holds a record, fails the whole call and* nothing is recorded.*/-export async function prepareRecoveries(engine: BrainEngine, members: { row: WriteRequest; record: RecoveryRecord; bytes: number }[]): Promise<void> {+export async function prepareRecoveries(engine: BrainEngine, members: { row: WriteRequest; record: RecoveryRecord; bytes: number }[],+ transaction: <T>(fn: (tx: BrainEngine) => Promise<T>) => Promise<T> = fn => engine.transaction(fn), knownLimits?: JournalLimits): Promise<void> {if (!members.length) return;const worktree = members[0]!.row.worktree_id;if (!worktree || members.some(member => member.row.worktree_id !== worktree)) throw new TypeError('Grouped filesystem recovery requires one worktree.');- const limits = await readJournalLimits(engine);+ const limits = knownLimits ?? await readJournalLimits(engine);const total = members.reduce((sum, member) => sum + member.bytes, 0);if (members.some(member => member.bytes > limits.worktreeRecoveryBytes || member.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 declareDurablePersistence(tx);- const counters = await lockCounters(tx, ['brain', `worktree:${worktree}`]);+ await transaction(async tx => {+ const [, counters] = await pipelined(tx, [() => declareDurablePersistence(tx), () => lockCounters(tx, ['brain', `worktree:${worktree}`])]) as [unknown, Counter[]];for (const c of counters) if (Number(c.recovery_bytes) + total > (c.key === 'brain' ? limits.brainRecoveryBytes : limits.worktreeRecoveryBytes)) throw capacityError('recovery bytes currently reserved by other requests');const recorded = await tx.executeRaw(`WITH recorded AS (UPDATE persistence_requests r SET recovery=t.record,recovery_bytes=t.bytes,updated_at=now()FROM jsonb_to_recordset($1::text::jsonb) AS t(id uuid,token uuid,record jsonb,bytes bigint)@@ -532,12 +552,13 @@ export async function prepareRecoveries(engine: BrainEngine, members: { row: Wri}/** Clears the resolved recovery records of a committed group in one transaction; a record that changed is cleared on its own. */-export async function clearResolvedRecoveries(engine: BrainEngine, rows: WriteRequest[]): Promise<void> {+export async function clearResolvedRecoveries(engine: BrainEngine, rows: WriteRequest[],+ transaction: <T>(fn: (tx: BrainEngine) => Promise<T>) => Promise<T> = fn => engine.transaction(fn)): Promise<void> {const resolved = rows.filter(row => row.recovery && isTerminal(row));- if (resolved.length < 2) { for (const row of resolved) await clearResolvedRecovery(engine, row.id, row); return; }+ if (resolved.length < 2) { for (const row of resolved) await clearResolvedRecovery(engine, row.id, row, transaction); return; }for (const row of resolved) for (const file of recoveryFiles(row.recovery!)) assertRecoveryStagingAbsent(file);const worktree = resolved[0]!.worktree_id;- const cleared = new Set((await engine.transaction(async tx => {+ const cleared = new Set((await transaction(async tx => {await declareDurablePersistence(tx);const keys = ['brain', ...(worktree ? [`worktree:${worktree}`] : [])];await lockCounters(tx, keys);@@ -608,21 +629,24 @@ export async function completeWrite(tx: SqlEngine, row: WriteRequest, state: 'co* 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> {+export async function clearResolvedRecovery(engine: BrainEngine, id: string, known?: WriteRequest,+ transaction: <T>(fn: (tx: BrainEngine) => Promise<T>) => Promise<T> = fn => engine.transaction(fn)): 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 declareDurablePersistence(tx);+ await transaction(async 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+ // The settings, the counter lock and the clear of the exact known record are sent together.+ const [, , [cleared]] = await pipelined(tx, [() => declareDurablePersistence(tx), () => lockCounters(tx, keys), () => tx.executeRaw(`WITH locked AS (SELECT id,recovery_bytes FROM persistence_requests WHERE id=$1::uuid AND recovery=$3::text::jsonbAND 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)]);+ [id, keys, JSON.stringify(row.recovery)])]) as [unknown, unknown, unknown[]];if (cleared) return;+ } else {+ await declareDurablePersistence(tx);+ await lockCounters(tx, keys);}const [locked] = await tx.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid FOR UPDATE', [id]);if (!locked?.recovery || !isTerminal(locked)) return;diff --git a/src/core/persistence/links-preparation.ts b/src/core/persistence/links-preparation.tsindex 950c0c99d3..cb9f9efe0d 100644--- a/src/core/persistence/links-preparation.ts+++ b/src/core/persistence/links-preparation.ts@@ -8,6 +8,7 @@ import { capturedLinkEndpoints, indexLinkSources, loadLinkSourcePolicy, resolveCimport { collectWantedLinks, isWantedPagesEnabled } from '../wanted-links.ts';import { readFix } from '../ops/op-fix.ts';import { lineGrammarOptions } from '../line-grammar.ts';+import { primeRelationSemantics } from '../link-semantics-pack.ts';async function liveSlugAliases(engine: BrainEngine, sourceId: string, targets: string[]): Promise<Map<string, string>> {if (!targets.length) return new Map();@@ -72,8 +73,13 @@ export const LINK_ENDPOINTS_SQL = `WITH own AS (FROM pages WHERE source_id=s.id AND slug=ANY(e.refs) AND deleted_at IS NULL OFFSET 0) pWHERE s.id<>$1`;+/**+ * `primeSemantics`: install the pack relation semantics now, during preparation, so apply's+ * replacement does not read them again inside the publication transaction.+ */export async function prepareAutomaticLinks(engine: BrainEngine, slug: string,- page: Pick<ParsedPage, 'type' | 'compiled_truth' | 'timeline' | 'frontmatter'>, sourceId: string) {+ page: Pick<ParsedPage, 'type' | 'compiled_truth' | 'timeline' | 'frontmatter'>, sourceId: string, primeSemantics = false) {+ if (primeSemantics) await primeRelationSemantics(engine);const resolver = makeResolver(engine, { mode: 'live', sourceId, basenameIndex: () => sourceBasenameIndex(engine, sourceId) });const opts = { globalBasename: await isGlobalBasenameEnabled(engine), lineGrammar: await lineGrammarOptions(engine),pack: (await loadActivePackForLocalEngine(engine, { sourceId }))?.manifest ?? null };@@ -122,7 +128,7 @@ export async function prepareAutomaticLinks(engine: BrainEngine, slug: string,if (!snapshot) throw new Error('Automatic link origin disappeared');try {const result = await tx.replaceDerivedLinks({ slug, sourceId, expectedRevision: snapshot.revision,- sourceIncarnation: snapshot.sourceIncarnation }, rows, { preserveExisting: true, wanted: { ...wanted, producers: [...wanted.producers] },+ sourceIncarnation: snapshot.sourceIncarnation, snapshot }, rows, { preserveExisting: true, semanticsPrimed: primeSemantics, wanted: { ...wanted, producers: [...wanted.producers] },expectedEndpoints: capturedLinkEndpoints(rows, new Map([...metadata,[`${sourceId}\0${slug}`, { slug, source_id: sourceId, type: page.type, knowledge_revision: snapshot.revision }]])).filter(endpoint => endpoint.slug !== slug || endpoint.sourceId !== sourceId) });diff --git a/src/core/persistence/ownership.ts b/src/core/persistence/ownership.tsindex 8092a77876..e9ad1ef865 100644--- a/src/core/persistence/ownership.ts+++ b/src/core/persistence/ownership.ts@@ -1,6 +1,7 @@import { randomUUID } from 'node:crypto';import { lstatSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';import { isAbsolute, join, relative, resolve, sep } from 'node:path';+import { pipelined } from '../page-state/transactions.ts';import type { BrainEngine } from '../engine.ts';import { OperationError, opError } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';@@ -181,9 +182,12 @@ export async function probeWorktreeWriter(binding: WorktreeBinding, engine?: Bra}export async function guardOwnership(tx: SqlEngine, row: WriteRequest, hostId: string): Promise<WorktreeBinding | null> {if (!row.worktree_id) return null;- const [owner] = await tx.executeRaw<{ owner_host_id: string; owner_epoch: string | number; state: string }>(- 'SELECT owner_host_id,owner_epoch,state FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE', [row.worktree_id]);- const binding = await getWorktreeBinding(tx, row.source_id, hostId);+ // The worktree lock and the binding read are sent together; the server takes the lock first.+ const [[owner], binding] = await pipelined(tx, [+ () => tx.executeRaw<{ owner_host_id: string; owner_epoch: string | number; state: string }>(+ 'SELECT owner_host_id,owner_epoch,state FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE', [row.worktree_id]),+ () => getWorktreeBinding(tx, row.source_id, hostId),+ ]) as [Array<{ owner_host_id: string; owner_epoch: string | number; state: string }>, WorktreeBinding | null];if (!owner || !binding || binding.worktree_id !== row.worktree_id || binding.source_incarnation !== row.source_incarnation ||owner.owner_host_id !== hostId || owner.state !== 'active' || String(binding.topology_generation) !== String(row.topology_generation)) {throw opError('owner_unavailable', 'The accepted worktree ownership or source topology changed.',diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex 8a16eaf9a0..e69941615e 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -11,7 +11,7 @@ import { computeContentHash } from '../ingestion/types.ts';import { resolveSlugForPath } from '../sync.ts';import { scannerSlugRootMode, scannerSourcePath } from '../write-through.ts';import { sha256 } from './digest.ts';-import { assertPersistenceAccepting, estimatedRetryAfterMs, waitForWrite, writeResponse } from './service.ts';+import { assertPersistenceAccepting, estimatedRetryAfterMs, onPersistenceLane, waitForWrite, writeResponse } from './service.ts';import { parseWireWriteWaitMs } from './write-wait.ts';import { admitWrite, assertPageRequestIdentity, assertReplayIntent, getWriteRequest, intentDigest, type WriteAdmission } from './journal.ts';import { submissionAuthority, authorizeStoredRequest } from './authority.ts';@@ -26,6 +26,8 @@ import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guimport { isUnboundSourcePage, readUnboundWritePolicy, unboundSourceError } from './unbound-source.ts';import { colonSlugWindowsRefusal, isWindowsColonTarget } from './native-file-target.ts';import { publishesDatabaseOnly } from './page-prepare.ts';+import { cachedPreadmitBrain, dropPreadmitCache, preadmitReads, preadmitRecheckFailed } from './preadmit-cache.ts';+import { pipelined } from '../page-state/transactions.ts';import { isMirrorOnlyPage, sourceMirrorReadOnly } from './mirror-read-only.ts';import { isConnectorSourceKind } from './connector-identity.ts';@@ -155,9 +157,24 @@ export async function submitPageMutation(ctx: OperationContext,const { wait_ms: wireWait, ...params } = input.params;const wireWaitMs = parseWireWriteWaitMs(wireWait);const waitMs = () => wireWaitMs !== undefined ? Math.max(0, wireWaitMs - (performance.now() - arrived)) : input.waitMs ?? ctx.writeWaitMs;- const prepared = await preparePageAdmission(ctx, { ...input, params });+ // Phase 4.2: pre-admission reads that admission rechecks come from this process's cache; a refusal the+ // cache could explain drops it and prepares the write once more, uncached, so it ends as it would without it.+ const cached = await preadmitReads(ctx.engine);+ let prepared = await preparePageAdmission(cached ? { ...ctx, engine: cached } : ctx, { ...input, params });if (prepared.prior) return pendingAwareResponse(ctx, await waitForWrite(ctx.engine, prepared.prior, ctx.config, waitMs()));- const row = await admitWrite(ctx.engine, prepared.admission);+ const brainId = cached ? cachedPreadmitBrain(ctx.engine) : undefined;+ // Phase 4.4: the admission transaction runs on the warm single-write lane when it is free.+ const admit = (admission: WriteAdmission) => onPersistenceLane(ctx.engine, transaction => admitWrite(ctx.engine, admission, undefined, transaction),+ () => admitWrite(ctx.engine, admission));+ let row: WriteRequest;+ try { row = await admit(brainId ? { ...prepared.admission, brainId } : prepared.admission); }+ catch (error) {+ if (!cached || !preadmitRecheckFailed(error)) throw error;+ dropPreadmitCache(ctx.engine);+ prepared = await preparePageAdmission(ctx, { ...input, params: { ...params, request_id: prepared.admission.requestId } });+ if (prepared.prior) return pendingAwareResponse(ctx, await waitForWrite(ctx.engine, prepared.prior, ctx.config, waitMs()));+ row = await admit(prepared.admission);+ }const response = pendingAwareResponse(ctx, await waitForWrite(ctx.engine, row, ctx.config, waitMs()));emitFenceNotice(ctx, response, row.slug);return { ...response, ...(prepared.typeWarning ? { type_warning: prepared.typeWarning } : {}), ...(prepared.slugAdvisory ? { slug_advisory: prepared.slugAdvisory } : {}) };@@ -186,8 +203,11 @@ export async function preparePageAdmission(ctx: OperationContext,await initializeLocalPersistence(ctx);const captureSlug = input.operation === 'capture' ? await resolveCaptureFile(ctx, sourceId, p) : null;const principal = await requestPrincipalForContext(ctx);- await assertPageRequestIdentity(ctx.engine, principal, requestId);- const prior = await getWriteRequest(ctx.engine, principal, requestId);+ // Independent reads go out together on Postgres; the first refusal in this order is the one reported.+ const [, prior] = await pipelined(ctx.engine, [+ () => assertPageRequestIdentity(ctx.engine, principal, requestId),+ () => getWriteRequest(ctx.engine, principal, requestId),+ ]) as [unknown, WriteRequest | null];const callerIntent = { ...p };delete callerIntent.request_id;if (prior) {@@ -244,9 +264,14 @@ export async function preparePageAdmission(ctx: OperationContext,if (input.operation === 'add_timeline_entry') await requireWritablePage({ ...ctx, sourceId }, slug, input.operation, 'page');intent.slug = slug;if (ctx.remote !== false) Object.assign(intent, { source_kind: `mcp:${input.operation}`, source_uri: null, ingested_via: `mcp:${input.operation}` });- const authority = await submissionAuthority(ctx, input.operation, sourceId, source.incarnation, slug);- await assertKnowledgePublicationAllowed(ctx.engine, { source_id: sourceId, source_incarnation: source.incarnation, slug });- const snapshot = await ctx.engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });+ const [authority, , snapshot, boundAtStart, writeThroughSetting, repoPath] = await pipelined(ctx.engine, [+ () => submissionAuthority(ctx, input.operation, sourceId, source.incarnation, slug),+ () => assertKnowledgePublicationAllowed(ctx.engine, { source_id: sourceId, source_incarnation: source.incarnation, slug }),+ () => ctx.engine.readPageSnapshot(slug, { sourceId, includeDeleted: true }),+ () => getWorktreeBinding(ctx.engine, sourceId),+ () => ctx.engine.getConfig('sync.write_through'),+ async () => !source.local_path && sourceId === 'default' ? ctx.engine.getConfig('sync.repo_path') : null,+ ]) as [Awaited<ReturnType<typeof submissionAuthority>>, unknown, Awaited<ReturnType<BrainEngine['readPageSnapshot']>>, Awaited<ReturnType<typeof getWorktreeBinding>>, string | null, string | null];const slugAdvisory = input.operation === 'put_page' && input.managedFileImport !== true? suffixedSlugAdmission(ctx, slug, !!snapshot && !snapshot.page.deleted_at) : null;// #5616: typed edit refusals before admission; publication repeats them on the locked snapshot.@@ -256,11 +281,11 @@ export async function preparePageAdmission(ctx: OperationContext,assertEditRevision(snapshot.revision, p.expected_revision);applyPageEdits(snapshot.page, snapshot.tags, ctx.remote !== false, parsePageEdits(p.edits));}- let binding = await getWorktreeBinding(ctx.engine, sourceId);+ let binding = boundAtStart;const sandbox = ctx.viaSubagent === true && !(ctx.allowedSlugPrefixes?.length);- const configuredWriteThrough = !/^(false|0|off|no)$/i.test(await ctx.engine.getConfig('sync.write_through') ?? 'true');+ const configuredWriteThrough = !/^(false|0|off|no)$/i.test(writeThroughSetting ?? 'true');const writeThrough = configuredWriteThrough && !sandbox;- const root = source.local_path || (sourceId === 'default' ? await ctx.engine.getConfig('sync.repo_path') : null);+ const root = source.local_path || repoPath;if (sandbox) authority.databaseOnlyReason = 'subagent_sandbox';else if (!configuredWriteThrough) authority.databaseOnlyReason = 'disabled_by_config';else if (!root && !binding) authority.databaseOnlyReason = 'no_repo_configured';diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 902d396cdd..e765864f32 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -5,7 +5,7 @@ import { join, relative, sep } from 'node:path';import type { BrainEngine } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import type { Page, PageVersion } from '../types.ts';-import { importFromContent, type ParsedPage } from '../import-file.ts';+import { importFromContent, verifyPageReadable, type ParsedPage } from '../import-file.ts';import { frontmatterHoldMessageWithoutKeys, parseMarkdown, resolveParsedSubtype, serializePageToMarkdown, resolveSourceLocalFilePath, type ParseOpts } from '../markdown.ts';import { OperationError, opError } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';@@ -30,6 +30,7 @@ import type { PreparedMutation } from './coordinator.ts';import type { SqlEngine, WriteRequest } from './model.ts';import { isUnboundSourcePage } from './unbound-source.ts';import { sealPageTextProjection } from '../page-state/projections.ts';+import { pipelined } from '../page-state/transactions.ts';import { overlayCanonicalBodies } from '../page-state/snapshot.ts';import { materializeTimeline, prepareCanonicalProjections } from './canonical-projections.ts';import { preserveProtectedTakes } from './protected-takes.ts';@@ -240,22 +241,31 @@ async function pageDatabaseOnlyPublication(engine: SqlEngine, row: WriteRequest,return reason.databaseOnlyReason && await isUnboundSourcePage(engine, row.source_id, row.slug) ? { databaseOnlyReason: 'unbound_source' } : reason;}-/** Providers and parsing run before the OS lock and before any publication transaction. */+/**+ * Providers and parsing run before the OS lock and before any publication transaction.+ * `coordinated`: the caller publishes this mutation itself through the coordinator, whose+ * page guard and revision check on `row.slug` cover this import (the put_page apply diet).+ */export async function preparePageMutation(engine: BrainEngine, row: WriteRequest, _config: GBrainConfig,preparedIntent?: { content: string; expectedRevision: string; tags?: string[] }, signal?: AbortSignal,- options: { allowMissingFile?: boolean } = {}): Promise<PreparedMutation> {+ options: { allowMissingFile?: boolean; coordinated?: boolean } = {}): Promise<PreparedMutation> {signal?.throwIfAborted();if (!row.intent) throw pageRefusal('storage_error', 'A pending write lost its normalized intent.', row,`The request has no stored intent for ${row.slug} (its payload was compacted or never recorded), so it cannot be published and wrote nothing.`);- await assertKnowledgePublicationAllowed(engine, row);const p = row.intent;const source = { sourceId: row.source_id };- const snapshot = await engine.readPageSnapshot(row.slug, { ...source, includeDeleted: true });+ // A coordinated (single-write) preparation sends its independent reads together; the first refusal in this order is reported.+ const together = options.coordinated ? engine : { kind: 'sequential' };+ const [, snapshot, pack] = await pipelined(together, [+ () => assertKnowledgePublicationAllowed(engine, row),+ () => engine.readPageSnapshot(row.slug, { ...source, includeDeleted: true }),+ () => loadActivePackForEngine(engine, { remote: row.authority.remote, sourceId: row.source_id }).catch(() => null),+ ]) as [unknown, PageSnapshot | null, Awaited<ReturnType<typeof loadActivePackForEngine>> | null];signal?.throwIfAborted();assertPageRevision(snapshot, preparedIntent ? { expectedRevision: preparedIntent.expectedRevision } : engineMutationPrecondition(parseMutationPrecondition(p)));if ((snapshot?.page.id ?? null) !== row.page_id) throw pageIdentityError(snapshot != null || row.page_id === null, 'The accepted page identity changed.');const observedRevision = snapshot?.revision ?? null;- const activePack = (await loadActivePackForEngine(engine, { remote: row.authority.remote, sourceId: row.source_id }).catch(() => null))?.manifest;+ const activePack = pack?.manifest;if (row.operation === 'put_page' && p.allow_empty !== true && snapshot && !snapshot.page.deleted_at&& typeof p.content === 'string' && `${snapshot.page.compiled_truth}\n${snapshot.page.timeline ?? ''}`.trim()) {const incoming = parseMarkdown(p.content, row.slug, { activePack });@@ -356,8 +366,12 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest}let prepared: PreparedContentImport | undefined;let provenance: CanonicalProvenance | undefined;+ // The apply diet: the publisher's locked read of row.slug is the import base, and one read after the+ // last page write serves the read-back check, the seal, the core notice and the receipt (as sync does).+ const lean = options.coordinated === true && !targetDeleted && row.operation !== 'restore_page' && !versionTags;const result = await importFromContent(engine, row.slug, content, {- ...source, noEmbed: true, remote: row.authority.remote, activePack, fences: projected ? 'coordinated' : 'lenient',+ ...source, noEmbed: true, remote: row.authority.remote, activePack, fences: projected ? 'coordinated' : 'lenient', coordinated: lean,+ ...(lean ? { existingSnapshot: snapshot } : {}),forceRechunk: row.operation === 'restore_page' || row.operation === 'revert_version',allowEmptyOverwrite: p.allow_empty === true || row.operation === 'restore_page' || row.operation === 'revert_version',source_kind: typeof p.source_kind === 'string' ? p.source_kind : null,@@ -405,58 +419,75 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequestconst rendered = serializePageToMarkdown(renderedPage, tags);const logicalNoop = snapshot !== null && digest(canonical(snapshot.page, snapshot.tags)) === digest(canonical(ready.parsedPage, tags));const noop = logicalNoop && (snapshot?.page.deleted_at != null) === targetDeleted;- const project = projected ? await prepareCanonicalProjections(engine,ready.parsedPage,row.slug,row.source_id,snapshot,writer) : undefined;const ordinaryPage = ['put_page','capture','restore_page','revert_version','edit_page'].includes(row.operation);- const advisories = noop || targetDeleted ? pageNoopAdvisories(row) : !ordinaryPage ? remoteLinkHint(row) : await preparePageAdvisories(engine,row,ready.parsedPage,snapshot);// A managed maintenance page (e.g. the dream write-back after grounding// quarantine) republishes a body; its automatic links follow that body.const autoLinkedPage = ordinaryPage || p.kind === 'managed_maintenance_page';- const links = !noop && !targetDeleted && autoLinkedPage && (row.authority.autoLinkTrusted ?? !row.authority.remote) && await isAutoLinkEnabled(engine)- ? await prepareAutomaticLinks(engine,row.slug,ready.parsedPage,row.source_id) : undefined;const capture = row.operation === 'capture' && typeof p.capture_path === 'string' && typeof p.capture_file_hash === 'string'? { path: p.capture_path, hash: p.capture_file_hash } : undefined;+ const [project, advisories, links, file, core] = await pipelined(together, [+ async () => projected ? prepareCanonicalProjections(engine,ready.parsedPage,row.slug,row.source_id,snapshot,writer) : undefined,+ async () => noop || targetDeleted ? pageNoopAdvisories(row) : !ordinaryPage ? remoteLinkHint(row) : preparePageAdvisories(engine,row,ready.parsedPage,snapshot),+ async () => !noop && !targetDeleted && autoLinkedPage && (row.authority.autoLinkTrusted ?? !row.authority.remote) && await isAutoLinkEnabled(engine)+ ? prepareAutomaticLinks(engine,row.slug,ready.parsedPage,row.source_id,options.coordinated === true) : undefined,+ () => prepareFileTarget(engine, row, snapshot, targetDeleted ? null : rendered, undefined, { capture, allowMissing: options.allowMissingFile, activePack, remote: row.authority.remote }),+ // Always-loaded core tier: owner-only marking, brain-wide budget, remote-edit policy (core-guard.ts).+ async () => noop ? null : prepareCoreGuard(engine, { row, snapshot, incoming: targetDeleted ? null : ready.parsedPage }),+ ]) as [Awaited<ReturnType<typeof prepareCanonicalProjections>> | undefined, Record<string, unknown>,+ Awaited<ReturnType<typeof prepareAutomaticLinks>> | undefined, PreparedMutation['file'], Awaited<ReturnType<typeof prepareCoreGuard>> | null];// #6188 (D12): what Tier 1 rewrote; a remote caller is never told about the takes fence it cannot read (preserved verbatim).const shownFixes = (ready.result.fences_normalized ?? []).filter(fix => !row.authority.remote || fix.fence !== 'takes');const fencesNormalized = shownFixes.length ? { fences_normalized: pageFencesNormalized({ sourceId: row.source_id, slug: row.slug, fixes: shownFixes,writer: row.principal_kind, path: snapshot?.page.source_path ?? null, remote: row.authority.remote }) } : {};- const file = await prepareFileTarget(engine, row, snapshot, targetDeleted ? null : rendered, undefined, { capture, allowMissing: options.allowMissingFile, activePack, remote: row.authority.remote });- const mintMode = file && !snapshot?.page.source_path ? await scannerSlugRootMode(engine, row.source_id, file.root) : undefined;+ const [mintMode, databaseOnly] = await pipelined(together, [+ async () => file && !snapshot?.page.source_path ? scannerSlugRootMode(engine, row.source_id, file.root) : undefined,+ () => pageDatabaseOnlyPublication(engine, row, file),+ ]) as [Awaited<ReturnType<typeof scannerSlugRootMode>> | undefined, Pick<PreparedMutation, 'databaseOnlyReason'>];const sourcePath = file && mintMode ? scannerSourcePath(file.root, file.path, mintMode) : undefined;// An inferred mode is pinned with the first origin it mints, so later pages cannot flip the inference (#5610).const pinMode = sourcePath && mintMode && scannerSourcePath(file!.root, file!.root) && !await readSlugRootMode(engine, row.source_id) ? mintMode : undefined;- // Always-loaded core tier: owner-only marking, brain-wide budget, remote-edit policy (core-guard.ts).- const core = noop ? null : await prepareCoreGuard(engine, { row, snapshot, incoming: targetDeleted ? null : ready.parsedPage });- return { observedRevision, noop, additionalPageKeys:links?.pageKeys, file, ...await pageDatabaseOnlyPublication(engine, row, file),+ const publication: PreparedMutation = { observedRevision, noop, additionalPageKeys:links?.pageKeys, file, ...databaseOnly,...(core ? { exclusiveSources: core.exclusiveSources } : {}),- validate: async tx => { await ready.validate(tx); await core?.validate(tx); }, apply: async tx => {+ validate: async tx => { await ready.validate(tx); await core?.validate(tx); }, apply: async (tx, preimage) => {let autoLinks: Awaited<ReturnType<NonNullable<typeof links>['apply']>> | undefined;if (!noop) {- const applied = await ready.apply(tx);- // Mandatory metadata shares publication rollback; exact no-ops never heal it.- if (sourcePath && !snapshot?.page.source_path) await tx.executeRaw(`UPDATE pages SET source_path = $1- WHERE source_id=$2 AND slug=$3 AND source_path IS NULL`, [sourcePath, row.source_id, row.slug]);- if (pinMode) {- const [pinned] = await tx.executeRaw<{ mode: string | null }>(`UPDATE sources SET config=CASE WHEN config->>'slug_root_mode' IS NULL+ const applied = await ready.apply(tx, lean ? preimage : undefined);+ // Mandatory metadata shares publication rollback; exact no-ops never heal it. These, and the+ // projections (facts, takes, timeline rows of the page the import just wrote live), are independent and sent together.+ const [, pinned] = await pipelined(tx, [+ async () => { if (sourcePath && !snapshot?.page.source_path) await tx.executeRaw(`UPDATE pages SET source_path = $1+ WHERE source_id=$2 AND slug=$3 AND source_path IS NULL`, [sourcePath, row.source_id, row.slug]); },+ async () => pinMode ? (await tx.executeRaw<{ mode: string | null }>(`UPDATE sources SET config=CASE WHEN config->>'slug_root_mode' IS NULLTHEN jsonb_set(${SOURCE_CONFIG_OBJECT_SQL},'{slug_root_mode}',to_jsonb($2::text)) ELSE config END WHERE id=$1 RETURNING config->>'slug_root_mode' AS mode`,- [row.source_id, pinMode]);- if (pinned?.mode !== pinMode) throw pageRefusal('revision_conflict', 'The source slug-root mode changed during preparation.', row,- `Another write pinned source ${row.source_id}'s slug-root mode while ${row.slug} was being prepared, so this publication rolled back. Once the request is final, submit the write again; it is prepared under the pinned mode.`);- }- if (provenance) await tx.executeRaw(`UPDATE pages SET source_kind=$3,ingested_via=$4,ingested_at=$5::timestamptz- WHERE source_id=$1 AND slug=$2`, [row.source_id, row.slug, provenance.source_kind, provenance.ingested_via, provenance.ingested_at]);+ [row.source_id, pinMode]))[0] : undefined,+ async () => { if (provenance) await tx.executeRaw(`UPDATE pages SET source_kind=$3,ingested_via=$4,ingested_at=$5::timestamptz+ WHERE source_id=$1 AND slug=$2`, [row.source_id, row.slug, provenance.source_kind, provenance.ingested_via, provenance.ingested_at]); },+ async () => { if (lean) await project?.(tx, applied?.pageId); },+ ]) as [unknown, { mode: string | null } | undefined, unknown, unknown];+ if (pinMode && pinned?.mode !== pinMode) throw pageRefusal('revision_conflict', 'The source slug-root mode changed during preparation.', row,+ `Another write pinned source ${row.source_id}'s slug-root mode while ${row.slug} was being prepared, so this publication rolled back. Once the request is final, submit the write again; it is prepared under the pinned mode.`);if (row.operation === 'restore_page') await tx.restorePage(row.slug, source);if (versionTags) {for (const tag of snapshot!.tags) if (!versionTags.includes(tag)) await tx.removeTag(row.slug, tag, source);for (const tag of versionTags) await tx.addTag(row.slug, tag, source);}// #6007: the page the import just wrote live is the page the projections describe; no re-read.- await project?.(tx, row.operation === 'restore_page' ? undefined : applied?.pageId);+ if (!lean) await project?.(tx, row.operation === 'restore_page' ? undefined : applied?.pageId);autoLinks = await links?.apply(tx);- if (targetDeleted) await tx.softDeletePage(row.slug, source);- // Index installation and terminal receipt share this transaction. The import sealed the projection- // as its last revision-changing step; only a later revision change (restore, tags, links, delete) reseals.- if (!(applied?.sealed && row.operation !== 'restore_page' && !versionTags && !links && !targetDeleted)) await sealPageTextProjection(tx, row.slug, row.source_id);- if (core) await core.record(tx, (await tx.readPageSnapshot(row.slug, source))?.revision ?? null);+ if (lean) {+ const final = await tx.readPageSnapshot(row.slug, { ...source, includeDeleted: true });+ const live = final && final.page.deleted_at == null ? final : null;+ await verifyPageReadable(tx, row.slug, ready.contentHash!, row.source_id, 'importFromContent', live?.page ?? null);+ if (live) await sealPageTextProjection(tx, row.slug, row.source_id, live);+ if (core) await core.record(tx, final?.revision ?? null);+ publication.postimage = final;+ } else {+ if (targetDeleted) await tx.softDeletePage(row.slug, source);+ // Index installation and terminal receipt share this transaction. The import sealed the projection+ // as its last revision-changing step; only a later revision change (restore, tags, links, delete) reseals.+ if (!(applied?.sealed && row.operation !== 'restore_page' && !versionTags && !links && !targetDeleted)) await sealPageTextProjection(tx, row.slug, row.source_id);+ if (core) await core.record(tx, (await tx.readPageSnapshot(row.slug, source))?.revision ?? null);+ }}const coreUsage = core?.usage();return { ...advisories, ...(autoLinks ? {auto_links:autoLinks} : {}), ...(coreUsage ? { core: coreUsage } : {}),@@ -467,6 +498,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest...(row.operation === 'capture' ? { channel: 'capture', content_hash: p.capture_hash } : {}),...(edited ? editDiff(row.slug, edited.before, edited.after) : {}), ...fencesNormalized };} };+ return publication;}function editLockedPage(row: WriteRequest, snapshot: PageSnapshot | null) {diff --git a/src/core/persistence/preadmit-cache.ts b/src/core/persistence/preadmit-cache.tsnew file mode 100644index 0000000000..264e3de9a6--- /dev/null+++ b/src/core/persistence/preadmit-cache.ts@@ -0,0 +1,101 @@+/**+ * Phase 4.2: a per-process cache of the pre-admission reads that admission+ * rechecks under lock, for foreground page writes on Postgres.+ *+ * Cached: the brain identity (admission's protocol statement returns it under+ * the brain row lock and must match), the source row (admission locks it+ * FOR SHARE and checks incarnation and archived), the worktree binding+ * (admission locks the worktree FOR SHARE and checks the binding's+ * worktree, incarnation and topology generation, publication rechecks the+ * owner) and the local writer registration (admission locks the writer row+ * FOR SHARE and checks revocation, lane and grant). An absence is never+ * cached: no row, a source without a local path, a binding without this+ * host's path, a revoked writer. Entries are kept per engine (one database+ * connection identity) under the brain id they were read for, for at most+ * PREADMIT_TTL_MS. When admission refuses a write the cache might explain+ * (`preadmitRecheckFailed`), the caller drops this engine's entries and runs+ * the whole pre-admission again uncached, once, so the write refuses (or+ * routes) exactly as without the cache.+ */+import type { BrainEngine } from '../engine.ts';+import { OperationError } from '../ops/contract.ts';+import { VIEWED_ENGINE, writeSwitchOn } from './switches.ts';++export const PREADMIT_TTL_MS = 30_000;+const BRAIN_SQL = 'SELECT brain_id FROM persistence_brain WHERE singleton=1';+const SOURCE_SQL = "SELECT incarnation,archived,local_path,config->>'kind' AS kind FROM sources WHERE id=$1";+const BINDING_SQL = 'SELECT s.source_id,s.source_incarnation,s.worktree_id,s.relative_path, s.topology_generation::text AS topology_generation,w.owner_host_id,w.owner_epoch::text AS owner_epoch,w.state, h.local_path,h.coordination_path FROM persistence_source_bindings s JOIN persistence_worktrees w ON w.id=s.worktree_id LEFT JOIN persistence_host_bindings h ON h.worktree_id=w.id AND h.host_id=$2::uuid WHERE s.source_id=$1';+const WRITER_SQL = new Set([+ 'SELECT revoked_at,credential_hash,lane FROM persistence_local_writers WHERE id=$1::uuid',+ 'SELECT lane,credential_hash,grant_ceiling,revoked_at FROM persistence_local_writers WHERE id=$1::uuid',+ 'SELECT lane,revoked_at,grant_ceiling FROM persistence_local_writers WHERE id=$1::uuid',+]);+/** Whether a read's rows are a presence worth keeping. */+function present(sql: string, rows: Array<Record<string, unknown>>): boolean {+ const row = rows[0];+ if (rows.length !== 1 || !row) return false;+ if (sql === BRAIN_SQL) return typeof row.brain_id === 'string';+ if (sql === SOURCE_SQL) return row.archived === false && typeof row.local_path === 'string' && row.local_path !== '';+ if (sql === BINDING_SQL) return typeof row.local_path === 'string' && row.local_path !== '' && row.state === 'active';+ return WRITER_SQL.has(sql) && row.revoked_at == null;+}++interface EngineCache { brainId?: { id: string; at: number }; reads: Map<string, { at: number; rows: unknown[] }> }+const caches = new WeakMap<object, EngineCache>();+const flat = (sql: string) => sql.replace(/\s+/g, ' ').trim();++export function dropPreadmitCache(engine: BrainEngine): void { caches.delete(engine); }++/** The brain id the cached reads of `engine` were taken for; admission must see the same one. */+export function cachedPreadmitBrain(engine: BrainEngine): string | undefined { return caches.get(engine)?.brainId?.id; }++/**+ * `engine` seen through the cache when the `preadmit_cache` switch is on (Postgres only),+ * else null. Statements outside the cached set pass through unchanged.+ */+export async function preadmitReads(engine: BrainEngine, now: () => number = Date.now): Promise<BrainEngine | null> {+ if (engine?.kind !== 'postgres' || !await writeSwitchOn(engine, 'preadmit_cache').catch(() => false)) return null;+ let cache = caches.get(engine);+ if (!cache) { cache = { reads: new Map() }; caches.set(engine, cache); }+ const held = cache;+ const read = async (sql: string, params: unknown[] | undefined, opts: { signal?: AbortSignal } | undefined): Promise<unknown[]> => {+ if (caches.get(engine) !== held) return engine.executeRaw(sql, params, opts);+ if (sql === BRAIN_SQL) {+ if (held.brainId && now() - held.brainId.at < PREADMIT_TTL_MS) return [{ brain_id: held.brainId.id }];+ const rows = await engine.executeRaw<Record<string, unknown>>(sql, params, opts);+ if (present(sql, rows) && caches.get(engine) === held) {+ if (held.brainId && held.brainId.id !== rows[0]!.brain_id) held.reads.clear();+ held.brainId = { id: String(rows[0]!.brain_id), at: now() };+ }+ return rows;+ }+ const key = JSON.stringify([held.brainId?.id ?? null, sql, params ?? null]);+ const hit = held.reads.get(key);+ if (hit && now() - hit.at < PREADMIT_TTL_MS) return hit.rows.map(row => ({ ...(row as object) }));+ const rows = await engine.executeRaw<Record<string, unknown>>(sql, params, opts);+ if (held.brainId && present(sql, rows) && caches.get(engine) === held) held.reads.set(key, { at: now(), rows: rows.map(row => ({ ...row })) });+ else held.reads.delete(key);+ return rows;+ };+ // Every cached read is filed under the brain it was taken for, which admission checks.+ if (!held.brainId || now() - held.brainId.at >= PREADMIT_TTL_MS) await read(BRAIN_SQL, undefined, undefined);+ return new Proxy(engine, { get(target, key) {+ if (key === VIEWED_ENGINE) return target;+ if (key === 'executeRaw') return (sql: string, params?: unknown[], opts?: { signal?: AbortSignal }) => {+ const text = flat(sql);+ return text === BRAIN_SQL || text === SOURCE_SQL || text === BINDING_SQL || WRITER_SQL.has(text) ? read(text, params, opts) : target.executeRaw(sql, params, opts);+ };+ const value = Reflect.get(target, key, target);+ return typeof value === 'function' ? value.bind(target) : value;+ } });+}++/** Thrown by admission when the brain behind the connection is not the one the cached reads came from; never leaves the retry. */+export class PreadmitBrainChanged extends Error {+ constructor() { super('The brain behind this connection changed since its identity was cached; the write is prepared again.'); this.name = 'PreadmitBrainChanged'; }+}++/** Admission refusals a stale cached read can cause: retried once without the cache. */+export function preadmitRecheckFailed(error: unknown): boolean {+ return error instanceof PreadmitBrainChanged || error instanceof OperationError && ['source_changed', 'permission_denied'].includes(error.code);+}diff --git a/src/core/persistence/protocol.ts b/src/core/persistence/protocol.tsindex 773de30771..5398564648 100644--- a/src/core/persistence/protocol.ts+++ b/src/core/persistence/protocol.ts@@ -15,7 +15,7 @@ const declared = new WeakSet<object>();* any other row lock. A transaction needing the exclusive brain lock takes it* first and declares after it.*/-const BRAIN_SHARE = '(SELECT singleton FROM persistence_brain WHERE singleton=1 FOR SHARE) AS brain';+const BRAIN_SHARE = '(SELECT brain_id::text FROM persistence_brain WHERE singleton=1 FOR SHARE) AS brain';/** Transaction-local; #5984: a transaction engine declares it once (a savepoint is its own engine object). */export async function declarePersistenceProtocol(tx: SqlEngine): Promise<void> {@@ -31,10 +31,12 @@ export async function declarePersistenceProtocol(tx: SqlEngine): Promise<void> {* under that lock timeout. 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),+/** Returns the brain id read under that lock (null when the row is missing). */+export async function declareDurablePersistence(tx: SqlEngine, lockTimeout = '1s', statementTimeout = '5s'): Promise<string | null> {+ const [row] = await tx.executeRaw<{ brain: string | null }>(`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),${BRAIN_SHARE}`, [lockTimeout, statementTimeout]);if ((tx as { _pageTransaction?: boolean })._pageTransaction === true) declared.add(tx);+ return row?.brain ?? null;}export const PERSISTENCE_PROTOCOL_PREDICATE = "set_config('gbrain.persistence_protocol','2',true)='2'";diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.tsindex 6b163228bd..25398555e5 100644--- a/src/core/persistence/service.ts+++ b/src/core/persistence/service.ts@@ -1,7 +1,7 @@import type { BrainEngine } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import { OperationError } from '../ops/contract.ts';-import { PersistenceConsumer, type PrepareMutation } from './consumer.ts';+import { LANE_BUSY, PersistenceConsumer, type PrepareMutation } from './consumer.ts';import { preparePageMutation } from './page-prepare.ts';import { prepareSemanticPageMutation } from './semantic-pages.ts';import { getWriteRequestById, getWriteRequestProgress, receiptFor, type WriteRequestProgress } from './journal.ts';@@ -9,6 +9,7 @@ import { isTerminal, type WriteRequest } from './model.ts';import { isWriteErrorCode, type WriteReceipt } from './types.ts';import { registerPgliteReopen } from '../pglite-lifecycle.ts';import { assertMutationProtocol } from './protocol.ts';+import { writeSwitchOn } from './switches.ts';import { pendingWriteHint } from './health.ts';import { receiptDeliveredHint } from './connector-errors.ts';import type { PgAccessReason } from '../pg-access-classify.ts';@@ -74,7 +75,8 @@ export async function preparePersistedMutation(e: BrainEngine, row: WriteRequestif (row.operation === 'relink_facts') return (await import('../facts/relink-publish.ts')).prepareRelinkMutation(e, row, cfg);if (['takes_add','takes_update','takes_supersede','takes_resolve','takes_remove'].includes(row.operation)) return (await import('./takes-prepare.ts')).prepareTakesMutation(e,row,cfg);if (['add_tag','remove_tag','add_timeline_entry'].includes(row.operation)) return prepareSemanticPageMutation(e, row, cfg);- if (['put_page','capture','delete_page','restore_page','revert_version','edit_page'].includes(row.operation)) return preparePageMutation(e, row, cfg, undefined, signal);+ if (['put_page','capture','delete_page','restore_page','revert_version','edit_page'].includes(row.operation)) return preparePageMutation(e, row, cfg, undefined, signal,+ { coordinated: await writeSwitchOn(e, 'single_write_group').catch(() => true) });throw new OperationError('unsupported_mutation_protocol', 'No compatible mutation preparer is registered for this operation.', `Request ${row.request_id} (${row.operation}) was accepted by a gbrain version whose preparer this one lacks, so it has not run. Run gbrain upgrade on every host that serves this brain; the request stays journaled and resumes after the upgrade.`);}export function startPersistenceConsumer(engine: BrainEngine, config: GBrainConfig): PersistenceConsumer {@@ -120,6 +122,17 @@ export async function disposePersistenceConsumer(engine: BrainEngine): Promise<vfunction discardStoppedService(engine: BrainEngine, service: Service): void {service.unregisterStop?.(); service.unregisterReopen?.(); services.delete(engine);}+/**+ * Phase 4.4: runs `run` on this process's warm single-write lane (consumer.ts `onLane`) when its+ * consumer is running and the lane is free; otherwise `fallback()`, on the pool.+ */+export async function onPersistenceLane<T>(engine: BrainEngine,+ run: (transaction: <R>(fn: (tx: BrainEngine) => Promise<R>) => Promise<R>) => Promise<T>, fallback: () => Promise<T>): Promise<T> {+ const service = services.get(engine);+ if (!service || service.stopping) return fallback();+ const done = await service.consumer.onLane(run);+ return done === LANE_BUSY ? fallback() : done;+}export function foregroundWriteCompletions(engine: BrainEngine, worktreeId: string): number {return services.get(engine)?.consumer.foregroundCompletions(worktreeId) ?? 0;}@@ -171,7 +184,7 @@ export async function awaitWrite(engine: BrainEngine, row: WriteRequest, config:const listener = (settled: WriteRequest) => { handed = settled; wake?.(); };listeners.add(listener); waiters.set(id, listeners);// The admission transaction has committed: publish now, not after the idle backoff.- consumer.wake();+ consumer.wake(true);const waitMs = opts.waitMs ?? 5000;const deadline = performance.now() + waitMs;const firstPoll = Math.min(WRITE_POLL_START_MS, waitMs / 2);diff --git a/src/core/persistence/switches.ts b/src/core/persistence/switches.tsnew file mode 100644index 0000000000..315169e113--- /dev/null+++ b/src/core/persistence/switches.ts@@ -0,0 +1,60 @@+/**+ * Kill switches for write-path behaviors, read from one per-process snapshot.+ *+ * Every switch is on by default. An environment variable overrides the brain+ * config key; `0` or `false` (either source) turns a switch off. The snapshot+ * reads every switch key in one statement and is reused for SWITCH_TTL_MS, so+ * `gbrain config set <key> false` reaches a running `serve` within that time+ * without a round trip per write. Config writes are trusted-local only (no+ * remote operation writes config), so a remote caller cannot flip a switch.+ */+import type { SqlEngine } from './model.ts';++export const WRITE_SWITCHES = {+ /** Phase 4.1/4.3/4.4: single page writes publish as a group of one, the own admission claims directly, publication reuses a warm connection. */+ single_write_group: { key: 'persistence.single_write_group', env: 'GBRAIN_SINGLE_WRITE_GROUP' },+ /** Phase 4.2: per-process cache of pre-admission reads that admission rechecks under lock. */+ preadmit_cache: { key: 'persistence.preadmit_cache', env: 'GBRAIN_PREADMIT_CACHE' },+ /** Batched waiver runs; `GBRAIN_SYNC_WAIVE_NOOP=0` wins over it. */+ waive_batch: { key: 'sync.waive_batch', env: 'GBRAIN_SYNC_WAIVE_BATCH' },+} as const;+export type WriteSwitch = keyof typeof WRITE_SWITCHES;+export type WriteSwitches = Record<WriteSwitch, boolean>;+export const WRITE_SWITCH_KEYS: readonly string[] = Object.values(WRITE_SWITCHES).map(s => s.key);+export const SWITCH_TTL_MS = 5000;++const off = (value: string | null | undefined) => typeof value === 'string' && /^(0|false)$/i.test(value.trim());+const on = (value: string | null | undefined) => typeof value === 'string' && /^(1|true)$/i.test(value.trim());+const snapshots = new WeakMap<object, { at: number; generation: number; read: Promise<WriteSwitches> }>();+let generation = 0;++function resolve(configured: Map<string, string>): WriteSwitches {+ const out = {} as WriteSwitches;+ for (const [name, { key, env }] of Object.entries(WRITE_SWITCHES) as Array<[WriteSwitch, { key: string; env: string }]>) {+ const fromEnv = process.env[env];+ out[name] = off(fromEnv) ? false : on(fromEnv) ? true : !off(configured.get(key));+ }+ return out;+}++/** A read-through view of an engine (preparation config, pre-admission cache) names its engine here, so it shares that engine's snapshot. */+export const VIEWED_ENGINE = Symbol('gbrain.viewedEngine');++/** The switch snapshot of `engine`'s brain, at most SWITCH_TTL_MS old. A failed read is not kept. */+export function readWriteSwitches(viewed: SqlEngine, now: () => number = Date.now): Promise<WriteSwitches> {+ const engine = (viewed as { [VIEWED_ENGINE]?: SqlEngine })[VIEWED_ENGINE] ?? viewed;+ const held = snapshots.get(engine);+ if (held && held.generation === generation && now() - held.at < SWITCH_TTL_MS) return held.read;+ const read = engine.executeRaw<{ key: string; value: string }>('SELECT key,value FROM config WHERE key = ANY($1::text[])', [WRITE_SWITCH_KEYS])+ .then(rows => resolve(new Map(rows.map(row => [row.key, row.value]))));+ snapshots.set(engine, { at: now(), generation, read });+ read.catch(() => { if (snapshots.get(engine)?.read === read) snapshots.delete(engine); });+ return read;+}++export async function writeSwitchOn(engine: SqlEngine, name: WriteSwitch): Promise<boolean> {+ return (await readWriteSwitches(engine))[name];+}++/** Test seam: the next read of every engine sees the current config. */+export function resetWriteSwitches(): void { generation++; }diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 9bbfc2836f..d25222292e 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -13,6 +13,7 @@ import type { PageReadScope } from './types.ts';import type { PageReadPolicy } from './types.ts';import { readRelationalFanout, readChainHop, readAliases, readBacklinkCounts, readAdjacencyBoosts, readContentFlags, readExtractionStates, readEffectiveDates, readSalienceScores } from './search/read-enrichment.ts';import postgres from '#postgres'+import { reservedTransactions, type ReservedTransactions } from './postgres-engine/reserved-transactions.ts';import { traceSqlOptions } from './sql-trace.ts';import { hasPostgresCancellationCapability, postgresCancellationUnavailable, reserveWithCancellation } from './postgres-engine/cancellation.ts';export { hasPostgresCancellationCapability } from './postgres-engine/cancellation.ts';@@ -674,7 +675,7 @@ export class PostgresEngine implements BrainEngine {return rows as unknown as R[];},};- return await fn(conn);+ return await fn(Object.assign(conn, { transaction: <R>(run: (engine: BrainEngine) => Promise<R>) => this.transactionOn(reservedTransactions(reserved), run) } satisfies ReservedTransactions));} finally {// Counter/gauge decrements run regardless of release() throwing// (double-release or socket error must not permanently leak a permitdiff --git a/src/core/postgres-engine/reserved-transactions.ts b/src/core/postgres-engine/reserved-transactions.tsnew file mode 100644index 0000000000..00deb3f67c--- /dev/null+++ b/src/core/postgres-engine/reserved-transactions.ts@@ -0,0 +1,49 @@+import type postgres from '#postgres';+import type { BrainEngine } from '../engine.ts';++/**+ * Phase 4.4: what `PostgresEngine.withReservedConnection` adds to its+ * `ReservedConnection`: one transaction at a time on the reserved backend,+ * with `transaction()`'s semantics. Its prepared statements stay on the+ * connection, so a caller that keeps the reservation reuses them. PGLite's+ * reserved connection has none.+ */+export interface ReservedTransactions { transaction<T>(fn: (engine: BrainEngine) => Promise<T>): Promise<T> }++/**+ * Phase 4.4: `begin` for one reserved postgres.js connection, as `sql.begin`+ * runs it on a pooled one: BEGIN, the callback with a handle whose+ * `savepoint` nests (rolled back to on error, like postgres.js), COMMIT, and+ * ROLLBACK on failure. BEGIN and SAVEPOINT are sent with the statements that+ * follow them instead of a round trip ahead (the server still runs them+ * first). A COMMIT the server answers with ROLLBACK (an earlier statement+ * failed unobserved) is an error, never a silent success.+ */+export function reservedTransactions(reserved: postgres.ReservedSql): ReturnType<typeof postgres> {+ const settle = async <T>(marker: Promise<unknown>, body: Promise<T>): Promise<T> => {+ const [opened, ran] = await Promise.allSettled([marker, body]);+ if (opened.status === 'rejected') throw opened.reason;+ if (ran.status === 'rejected') throw ran.reason;+ return ran.value;+ };+ const begin = async (fn: (handle: unknown) => Promise<unknown>) => {+ let savepoints = 0;+ const handle = Object.assign(reserved, {+ savepoint: async (inner: (child: unknown) => Promise<unknown>) => {+ const name = `s${savepoints++}`;+ const marker = reserved.unsafe(`savepoint ${name}`).execute();+ try { return await settle(marker, Promise.resolve().then(() => inner(handle))); }+ catch (error) { if (await marker.then(() => true, () => false)) await reserved.unsafe(`rollback to ${name}`); throw error; }+ },+ });+ const opened = reserved.unsafe('begin').execute();+ let result: unknown;+ try { result = await settle(opened, Promise.resolve().then(() => fn(handle))); }+ catch (error) { await reserved.unsafe('rollback').catch(() => reserved.discard()); throw error; }+ const done = await reserved.unsafe('commit') as unknown as { command?: string };+ if (done.command !== 'COMMIT') throw Object.assign(new Error('The transaction was rolled back at commit.'), { code: '25P02' });+ return result;+ };+ return { begin } as unknown as ReturnType<typeof postgres>;+}+diff --git a/src/core/shared-skills/knowledge-guard.ts b/src/core/shared-skills/knowledge-guard.tsindex 1e28a0ab8e..67c1b1c702 100644--- a/src/core/shared-skills/knowledge-guard.ts+++ b/src/core/shared-skills/knowledge-guard.ts@@ -1,4 +1,5 @@import { isAbsolute, relative, resolve, sep } from 'node:path';+import { VIEWED_ENGINE } from '../persistence/switches.ts';import { fileURLToPath } from 'node:url';import { OperationError } from '../ops/contract.ts';import { isRelativeFileUri, resolveSourceLocalFilePath } from '../markdown.ts';@@ -31,7 +32,7 @@ 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;+ let owner = (engine as { [VIEWED_ENGINE]?: object })[VIEWED_ENGINE] ?? engine;while (Object.hasOwn(owner, '_pageTransaction') && (owner as { _pageTransaction?: boolean })._pageTransaction === true) owner = Object.getPrototypeOf(owner);return owner;}diff --git a/test/e2e/single-write-fast-path-postgres.test.ts b/test/e2e/single-write-fast-path-postgres.test.tsnew file mode 100644index 0000000000..8534c6df43--- /dev/null+++ b/test/e2e/single-write-fast-path-postgres.test.ts@@ -0,0 +1,197 @@+/**+ * Phase 4.1-4.4 on Postgres: a single put_page published as a group of one,+ * the pre-admission cache and their kill switches. Each case runs on a fresh+ * activated managed brain (test/helpers/managed-brain.ts).+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';+import { hasDatabase } from './helpers.ts';+import { managedBrain } from '../helpers/managed-brain.ts';+import { withEnv } from '../helpers/with-env.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { OperationContext } from '../../src/core/ops/contract.ts';+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';+import { revokeLocalWriter } from '../../src/core/persistence/identity.ts';+import { installFaultHook } from '../../src/core/persistence/fault-points.ts';+import { resetWriteSwitches } from '../../src/core/persistence/switches.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { getWorktreeBinding } from '../../src/core/persistence/ownership.ts';++const d = hasDatabase() ? describe : describe.skip;+const url = () => process.env.DATABASE_URL!;+const page = (title: string, body: string) => `---\ntitle: ${title}\n---\n\n${body}\n`;+const put = (ctx: OperationContext, slug: string, body: string, extra: Record<string, unknown> = {}, waitMs = 20_000) =>+ submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), content: page(slug, body), ...extra }, waitMs }) as Promise<Record<string, any>>;+const failure = (run: Promise<unknown>) => run.then(() => null, (error: { code?: string; message?: string }) => ({ code: error.code, message: error.message }));++/** Counts statements this engine sends whose text contains `fragment`. */+function countStatements(engine: BrainEngine, fragment: string): { count: () => number; restore: () => void } {+ const proto = Object.getPrototypeOf(engine) as { executeRaw: (sql: string, ...rest: unknown[]) => Promise<unknown> };+ const original = proto.executeRaw;+ let n = 0;+ proto.executeRaw = function (this: unknown, sql: string, ...rest: unknown[]) {+ if (typeof sql === 'string' && sql.replace(/\s+/g, ' ').includes(fragment)) n++;+ return original.call(this, sql, ...rest);+ };+ return { count: () => n, restore: () => { proto.executeRaw = original; } };+}+const GROUP_COMPLETION = "UPDATE persistence_requests r SET state='committed'";+const SOURCE_READ = "SELECT incarnation,archived,local_path,config->>'kind' AS kind FROM sources WHERE id=$1";++afterEach(() => { installFaultHook(undefined); resetWriteSwitches(); });++d('single page writes on Postgres (Phase 4.1-4.4)', () => {+ test('a put_page file write publishes as a group of one; GBRAIN_SINGLE_WRITE_GROUP=0 and persistence.single_write_group=false restore publishMutation', async () => {+ await managedBrain(async ({ engine, ctx, root }) => {+ const groups = countStatements(engine, GROUP_COMPLETION);+ try {+ expect((await put(ctx, 'notes/fast', 'Fast path.')).state).toBe('committed');+ expect(groups.count()).toBe(1);+ expect(readFileSync(join(root, 'notes/fast.md'), 'utf8')).toContain('Fast path.');+ await withEnv({ GBRAIN_SINGLE_WRITE_GROUP: '0' }, async () => {+ resetWriteSwitches();+ expect((await put(ctx, 'notes/env-off', 'Env off.')).state).toBe('committed');+ });+ expect(groups.count()).toBe(1);+ await engine.setConfig('persistence.single_write_group', 'false');+ resetWriteSwitches();+ expect((await put(ctx, 'notes/config-off', 'Config off.')).state).toBe('committed');+ expect(groups.count()).toBe(1);+ await engine.setConfig('persistence.single_write_group', 'true');+ resetWriteSwitches();+ expect((await put(ctx, 'notes/config-on', 'Config on.')).state).toBe('committed');+ expect(groups.count()).toBe(2);+ } finally { groups.restore(); }+ }, { databaseUrl: url() });+ }, 120_000);++ test('the pre-admission cache answers repeated source reads; GBRAIN_PREADMIT_CACHE=0 and persistence.preadmit_cache=false read every time', async () => {+ await managedBrain(async ({ engine, ctx }) => {+ const reads = countStatements(engine, SOURCE_READ);+ try {+ await put(ctx, 'notes/c-1', 'First.');+ const afterFirst = reads.count();+ await put(ctx, 'notes/c-2', 'Second.');+ expect(reads.count()).toBe(afterFirst);+ await withEnv({ GBRAIN_PREADMIT_CACHE: '0' }, async () => {+ resetWriteSwitches();+ await put(ctx, 'notes/c-3', 'Third.');+ });+ expect(reads.count()).toBeGreaterThan(afterFirst);+ const beforeConfig = reads.count();+ await engine.setConfig('persistence.preadmit_cache', 'false');+ resetWriteSwitches();+ await put(ctx, 'notes/c-4', 'Fourth.');+ expect(reads.count()).toBeGreaterThan(beforeConfig);+ } finally { reads.restore(); }+ }, { databaseUrl: url() });+ }, 120_000);++ for (const caseName of ['revoked writer', 'archived source', 'moved binding', 'refreshing worktree'] as const) {+ test(`a ${caseName} after the cache was filled refuses the next write with the same error as without the cache`, async () => {+ const outcome = async (cache: '0' | '1') => withEnv({ GBRAIN_PREADMIT_CACHE: cache }, async () => {+ resetWriteSwitches();+ let refused: { code?: string; message?: string } | null = null;+ await managedBrain(async ({ engine, ctx }) => {+ const first = await put(ctx, 'notes/warm', 'Warm the cache.');+ expect(first.state).toBe('committed');+ if (caseName === 'revoked writer') {+ const [row] = await engine.executeRaw<{ principal_id: string }>("SELECT principal_id FROM persistence_requests WHERE slug='notes/warm'");+ await revokeLocalWriter(engine, row!.principal_id);+ }+ const administered = (sql: string) => engine.transaction(async tx => {+ await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true),set_config('gbrain.persistence_protocol','2',true)");+ await tx.executeRaw(sql);+ });+ if (caseName === 'archived source') await administered("UPDATE sources SET archived=true WHERE id='default'");+ if (caseName === 'moved binding') await administered("UPDATE persistence_source_bindings SET topology_generation=topology_generation+1 WHERE source_id='default'");+ if (caseName === 'refreshing worktree') {+ const binding = (await getWorktreeBinding(engine, 'default'))!;+ await engine.executeRaw(`INSERT INTO persistence_worktree_refreshes (worktree_id,source_ids,principal_id,owner_epoch,topology_generation,state,old_head,target_head,upstream_ref)+ VALUES ($1::uuid,ARRAY['default'],gen_random_uuid(),$2,$3,'fenced','a','b','origin/main')`, [binding.worktree_id, binding.owner_epoch, binding.topology_generation]);+ }+ refused = await failure(put(ctx, 'notes/next', 'Next write.'));+ const [admitted] = await engine.executeRaw<{ n: number; generation: string | null }>(+ "SELECT count(*)::int AS n,max(topology_generation)::text AS generation FROM persistence_requests WHERE slug='notes/next'");+ // A moved binding is not a refusal: the write is admitted under the current binding, as without the cache.+ if (caseName === 'moved binding') {+ const [binding] = await engine.executeRaw<{ generation: string }>("SELECT topology_generation::text AS generation FROM persistence_source_bindings WHERE source_id='default'");+ expect(admitted).toEqual({ n: 1, generation: binding!.generation });+ } else expect(admitted!.n).toBe(0);+ }, { databaseUrl: url() });+ const seen = refused as { code?: string; message?: string } | null;+ return seen && { ...seen, message: seen.message?.replace(/[0-9a-f]{8}-[0-9a-f-]{27}/g, 'uuid') };+ });+ const uncached = await outcome('0');+ const cached = await outcome('1');+ if (caseName !== 'moved binding') expect(uncached).not.toBeNull();+ expect(cached).toEqual(uncached);+ }, 180_000);+ }++ test('the same request_id replays its committed receipt with the switch on and off', async () => {+ await managedBrain(async ({ ctx }) => {+ for (const [first, second] of [['1', '0'], ['0', '1']] as const) {+ const params = { slug: `notes/replay-${first}`, request_id: randomUUID(), content: page('Replay', `Replayed ${first}.`) };+ const original = await withEnv({ GBRAIN_SINGLE_WRITE_GROUP: first }, async () => { resetWriteSwitches();+ return submitPageMutation(ctx, { operation: 'put_page', params: { ...params }, waitMs: 20_000 }); });+ const replayed = await withEnv({ GBRAIN_SINGLE_WRITE_GROUP: second }, async () => { resetWriteSwitches();+ return submitPageMutation(ctx, { operation: 'put_page', params: { ...params }, waitMs: 20_000 }); });+ expect(original.state).toBe('committed');+ expect(replayed).toEqual(original);+ const conflict = await failure(submitPageMutation(ctx, { operation: 'put_page', params: { ...params, content: page('Replay', 'Different.') }, waitMs: 20_000 }));+ expect(conflict?.code).toBe('idempotency_conflict');+ }+ }, { databaseUrl: url() });+ }, 120_000);++ test('a failure after the file rename and before commit restores the file through the recovery path, then the write publishes alone', async () => {+ await managedBrain(async ({ ctx, root }) => {+ const path = join(root, 'notes/crash.md');+ mkdirSync(join(root, 'notes'), { recursive: true });+ expect((await put(ctx, 'notes/crash', 'Original body.')).state).toBe('committed');+ const original = readFileSync(path, 'utf8');+ const seen: Array<{ point: string; bytes: string | null }> = [];+ let thrown = false;+ installFaultHook(point => {+ if (!point.startsWith('publication:')) return;+ seen.push({ point, bytes: existsSync(path) ? readFileSync(path, 'utf8') : null });+ if (point === 'publication:after_publication' && !thrown) { thrown = true; throw new Error('injected failure after the file rename'); }+ });+ const snapshot = await ctx.engine.readPageSnapshot('notes/crash', { sourceId: 'default' });+ const done = await put(ctx, 'notes/crash', 'Replacement body.', { expected_revision: snapshot!.revision });+ expect(done.state).toBe('committed');+ // The group published the new bytes, then failed; the fallback's first seam sees the restored original.+ const failedAt = seen.findIndex(s => s.point === 'publication:after_publication');+ expect(seen[failedAt]!.bytes).toContain('Replacement body.');+ expect(seen.slice(failedAt + 1).find(s => s.point === 'publication:prepared')!.bytes).toBe(original);+ expect(readFileSync(path, 'utf8')).toContain('Replacement body.');+ const [row] = await ctx.engine.executeRaw<{ recovery: unknown; n: number }>("SELECT recovery,(SELECT count(*)::int FROM persistence_requests WHERE recovery IS NOT NULL) AS n FROM persistence_requests WHERE slug='notes/crash' ORDER BY sequence DESC LIMIT 1");+ expect(row).toMatchObject({ recovery: null, n: 0 });+ }, { databaseUrl: url() });+ }, 120_000);++ test('a recovery record on the worktree blocks the own-admission direct claim', async () => {+ await managedBrain(async ({ engine, ctx, root }) => {+ expect((await put(ctx, 'notes/head', 'Head.')).state).toBe('committed');+ await disposePersistenceConsumer(engine);+ // A recovering request whose canonical file matches neither its prior nor its published bytes stays blocked.+ const path = join(root, 'notes/blocked.md');+ writeFileSync(path, 'edited outside gbrain\n');+ await engine.transaction(async tx => {+ await tx.executeRaw("SELECT set_config('gbrain.persistence_protocol','2',true)");+ await tx.executeRaw(`UPDATE persistence_requests SET state='recovering',execution_token=gen_random_uuid(),blocked_reason='unexpected_file_bytes',+ recovery=$1::text::jsonb WHERE slug='notes/head'`, [JSON.stringify({ version: 1, path, root, before: null, beforeHash: 'a'.repeat(64), afterHash: 'b'.repeat(64), mode: null,+ ownerEpoch: '1', attempt: randomUUID(), staging: {} })]);+ });+ const pending = await put(ctx, 'notes/after', 'After.', {}, 2000).catch((error: { writeRequest?: { state: string } }) => error.writeRequest);+ expect(pending?.state).toBe('queued');+ // Never claimed: a claim the publisher's own recheck released would leave blocked_reason 'recovery_required'.+ const [row] = await engine.executeRaw<{ state: string; blocked_reason: string | null }>("SELECT state,blocked_reason FROM persistence_requests WHERE slug='notes/after'");+ expect(row).toEqual({ state: 'queued', blocked_reason: null });+ expect(existsSync(join(root, 'notes/after.md'))).toBe(false);+ }, { databaseUrl: url() });+ }, 120_000);+});diff --git a/test/e2e/single-write-group-parity-postgres.test.ts b/test/e2e/single-write-group-parity-postgres.test.tsnew file mode 100644index 0000000000..c728f38594--- /dev/null+++ b/test/e2e/single-write-group-parity-postgres.test.ts@@ -0,0 +1,10 @@+import { describe, test } from 'bun:test';+import { hasDatabase } from './helpers.ts';+import { expectSingleWriteParity } from '../helpers/single-write-parity.ts';++const d = hasDatabase() ? describe : describe.skip;+d('single-write fast path parity on Postgres', () => {+ test('single page writes dump the same rows, effects, receipts and files with the fast path on and off (Postgres)', async () => {+ await expectSingleWriteParity(process.env.DATABASE_URL!);+ }, 300_000);+});diff --git a/test/fixtures/goldens/sql-text/_driver.json b/test/fixtures/goldens/sql-text/_driver.jsonindex c5767e6cc4..f1b84060a3 100644--- a/test/fixtures/goldens/sql-text/_driver.json+++ b/test/fixtures/goldens/sql-text/_driver.json@@ -643,7 +643,7 @@"via": "unsafe"},{- "paramCount": 2,+ "paramCount": 0,"unsafeOptions": {"cancelFence": false,"prepare": true,@@ -654,7 +654,8 @@{"paramCount": 2,"unsafeOptions": {- "prepare": false,+ "cancelFence": false,+ "prepare": true,"simple": false},"via": "unsafe"@@ -662,14 +663,13 @@{"paramCount": 2,"unsafeOptions": {- "cancelFence": false,- "prepare": true,+ "prepare": false,"simple": false},"via": "unsafe"},{- "paramCount": 0,+ "paramCount": 2,"unsafeOptions": {"cancelFence": false,"prepare": true,@@ -725,7 +725,7 @@"via": "unsafe"},{- "paramCount": 2,+ "paramCount": 0,"unsafeOptions": {"cancelFence": false,"prepare": true,@@ -736,7 +736,8 @@{"paramCount": 2,"unsafeOptions": {- "prepare": false,+ "cancelFence": false,+ "prepare": true,"simple": false},"via": "unsafe"@@ -744,14 +745,13 @@{"paramCount": 2,"unsafeOptions": {- "cancelFence": false,- "prepare": true,+ "prepare": false,"simple": false},"via": "unsafe"},{- "paramCount": 0,+ "paramCount": 2,"unsafeOptions": {"cancelFence": false,"prepare": true,@@ -952,7 +952,7 @@"via": "unsafe"},{- "paramCount": 2,+ "paramCount": 0,"unsafeOptions": {"cancelFence": false,"prepare": true,@@ -963,7 +963,8 @@{"paramCount": 2,"unsafeOptions": {- "prepare": false,+ "cancelFence": false,+ "prepare": true,"simple": false},"via": "unsafe"@@ -971,14 +972,13 @@{"paramCount": 2,"unsafeOptions": {- "cancelFence": false,- "prepare": true,+ "prepare": false,"simple": false},"via": "unsafe"},{- "paramCount": 0,+ "paramCount": 2,"unsafeOptions": {"cancelFence": false,"prepare": true,@@ -2054,14 +2054,6 @@},"replaceDerivedLinks": {"default": [- {- "paramCount": 1,- "via": "tagged"- },- {- "paramCount": 1,- "via": "tagged"- },{"paramCount": 1,"unsafeOptions": {@@ -2098,6 +2090,14 @@},"via": "unsafe"},+ {+ "paramCount": 1,+ "via": "tagged"+ },+ {+ "paramCount": 1,+ "via": "tagged"+ },{"paramCount": 3,"unsafeOptions": {@@ -2133,6 +2133,14 @@},"via": "unsafe"},+ {+ "paramCount": 1,+ "via": "tagged"+ },+ {+ "paramCount": 1,+ "via": "tagged"+ },{"paramCount": 2,"unsafeOptions": {@@ -2151,14 +2159,6 @@},"via": "unsafe"},- {- "paramCount": 1,- "via": "tagged"- },- {- "paramCount": 1,- "via": "tagged"- },{"paramCount": 2,"unsafeOptions": {diff --git a/test/fixtures/goldens/sql-text/chunks.json b/test/fixtures/goldens/sql-text/chunks.jsonindex 8b8cc05f17..e0c86152bc 100644--- a/test/fixtures/goldens/sql-text/chunks.json+++ b/test/fixtures/goldens/sql-text/chunks.json@@ -621,8 +621,8 @@"string","string"],- "sql": "INSERT INTO page_write_guards(source_incarnation,slug) VALUES ($1::uuid,$2) ON CONFLICT DO NOTHING",- "textSha256": "fa56fa770a66caa8ae77b19c2c3ae9caac336d8e8281bc16f09d36a7fcdd74fd"+ "sql": "INSERT INTO page_write_guards(source_incarnation,slug) SELECT incarnation,$1 FROM sources WHERE id=$2 ON CONFLICT DO NOTHING",+ "textSha256": "91584b13aae786f054e246bcc667c9ebe8c065d61b42d5ae775634739bce9f54"},{"lane": "tx",@@ -630,8 +630,8 @@"string","string"],- "sql": "SELECT slug FROM page_write_guards WHERE source_incarnation=$1::uuid AND slug=$2 FOR UPDATE",- "textSha256": "3d08e10394edab70fb78946e378dd11528213526b214a8516d8cf3825e87ac19"+ "sql": "SELECT g.slug FROM page_write_guards g JOIN sources s ON s.incarnation=g.source_incarnation WHERE s.id=$1 AND g.slug=$2 FOR UPDATE OF g",+ "textSha256": "becdf4418f95796c9bab86a61f0f6e9d42bba2f74baedfe40ba9d9705977d77a"},{"lane": "tx",@@ -642,6 +642,12 @@"sql": "SELECT id FROM pages WHERE source_id=$1 AND slug=$2 FOR UPDATE","textSha256": "6c2eb61492fe7470a32169e89b9f04d471f3311d55ff790ad08f4736af483a2c"},+ {+ "lane": "tx",+ "params": [],+ "sql": "SELECT key, value FROM config WHERE key IN ('search_embedding_column', 'embedding_columns')",+ "textSha256": "0c97097b286eb3415cffbfa812bc301187d88bc7a5266678332b0f4c8c571371"+ },{"lane": "tx","params": [@@ -670,12 +676,6 @@"sql": "DELETE FROM content_chunks WHERE page_id = $1 AND chunk_index != ALL($2)","textSha256": "dc4fdfddf00f65b0aad2aa0ec3f1e3a981e7c61f2253f485925d90c371ba372c"},- {- "lane": "tx",- "params": [],- "sql": "SELECT key, value FROM config WHERE key IN ('search_embedding_column', 'embedding_columns')",- "textSha256": "0c97097b286eb3415cffbfa812bc301187d88bc7a5266678332b0f4c8c571371"- },{"lane": "tx","params": [@@ -709,8 +709,8 @@"string","string"],- "sql": "INSERT INTO page_write_guards(source_incarnation,slug) VALUES ($1::uuid,$2) ON CONFLICT DO NOTHING",- "textSha256": "fa56fa770a66caa8ae77b19c2c3ae9caac336d8e8281bc16f09d36a7fcdd74fd"+ "sql": "INSERT INTO page_write_guards(source_incarnation,slug) SELECT incarnation,$1 FROM sources WHERE id=$2 ON CONFLICT DO NOTHING",+ "textSha256": "91584b13aae786f054e246bcc667c9ebe8c065d61b42d5ae775634739bce9f54"},{"lane": "tx",@@ -718,8 +718,8 @@"string","string"],- "sql": "SELECT slug FROM page_write_guards WHERE source_incarnation=$1::uuid AND slug=$2 FOR UPDATE",- "textSha256": "3d08e10394edab70fb78946e378dd11528213526b214a8516d8cf3825e87ac19"+ "sql": "SELECT g.slug FROM page_write_guards g JOIN sources s ON s.incarnation=g.source_incarnation WHERE s.id=$1 AND g.slug=$2 FOR UPDATE OF g",+ "textSha256": "becdf4418f95796c9bab86a61f0f6e9d42bba2f74baedfe40ba9d9705977d77a"},{"lane": "tx",@@ -730,6 +730,12 @@"sql": "SELECT id FROM pages WHERE source_id=$1 AND slug=$2 FOR UPDATE","textSha256": "6c2eb61492fe7470a32169e89b9f04d471f3311d55ff790ad08f4736af483a2c"},+ {+ "lane": "tx",+ "params": [],+ "sql": "SELECT key, value FROM config WHERE key IN ('search_embedding_column', 'embedding_columns')",+ "textSha256": "0c97097b286eb3415cffbfa812bc301187d88bc7a5266678332b0f4c8c571371"+ },{"lane": "tx","params": [@@ -758,12 +764,6 @@"sql": "DELETE FROM content_chunks WHERE page_id = $1 AND chunk_index != ALL($2)","textSha256": "dc4fdfddf00f65b0aad2aa0ec3f1e3a981e7c61f2253f485925d90c371ba372c"},- {- "lane": "tx",- "params": [],- "sql": "SELECT key, value FROM config WHERE key IN ('search_embedding_column', 'embedding_columns')",- "textSha256": "0c97097b286eb3415cffbfa812bc301187d88bc7a5266678332b0f4c8c571371"- },{"lane": "tx","params": [@@ -797,8 +797,8 @@"string","string"],- "sql": "INSERT INTO page_write_guards(source_incarnation,slug) VALUES ($1::uuid,$2) ON CONFLICT DO NOTHING",- "textSha256": "fa56fa770a66caa8ae77b19c2c3ae9caac336d8e8281bc16f09d36a7fcdd74fd"+ "sql": "INSERT INTO page_write_guards(source_incarnation,slug) SELECT incarnation,$1 FROM sources WHERE id=$2 ON CONFLICT DO NOTHING",+ "textSha256": "91584b13aae786f054e246bcc667c9ebe8c065d61b42d5ae775634739bce9f54"},{"lane": "tx",@@ -806,8 +806,8 @@"string","string"],- "sql": "SELECT slug FROM page_write_guards WHERE source_incarnation=$1::uuid AND slug=$2 FOR UPDATE",- "textSha256": "3d08e10394edab70fb78946e378dd11528213526b214a8516d8cf3825e87ac19"+ "sql": "SELECT g.slug FROM page_write_guards g JOIN sources s ON s.incarnation=g.source_incarnation WHERE s.id=$1 AND g.slug=$2 FOR UPDATE OF g",+ "textSha256": "becdf4418f95796c9bab86a61f0f6e9d42bba2f74baedfe40ba9d9705977d77a"},{"lane": "tx",@@ -879,8 +879,8 @@"string","string"],- "sql": "INSERT INTO page_write_guards(source_incarnation,slug) VALUES ($1::uuid,$2) ON CONFLICT DO NOTHING",- "textSha256": "fa56fa770a66caa8ae77b19c2c3ae9caac336d8e8281bc16f09d36a7fcdd74fd"+ "sql": "INSERT INTO page_write_guards(source_incarnation,slug) SELECT incarnation,$1 FROM sources WHERE id=$2 ON CONFLICT DO NOTHING",+ "textSha256": "91584b13aae786f054e246bcc667c9ebe8c065d61b42d5ae775634739bce9f54"},{"lane": "tx",@@ -888,8 +888,8 @@"string","string"],- "sql": "SELECT slug FROM page_write_guards WHERE source_incarnation=$1::uuid AND slug=$2 FOR UPDATE",- "textSha256": "3d08e10394edab70fb78946e378dd11528213526b214a8516d8cf3825e87ac19"+ "sql": "SELECT g.slug FROM page_write_guards g JOIN sources s ON s.incarnation=g.source_incarnation WHERE s.id=$1 AND g.slug=$2 FOR UPDATE OF g",+ "textSha256": "becdf4418f95796c9bab86a61f0f6e9d42bba2f74baedfe40ba9d9705977d77a"},{"lane": "tx",@@ -951,8 +951,8 @@"string","string"],- "sql": "INSERT INTO page_write_guards(source_incarnation,slug) VALUES ($1::uuid,$2) ON CONFLICT DO NOTHING",- "textSha256": "fa56fa770a66caa8ae77b19c2c3ae9caac336d8e8281bc16f09d36a7fcdd74fd"+ "sql": "INSERT INTO page_write_guards(source_incarnation,slug) SELECT incarnation,$1 FROM sources WHERE id=$2 ON CONFLICT DO NOTHING",+ "textSha256": "91584b13aae786f054e246bcc667c9ebe8c065d61b42d5ae775634739bce9f54"},{"lane": "tx",@@ -960,8 +960,8 @@"string","string"],- "sql": "SELECT slug FROM page_write_guards WHERE source_incarnation=$1::uuid AND slug=$2 FOR UPDATE",- "textSha256": "3d08e10394edab70fb78946e378dd11528213526b214a8516d8cf3825e87ac19"+ "sql": "SELECT g.slug FROM page_write_guards g JOIN sources s ON s.incarnation=g.source_incarnation WHERE s.id=$1 AND g.slug=$2 FOR UPDATE OF g",+ "textSha256": "becdf4418f95796c9bab86a61f0f6e9d42bba2f74baedfe40ba9d9705977d77a"},{"lane": "tx",@@ -983,6 +983,12 @@"sql": "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 AND p.deleted_at IS NULL ORDER BY (p.slug=$3) DESC, (p.source_id=$4) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) AS snapshot_withdrawals, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_body, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_timeline FROM chosen p","textSha256": "22ce659b8fb6104bf08b6ee101bd0e0bafb2769bb7c399380a38e9a4a26c693e"},+ {+ "lane": "tx",+ "params": [],+ "sql": "SELECT key, value FROM config WHERE key IN ('search_embedding_column', 'embedding_columns')",+ "textSha256": "0c97097b286eb3415cffbfa812bc301187d88bc7a5266678332b0f4c8c571371"+ },{"lane": "tx","params": [@@ -1011,12 +1017,6 @@"sql": "DELETE FROM content_chunks WHERE page_id = $1 AND chunk_index != ALL($2)","textSha256": "dc4fdfddf00f65b0aad2aa0ec3f1e3a981e7c61f2253f485925d90c371ba372c"},- {- "lane": "tx",- "params": [],- "sql": "SELECT key, value FROM config WHERE key IN ('search_embedding_column', 'embedding_columns')",- "textSha256": "0c97097b286eb3415cffbfa812bc301187d88bc7a5266678332b0f4c8c571371"- },{"lane": "tx","params": [diff --git a/test/fixtures/goldens/sql-text/links.json b/test/fixtures/goldens/sql-text/links.jsonindex 56f4575c6b..b624900146 100644--- a/test/fixtures/goldens/sql-text/links.json+++ b/test/fixtures/goldens/sql-text/links.json@@ -281,22 +281,6 @@"event": "begin","lane": "tx"},- {- "lane": "tx",- "params": [- "string"- ],- "sql": "SELECT key FROM config WHERE key LIKE $1 ESCAPE '\\' ORDER BY key",- "textSha256": "3b7f63477b863dc13bb07fe9cd6980979bd0f7e84196810c1f74ea994df43e79"- },- {- "lane": "tx",- "params": [- "string"- ],- "sql": "SELECT value FROM config WHERE key = $1",- "textSha256": "32d050605cb95dccb4dcc33a20003cfd10f1fd8e194c317d54e08869acb32e9c"- },{"lane": "tx","params": [@@ -332,6 +316,22 @@"sql": "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","textSha256": "d2598c8eb0d051b3f8d25208513a7494b6db488c95574a3781e6db376d945b56"},+ {+ "lane": "tx",+ "params": [+ "string"+ ],+ "sql": "SELECT key FROM config WHERE key LIKE $1 ESCAPE '\\' ORDER BY key",+ "textSha256": "3b7f63477b863dc13bb07fe9cd6980979bd0f7e84196810c1f74ea994df43e79"+ },+ {+ "lane": "tx",+ "params": [+ "string"+ ],+ "sql": "SELECT value FROM config WHERE key = $1",+ "textSha256": "32d050605cb95dccb4dcc33a20003cfd10f1fd8e194c317d54e08869acb32e9c"+ },{"lane": "tx","params": [@@ -372,6 +372,22 @@"sql": "SELECT 1 FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(from_slug text, to_slug text, from_source_id text, to_source_id text) LEFT JOIN pages f ON f.slug=v.from_slug AND f.source_id=v.from_source_id AND f.deleted_at IS NULL LEFT JOIN pages t ON t.slug=v.to_slug AND t.source_id=v.to_source_id AND t.deleted_at IS NULL WHERE f.id IS NULL OR t.id IS NULL LIMIT 1","textSha256": "6446f477cc034315f2e55e7d2489029b3229ffa2bcd339ee147aa3475914c957"},+ {+ "lane": "tx",+ "params": [+ "string"+ ],+ "sql": "SELECT value FROM config WHERE key = $1",+ "textSha256": "32d050605cb95dccb4dcc33a20003cfd10f1fd8e194c317d54e08869acb32e9c"+ },+ {+ "lane": "tx",+ "params": [+ "string"+ ],+ "sql": "SELECT value FROM config WHERE key = $1",+ "textSha256": "32d050605cb95dccb4dcc33a20003cfd10f1fd8e194c317d54e08869acb32e9c"+ },{"lane": "tx","params": [@@ -398,22 +414,6 @@"event": "savepoint-release","lane": "tx>sp"},- {- "lane": "tx",- "params": [- "string"- ],- "sql": "SELECT value FROM config WHERE key = $1",- "textSha256": "32d050605cb95dccb4dcc33a20003cfd10f1fd8e194c317d54e08869acb32e9c"- },- {- "lane": "tx",- "params": [- "string"- ],- "sql": "SELECT value FROM config WHERE key = $1",- "textSha256": "32d050605cb95dccb4dcc33a20003cfd10f1fd8e194c317d54e08869acb32e9c"- },{"lane": "tx","params": [diff --git a/test/fixtures/goldens/sql-text/pages.json b/test/fixtures/goldens/sql-text/pages.jsonindex 3ede4b6ffa..a130993fa0 100644--- a/test/fixtures/goldens/sql-text/pages.json+++ b/test/fixtures/goldens/sql-text/pages.json@@ -64,8 +64,8 @@"string","string"],- "sql": "INSERT INTO page_write_guards(source_incarnation,slug) VALUES ($1::uuid,$2) ON CONFLICT DO NOTHING",- "textSha256": "fa56fa770a66caa8ae77b19c2c3ae9caac336d8e8281bc16f09d36a7fcdd74fd"+ "sql": "INSERT INTO page_write_guards(source_incarnation,slug) SELECT incarnation,$1 FROM sources WHERE id=$2 ON CONFLICT DO NOTHING",+ "textSha256": "91584b13aae786f054e246bcc667c9ebe8c065d61b42d5ae775634739bce9f54"},{"lane": "tx",@@ -73,8 +73,8 @@"string","string"],- "sql": "SELECT slug FROM page_write_guards WHERE source_incarnation=$1::uuid AND slug=$2 FOR UPDATE",- "textSha256": "3d08e10394edab70fb78946e378dd11528213526b214a8516d8cf3825e87ac19"+ "sql": "SELECT g.slug FROM page_write_guards g JOIN sources s ON s.incarnation=g.source_incarnation WHERE s.id=$1 AND g.slug=$2 FOR UPDATE OF g",+ "textSha256": "becdf4418f95796c9bab86a61f0f6e9d42bba2f74baedfe40ba9d9705977d77a"},{"lane": "tx",@@ -673,8 +673,8 @@"string","string"],- "sql": "INSERT INTO page_write_guards(source_incarnation,slug) VALUES ($1::uuid,$2) ON CONFLICT DO NOTHING",- "textSha256": "fa56fa770a66caa8ae77b19c2c3ae9caac336d8e8281bc16f09d36a7fcdd74fd"+ "sql": "INSERT INTO page_write_guards(source_incarnation,slug) SELECT incarnation,$1 FROM sources WHERE id=$2 ON CONFLICT DO NOTHING",+ "textSha256": "91584b13aae786f054e246bcc667c9ebe8c065d61b42d5ae775634739bce9f54"},{"lane": "tx",@@ -682,8 +682,8 @@"string","string"],- "sql": "SELECT slug FROM page_write_guards WHERE source_incarnation=$1::uuid AND slug=$2 FOR UPDATE",- "textSha256": "3d08e10394edab70fb78946e378dd11528213526b214a8516d8cf3825e87ac19"+ "sql": "SELECT g.slug FROM page_write_guards g JOIN sources s ON s.incarnation=g.source_incarnation WHERE s.id=$1 AND g.slug=$2 FOR UPDATE OF g",+ "textSha256": "becdf4418f95796c9bab86a61f0f6e9d42bba2f74baedfe40ba9d9705977d77a"},{"lane": "tx",@@ -770,8 +770,8 @@"string","string"],- "sql": "INSERT INTO page_write_guards(source_incarnation,slug) VALUES ($1::uuid,$2) ON CONFLICT DO NOTHING",- "textSha256": "fa56fa770a66caa8ae77b19c2c3ae9caac336d8e8281bc16f09d36a7fcdd74fd"+ "sql": "INSERT INTO page_write_guards(source_incarnation,slug) SELECT incarnation,$1 FROM sources WHERE id=$2 ON CONFLICT DO NOTHING",+ "textSha256": "91584b13aae786f054e246bcc667c9ebe8c065d61b42d5ae775634739bce9f54"},{"lane": "tx",@@ -779,8 +779,8 @@"string","string"],- "sql": "SELECT slug FROM page_write_guards WHERE source_incarnation=$1::uuid AND slug=$2 FOR UPDATE",- "textSha256": "3d08e10394edab70fb78946e378dd11528213526b214a8516d8cf3825e87ac19"+ "sql": "SELECT g.slug FROM page_write_guards g JOIN sources s ON s.incarnation=g.source_incarnation WHERE s.id=$1 AND g.slug=$2 FOR UPDATE OF g",+ "textSha256": "becdf4418f95796c9bab86a61f0f6e9d42bba2f74baedfe40ba9d9705977d77a"},{"lane": "tx",@@ -849,8 +849,8 @@"string","string"],- "sql": "INSERT INTO page_write_guards(source_incarnation,slug) VALUES ($1::uuid,$2) ON CONFLICT DO NOTHING",- "textSha256": "fa56fa770a66caa8ae77b19c2c3ae9caac336d8e8281bc16f09d36a7fcdd74fd"+ "sql": "INSERT INTO page_write_guards(source_incarnation,slug) SELECT incarnation,$1 FROM sources WHERE id=$2 ON CONFLICT DO NOTHING",+ "textSha256": "91584b13aae786f054e246bcc667c9ebe8c065d61b42d5ae775634739bce9f54"},{"lane": "tx",@@ -858,8 +858,8 @@"string","string"],- "sql": "SELECT slug FROM page_write_guards WHERE source_incarnation=$1::uuid AND slug=$2 FOR UPDATE",- "textSha256": "3d08e10394edab70fb78946e378dd11528213526b214a8516d8cf3825e87ac19"+ "sql": "SELECT g.slug FROM page_write_guards g JOIN sources s ON s.incarnation=g.source_incarnation WHERE s.id=$1 AND g.slug=$2 FOR UPDATE OF g",+ "textSha256": "becdf4418f95796c9bab86a61f0f6e9d42bba2f74baedfe40ba9d9705977d77a"},{"lane": "tx",@@ -919,8 +919,8 @@"string","string"],- "sql": "INSERT INTO page_write_guards(source_incarnation,slug) VALUES ($1::uuid,$2) ON CONFLICT DO NOTHING",- "textSha256": "fa56fa770a66caa8ae77b19c2c3ae9caac336d8e8281bc16f09d36a7fcdd74fd"+ "sql": "INSERT INTO page_write_guards(source_incarnation,slug) SELECT incarnation,$1 FROM sources WHERE id=$2 ON CONFLICT DO NOTHING",+ "textSha256": "91584b13aae786f054e246bcc667c9ebe8c065d61b42d5ae775634739bce9f54"},{"lane": "tx",@@ -928,8 +928,8 @@"string","string"],- "sql": "SELECT slug FROM page_write_guards WHERE source_incarnation=$1::uuid AND slug=$2 FOR UPDATE",- "textSha256": "3d08e10394edab70fb78946e378dd11528213526b214a8516d8cf3825e87ac19"+ "sql": "SELECT g.slug FROM page_write_guards g JOIN sources s ON s.incarnation=g.source_incarnation WHERE s.id=$1 AND g.slug=$2 FOR UPDATE OF g",+ "textSha256": "becdf4418f95796c9bab86a61f0f6e9d42bba2f74baedfe40ba9d9705977d77a"},{"lane": "tx",@@ -1246,8 +1246,8 @@"string","string"],- "sql": "INSERT INTO page_write_guards(source_incarnation,slug) VALUES ($1::uuid,$2) ON CONFLICT DO NOTHING",- "textSha256": "fa56fa770a66caa8ae77b19c2c3ae9caac336d8e8281bc16f09d36a7fcdd74fd"+ "sql": "INSERT INTO page_write_guards(source_incarnation,slug) SELECT incarnation,$1 FROM sources WHERE id=$2 ON CONFLICT DO NOTHING",+ "textSha256": "91584b13aae786f054e246bcc667c9ebe8c065d61b42d5ae775634739bce9f54"},{"lane": "tx",@@ -1255,8 +1255,8 @@"string","string"],- "sql": "SELECT slug FROM page_write_guards WHERE source_incarnation=$1::uuid AND slug=$2 FOR UPDATE",- "textSha256": "3d08e10394edab70fb78946e378dd11528213526b214a8516d8cf3825e87ac19"+ "sql": "SELECT g.slug FROM page_write_guards g JOIN sources s ON s.incarnation=g.source_incarnation WHERE s.id=$1 AND g.slug=$2 FOR UPDATE OF g",+ "textSha256": "becdf4418f95796c9bab86a61f0f6e9d42bba2f74baedfe40ba9d9705977d77a"},{"lane": "tx",@@ -1310,8 +1310,8 @@"string","string"],- "sql": "INSERT INTO page_write_guards(source_incarnation,slug) VALUES ($1::uuid,$2) ON CONFLICT DO NOTHING",- "textSha256": "fa56fa770a66caa8ae77b19c2c3ae9caac336d8e8281bc16f09d36a7fcdd74fd"+ "sql": "INSERT INTO page_write_guards(source_incarnation,slug) SELECT incarnation,$1 FROM sources WHERE id=$2 ON CONFLICT DO NOTHING",+ "textSha256": "91584b13aae786f054e246bcc667c9ebe8c065d61b42d5ae775634739bce9f54"},{"lane": "tx",@@ -1319,8 +1319,8 @@"string","string"],- "sql": "SELECT slug FROM page_write_guards WHERE source_incarnation=$1::uuid AND slug=$2 FOR UPDATE",- "textSha256": "3d08e10394edab70fb78946e378dd11528213526b214a8516d8cf3825e87ac19"+ "sql": "SELECT g.slug FROM page_write_guards g JOIN sources s ON s.incarnation=g.source_incarnation WHERE s.id=$1 AND g.slug=$2 FOR UPDATE OF g",+ "textSha256": "becdf4418f95796c9bab86a61f0f6e9d42bba2f74baedfe40ba9d9705977d77a"},{"lane": "tx",diff --git a/test/fixtures/goldens/sql-text/tags.json b/test/fixtures/goldens/sql-text/tags.jsonindex 5051bb50fe..75092898b6 100644--- a/test/fixtures/goldens/sql-text/tags.json+++ b/test/fixtures/goldens/sql-text/tags.json@@ -22,8 +22,8 @@"string","string"],- "sql": "INSERT INTO page_write_guards(source_incarnation,slug) VALUES ($1::uuid,$2) ON CONFLICT DO NOTHING",- "textSha256": "fa56fa770a66caa8ae77b19c2c3ae9caac336d8e8281bc16f09d36a7fcdd74fd"+ "sql": "INSERT INTO page_write_guards(source_incarnation,slug) SELECT incarnation,$1 FROM sources WHERE id=$2 ON CONFLICT DO NOTHING",+ "textSha256": "91584b13aae786f054e246bcc667c9ebe8c065d61b42d5ae775634739bce9f54"},{"lane": "tx",@@ -31,8 +31,8 @@"string","string"],- "sql": "SELECT slug FROM page_write_guards WHERE source_incarnation=$1::uuid AND slug=$2 FOR UPDATE",- "textSha256": "3d08e10394edab70fb78946e378dd11528213526b214a8516d8cf3825e87ac19"+ "sql": "SELECT g.slug FROM page_write_guards g JOIN sources s ON s.incarnation=g.source_incarnation WHERE s.id=$1 AND g.slug=$2 FOR UPDATE OF g",+ "textSha256": "becdf4418f95796c9bab86a61f0f6e9d42bba2f74baedfe40ba9d9705977d77a"},{"lane": "tx",@@ -85,8 +85,8 @@"string","string"],- "sql": "INSERT INTO page_write_guards(source_incarnation,slug) VALUES ($1::uuid,$2) ON CONFLICT DO NOTHING",- "textSha256": "fa56fa770a66caa8ae77b19c2c3ae9caac336d8e8281bc16f09d36a7fcdd74fd"+ "sql": "INSERT INTO page_write_guards(source_incarnation,slug) SELECT incarnation,$1 FROM sources WHERE id=$2 ON CONFLICT DO NOTHING",+ "textSha256": "91584b13aae786f054e246bcc667c9ebe8c065d61b42d5ae775634739bce9f54"},{"lane": "tx",@@ -94,8 +94,8 @@"string","string"],- "sql": "SELECT slug FROM page_write_guards WHERE source_incarnation=$1::uuid AND slug=$2 FOR UPDATE",- "textSha256": "3d08e10394edab70fb78946e378dd11528213526b214a8516d8cf3825e87ac19"+ "sql": "SELECT g.slug FROM page_write_guards g JOIN sources s ON s.incarnation=g.source_incarnation WHERE s.id=$1 AND g.slug=$2 FOR UPDATE OF g",+ "textSha256": "becdf4418f95796c9bab86a61f0f6e9d42bba2f74baedfe40ba9d9705977d77a"},{"lane": "tx",@@ -185,8 +185,8 @@"string","string"],- "sql": "INSERT INTO page_write_guards(source_incarnation,slug) VALUES ($1::uuid,$2) ON CONFLICT DO NOTHING",- "textSha256": "fa56fa770a66caa8ae77b19c2c3ae9caac336d8e8281bc16f09d36a7fcdd74fd"+ "sql": "INSERT INTO page_write_guards(source_incarnation,slug) SELECT incarnation,$1 FROM sources WHERE id=$2 ON CONFLICT DO NOTHING",+ "textSha256": "91584b13aae786f054e246bcc667c9ebe8c065d61b42d5ae775634739bce9f54"},{"lane": "tx",@@ -194,8 +194,8 @@"string","string"],- "sql": "SELECT slug FROM page_write_guards WHERE source_incarnation=$1::uuid AND slug=$2 FOR UPDATE",- "textSha256": "3d08e10394edab70fb78946e378dd11528213526b214a8516d8cf3825e87ac19"+ "sql": "SELECT g.slug FROM page_write_guards g JOIN sources s ON s.incarnation=g.source_incarnation WHERE s.id=$1 AND g.slug=$2 FOR UPDATE OF g",+ "textSha256": "becdf4418f95796c9bab86a61f0f6e9d42bba2f74baedfe40ba9d9705977d77a"},{"lane": "tx",diff --git a/test/helpers/single-write-parity.ts b/test/helpers/single-write-parity.tsnew file mode 100644index 0000000000..d2330faa90--- /dev/null+++ b/test/helpers/single-write-parity.ts@@ -0,0 +1,155 @@+/**+ * Phase 4.1 parity: one scenario of page writes (local and remote callers;+ * aliases, frontmatter, tags, timeline, takes and facts fences, links and+ * wanted links, an update, a delete and a database-only write without a+ * binding) run on a fresh managed brain, then every row it produced dumped+ * with run-specific identities (ids, timestamps, revisions, request ids,+ * writer and host ids) replaced by stable names. Two runs of the scenario,+ * one per publication path, must dump the same rows, effects, receipts,+ * attribution and files.+ */+import { randomUUID } from 'node:crypto';+import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';+import { join, relative } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { OperationContext } from '../../src/core/ops/contract.ts';+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';+import { registerLocalWriter, withVerifiedLocalRegistration } from '../../src/core/persistence/identity.ts';+import { dispatchToolCall } from '../../src/mcp/dispatch.ts';+import { renderFactsTable } from '../../src/core/facts-fence.ts';+import { renderTakesFence } from '../../src/core/takes-fence.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { expect } from 'bun:test';+import { managedBrain } from './managed-brain.ts';+import { withEnv } from './with-env.ts';+import { resetWriteSwitches } from '../../src/core/persistence/switches.ts';++const facts = renderFactsTable([{ rowNum: 1, claim: 'Alice Example leads the platform team', kind: 'fact', confidence: 0.9,+ visibility: 'world', notability: 'medium', source: 'notes/standup', context: 'team update', active: true }]);+const takes = renderTakesFence([{ rowNum: 1, claim: 'Acme Example will ship the beta this quarter', kind: 'bet',+ holder: 'world', weight: 0.6, source: 'notes/standup', active: true }]);+const person = (body: string) => `---\ntitle: Alice Example\ntype: person\naliases: [Alice E, A. Example]\ntags: [team, platform]\nrole: lead\n---\n\n${body}`;+const ALICE_V1 = person(`# Alice Example\n\nAlice works with [[companies/acme-example]] and [[people/bob-example]] (no page yet).\n\n## Facts\n\n${facts}\n\n## Takes\n\n${takes}\n\n## Timeline\n\n- **2026-01-02** | standup — Joined [[companies/acme-example]]\n- **2026-02-03** | standup — Led the platform review\n`);+const ALICE_V2 = person(`# Alice Example\n\nAlice now advises [[companies/acme-example]].\n\n## Timeline\n\n- **2026-01-02** | standup — Joined [[companies/acme-example]]\n- **2026-03-04** | standup — Moved to an advisory role\n`);++export type ParityDump = Record<string, unknown>;++async function waitCommitted(engine: BrainEngine): Promise<void> {+ for (let i = 0; i < 400; i++) {+ const [open] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE state NOT IN ('committed','conflict','failed','cancelled')");+ if (open!.n === 0) return;+ await Bun.sleep(50);+ }+ throw new Error('writes did not settle');+}++/**+ * Runs the scenario on a fresh managed brain (PGLite unless `databaseUrl`) and returns its normalized dump,+ * plus `groupCompletions`: how many publications completed through the group path (not compared).+ */+export async function runSingleWriteParityScenario(databaseUrl?: string): Promise<{ dump: ParityDump; groupCompletions: number }> {+ let dump: ParityDump = {};+ let groupCompletions = 0;+ await managedBrain(async ({ engine, ctx, root }) => {+ const proto = Object.getPrototypeOf(engine) as { executeRaw: (sql: string, ...rest: unknown[]) => Promise<unknown> };+ const original = proto.executeRaw;+ proto.executeRaw = function (this: unknown, sql: string, ...rest: unknown[]) {+ if (typeof sql === 'string' && sql.includes("UPDATE persistence_requests r SET state='committed'")) groupCompletions++;+ return original.call(this, sql, ...rest);+ };+ try {+ await engine.setConfig('unbound_writes.policy', 'database_only').catch(() => undefined);+ const local = (params: Record<string, unknown>, operation = 'put_page', sourceId?: string) =>+ submitPageMutation({ ...ctx, ...(sourceId ? { sourceId } : {}) }, { operation, params: { request_id: randomUUID(), ...params }, waitMs: 30_000 });+ const remoteWriter = await registerLocalWriter(engine, 'stdio', { sourceIds: ['default'], operations: null, scopes: ['read', 'write'], slugPrefixes: ['notes'] });+ const remote = (params: Record<string, unknown>) => withVerifiedLocalRegistration(engine, remoteWriter, () => dispatchToolCall(engine, 'put_page',+ { request_id: randomUUID(), wait_ms: 30_000, ...params }, { remote: true, config: ctx.config, sourceId: 'default',+ auth: { token: 'fixture', clientId: 'fixture-client', scopes: ['read', 'write'], sourceId: 'default', boundSlugPrefixes: ['notes'] },+ logger: { info() {}, warn() {}, error() {} } }));+ await local({ slug: 'companies/acme-example', content: '---\ntitle: Acme Example\ntype: company\n---\n\nAcme Example builds tools.\n' });+ await local({ slug: 'people/alice-example', content: ALICE_V1 });+ const [alice] = await engine.executeRaw<{ revision: string }>("SELECT knowledge_revision::text AS revision FROM pages WHERE slug='people/alice-example'");+ await local({ slug: 'people/alice-example', content: ALICE_V2, expected_revision: alice!.revision });+ await local({ slug: 'people/carol-example', content: ALICE_V1.replaceAll('Alice', 'Carol') });+ await remote({ slug: 'notes/remote-note', content: '---\ntitle: Remote note\ntags: [inbox]\n---\n\nMentions Acme Example and [[people/alice-example]].\n' });+ await local({ slug: 'notes/doomed', content: '---\ntitle: Doomed\n---\n\nShort-lived page.\n' });+ const [doomed] = await engine.executeRaw<{ revision: string }>("SELECT knowledge_revision::text AS revision FROM pages WHERE slug='notes/doomed'");+ await local({ slug: 'notes/doomed', expected_revision: doomed!.revision }, 'delete_page');+ await local({ slug: 'notes/db-only', content: '---\ntitle: Database only\n---\n\nNo binding for this source.\n' }, 'put_page', 'scratch').catch(error => ({ refused: (error as { code?: string }).code }));+ await waitCommitted(engine);+ await disposePersistenceConsumer(engine);+ dump = await normalizedDump(engine, root);+ } finally { proto.executeRaw = original; }+ }, { databaseUrl, setup: async ({ engine }) => {+ await engine.executeRaw("INSERT INTO sources (id, name, config) VALUES ('scratch', 'scratch', '{}'::jsonb) ON CONFLICT (id) DO NOTHING");+ } });+ return { dump, groupCompletions };+}++const VOLATILE = /(^id$|_at$|^effective_date$|^valid_from$|^expected_hash$|^sequence$|knowledge_revision|text_projection_revision|^revision$|execution_token|_host_id$|^search_vector$|^embedding)/;+const ISO_TIME = /\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)/g;+const PAGE_REF = /^(page_id|from_page_id|to_page_id|origin_page_id|event_page_id|target_page_id)$/;++async function normalizedDump(engine: BrainEngine, root: string): Promise<ParityDump> {+ const rows = async (sql: string) => (await engine.executeRaw<{ j: Record<string, unknown> }>(sql)).map(r => typeof r.j === 'string' ? JSON.parse(r.j) : r.j);+ const pages = await rows('SELECT row_to_json(p) AS j FROM pages p ORDER BY source_id,slug');+ const requests = await rows('SELECT row_to_json(r) AS j FROM persistence_requests r ORDER BY sequence');+ const names = new Map<string, string>();+ pages.forEach(p => names.set(`page:${p.id}`, `${p.source_id}/${p.slug}`));+ requests.forEach((r, i) => names.set(String(r.id), `request#${i}`));+ for (const w of await rows('SELECT row_to_json(w) AS j FROM persistence_local_writers w')) names.set(String(w.id), `writer:${w.lane}`);+ for (const w of await rows('SELECT row_to_json(w) AS j FROM persistence_worktrees w')) names.set(String(w.id), 'worktree');+ for (const s of await rows('SELECT row_to_json(s) AS j FROM sources s')) names.set(String(s.incarnation), `incarnation:${s.id}`);+ const normalize = (value: unknown, key = ''): unknown => {+ if (PAGE_REF.test(key) && (typeof value === 'number' || typeof value === 'string')) return names.get(`page:${value}`) ?? value;+ if (typeof value === 'string') {+ const named = names.get(value);+ if (named) return named;+ return value.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g, id => names.get(id) ?? 'uuid').replace(ISO_TIME, 'time');+ }+ if (Array.isArray(value)) return value.map(item => normalize(item));+ if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value as Record<string, unknown>)+ .filter(([k]) => !VOLATILE.test(k)).map(([k, v]) => [k, normalize(v, k)]));+ return value;+ };+ const table = async (name: string) => (await rows(`SELECT row_to_json(t) AS j FROM ${name} t`)).map(r => normalize(r))+ .map(r => JSON.stringify(r)).sort().map(r => JSON.parse(r));+ const files: Record<string, string> = {};+ const walk = (dir: string) => { for (const entry of readdirSync(dir)) {+ const path = join(dir, entry);+ if (entry.startsWith('.')) continue;+ if (statSync(path).isDirectory()) walk(path); else files[relative(root, path)] = readFileSync(path, 'utf8').replace(ISO_TIME, 'time');+ } };+ if (existsSync(root)) walk(root);+ return {+ pages: pages.map(p => normalize(p)),+ requests: requests.map(r => normalize({ operation: r.operation, slug: r.slug, source_id: r.source_id, state: r.state, error_code: r.error_code,+ blocked_reason: r.blocked_reason, outcome: r.outcome, intent: r.intent, authority: r.authority, publication_started: r.publication_started,+ recovery: r.recovery, recovery_bytes: r.recovery_bytes, intent_bytes: r.intent_bytes, terminal_reservation: r.terminal_reservation, worktree_id: r.worktree_id })),+ effects: (await rows('SELECT row_to_json(e) AS j FROM persistence_effects e ORDER BY id')).map(e => normalize({ request_id: e.request_id, kind: e.kind, data: e.data, source_id: e.source_id, worktree_id: e.worktree_id }))+ .map(e => JSON.stringify(e)).sort().map(e => JSON.parse(e)),+ counters: (await rows('SELECT row_to_json(c) AS j FROM persistence_counters c')).map(c => normalize(c)).map(c => JSON.stringify(c)).sort(),+ content_chunks: await table('content_chunks'), page_aliases: await table('page_aliases'), tags: await table('tags'),+ timeline_entries: await table('timeline_entries'), facts: await table('facts'), takes: await table('takes'),+ links: await table('links'), wanted_links: await table('wanted_links'), link_transitions: await table('link_transitions'),+ page_versions: await table('page_versions'), files,+ };+}++/** Runs the scenario with the fast-path switches off, then on, and requires identical dumps. */+export async function expectSingleWriteParity(databaseUrl?: string): Promise<void> {+ const run = (value: string) => withEnv({ GBRAIN_SINGLE_WRITE_GROUP: value, GBRAIN_PREADMIT_CACHE: value }, async () => {+ resetWriteSwitches();+ try { return await runSingleWriteParityScenario(databaseUrl); } finally { resetWriteSwitches(); }+ });+ const { dump: before, groupCompletions: offGroups } = await run('0');+ const { dump: after, groupCompletions: onGroups } = await run('1');+ // Off: every single write takes publishMutation. On: Postgres publishes them as groups of one; PGLite keeps publishMutation.+ expect(offGroups).toBe(0);+ if (databaseUrl) expect(onGroups).toBeGreaterThanOrEqual(7); else expect(onGroups).toBe(0);+ expect((before.requests as Array<{ state: string }>).every(r => r.state === 'committed')).toBe(true);+ expect((before.effects as Array<{ kind: string }>).some(e => e.kind === 'links')).toBe(true);+ for (const table of ['facts', 'takes', 'timeline_entries', 'page_aliases', 'tags', 'wanted_links', 'links']) expect((before[table] as unknown[]).length).toBeGreaterThan(0);+ expect(Object.keys(before.files as object).length).toBeGreaterThan(0);+ for (const key of Object.keys(before)) expect({ [key]: after[key] }).toEqual({ [key]: before[key] });+}diff --git a/test/managed-sync-group-completion.test.ts b/test/managed-sync-group-completion.test.tsindex 2ea846a43b..9713423317 100644--- a/test/managed-sync-group-completion.test.ts+++ b/test/managed-sync-group-completion.test.ts@@ -140,7 +140,8 @@ test('the counters are held for the lock and one completion statement, pipelinedawait completeGroup(recording, rows, outcomes(rows));});const lock = issued.findIndex(s => s.sql === LOCK_COUNTERS_SQL);- expect(lock).toBe(2);+ // Missing counter rows are created first; the effect sizes are read inside the completing UPDATE.+ expect(lock).toBe(1);// Under the counter lock: the lock itself and one UPDATE, whatever the group size; COMMIT follows.expect(issued.slice(lock)).toHaveLength(2);expect(issued[lock + 1]!.sql).toContain('UPDATE persistence_requests r SET');diff --git a/test/single-write-group-parity.test.ts b/test/single-write-group-parity.test.tsnew file mode 100644index 0000000000..c3ac969e95--- /dev/null+++ b/test/single-write-group-parity.test.ts@@ -0,0 +1,13 @@+/**+ * Phase 4.1/4.2/4.4 and the put_page apply diet: the same page writes produce+ * the same rows, effects (the links effect included), receipts, attribution+ * and files with the single-write fast path on as with it off (publishMutation+ * and the full apply). PGLite here; Postgres in+ * test/e2e/single-write-group-parity-postgres.test.ts.+ */+import { test } from 'bun:test';+import { expectSingleWriteParity } from './helpers/single-write-parity.ts';++test('single page writes dump the same rows, effects, receipts and files with the fast path on and off (PGLite)', async () => {+ await expectSingleWriteParity();+}, 300_000);