Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(import): batch managed import per-page reads per group (GBRA-75 wave 10)

time-attack729931eb617a
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.md
index 69a91f739d..c74a0aae66 100644
--- a/docs/architecture/key-files/core-persistence-continued.md
+++ b/docs/architecture/key-files/core-persistence-continued.md
@@ -36,6 +36,7 @@ Managed connector ingestion, connector item holds, sync checkpoint validation an
- `src/core/persistence/connector-errors.ts` — `connector_account_changed` with its two-exit hint, the retired-intent messages, and `receiptDeliveredHint`, which rebuilds `suggestion`/`detail`/`docs` for codes delivered through a stored receipt (the coordinator persists only code and message); `writeResponse` applies it.
- `src/core/persistence/checkpoint-validation.ts` — the managed sync checkpoint's incomplete-receipt validation (#5762): `INCOMPLETE_SYNC_RECEIPT_SQL` is three `LIMIT 1` probes (recovery; an open page receipt of the run; a non-committed page receipt with no committed sibling at its index) served by `persistence_requests_recovery`, `persistence_requests_sync_run_open` and `persistence_requests_sync_run_committed`, with the same result as the former single predicate. `findIncompleteSyncReceipt` returns the blocking receipt's request id and maps only this statement's 57014 statement timeout to the terminal, non-transient `checkpoint_validation_timeout`. `readRequestIndexStates` reads each index as valid, missing, INVALID or building (Postgres `pg_stat_progress_create_index`); `formatCheckpointTimeoutHint` / `checkpointTimeoutHint` is the one formatter for the three-state hint and the filled retry (`gbrain sync --source <id> --no-pull --retry-failed` plus the cursor-selecting options the checkpoint intent records in `syncOptions` and the saved processing flags), used by the sync summary and `get_write_request`. Tests: `test/persistence-sync-checkpoint-validation.test.ts`, `test/e2e/persistence-request-indexes-postgres.test.ts`.
- `src/core/persistence/noop-kernel.ts` — the #5470 no-op kernel. `inspectUnchanged` takes a preparer's `PreparedMutation` for an unadmitted `screeningRequest` and returns `contentUnchanged`, `projectionWorkRequired` (safe-chunk fence, text projection behind the knowledge revision, embedded page without a contextual mode), `metadataWorkRequired` (source path) and `observedRevision`; bound pages also need local file bytes equal to the serialized page. The page's current `knowledge_revision`, read with the projection flags, must still equal the snapshot's revision (a write after the screen's snapshot admits as `revision_moved`). Callers run the preparer's own `validate` before counting a skip. An optional `waive` list (#5751) lets a caller skip two admit reasons its no-op publication can never resolve, a pending contextual-mode stamp and file bytes that differ from the prepared content (never a missing file); the result lists each waiver applied in `waived`; only managed working-tree sync entries pass it. Used by connector sync, `import-mutations.ts`, and `sync-run.ts` (working-tree and company-profile entries; renames and overlays always admit). Tests: `test/noop-kernel-paths.test.ts`, `test/connector-wave3.test.ts`.
+- `src/core/persistence/import-reads.ts` — GBRA-75 wave 10: `readImportSnapshots` reads a run of pages as `readPageSnapshot(slug, { sourceId, includeDeleted: true })` returns each (soft-deleted rows, withdrawals and purge markers included) through `readPageSnapshotsBatch({ includeDeleted, absentIsNull })`, looping over its byte-budget prefixes; the managed import screen uses it for two or more new members. `importGroupReads` serves an import group's preparation (`group-publish.ts` `preparationReads`): each member's first own snapshot read comes from one batch, and `findDuplicatePage` calls that arrive together (all members, or a 2 ms window) are answered by one `findDuplicatePages` (`engine-sql/pages.ts`, same predicate and ranking per input); a failed batch falls back to each member's single read. Tests: `test/import-reads.test.ts`, Postgres arm `test/e2e/import-reads.test.ts`.
- `src/core/persistence/screening-paths.ts` — GBRA-75 wave 7: `withScreeningPaths(run)` opens one screening batch's memo of root-level filesystem facts and `screeningPath(key, compute)` resolves each once inside it: other sources' root realpaths (`assertImportPaths`), shared skillpack root canonical paths and the source root's Git scope (`knowledge-guard.ts`). Per-file paths are never memoized; a nested batch joins the open one; the memo closes with `run`, so work that outlives it computes fresh; a throwing compute is never memoized. Opened by the managed import plan and screen loops (`import-mutations.ts`), each sync waiver screen (`screenWaiver`) and `sync-run.ts` `waiveRun`'s screens. Tests: `test/persistence-skip-cost.test.ts`.
- `src/core/persistence/sync-waivers.ts` — managed-sync no-op waivers (#5470, #5984). `waiveNoopEntry` screens a frozen, unadmitted entry: an unchanged import (`unchangedSyncImport`, moved here from `sync-run.ts`, with the #5751 working-tree kernel waivers) or a delete whose page is already soft-deleted at the entry's frozen `expected_revision` with its file absent (never an unowned deletion or a rename). A candidate runs `validateSyncAuthority` first (a revoked grant throws before any waiver), then commits in one transaction with a fixed lock order: page guard (`lockPageKeys`), then the managed-sync cursor row `FOR UPDATE`; it re-reads the snapshot (and, for deletes, the origin and file absence) and refuses while `UNFINISHED_PAGE_REQUEST_SQL` finds an unfinished request for the page by slug, page id or a `renameFrom` naming it. That lookup is three `LIMIT 1` branches served by `persistence_requests_pending`, `persistence_requests_recovery` and the database-only pending index (EXPLAIN pinned in `test/persistence-managed-sync.test.ts`). A cursor that moved meanwhile is adopted instead of waived again, so `waived` counts only increment in the winning transaction. `GBRAIN_SYNC_WAIVE_NOOP=0` admits every entry. #6278: the lookup also matches the entry's file path, origin and a rename from that origin (`unfinishedPageRequestParams`), so the hold gate in `sync-run.ts` shares it. `unchangedSyncImport` (and so `sameContentAtOrigin`'s preparation) runs the sync preparer under `raceSyncBudget` against `persistence.sync_preparation_ms` (`syncPreparationBudgetMs`, read at most every 5 s, default 120 s) and the run's signal: past the budget nothing is waived and the origin refusal stands (fail open, nothing counted or held, `SyncPreparationBudgetExceeded`); a cancelled run propagates. GBRA-75 wave 8: `unchangedSyncImport` prepares with `{ unsaved: true }`, so its validation also accepts this run's cursor with nothing pending; before that every import waiver-run screen failed the cursor check and each unchanged file took a pending save, a second screen and its own waiver transaction. `waiveNoopRun` (up to 64 entries, one cursor write) re-reads the owner epoch under its lock (a change passes nothing; the per-entry path then refuses it) and each import's file bytes (an edit ends the prefix). Tests: `test/sync-waiver-budget.test.ts`, `test/sync-waiver-run-imports.test.ts`, `test/persistence-managed-sync.test.ts` (#5984 waiver cases), `test/persistence-sync-legacy-files-5751.test.ts`.
- `src/core/persistence/accepted-pending.ts` — `acceptedPendingReceipt(error)`: the shared test for an accepted, not yet committed write, used by managed atom publication, extract_atoms, managed import and the connector budget. `publicationHold(error)` returns `pending` for such a receipt or `contention` for an OperationError `storage_error` with detail `database_contention` and no receipt (admission rolled back, nothing recorded), else null — never from a message, a terminal receipt, a contention error carrying a receipt or a permission refusal; `publishOrHold(fn)` runs one publication and returns null on commit, the hold when there is one, and rethrows anything else. Used by the patterns, drift and synthesize dream phases.
diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.md
index fc498cb79d..e51dc3f108 100644
--- a/docs/architecture/key-files/persistence-stalls.md
+++ b/docs/architecture/key-files/persistence-stalls.md
@@ -25,7 +25,7 @@ owner (`owner_wedged_here`), movement surfaces (`data_moving`, doctor
- `src/core/persistence/owner-refusal.ts` — #6278: the `owner_unavailable` reasons matrix. `checkOwner(binding, incarnation, hostId)` names the first failing condition in a fixed order (`binding_missing`, `incarnation_changed`, `host_mismatch`, `transfer_in_progress` for a `draining` worktree, `clone_in_progress` for `recovering`, `local_path_missing`, `coordination_path_missing`) or returns the usable `ActiveOwnerBinding`; `ownerRefusal` gives each reason its message, `why`, actor, fix (always the read-only `gbrain sources writer status --source <id> --json`, with the same verify; `actor: provider` so the two in-progress reasons render `next: wait` with a 30 s delay, `host_admin` for the rest) and `retryable` (`host_mismatch` false at the site, carried by `OperationError.retryable`); `ownerUnavailableError` is the thrown form. `host_mismatch` prints both host ids' first 8 characters and, when `remote` is false, the `host.json` path this process read; nothing here claims or transfers ownership. Used by `maintenancePreflight`, `loadFenceSource` and `managedRepairRoot`; the registry's `owner_unavailable.reasons` and the `FENCE_REASONS` owner entries carry the same vocabulary. Tests: `test/owner-refusal.test.ts` (matrix, every preflight condition on a claimed worktree, the HTTP envelope without a local path), `test/fence-repair-reasons.test.ts`.
- `src/core/persistence/repair-busy.ts` — #6278: the busy set a repair must not write while a managed sync runs. `loadRepairBusySet(engine, sourceId, incarnation)` returns the paths and slugs named by queued, running and recovering requests and terminal rows with an open recovery (both rename endpoints included) plus, for every unfinished `managed-sync` cursor of the incarnation, the entries of its frozen `managed-sync-manifest` from the cursor's index on (a path with a `sync-hold` record is left out: the sync retries a held file only when its bytes change); it never throws and fails closed (`unknown` set, so `repairBusy` answers true for everything) when a query fails or a cursor's manifest is missing. `repairBusyMessage` is the hold text, `repairBusyError` the `sync_in_progress` refusal (`reason` `candidate_in_flight` or `busy_set_unreadable`) `submitManagedFileRepair` raises at admission. Tests: `test/repair-busy.test.ts`, `test/repair-fences.test.ts`, `test/repair-fences-during-catchup.test.ts` (Postgres: `test/e2e/repair-fences-during-catchup-postgres.test.ts`).
- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Every claimed write has a preparation budget (`preparation-budget.ts`): `execute` races the preparation against it (`startPreparation`), so the claim is released with `blocked_reason` `preparation_deadline` and one counted attempt at the budget even when the preparer ignores its signal, and a late result never publishes (the execution-token fence). A request already at `persistence.max_preparation_attempts` is finished `failed` with `preparation_stalled` at claim without preparing again, and the release that reaches the limit finishes it there (`coordinator.ts` `finishPreparationStalled`; a waiting `awaitWrite` caller gets the terminal receipt, foreground writes included); a preparer's rejection on the consumer's own abort (its reason, an `AbortError` or a cancelled statement, `preparationAbortReason`) is a release, never a receipt. The expired-claim sweep (Postgres, and PGLite's `releaseAbandonedClaims`) charges one attempt for a claim stamped `preparing` (a process killed mid-preparation); `claim_lost`, `consumer_stopping` and `group_member_waiting` never charge, and a commit resets the counter. The #5373 root barrier for an abandoned preparation ends at `persistence.preparation_ceiling_ms` measured from the claim: the root is freed, the counter is pinned at the limit (an overrun proves cancellation is ignored, so the next claim fails the request `preparation_stalled`) and the zombie stays in `status().outlived_ceiling`; at the per-process cap (`zombieCap`, default 1) the consumer claims nothing more and `status().restart_required` is true. `stop()` gives abandoned preparations `ABANDONED_STOP_GRACE_MS` (5 s) after aborting them instead of waiting forever. The fault point `consumer:preparing` sits inside the budget, `status()` reports `preparation_policy` and `abandoned_preparations`, and the stderr line carries `phase=preparation reason=deadline_exceeded | preparation_stalled | ceiling_exceeded`. With the `preparation_deadlines` switch off only `remember` and intent-less `put_page`/`edit_page` keep the 30 s budget, the old unbounded wait applies and no attempt is counted. 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 `claimableWriteSql` 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 or the ceiling passes, while the consumer slot frees at once. Renewals are never awaited on the way out: `stop()` drains in-flight renewals and gives abandoned preparations their grace before engine close. Tests: `test/persistence-claim-lease.test.ts`, `test/persistence-consumer-scheduling.test.ts`, `test/e2e/persistence-consumer-claim-loss.test.ts`, `test/persistence-preparation-kill-accounting.test.ts`, `test/e2e/persistence-preparation-deadline.e2e.test.ts`. #6355: `onLane` lends its warm lane's transaction through a wrapper that notes a connection loss (`isConnectionLoss`); in `finally` a lost lane is released and `idleLaneRetryAt` set a minute out, whatever `run` returned or threw (admission turns the loss into `write_outcome_unknown` or succeeds on the pool, so the catch alone never saw it), because the dead reservation answers every later statement with "Connection is no longer owned" (`test/persistence-consumer-lane-loss.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. #6075: when another owner loop already admitted the group's head on the single path with the head's pre-group intent (the intent minus the `group`/`lane` keys `formGroup` adds, `groupedIntent`/`ungroupedIntent`), `groupStep` drops the group and the single path takes that request, and the never-admitted followers are frozen again; a different intent under the head's request ID still refuses `idempotency_conflict`. The single path's ENG-A7 admission guard compares the stored pending intent as well as its request ID, so a pass that read the head before a drain grouped it re-reads the cursor instead of admitting the stale intent, and an `idempotency_conflict` against a head the group admitted first re-reads the cursor too (`test/managed-sync-stale-group-head.test.ts`). 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`) and the files of one managed import batch (`intent.import_batch`, key `import:`, grouped on PGLite too; `independentGroup` names both) 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-continued.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. Each member has its own preparation budget (#6278): `executeClaimedGroup` marks a wave durably (`markDispatched`) and starts each member's clock when the wave dispatches it, so a follower waiting behind four others is never charged; the lease renews the mutable set of members still held (`renewGroupClaims` stamps each member's own phase), so releasing one member never reads as a lost group lease. When member k's budget passes, nothing later is dispatched, the in-flight suffix is aborted, k is released `preparation_deadline` (charged; finished `preparation_stalled` when that reaches the limit) and the later members `group_member_waiting` (not charged), and the contiguous prepared prefix 0..k-1 publishes (singly when shorter than two; under lanes in the original group's key order). An independent `put_pages` batch group releases only k, `laneFallback` keeps the expired member's reason, and an abandoned member's preparation goes to the consumer with its clock, so the root waits for it until it settles or the ceiling. A member's signal reaches its preparer through its clock (`enterClaimStep`), never as a blanket statement signal: `preparationReads` and `groupReads` answer one read for every member and skip their memo for a signalled statement, so a member that must give up on a shared read races its own signal against the shared promise (pinned by `test/persistence-preparation-memo-rule.test.ts`). A commit resets `preparation_attempts` (`completeGroup`). Tests: `test/managed-sync-bulk.test.ts`, `test/e2e/put-pages-group-postgres.test.ts`, `test/e2e/persistence-group-deadline-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. #6075: when another owner loop already admitted the group's head on the single path with the head's pre-group intent (the intent minus the `group`/`lane` keys `formGroup` adds, `groupedIntent`/`ungroupedIntent`), `groupStep` drops the group and the single path takes that request, and the never-admitted followers are frozen again; a different intent under the head's request ID still refuses `idempotency_conflict`. The single path's ENG-A7 admission guard compares the stored pending intent as well as its request ID, so a pass that read the head before a drain grouped it re-reads the cursor instead of admitting the stale intent, and an `idempotency_conflict` against a head the group admitted first re-reads the cursor too (`test/managed-sync-stale-group-head.test.ts`). 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`) and the files of one managed import batch (`intent.import_batch`, key `import:`, grouped on PGLite too; `independentGroup` names both) 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-continued.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. Each member has its own preparation budget (#6278): `executeClaimedGroup` marks a wave durably (`markDispatched`) and starts each member's clock when the wave dispatches it, so a follower waiting behind four others is never charged; the lease renews the mutable set of members still held (`renewGroupClaims` stamps each member's own phase), so releasing one member never reads as a lost group lease. When member k's budget passes, nothing later is dispatched, the in-flight suffix is aborted, k is released `preparation_deadline` (charged; finished `preparation_stalled` when that reaches the limit) and the later members `group_member_waiting` (not charged), and the contiguous prepared prefix 0..k-1 publishes (singly when shorter than two; under lanes in the original group's key order). An independent `put_pages` batch group releases only k, `laneFallback` keeps the expired member's reason, and an abandoned member's preparation goes to the consumer with its clock, so the root waits for it until it settles or the ceiling. A member's signal reaches its preparer through its clock (`enterClaimStep`), never as a blanket statement signal: `preparationReads` and `groupReads` answer one read for every member (GBRA-75 wave 10: `preparationReads` answers `getConfig` from one `getAllConfig` per group; an import group's members also read their own `{ sourceId, includeDeleted: true }` snapshot from one batch and coalesce `findDuplicatePage` into one `findDuplicatePages` statement through `import-reads.ts`, and the group's preparation runs inside `withScreeningPaths`; publication's `validate`/`checkPaths` run after it, unmemoized) and skip their memo for a signalled statement, so a member that must give up on a shared read races its own signal against the shared promise (pinned by `test/persistence-preparation-memo-rule.test.ts`). A commit resets `preparation_attempts` (`completeGroup`). Tests: `test/managed-sync-bulk.test.ts`, `test/e2e/put-pages-group-postgres.test.ts`, `test/e2e/persistence-group-deadline-postgres.test.ts`.
- `src/core/persistence/identity.ts` — local writer and host identity. GBRA-75 wave 7: `localHostId` / `localHostIdentity` / `existingLocalHostId` share one cache of the validated `host.json`, keyed on the path (recomputed from `persistenceHome()` on every call, so a `GBRAIN_HOME` change misses) plus `statSync(bigint)` dev, ino, mtimeNs, ctimeNs and size. ENOENT is a miss (`existingLocalHostId` never mints); any other stat error reads uncached, so `writer_identity_invalid` still throws on every call; an invalid document is never cached; a file modified under 2 s ago is read but not cached (same-size rewrites inside one timestamp tick). `scripts/persistence/harness.ts` `selectFixtureHost` (rename over the path) stays correct. Tests: `test/persistence-host-identity-cache.test.ts`.
- `src/core/persistence/consumer-heartbeat.ts` — #6317 (B1a, B3): the probe and heartbeat behind one full consumer per host. `consumerIdentity()` is this process's `{pid, nonce, pid_ns}` (a random per-process nonce and the pid-namespace inode from `/proc/self/ns/pid` where readable), so a reused pid after a container restart is a new row; every `owner_pid === process.pid` check compares the nonce too. `startConsumerHeartbeat(engine, row, opts)` renews this process's `persistence_consumers` row every 10 s on its own single-flight timer through `executeRawDirect` (independent of claim renewal: an idle `serve` holds no claim), carrying kind (`claimOwner().kind`), mode (`probing|full|waiter_only|promoted`), `restart_required`, the age of the oldest abandoned root barrier, the pool gauge `{checked_out, max, waiters}`, `host_json_path`, `persistence_home`, `minted_under` and the build; each renewal deletes rows lapsed over 60 s in the same CTE, and a failed write is logged once and never stops the consumer. `probeLiveFullConsumer(engine, hostId, self)` is the database-only probe (never a socket: the persistence IPC socket exists only on PGLite): a row of a resident kind (`serve`, `sync`, `jobs`, `autopilot`, `mcp`), mode `full`, not this process, renewed within 30 s, not `restart_required` and not wedged (no root barrier older than `persistence.preparation_ceiling_ms`), on an `active` binding. `listHostConsumers(engine, hostId)` feeds `writer status --json` `host.consumers` and doctor. Live is 30 s, lapsed 60 s. The consumer mode machine in `consumer.ts` (`probing` → `full` or `waiter_only` → `promoted` → back to `waiter_only` after three healthy owner ticks) consumes the probe on every tick; `startPersistenceConsumer` in `service.ts` stays synchronous and returns the waiter-only seam (`WaiterOnlyConsumer` behind `PersistenceConsumerLike`: `wake()` no-op, settlement listeners kept, `holds()` false, `status()` `waiter_only` with the owner pid) when the probe finds an owner and `persistence.single_consumer` is on. A `serve` always starts full; short-lived kinds (`put`, `import`, `dream`, `cycle`, `sources`, `cli`) keep their own consumer; PGLite is inert.
- `src/core/schema-migrations/v222-persistence-consumers.ts` — #6317 (T-01): the `persistence_consumers` table, primary key `(host_id, pid, nonce)`, columns `pid_ns`, `kind`, `mode`, `started_at`, `renewed_at`, `restart_required`, `root_barrier_age_ms`, `pool` jsonb, `host_json_path`, `persistence_home`, `minted_under` jsonb, `version`; plus the partial index `persistence_requests (worktree_id, completed_at DESC) WHERE state = 'committed'` that the movement watermark reads (the baseline indexes cover pending, recovery and principal reads only). Both objects are also in `src/schema.sql` for fresh installs (PGLite and Postgres parity, goldens). The number is taken at the merge slot by `bun run release:restamp`.
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index df40047a15..4d90649045 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -16,12 +16,12 @@ src/commands/sync.ts 514 ratchet refactor wave 1 split target (W4 sync); ceiling
src/core/cycle.ts 3293 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts)
src/core/cycle/synthesize.ts 3228 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import)
src/core/cycle/extract-atoms.ts 1654 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt; +4 GBRA-75: octet_length-bounded body-length predicate (minCompiledTruthChars) for discovery and the backlog count
-src/core/engine.ts 2750 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move)
+src/core/engine.ts 2751 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts)
src/core/import-file.ts 2049 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts)
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 nullable
src/core/operations.ts 342 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 row
-src/core/pglite-engine.ts 3007 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); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts)
-src/core/postgres-engine.ts 3002 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); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts)
+src/core/pglite-engine.ts 3008 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); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts)
+src/core/postgres-engine.ts 3003 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); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts)
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 opts
src/core/types.ts 2250 ratchet +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +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); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move)
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/engine-sql/pages.ts b/src/core/engine-sql/pages.ts
index 0e482d202f..67601faa41 100644
--- a/src/core/engine-sql/pages.ts
+++ b/src/core/engine-sql/pages.ts
@@ -60,6 +60,31 @@ export async function findDuplicatePage(
return { slug: r.slug, id: Number(r.id) };
}
+/**
+ * GBRA-75 wave 10: `findDuplicatePage` for several inputs of one source in one statement. Entry i is the row the
+ * single call returns for `inputs[i]`: the same predicate, the same order and the first row per input.
+ */
+export async function findDuplicatePages(
+ exec: ScopedRead,
+ sourceId: string,
+ inputs: ReadonlyArray<{ hash: string; frontmatterId?: string | null; excludeSlug?: string }>,
+): Promise<Array<{ slug: string; id: number } | null>> {
+ if (!inputs.length) return [];
+ const { rows } = await exec.run<{ n: number | string; id: number | string; slug: string }>(sqlFragment`
+ SELECT DISTINCT ON (k.n) k.n, p.id, p.slug
+ FROM jsonb_to_recordset(${JSON.stringify(inputs.map((input, i) => ({ n: i + 1, hash: input.hash, frontmatter_id: input.frontmatterId ?? null,
+ exclude_slug: input.excludeSlug ?? null })))}::text::jsonb) AS k(n int, hash text, frontmatter_id text, exclude_slug text)
+ JOIN pages p ON p.source_id = ${sourceId}
+ AND p.deleted_at IS NULL
+ AND (p.content_hash = k.hash OR (p.frontmatter->>'id' = k.frontmatter_id AND k.frontmatter_id IS NOT NULL))
+ AND (k.exclude_slug IS NULL OR p.slug <> k.exclude_slug)
+ ORDER BY k.n, (p.frontmatter->>'id' IS NOT DISTINCT FROM k.frontmatter_id) DESC, p.id
+ `);
+ const found: Array<{ slug: string; id: number } | null> = inputs.map(() => null);
+ for (const row of rows) found[Number(row.n) - 1] = { slug: row.slug, id: Number(row.id) };
+ return found;
+}
+
export async function putPage(
exec: SqlExecutor,
slug: string,
diff --git a/src/core/engine.ts b/src/core/engine.ts
index 539452de60..8911820503 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -811,7 +811,7 @@ export interface BrainEngine {
* `readPageSnapshot(slug, { sourceId })` for a run of exact refs in one statement (page-snapshot-batch.ts):
* the longest prefix whose bodies fit `maxBytes`. Postgres binds the refs' sources for RLS.
*/
- readPageSnapshotsBatch(refs: ReadonlyArray<{ slug: string; sourceId: string }>, opts?: { maxBytes?: number }): Promise<PageSnapshotBatch>;
+ readPageSnapshotsBatch(refs: ReadonlyArray<{ slug: string; sourceId: string }>, opts?: { maxBytes?: number; includeDeleted?: boolean; absentIsNull?: boolean }): Promise<PageSnapshotBatch>;
/** Hold exact page identities through commit, including absent rows. Requires a transaction. */
lockPageKeys(keys: readonly PageKey[]): Promise<void>;
/**
@@ -862,6 +862,7 @@ export interface BrainEngine {
sourceId: string,
opts: { hash: string; frontmatterId?: string | null; excludeSlug?: string },
): Promise<{ slug: string; id: number } | null>;
+ findDuplicatePages?(sourceId: string, inputs: ReadonlyArray<{ hash: string; frontmatterId?: string | null; excludeSlug?: string }>): Promise<Array<{ slug: string; id: number } | null>>;
/**
* Hard-delete a page row. Cascades to content_chunks, page_links,
* chunk_relations via existing FK ON DELETE CASCADE.
diff --git a/src/core/page-snapshot-batch.ts b/src/core/page-snapshot-batch.ts
index c461e11f2c..a8ee3884d1 100644
--- a/src/core/page-snapshot-batch.ts
+++ b/src/core/page-snapshot-batch.ts
@@ -3,7 +3,8 @@
*
* One statement returns, for a run of `(slug, sourceId)` refs, the same
* `PageSnapshot` that `engine.readPageSnapshot(slug, { sourceId })` returns
- * for each: live rows only, tags, withdrawals and page-subject purges, the
+ * for each (with `includeDeleted`, the one `{ sourceId, includeDeleted: true }`
+ * returns: a soft-deleted row too, as the managed import reads it): tags, withdrawals and page-subject purges, the
* source's '*' purge marker, source incarnation and the withdrawal overlay.
* The projection mirrors `page-state/snapshot.ts` (pinned by
* test/page-snapshot-batch.test.ts); the line fingerprints the overlay needs
@@ -14,7 +15,9 @@
* whose bodies fit `maxBytes` (always at least one ref); `covered` says how
* many refs the result answers. A ref the statement does not return is read
* again through `readPageSnapshot`, so a caller never gets less than the
- * per-page read would give it. Engines run every statement on `query`, so
+ * per-page read would give it; with `absentIsNull` (GBRA-75 wave 10, the managed
+ * import, where most refs name new pages) the statement's own answer stands.
+ * Engines run every statement on `query`, so
* Postgres can bind the batch's sources for RLS (`engine.readPageSnapshotsBatch`).
*/
import { overlayWithdrawalBody } from './facts/withdrawal-overlay.ts';
@@ -38,7 +41,7 @@ export interface PageSnapshotBatch {
export async function readPageSnapshotsBatch(
query: ReadQuery,
refs: ReadonlyArray<{ slug: string; sourceId: string }>,
- opts: { maxBytes?: number } = {},
+ opts: { maxBytes?: number; includeDeleted?: boolean; absentIsNull?: boolean } = {},
): Promise<PageSnapshotBatch> {
const snapshots = new Map<string, PageSnapshot>();
if (!refs.length) return { snapshots, covered: 0 };
@@ -47,7 +50,7 @@ export async function readPageSnapshotsBatch(
COALESCE(sum(octet_length(p.compiled_truth) + COALESCE(octet_length(p.timeline), 0))
OVER (ORDER BY v.n ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING), 0) AS batch_prior_bytes
FROM unnest($1::text[], $2::text[]) WITH ORDINALITY AS v(slug, source_id, n)
- LEFT JOIN pages p ON p.slug = v.slug AND p.source_id = v.source_id AND p.deleted_at IS NULL
+ LEFT JOIN pages p ON p.slug = v.slug AND p.source_id = v.source_id AND ($4::boolean OR p.deleted_at IS NULL)
), chosen AS (
SELECT w.batch_n, w.batch_slug, w.batch_source_id, p.* FROM wanted w LEFT JOIN pages p ON p.id = w.batch_page_id
WHERE w.batch_n = 1 OR w.batch_prior_bytes < $3
@@ -71,11 +74,12 @@ export async function readPageSnapshotsBatch(
(SELECT jsonb_build_object('count',count(*),'latest',max(g.purged_at)) FROM fact_purges g
WHERE g.source_id=p.source_id AND g.subject='*') AS snapshot_global_purges) wd
ORDER BY p.batch_n`,
- [refs.map(r => r.slug), refs.map(r => r.sourceId), opts.maxBytes ?? PAGE_SNAPSHOT_BATCH_MAX_BYTES]);
+ [refs.map(r => r.slug), refs.map(r => r.sourceId), opts.maxBytes ?? PAGE_SNAPSHOT_BATCH_MAX_BYTES, opts.includeDeleted === true]);
for (const row of rows) {
const key = pageSnapshotKey(String(row.batch_source_id), String(row.batch_slug));
if (row.id == null) {
- const snapshot = await readPageSnapshot(query, String(row.batch_slug), { sourceId: String(row.batch_source_id) });
+ if (opts.absentIsNull) continue;
+ const snapshot = await readPageSnapshot(query, String(row.batch_slug), { sourceId: String(row.batch_source_id), ...(opts.includeDeleted ? { includeDeleted: true } : {}) });
if (snapshot) snapshots.set(key, snapshot);
continue;
}
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index 2bd1cf2c63..b33a388941 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -66,6 +66,8 @@ 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';
+import { importGroupReads, type ImportGroupReads } from './import-reads.ts';
+import { withScreeningPaths } from './screening-paths.ts';
/** A `put_pages` or managed import group publishes at most this many pages per transaction, so one commit stays a few seconds long. */
export const PAGE_BATCH_GROUP_MAX = 8;
@@ -87,7 +89,17 @@ export function groupable(row: WriteRequest, prepared: PreparedMutation): boolea
return independentGroup(publicationGroupKey(row)) || singleWrite(row);
}
-const flat = (sql: string) => sql.replace(/\s+/g, ' ').trim();
+const flattened = new Map<string, string>();
+/** A statement's whitespace-normalized text, remembered for the (bounded) set of statements the memos see. */
+const flat = (sql: string) => {
+ let text = flattened.get(sql);
+ if (text === undefined) {
+ if (flattened.size >= 1024) flattened.clear();
+ text = sql.replace(/\s+/g, ' ').trim();
+ flattened.set(sql, text);
+ }
+ return text;
+};
/**
* Reads a group transaction repeats for every member and whose answer cannot
* change before it commits: the source's local path (its source row is held
@@ -145,7 +157,7 @@ const STABLE_IN_PREPARATION = new Set([
* publication re-checks what it relies on under its locks. It lives only for
* one group's preparation; a failed read is not kept.
*/
-export function preparationReads(engine: BrainEngine): BrainEngine {
+export function preparationReads(engine: BrainEngine, imports?: ImportGroupReads): BrainEngine {
const reads = new Map<string, Promise<unknown>>();
const once = <T>(id: string, read: () => Promise<T>): Promise<T> => {
let value = reads.get(id) as Promise<T> | undefined;
@@ -158,8 +170,12 @@ export function preparationReads(engine: BrainEngine): BrainEngine {
if (key === 'executeRaw') return (sql: string, params?: unknown[], opts?: { signal?: AbortSignal; timeoutMs?: number }) =>
STABLE_IN_PREPARATION.has(flat(sql)) && (!opts?.signal || opts.timeoutMs !== undefined)
? once(JSON.stringify([flat(sql), params ?? null]), () => target.executeRaw(sql, params)) : target.executeRaw(sql, params, opts);
- if (key === 'getConfig') return (name: string) => once(`config:${name}`, () => target.getConfig(name));
+ // GBRA-75 wave 10: every config key a member reads comes from one config read for the group (the same value per key).
+ if (key === 'getConfig') return (name: string) => once('config:*', () => target.getAllConfig()).then(all => Object.hasOwn(all, name) ? all[name]! : null);
if (key === 'getAllConfig') return () => once('config:*', () => target.getAllConfig()).then(all => ({ ...all }));
+ if (imports && key === 'readPageSnapshot') return (slug: string, opts?: Parameters<BrainEngine['readPageSnapshot']>[1]) =>
+ imports.snapshot(slug, opts) ?? target.readPageSnapshot(slug, opts);
+ if (imports && key === 'findDuplicatePage') return (sourceId: string, opts: Parameters<NonNullable<BrainEngine['findDuplicatePage']>>[1]) => imports.findDuplicate(sourceId, opts);
const value = Reflect.get(target, key, target);
return typeof value === 'function' ? value.bind(target) : value;
} });
@@ -549,10 +565,12 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteReques
let cut: number | null = null;
const abandon = (i: number, work: Promise<unknown>) => run.leftRunning?.(work, true, { row: rows[i]!, clock: clocks[i]! });
try {
- const reads = preparationReads(engine);
+ // GBRA-75 wave 10: an import group's members read their pages and duplicate candidates through one batch each (import-reads.ts).
+ const reads = preparationReads(engine, publicationGroupKey(rows[0]!)?.startsWith('import:') ? importGroupReads(engine, rows) : undefined);
// A put_pages or import group prepares all of its (at most PAGE_BATCH_GROUP_MAX) pages at once.
const width = independent ? PAGE_BATCH_GROUP_MAX : 4;
- const preparing = (async () => {
+ // GBRA-75 wave 10: the members' preparations share one memo of root-level path facts; publication re-checks every path.
+ const preparing = withScreeningPaths(async () => {
for (let start = 0; start < rows.length && (independent || cut === null); start += width) {
const wave = rows.slice(start, start + width);
const now = Date.now();
@@ -590,7 +608,7 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteReques
} finally { inFlight.delete(i); }
}));
}
- })();
+ });
if (await lease.whileHeld(preparing) === CLAIM_LOST) {
run.leftRunning?.(preparing, true, { row: rows[0]!, clock: groupClock });
await endLostLease(lease);
diff --git a/src/core/persistence/import-mutations.ts b/src/core/persistence/import-mutations.ts
index f89ab6effd..23bdd21da6 100644
--- a/src/core/persistence/import-mutations.ts
+++ b/src/core/persistence/import-mutations.ts
@@ -19,6 +19,8 @@ import { assertImportPaths, managedImportContent, prepareManagedImportMutation,
import { submissionAuthority } from './authority.ts';
import { inspectUnchanged, screeningRequest } from './noop-kernel.ts';
import { withScreeningPaths } from './screening-paths.ts';
+import { readImportSnapshots } from './import-reads.ts';
+import { pageSnapshotKey } from '../page-snapshot-batch.ts';
import type { WorktreeBinding } from './ownership.ts';
import type { PageSnapshot } from '../page-state/types.ts';
import { readFix, trustedCliRequired } from '../ops/op-fix.ts';
@@ -166,11 +168,14 @@ async function importPlanned(ctx: OperationContext, binding: WorktreeBinding,
try {
const pending = await readPending(members.map(member => member.key));
const fresh: typeof members = [];
+ // GBRA-75 wave 10: the screen reads its new members' pages in one batch; a lone member or a failed batch keeps each member's own read.
+ const unscreened = members.filter(member => !pending.has(member.key)).map(member => ({ slug: member.slug, sourceId }));
+ const screened = unscreened.length > 1 ? await readImportSnapshots(engine, unscreened).catch(() => null) : null;
await withScreeningPaths(async () => { for (const member of members) {
try {
const stored = pending.get(member.key);
if (stored) { resume(member, stored); continue; }
- const snapshot = await engine.readPageSnapshot(member.slug, { sourceId, includeDeleted: true });
+ const snapshot = screened ? screened.get(pageSnapshotKey(sourceId, member.slug)) ?? null : await engine.readPageSnapshot(member.slug, { sourceId, includeDeleted: true });
// The input is the canonical file itself (the common case): its hash was taken from the bytes just read.
const targetHash = member.target === member.inputPath ? member.inputHash : existsSync(member.target) ? sha256(readImportBytes(member.target)) : null;
const intent: ManagedImportIntent = { kind: 'managed_file_import', slug: member.slug, content: member.content, sourcePath: member.sourcePath, path: member.path,
diff --git a/src/core/persistence/import-reads.ts b/src/core/persistence/import-reads.ts
new file mode 100644
index 0000000000..8484aef78e
--- /dev/null
+++ b/src/core/persistence/import-reads.ts
@@ -0,0 +1,82 @@
+/**
+ * GBRA-75 wave 10: the managed import's per-page reads, batched.
+ *
+ * `readImportSnapshots` reads the snapshots of a run of pages exactly as
+ * `readPageSnapshot(slug, { sourceId, includeDeleted: true })` returns each one
+ * (soft-deleted rows included), in as few `readPageSnapshotsBatch` statements as
+ * its byte cap allows; a page a statement does not find is absent (null), as
+ * the single read at that moment answers. The admission screen reads its batch with it.
+ *
+ * `importGroupReads` serves a claimed import group's preparation, whose members
+ * prepare concurrently and publish together (group-publish.ts
+ * `preparationReads`): each member's own snapshot read comes from one batch read
+ * for the group, once, and the members' `findDuplicatePage` calls that arrive
+ * together are answered by one `findDuplicatePages` statement, entry for entry
+ * what each single call returns. As with every preparation read, publication
+ * re-checks what it relies on under its locks. A failed batch read falls back to
+ * each member's own read, so a member sees the outcome its single read would give.
+ */
+import type { BrainEngine, PageSnapshot } from '../engine.ts';
+import { pageSnapshotKey } from '../page-snapshot-batch.ts';
+
+type DuplicateInput = { hash: string; frontmatterId?: string | null; excludeSlug?: string };
+type Duplicate = { slug: string; id: number } | null;
+
+/** How long the first queued duplicate lookup waits for the group's other members before it is sent. */
+export const DUPLICATE_BATCH_WINDOW_MS = 2;
+
+export async function readImportSnapshots(engine: BrainEngine, refs: ReadonlyArray<{ slug: string; sourceId: string }>): Promise<Map<string, PageSnapshot>> {
+ const out = new Map<string, PageSnapshot>();
+ for (let start = 0; start < refs.length;) {
+ const { snapshots, covered } = await engine.readPageSnapshotsBatch(refs.slice(start), { includeDeleted: true, absentIsNull: true });
+ for (const [key, snapshot] of snapshots) out.set(key, snapshot);
+ start += Math.max(1, covered);
+ }
+ return out;
+}
+
+export interface ImportGroupReads {
+ /** A member's first `{ sourceId, includeDeleted: true }` read of its own page, from the group's batch; undefined for any other read. */
+ snapshot(slug: string, opts: unknown): Promise<PageSnapshot | null> | undefined;
+ findDuplicate(sourceId: string, opts: DuplicateInput): Promise<Duplicate>;
+}
+
+export function importGroupReads(engine: BrainEngine, rows: ReadonlyArray<{ slug: string; source_id: string }>): ImportGroupReads {
+ const refs = rows.map(row => ({ slug: row.slug, sourceId: row.source_id }));
+ const unread = new Set(refs.map(ref => pageSnapshotKey(ref.sourceId, ref.slug)));
+ let batch: Promise<Map<string, PageSnapshot>> | undefined;
+ let queue: Array<{ sourceId: string; input: DuplicateInput; resolve: (value: Duplicate) => void; reject: (error: unknown) => void }> = [];
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let waiting = rows.length;
+ const single = (sourceId: string, input: DuplicateInput) => engine.findDuplicatePage ? engine.findDuplicatePage(sourceId, input) : Promise.resolve(null);
+ const flush = () => {
+ if (timer) clearTimeout(timer);
+ timer = undefined;
+ const sent = queue;
+ queue = [];
+ for (const sourceId of new Set(sent.map(entry => entry.sourceId))) {
+ const entries = sent.filter(entry => entry.sourceId === sourceId);
+ const answered = entries.length > 1 && engine.findDuplicatePages ? engine.findDuplicatePages(sourceId, entries.map(entry => entry.input)) : Promise.reject(new Error('single'));
+ answered.then(found => entries.forEach((entry, i) => entry.resolve(found[i] ?? null)),
+ () => { for (const entry of entries) single(entry.sourceId, entry.input).then(entry.resolve, entry.reject); });
+ }
+ };
+ return {
+ snapshot(slug, opts) {
+ const read = opts as { sourceId?: unknown; includeDeleted?: unknown } | undefined;
+ if (!read || Object.keys(read).length !== 2 || read.includeDeleted !== true || typeof read.sourceId !== 'string') return undefined;
+ const key = pageSnapshotKey(read.sourceId, slug);
+ if (!unread.delete(key)) return undefined;
+ batch ??= readImportSnapshots(engine, refs);
+ return batch.then(snapshots => snapshots.get(key) ?? null, () => engine.readPageSnapshot(slug, { sourceId: read.sourceId as string, includeDeleted: true }));
+ },
+ findDuplicate(sourceId, input) {
+ return new Promise<Duplicate>((resolve, reject) => {
+ queue.push({ sourceId, input, resolve, reject });
+ waiting = Math.max(0, waiting - 1);
+ if (waiting === 0) flush();
+ else timer ??= setTimeout(flush, DUPLICATE_BATCH_WINDOW_MS);
+ });
+ },
+ };
+}
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 5c93f1597f..42c89cd2da 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -1196,7 +1196,7 @@ export class PGLiteEngine implements BrainEngine {
return readCanonicalPageSnapshot(this.executeRaw.bind(this), slug, opts);
}
- async readPageSnapshotsBatch(refs: ReadonlyArray<{ slug: string; sourceId: string }>, opts?: { maxBytes?: number }) {
+ async readPageSnapshotsBatch(refs: ReadonlyArray<{ slug: string; sourceId: string }>, opts?: { maxBytes?: number; includeDeleted?: boolean; absentIsNull?: boolean }) {
return readPageSnapshotsBatch(this.executeRaw.bind(this), refs, opts);
}
@@ -1216,6 +1216,7 @@ export class PGLiteEngine implements BrainEngine {
): Promise<{ slug: string; id: number } | null> {
return pagesImpl.findDuplicatePage(scopedRead(this.engineSql), sourceId, opts);
}
+ async findDuplicatePages(sourceId: string, inputs: Parameters<typeof pagesImpl.findDuplicatePages>[2]) { return pagesImpl.findDuplicatePages(scopedRead(this.engineSql), sourceId, inputs); }
private _pageTransaction = false;
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 2d85898045..d1fdc83885 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -746,7 +746,7 @@ export class PostgresEngine implements BrainEngine {
opts?.resolveAlias && opts.excludePrivate ? { alwaysTransaction: true, jitOff: true } : undefined);
}
- async readPageSnapshotsBatch(refs: ReadonlyArray<{ slug: string; sourceId: string }>, opts?: { maxBytes?: number }) {
+ async readPageSnapshotsBatch(refs: ReadonlyArray<{ slug: string; sourceId: string }>, opts?: { maxBytes?: number; includeDeleted?: boolean; absentIsNull?: boolean }) {
const sourceIds = [...new Set(refs.map(ref => ref.sourceId))];
return this.withScopedReadTransaction(sourceIds.length ? sourceIds : undefined, undefined, tx =>
readPageSnapshotsBatch(async (query, params) => Array.from(await tx.unsafe(query, params as never, { prepare: true })) as never, refs, opts));
@@ -768,6 +768,7 @@ export class PostgresEngine implements BrainEngine {
): Promise<{ slug: string; id: number } | null> {
return this.withScopedReadTransaction(undefined, sourceId, tx => pagesImpl.findDuplicatePage(scopedRead(this.engineSqlOn(tx)), sourceId, opts));
}
+ async findDuplicatePages(sourceId: string, inputs: Parameters<typeof pagesImpl.findDuplicatePages>[2]) { return this.withScopedReadTransaction(undefined, sourceId, tx => pagesImpl.findDuplicatePages(scopedRead(this.engineSqlOn(tx)), sourceId, inputs)); }
private _pageTransaction = false;
diff --git a/test/e2e/import-reads.test.ts b/test/e2e/import-reads.test.ts
new file mode 100644
index 0000000000..3d944c7af0
--- /dev/null
+++ b/test/e2e/import-reads.test.ts
@@ -0,0 +1,17 @@
+/** Postgres arm of test/import-reads.test.ts (GBRA-75 wave 10). */
+import { afterAll, beforeAll, describe, test } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { findDuplicatePagesMatchesSingle, importGroupReadsCoalesce, importSnapshotsDropPurgedIncomingRows, importSnapshotsMatchSingleReads } from '../helpers/import-reads-cases.ts';
+
+const url = process.env.DATABASE_URL;
+describe.skipIf(!url)('Postgres managed import batched reads', () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ beforeAll(async () => { ({ engine, close } = await isolatedPersistencePostgres(url!)); }, 120_000);
+ afterAll(async () => { await close?.(); });
+ test('batched import snapshots equal the includeDeleted single reads, deleted, missing and purged pages included', () => importSnapshotsMatchSingleReads(engine));
+ test('an incoming file drops page-subject and \'*\' purged rows through the batched snapshot as through the single read', () => importSnapshotsDropPurgedIncomingRows(engine));
+ test('findDuplicatePages answers each input as findDuplicatePage does', () => findDuplicatePagesMatchesSingle(engine));
+ test('an import group coalesces its members\' reads and falls back to single reads when a batch fails', () => importGroupReadsCoalesce(engine));
+});
diff --git a/test/helpers/import-reads-cases.ts b/test/helpers/import-reads-cases.ts
new file mode 100644
index 0000000000..85a4ec463f
--- /dev/null
+++ b/test/helpers/import-reads-cases.ts
@@ -0,0 +1,134 @@
+/** Shared cases for the managed import's batched reads (GBRA-75 wave 10): PGLite unit test and Postgres E2E. */
+import { expect } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { pageSnapshotKey } from '../../src/core/page-snapshot-batch.ts';
+import { overlayCanonicalBodies } from '../../src/core/page-state/snapshot.ts';
+import { importGroupReads, readImportSnapshots } from '../../src/core/persistence/import-reads.ts';
+import { FENCE, PURGED, REFS, seed, seedPurged } from './page-snapshot-batch-cases.ts';
+
+const PURGED_REFS = ['people/carol-example', 'people/dave-example', 'notes/plain-example', 'notes/missing-example'].map(slug => ({ slug, sourceId: PURGED }));
+const single = (engine: BrainEngine, ref: { slug: string; sourceId: string }) => engine.readPageSnapshot(ref.slug, { sourceId: ref.sourceId, includeDeleted: true });
+
+/** Each batched snapshot is the `{ sourceId, includeDeleted: true }` read: soft-deleted and missing pages, withdrawals and purge markers included. */
+export async function importSnapshotsMatchSingleReads(engine: BrainEngine) {
+ await seed(engine);
+ await seedPurged(engine);
+ const refs = [...REFS, ...PURGED_REFS];
+ const batched = await readImportSnapshots(engine, refs);
+ for (const ref of refs) {
+ const one = await single(engine, ref);
+ const many = batched.get(pageSnapshotKey(ref.sourceId, ref.slug)) ?? null;
+ expect(many).toEqual(one);
+ expect(many?.withdrawals ?? null).toEqual(one?.withdrawals ?? null);
+ expect(many?.globalPurges ?? null).toEqual(one?.globalPurges ?? null);
+ }
+ expect(batched.get(pageSnapshotKey('default', 'notes/deleted-example'))?.page.deleted_at).toBeTruthy();
+ expect(batched.has(pageSnapshotKey('default', 'notes/missing-example'))).toBe(false);
+ expect(batched.has(pageSnapshotKey(PURGED, 'notes/missing-example'))).toBe(false);
+ expect(batched.get(pageSnapshotKey(PURGED, 'people/dave-example'))?.globalPurges?.count).toBe(1);
+ expect((await readImportSnapshots(engine, [])).size).toBe(0);
+}
+
+/** An incoming file that carries purged claims drops those rows through the batched snapshot exactly as through the single read. */
+export async function importSnapshotsDropPurgedIncomingRows(engine: BrainEngine) {
+ await seedPurged(engine);
+ const incoming = `Incoming.\n\n${FENCE}`;
+ const batched = await readImportSnapshots(engine, PURGED_REFS);
+ const query = engine.executeRaw.bind(engine);
+ const overlay = (snapshot: NonNullable<Awaited<ReturnType<typeof single>>>) =>
+ overlayCanonicalBodies(query, incoming, '', snapshot.withdrawals, { sourceId: PURGED, marker: snapshot.globalPurges });
+ for (const slug of ['people/carol-example', 'people/dave-example']) {
+ const one = (await single(engine, { slug, sourceId: PURGED }))!;
+ const many = batched.get(pageSnapshotKey(PURGED, slug))!;
+ const viaSingle = await overlay(one);
+ expect(await overlay(many)).toEqual(viaSingle);
+ expect(viaSingle.compiled_truth).not.toContain('Ships Weekly');
+ expect(viaSingle.compiled_truth.includes('Hires slowly')).toBe(slug === 'people/dave-example');
+ }
+}
+
+const DUP = 'import-reads-dup-example';
+async function seedDuplicates(engine: BrainEngine): Promise<Record<string, string>> {
+ if (!(await engine.executeRaw('SELECT 1 FROM sources WHERE id=$1', [DUP])).length) {
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES ($1,$1)', [DUP]);
+ const put = (slug: string, hash: string, frontmatter: Record<string, unknown> = {}, sourceId = DUP) =>
+ engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `Body of ${slug}.`, timeline: '', frontmatter, content_hash: hash }, { sourceId });
+ await put('notes/a-example', 'hash-shared');
+ await put('notes/b-example', 'hash-shared', { id: 'fm-b' });
+ await put('notes/c-example', 'hash-c', { id: 'fm-c' });
+ await put('notes/d-example', 'hash-d', { id: 'q"u,o{t}e\\s' });
+ await put('notes/gone-example', 'hash-gone', { id: 'fm-gone' });
+ await engine.softDeletePage('notes/gone-example', { sourceId: DUP });
+ await put('notes/z-example', 'hash-shared', { id: 'fm-b' }, 'default');
+ }
+ const rows = await engine.executeRaw<{ slug: string; content_hash: string }>('SELECT slug, content_hash FROM pages WHERE source_id=$1', [DUP]);
+ return Object.fromEntries(rows.map(row => [row.slug, row.content_hash]));
+}
+
+/** `findDuplicatePages` answers entry i exactly as `findDuplicatePage(inputs[i])`. */
+export async function findDuplicatePagesMatchesSingle(engine: BrainEngine) {
+ const hash = await seedDuplicates(engine);
+ const shared = hash['notes/a-example']!;
+ const inputs = [
+ { hash: shared },
+ { hash: shared, frontmatterId: 'fm-b' },
+ { hash: shared, excludeSlug: 'notes/a-example' },
+ { hash: shared, excludeSlug: 'notes/b-example', frontmatterId: 'fm-b' },
+ { hash: 'no-such-hash', frontmatterId: 'fm-c' },
+ { hash: 'no-such-hash', frontmatterId: 'fm-c', excludeSlug: 'notes/c-example' },
+ { hash: 'no-such-hash', frontmatterId: null },
+ { hash: hash['notes/gone-example']!, frontmatterId: 'fm-gone' },
+ { hash: 'no-such-hash', frontmatterId: 'q"u,o{t}e\\s' },
+ { hash: hash['notes/c-example']!, frontmatterId: 'fm-b', excludeSlug: '' },
+ ];
+ const batched = await engine.findDuplicatePages!(DUP, inputs);
+ const singles = await Promise.all(inputs.map(input => engine.findDuplicatePage!(DUP, input)));
+ expect(batched).toEqual(singles);
+ expect(batched.map(found => found?.slug ?? null)).toEqual(['notes/a-example', 'notes/b-example', 'notes/b-example', 'notes/a-example',
+ 'notes/c-example', null, null, null, 'notes/d-example', 'notes/b-example']);
+ expect(await engine.findDuplicatePages!(DUP, [])).toEqual([]);
+}
+
+/** A counting view of an engine, for the coalescing cases. */
+function counting(engine: BrainEngine, overrides: { findDuplicatePages?: BrainEngine['findDuplicatePages']; readPageSnapshotsBatch?: BrainEngine['readPageSnapshotsBatch'] } = {}) {
+ const calls = { batchSnapshots: 0, snapshots: 0, batchDuplicates: 0, duplicates: 0 };
+ const view = new Proxy(engine, { get(target, key) {
+ if (key === 'readPageSnapshotsBatch') return (...args: Parameters<BrainEngine['readPageSnapshotsBatch']>) => { calls.batchSnapshots++; return (overrides.readPageSnapshotsBatch ?? target.readPageSnapshotsBatch.bind(target))(...args); };
+ if (key === 'readPageSnapshot') return (...args: Parameters<BrainEngine['readPageSnapshot']>) => { calls.snapshots++; return target.readPageSnapshot(...args); };
+ if (key === 'findDuplicatePages') return (...args: Parameters<NonNullable<BrainEngine['findDuplicatePages']>>) => { calls.batchDuplicates++; return (overrides.findDuplicatePages ?? target.findDuplicatePages!.bind(target))(...args); };
+ if (key === 'findDuplicatePage') return (...args: Parameters<NonNullable<BrainEngine['findDuplicatePage']>>) => { calls.duplicates++; return target.findDuplicatePage!(...args); };
+ const value = Reflect.get(target, key, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ return { view, calls };
+}
+
+/** A group's members get their single-read answers from one snapshot batch and one duplicate statement; a failed batch falls back to each member's own read. */
+export async function importGroupReadsCoalesce(engine: BrainEngine) {
+ const hash = await seedDuplicates(engine);
+ const rows = ['notes/a-example', 'notes/c-example', 'notes/missing-example'].map(slug => ({ slug, source_id: DUP }));
+ const inputs = [{ hash: hash['notes/a-example']!, excludeSlug: 'notes/a-example' }, { hash: 'no-such-hash', frontmatterId: 'fm-c' }, { hash: 'no-such-hash', excludeSlug: 'notes/missing-example' }];
+ const expected = await Promise.all(inputs.map(input => engine.findDuplicatePage!(DUP, input)));
+ const expectedSnapshots = await Promise.all(rows.map(row => single(engine, { slug: row.slug, sourceId: DUP })));
+
+ const { view, calls } = counting(engine);
+ const reads = importGroupReads(view, rows);
+ const opts = { sourceId: DUP, includeDeleted: true };
+ expect(await Promise.all(rows.map(row => reads.snapshot(row.slug, opts)))).toEqual(expectedSnapshots);
+ expect(await Promise.all(inputs.map(input => reads.findDuplicate(DUP, input)))).toEqual(expected);
+ expect(calls).toEqual({ batchSnapshots: 1, snapshots: 0, batchDuplicates: 1, duplicates: 0 });
+ expect(reads.snapshot('notes/a-example', opts)).toBeUndefined();
+ expect(reads.snapshot('notes/c-example', { sourceId: DUP })).toBeUndefined();
+ expect(reads.snapshot('notes/c-example', { sourceId: DUP, includeDeleted: true, resolveAlias: true })).toBeUndefined();
+
+ const failing = counting(engine, { findDuplicatePages: async () => { throw new Error('batch failed'); }, readPageSnapshotsBatch: async () => { throw new Error('batch failed'); } });
+ const fallback = importGroupReads(failing.view, rows);
+ expect(await Promise.all(rows.map(row => fallback.snapshot(row.slug, opts)))).toEqual(expectedSnapshots);
+ expect(await Promise.all(inputs.map(input => fallback.findDuplicate(DUP, input)))).toEqual(expected);
+ expect(failing.calls).toEqual({ batchSnapshots: 1, snapshots: 3, batchDuplicates: 1, duplicates: 3 });
+
+ const partial = counting(engine);
+ const late = importGroupReads(partial.view, rows);
+ expect(await late.findDuplicate(DUP, inputs[1]!)).toEqual(expected[1]!);
+ expect(partial.calls.duplicates).toBe(1);
+}
diff --git a/test/helpers/page-snapshot-batch-cases.ts b/test/helpers/page-snapshot-batch-cases.ts
index b97fe6977e..faaf1cb1d8 100644
--- a/test/helpers/page-snapshot-batch-cases.ts
+++ b/test/helpers/page-snapshot-batch-cases.ts
@@ -5,13 +5,13 @@ import type { BrainEngine } from '../../src/core/engine.ts';
import { normalizeLoweredClaim } from '../../src/core/facts/withdrawal-schema.ts';
import { pageSnapshotKey } from '../../src/core/page-snapshot-batch.ts';
-const OTHER = 'snapshot-batch-example';
-const FENCE = '<!--- gbrain:facts:begin -->\n| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n'
+export const OTHER = 'snapshot-batch-example';
+export const FENCE = '<!--- gbrain:facts:begin -->\n| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n'
+ '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|\n'
+ '| 1 | Ships Weekly | fact | 1.0 | world | high | 2026-01-01 | | remember | |\n'
+ '| 2 | Hires slowly | fact | 1.0 | world | high | 2026-01-01 | | remember | |\n<!--- gbrain:facts:end -->';
-async function seed(engine: BrainEngine) {
+export async function seed(engine: BrainEngine) {
if ((await engine.executeRaw('SELECT 1 FROM sources WHERE id=$1', [OTHER])).length) return;
await engine.executeRaw('INSERT INTO sources(id,name) VALUES ($1,$1)', [OTHER]);
await engine.putPage('people/alice-example', { type: 'person', title: 'Alice', compiled_truth: `Alice.\n\n${FENCE}`, timeline: '- **2026-01-02** | call — Met' });
@@ -25,7 +25,7 @@ async function seed(engine: BrainEngine) {
[createHash('sha256').update(normalizeLoweredClaim('ships weekly')).digest('hex')]);
}
-const REFS = [
+export const REFS = [
{ slug: 'people/alice-example', sourceId: 'default' },
{ slug: 'companies/acme-example', sourceId: 'default' },
{ slug: 'people/alice-example', sourceId: OTHER },
@@ -67,11 +67,11 @@ export async function pageSnapshotBatchRespectsByteBudget(engine: BrainEngine) {
expect((await engine.readPageSnapshotsBatch([])).covered).toBe(0);
}
-const PURGED = 'snapshot-batch-purge-example';
+export const PURGED = 'snapshot-batch-purge-example';
const claimHash = (claim: string) => createHash('sha256').update(normalizeLoweredClaim(claim)).digest('hex');
/** Page-subject purges and the source's '*' purge marker overlay batched bodies exactly as the per-page read does. */
-export async function pageSnapshotBatchMatchesPurgedReads(engine: BrainEngine) {
+export async function seedPurged(engine: BrainEngine) {
if (!(await engine.executeRaw('SELECT 1 FROM sources WHERE id=$1', [PURGED])).length) {
await engine.executeRaw('INSERT INTO sources(id,name) VALUES ($1,$1)', [PURGED]);
await engine.putPage('people/carol-example', { type: 'person', title: 'Carol', compiled_truth: `Carol.\n\n${FENCE}`, timeline: '' }, { sourceId: PURGED });
@@ -81,6 +81,10 @@ export async function pageSnapshotBatchMatchesPurgedReads(engine: BrainEngine) {
await engine.executeRaw(purge, [PURGED, 'people/carol-example', claimHash('hires slowly'), '00000000-0000-4000-8000-000000000001']);
await engine.executeRaw(purge, [PURGED, '*', claimHash('ships weekly'), '00000000-0000-4000-8000-000000000002']);
}
+}
+
+export async function pageSnapshotBatchMatchesPurgedReads(engine: BrainEngine) {
+ await seedPurged(engine);
const refs = ['people/carol-example', 'people/dave-example', 'notes/plain-example'].map(slug => ({ slug, sourceId: PURGED }));
const { snapshots, covered } = await engine.readPageSnapshotsBatch(refs);
expect(covered).toBe(refs.length);
diff --git a/test/import-reads.test.ts b/test/import-reads.test.ts
new file mode 100644
index 0000000000..268fbac8a1
--- /dev/null
+++ b/test/import-reads.test.ts
@@ -0,0 +1,21 @@
+/**
+ * GBRA-75 wave 10: the managed import's batched reads answer exactly what the
+ * single reads answer. Postgres arm: test/e2e/import-reads.test.ts.
+ */
+import { afterAll, beforeAll, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { findDuplicatePagesMatchesSingle, importGroupReadsCoalesce, importSnapshotsDropPurgedIncomingRows, importSnapshotsMatchSingleReads } from './helpers/import-reads-cases.ts';
+
+let engine: BrainEngine;
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+afterAll(async () => { await engine?.disconnect(); });
+
+test('batched import snapshots equal the includeDeleted single reads, deleted, missing and purged pages included', () => importSnapshotsMatchSingleReads(engine));
+test('an incoming file drops page-subject and \'*\' purged rows through the batched snapshot as through the single read', () => importSnapshotsDropPurgedIncomingRows(engine));
+test('findDuplicatePages answers each input as findDuplicatePage does', () => findDuplicatePagesMatchesSingle(engine));
+test('an import group coalesces its members\' reads and falls back to single reads when a batch fails', () => importGroupReadsCoalesce(engine));