Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

G3.1 #6511: page purge journal lookup runs at preparation; in-transaction timeouts are terminal purge_lookup_timeout

garrytandb9c8c08a634
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index afe6cf4f41..d7f4c5bff3 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -45,7 +45,8 @@ link it here rather than raising the cap.
| [Core Minions (1/2)](key-files/core-minions-1.md) | `src/core/minions/` through `src/core/minions/rss-default.ts` |
| [Core Minions (2/2)](key-files/core-minions-2.md) | `src/core/minions/run-child.ts` through `src/core/minions/worker.ts` |
| [Core Persistence](key-files/core-persistence.md) | `src/core/persistence/` write journal, coordinator, effects, canonical projections and managed sync |
-| [Core Persistence (continued)](key-files/core-persistence-continued.md) | `worktree-refresh*.ts`, `persistence/connector-*.ts`, `connectors/item-holds*.ts`, checkpoint validation, no-op kernel, accepted-pending receipts, verb types/errors, attribution, purge-deleted, fact retirement, sync orphans |
+| [Core Persistence (continued)](key-files/core-persistence-continued.md) | `worktree-refresh*.ts`, `persistence/connector-*.ts`, `connectors/item-holds*.ts`, no-op kernel, accepted-pending receipts, verb types/errors, attribution, purge-deleted, fact retirement, sync orphans |
+| [Core Persistence (request indexes and fault seams)](key-files/core-persistence-request-indexes.md) | `checkpoint-validation.ts` (`readRequestIndexStates`, the checkpoint timeout hint), `fault-points.ts` (`faultPoint`, `installFaultHook`, the `purge:*` seams) |
| [Core Persistence (engine graduation)](key-files/core-persistence-graduation.md) | `engine-graduation*.ts`, `graduation-*.ts`, `src/commands/migrate-graduation.ts`, its doctor finding |
| [Managed sync and persistence stalls](key-files/persistence-stalls.md) | preparation budgets, `claim-phase.ts`, `consumer.ts`, `group-publish.ts`, `journal.ts`, `diagnostics.ts`, `worktree-manifest.ts` |
| [Core Search (1/2)](key-files/core-search-1.md) | `src/core/search/` through `src/core/search/read-policy-sql.ts` |
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.md
index 177f870aa1..c3eb995c63 100644
--- a/docs/architecture/key-files/core-persistence-continued.md
+++ b/docs/architecture/key-files/core-persistence-continued.md
@@ -2,7 +2,7 @@
[Subsystem index](../KEY_FILES.md) · [Previous entries](core-persistence.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-Managed connector ingestion, connector item holds, sync checkpoint validation and the no-op kernel. Also the persistence verb types and errors, database-write and manual links, write attribution, purge-deleted and loop-fact retirement.
+Managed connector ingestion, connector item holds and the no-op kernel (checkpoint validation and the fault seams: [request indexes and fault seams](core-persistence-request-indexes.md)). Also the persistence verb types and errors, database-write and manual links, write attribution, purge-deleted and loop-fact retirement.
- `src/core/persistence/{worktree-refresh,worktree-refresh-schema}.ts` — `gbrain sources refresh` (F0), the one sanctioned managed Git writer. `persistence_worktree_refreshes` holds one row per refresh with a partial unique index (one active refresh per worktree; its 23505 maps to `refresh_in_progress`). `refreshWorktree` prechecks with no database state (managed, owner host, upstream, no active refresh, no recovery, no unexhausted managed-sync cursor, hardened `git fetch` bounded by `sources.refresh_fetch_timeout_ms`, ancestry, dirty paths intersected with the incoming diff), then: `draining` (inserted under `withTopologyLocks` + `lockTopologyRows`; admission in `journal.ts` refuses `worktree_refreshing` for every request with that `worktree_id`, and `assertManagedSyncAllowed` refuses a managed sync before discovery), poll until no queued/running/recovering request, no queued/running `git`/`withdrawal-mirror` effect and no recovery record remain (else `refresh_drain_timeout`, aborted), `fenced` (both native locks held, rechecked in one transaction; `refreshFenceClear` stops request and effect claims), HEAD verified, dirt rechecked, `git merge --ff-only`, HEAD verified again, then one transaction `merged` + upstream observation + `syncing`; native locks are released and the managed `--no-pull` sync runs per member (only `managed_sync_*` `submit_job` admissions pass during `syncing`); `completed` when every member's `last_commit` is the target, or with `outcome.sync_blocked` when a member sync blocks. A per-worktree `refresh-<worktree>.lock` held for the whole run proves liveness: `resumeWorktreeRefreshes` (called from `recoverSourceTopologies`, so on owner start) touches only interrupted `draining`/`fenced`/`merged` rows whose lock is free and applies the section 1.5 table (draining or fenced at the old HEAD abort; HEAD at the verified target moves to `syncing`; anything else is `recovery_required`, which admission refuses with `refresh_recovery_required`). Admission also completes a `syncing` row whose members all reached the target. `--resume` converges and runs the member syncs; `--abandon` lifts a fence only with HEAD back at the start commit. `gbrain sources writer status` lists active refreshes as `worktree_refreshes` (state, heads, the next command), which the refusal hints point at. Doctor `worktree_refresh_stuck` lists rows active over 15 minutes. CLI body: `src/commands/sources-refresh.ts`; while a resident PGLite owner (`gbrain serve`, stdio MCP) holds the database, `src/commands/sources-refresh-delegate.ts` runs the refresh inside it through the `writer_refresh` administration operation (trusted CLI registration only) and prints the same result or refusal. The consumer's idle probe applies `refreshFenceClear` to effects like the claims, so a fenced worktree's queued effects do not wake it. Tests: `test/persistence-worktree-refresh.test.ts`, `test/persistence-worktree-refresh-restart.test.ts` (child-process crash after merge), Postgres via `test/e2e/worktree-refresh-postgres.test.ts`, owner delegation in `test/persistence-sync-stdio-owner.test.ts`.
@@ -34,14 +34,12 @@ Managed connector ingestion, connector item holds, sync checkpoint validation an
- `src/core/connectors/connector-text.ts` — #5752 render boundary: prose sanitized with `sanitizeForJsonb` before the no-op screen; identity fields refuse with `invalid_connector_text`.
- `src/core/persistence/connector-account.ts` — resolves the credential's account before any service runs: Google through Gmail profile, Calendar primary calendar or People `me` (first enabled service that answers; none refuses), GitHub App installation id from the minted token, or the `/user` login for token auth under `scope: auto`.
- `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.
- `src/core/persistence/connector-checkpoint-migration.ts` — migration 176 and orphan cleanup. The newest committed checkpoint receipt per source incarnation (found by slug, so a compacted one is still seen and re-walks) is copied to the stable key with `INSERT … ON CONFLICT DO NOTHING`; state rows are seeded; the cutoff is stored in `op_checkpoints` (`op=managed-connector-migration`, fingerprint `v2-cutoff`, excluded from the checkpoint purge). `orphanConnectorCheckpoints` keeps rows touched after the start, rows any registered source (archived included) can load, and rows referenced by a non-terminal request or a pending set; timestamps bind as text. `gbrain repair connector-checkpoints` (`src/core/repair/connector-checkpoints.ts`) and the `connector_checkpoints` doctor check reuse it with a 7-day floor. `connector-reset.ts` guards `gbrain sync --reset-checkpoint` to connector sources.
-- `src/core/persistence/fault-points.ts` — named crash seams for the persistence gate. `faultPoint(point, detail)` is a no-op unless a gate worker installed a hook with `installFaultHook`; production never does. Seams: `publication:<boundary>` (the five `PublicationHooks.boundary` names, routed through `withFaultPoints` in `publishMutation`), `effect:<kind>:mid` for every `EffectKind` in `completeEffect` (after the side effect, before its completion is recorded; `EFFECT_FAULT_POINTS` is a `Record<EffectKind, FaultPoint>`), `effect_recovery:before_clear` (`effect-recovery.ts`), `publication_recovery:before_clear` (`recoverPublication`), `sync:mid_checkpoint` (after each committed cursor step in `sync-run.ts` `saveCursor`) and `consumer:prepared` (between preparing a claimed request and publishing it). Used by `scripts/persistence/crash-robot.ts`.
- `src/core/persistence/graduation-target.ts` — engine graduation target side. `resolveTargetRoutes` reads the URL from `--url` or the `--url-env` variable and resolves the DDL route once (explicit `GBRAIN_DIRECT_DATABASE_URL`, else the Supabase direct derivation, else the main URL); `connectTargetEngines` hands that route to the connection manager as an explicit override, so no session-pooler fallback is chosen for the run. `targetIdentity` hashes host, port, database and user, never the password; `redactTargetUrl` is the only display form. `probeTarget` runs read-only probes in `BEGIN READ ONLY` sessions on both routes (server version, `vector` with halfvec, CREATE privilege, `session_replication_role` permission inside a savepoint, table ownership, seed-only emptiness, existing embedding columns, the role's superuser and BYPASSRLS standing and the auto-RLS event trigger and its function owner); `targetProbeBlockers` (non-superuser targets get the exact SQL a DBA runs for `vector`, BYPASSRLS and the event trigger) and `assertTargetReachable` turn a probe into plan blockers and typed refusals. `crossCheckRoutes` proves both routes reach one database with a transaction-scoped advisory lock keyed by a fresh nonce, read back from `pg_locks` through the other route. Tests: `test/graduation-target.test.ts`.
- `src/core/persistence/graduation-drain.ts` — engine graduation drain. `graduationBlockers` lists what keeps a brain from copying, each with its structured action: requests this host owns (drained), requests and host bindings owned by another host, recovering topology changes and effects, the writer admin lock, and OAuth clients bound to a missing source (an FK only Postgres enforces; never cleared silently, since unbinding widens access). `drainForGraduation` refuses up front on anything the drain cannot clear, then publishes this host's queued, running and recovering requests with a `requestsOnly` `PersistenceConsumer` bounded by the timeout and always runs its stop barrier before returning; the `graduation_drain_timeout` refusal is built by `graduation-errors.ts`. `freezeSource` stops the resident consumer and sets the PGLite connection to read-only transactions; `withSourceWritable` runs one read-write transaction for custody writes. Tests: `test/graduation-drain.test.ts`.
- `src/core/persistence/graduation-copy.ts` — engine graduation copier (in process). `copyTable` reads source rows through the digest's own plan (`digestPlan` with inventory transforms, `rowFilter`, `::text` values, COLLATE "C" keyset batches) and writes them in one target transaction per table that sets `gbrain.graduation_run`, bypasses user triggers (`session_replication_role = replica`, or DISABLE/ENABLE TRIGGER by name in the same transaction, never the `gbrain_graduation_fence` triggers), deletes the target's rows (seed rows included) and inserts byte-sized batches as one `$1::text::jsonb` array cast back per column type. The per-column contract (`columnContract`) refuses missing, retyped, target-only or differently generated columns outside the entry's `columnAllowlist`; generated columns are never inserted. Self-FKs take a second update pass under DISABLE TRIGGER. `copySequences` applies each source sequence's exact position, raised to the target column maximum. `deferIndexes`/`buildDeferredIndexes` drop and rebuild HNSW (through `buildDeferredAnnIndexes`) and GIN indexes, keeping the pending list in the target-owned `graduation.deferred_indexes` config row. Tests: `test/graduation-copy.test.ts`, `test/e2e/graduation-copy.test.ts`.
diff --git a/docs/architecture/key-files/core-persistence-request-indexes.md b/docs/architecture/key-files/core-persistence-request-indexes.md
new file mode 100644
index 0000000000..33a343f356
--- /dev/null
+++ b/docs/architecture/key-files/core-persistence-request-indexes.md
@@ -0,0 +1,8 @@
+# Key files: Core Persistence (request indexes and fault seams)
+
+[Subsystem index](../KEY_FILES.md) · [Core Persistence](core-persistence.md) · [continued](core-persistence-continued.md). Read only the entries relevant to your change.
+Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
+The online-built request-table indexes (the managed sync checkpoint pair, the page purge's slug index), the checkpoint validation they serve, and the named fault seams the persistence gate and the purge tests inject at.
+
+- `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 of `PERSISTENCE_REQUEST_ONLINE_INDEXES` (or the list passed) 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/fault-points.ts` — named crash seams for the persistence gate. `faultPoint(point, detail)` is a no-op unless a gate worker installed a hook with `installFaultHook`; production never does. Seams: `publication:<boundary>` (the five `PublicationHooks.boundary` names, routed through `withFaultPoints` in `publishMutation`), `effect:<kind>:mid` for every `EffectKind` in `completeEffect` (after the side effect, before its completion is recorded; `EFFECT_FAULT_POINTS` is a `Record<EffectKind, FaultPoint>`), `effect_recovery:before_clear` (`effect-recovery.ts`), `publication_recovery:before_clear` (`recoverPublication`), `sync:mid_checkpoint` (after each committed cursor step in `sync-run.ts` `saveCursor`) `consumer:prepared` (between preparing a claimed request and publishing it) and the purge lookups `purge:*` (page-purge.ts, intent-redaction.ts, facts/purge.ts; a hook throwing a 57014 models a statement timeout). Used by `scripts/persistence/crash-robot.ts` and the #6511 tests.
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.md
index a47fe5ebc3..8729ee37ae 100644
--- a/docs/architecture/key-files/core-utilities-2.md
+++ b/docs/architecture/key-files/core-utilities-2.md
@@ -4,7 +4,7 @@ Memory trust tiers and read eligibility (#5575, the trust and eligibility direct
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `src/core/repair/` — `gbrain repair` core. `core.ts`: `resolveRepairScope` (default every active source; prints brain and source ids), `runRepair` (dry run unless `apply`; each item is one revision-bound `put_page` with a deterministic request id (replayed while pending, a new attempt id after a terminal failure), re-decided against current state just before it is applied; a cursor in `op_checkpoints` keyed by kind + scope resumes an interrupted or `--limit` run and is cleared when a scan completes; the same row carries the run id (written before the first applied item and passed to `apply` as `runId`), so a resumed run keeps the id that any authorization it granted is bound to; a kind may return a named per-item outcome (`RepairItemOutcome`), tallied in `outcomes` and `outcome_items`; a `spends: 'llm'` kind's plan reports `llm` (its paid-model estimate, null for an unpriced model under a user-set cap, and what is left under its own daily cap), and its result's `cost` adds `llm_usd` (the estimate on a dry run, the actual spend summed from each item's `llm_usd` on an apply) and `llm_cap_remaining_usd` (the smaller of the daily cap and the run allowance, less the spend), keys other kinds never carry; `maxLlmUsd` is the run's paid-model allowance: each item's `apply` gets what is left as `llmAllowanceUsd`, and once it is used up, or an item's own `llm_usd` estimate exceeds what is left, the run stops `budget_exhausted` before that item, naming spent and allowance, and rerunning the apply command resumes it (a dry run sums the per-item estimates of the items it would apply, so `--limit` lowers it); the core opens no budget tracker; `deadline` (epoch ms) stops the run with `time_budget` before the next item; an item outcome's `stop` ends the run after that item with its reason, message and fix; a kind's `report` hook adds `repaired`, `remaining`, `verification` (or refines `stopped`) once the run ends, and a plan's `scan` is copied to the result; stops before crossing 90% of the brain or principal lifetime-ID / receipt-byte caps with the `gbrain config set` value that finishes; a held writer stops with `gbrain sources writer status <source>`). `timeline.ts`: `scanTimelineHistory` (bounded id-order scan shared with the doctor; one stored-row read per page batch for the retraction check) and the materialize kind. `visibility.ts`: `planVisibilityRepair`, the tighten-only atom/concept backfill (atoms from `effectiveVisibility` of their origin, concepts from the strictest input over provenance edges and atoms' `concepts:`; no-lineage concepts are counted and left alone). `safe-chunks.ts`: a `publication: 'projection'` kind (no admission, zero lifetime-ID and receipt cost, no capacity stop) that re-seals markdown and code pages below the safe-chunk fence through `resealSafeChunks`, then embeds their NULL chunks unless `--no-embed`; code pages without a recorded path and other page kinds are residuals. The pending count is reported only by the doctor check `safe_index_pending`, which the post-upgrade recovery banner uses. `contextual-mode.ts`: a `publication: 'projection'` kind (#5621) that stamps `contextual_retrieval_mode` + `corpus_generation` on sealed live markdown pages with a NULL mode through `resolveImportContextualMode` (`src/core/import-contextual-mode.ts`, the resolver `importFromContent` also uses, strict source-row read), then under the page guard clears only vectors whose recorded embedding input the stamped convention no longer accepts (the #5553 rule) and re-embeds that page once unless `--no-embed`; unsealed pages are the `unsealed_projection` residual. `connector-checkpoints.ts`: a `publication: 'projection'` bookkeeping kind (#5686, `embeds: false`) that deletes connector checkpoint rows and retry pointers no registered source can load and that are older than 7 days, keeping rows a non-terminal request or recorded pending set references; brain-wide. `request-indexes.ts`: a `publication: 'projection'` brain-wide kind (#5762, `embeds: false`) that builds a missing managed sync request index or drops an INVALID one and rebuilds it through `buildIndexOnline` (`src/core/schema-migrations/helpers.ts`: CONCURRENTLY on Postgres under the session's startup timeouts with no session SET, inline on PGLite, the result re-checked for validity, an index another session is still building is left alone); it clears `persistence_request_indexes`. `orphan-bindings.ts`: a projection bookkeeping kind (#5732) over `persistence/orphan-bindings.ts` that deletes persistence source bindings of a removed source or an earlier incarnation, brain-wide, keeping one a pending request of that incarnation references. `embedding-effects.ts`: a projection kind (#5629/#5734, `embeds: 'effect'`) over `persistence/embedding-settlement.ts`; each stale queued or failed embedding effect of a committed write is `reconciled` (the effect projection verifier passes), `superseded` (page deleted, or a newer revision of the same page owns its own effect), `retry_queued` (stale queued re-queued for the owner; failed granted the retry-effects allowance; an exhausted allowance gets one new bounded cycle under `embeddingGrantId(runId, effect)`, which a resumed run replays) or `blocked` with a reason; every change is a compare-and-set on state, attempts, execution token and recovery, and a changed candidate is `changed_since_preview`. Retry items count the whole retry budget in the embedding estimate. `registry.ts`: `REPAIR_REGISTRY` (one entry per `REPAIR_KINDS` name in `--all` order: handler, help summary, `embeds` — `effect` when the publication's embedding effect re-embeds each page outside the run, `inline` when the kind embeds in-process and honors `--no-embed`, `none` for bookkeeping kinds — `spends: 'llm'` for a kind that may call a paid chat model, and the doctor `checks` it clears), `repairMayEmbed` (embedding spend under the flags) and `repairMaySpend` (that or `spends: 'llm'`), `repairForCheck`, `repairApplyCommand` and `repairRunner`, the one trusted local runner that both `gbrain repair` and doctor remediation use (an applying runner resolves the CLI write wait once, before any kind runs, and puts it on the ctx as `writeWaitMs`, so every publication waits like other CLI writes and a malformed `GBRAIN_WRITE_WAIT_MS` refuses before a checkpoint; a preview never reads it) (its `run` takes `maxLlmUsd`; `repairRunner` and `repairSpec` take an optional `registry` of stub specs for tests, and production callers use the registered kinds); a new kind plugs in by adding its name to `REPAIR_KINDS` and one registry entry. A kind with `explicit_only` (`stale-atoms`, `extractor-facts`; the `extractor-facts.ts` stub refuses with `unavailable` until its fix wave 5 lane lands) runs only when named: `AUTO_REPAIR_REGISTRY` is the `--all`, no-kind and remediation set, `explicitRepairNotices` lists the rest as `explicit_kind_required` with `repairPreviewCommand`, and `runRepair` refuses an unnamed explicit-only kind (`explicitKindRequired`), so a supplied remediation step cannot run one. Explicit-only kinds and kinds with `preview_bound` (`fences`, which is not explicit-only and so also runs from `--all`, the remediation run and the maintenance cycle with a bare `--apply`) accept `--expect <hash>`; only explicit-only kinds accept `--include-ambiguous`; `--only`/`--skip`/`--slug` selections, `--no-llm` and `--max-usd` (only `spends: 'llm'` kinds; it only lowers their cap) are passed to `plan` as `RepairPlanOptions` and printed in the apply command; a plan's `preview_hash` is appended to its apply command, and its `listing` (every previewed item with its class) is printed by the dry run. `stale-atoms.ts` (#5770): live page-bound atoms (never `imported_from`, never `source_path`-only) whose source page is gone (`origin_gone`) or whose stripped 16-character `source_hash` differs from a source page that already completed an extraction at its current hash (`origin_changed`; managed evidence is the completed `managed-atoms` checkpoint via `managedAtomCompletedSql`, unmanaged evidence a non-managed atom at that hash). The preview saves the set with `saveApprovedSet`; `--apply --expect <hash>` loads it (`preview_changed` otherwise; `--apply` alone refuses with the filled commands), rechecks each atom (revision, class, origin, evidence) and reports `retired`, `changed_since_preview` or `file_conflict` (an uncoordinated edit of the atom file; its attempt-aware `repairRequestId` lets a later apply retry once the file is fixed). An approved set applies only under the source selection it was previewed with, and the apply's resume cursor is keyed by its approval hash. Managed brains admit one `managed_maintenance_retire_stale_atoms` request per atom bound to its revision (`prepareStaleAtomRetirement`, rechecked under the atom and origin page locks, no live origin needed); unmanaged brains soft-delete in one locked transaction. Both stamp `retired_by: stale-atoms`/`retired_at` and bump the origin page's `managed-atoms-generation` (clearing its page state and completed checkpoints, keeping the current hash for `origin_changed`), so a restored page is extracted again and `publishManagedAtoms` restores the retired atoms. Tests: `test/repair-explicit-only.test.ts`, `test/repair-stale-atoms.test.ts` and `test/journey-atoms-sync-race.test.ts` (PGLite and Postgres). Tests: `test/repair-command.test.ts`, `test/derived-visibility-repair.test.ts`, `test/safe-chunk-reseal.test.ts` (PGLite and Postgres), `test/repair-contextual-mode-5621.serial.test.ts` (PGLite and Postgres), `test/repair-flags.test.ts`, `test/persistence-request-indexes.test.ts`. `attribution-backfill.ts` (Foundations 1, F1b): an automatic `publication: 'projection'` bookkeeping kind (`embeds: 'none'`, no doctor check) that fills NULL write attribution only where exactly one committed request proves it: `pages.revision_*` and `page_versions.write_*` from the page mutation (or fenced `remember`) whose `outcome.revision` is the row's `knowledge_revision` (skipped, duplicate and observe-only requests prove nothing), and `facts.write_*` from the `remember` whose `outcome.id` names the fact with status `inserted` or `superseded`. The preview proofs and each batch run inside a short transaction with `enable_nestloop` off (the journal join on the outcome key has no index, and fresh attribution columns have no statistics), restoring the caller's setting before it ends. Items are batches of up to 1,000 ids per table in (table, id) cursor order; each batch re-runs the proof under `lockPageKeys` for its pages and commits on its own, so an interrupted run resumes after the last committed batch. Unproven NULL rows are the `unrecorded_<table>` residuals. Test: `test/write-attribution-read.test.ts`. `google-file-modes.ts`: an explicit-only (`explicit_only: true`), `publication: 'projection'` filesystem-only kind (`embeds: false`, no admission, no request ids) that plans one item per loose entry from `scanGoogleFileModes` (cursor phase = source index; the item carries root, relative path, kind and old mode) and applies `tightenGoogleEntry` (outcomes `tightened`, `already_private`, `skipped` with a reason); symlink, foreign-owner and wrong-type entries are `skipped_*` residuals. It is last in `REPAIR_KINDS`, so `--all` runs it after `embedding-effects`; registry check `google_file_modes`. Every run re-scans, so a rerun after `--limit` picks up exactly what is still loose.
+- `src/core/repair/` — `gbrain repair` core. `core.ts`: `resolveRepairScope` (default every active source; prints brain and source ids), `runRepair` (dry run unless `apply`; each item is one revision-bound `put_page` with a deterministic request id (replayed while pending, a new attempt id after a terminal failure), re-decided against current state just before it is applied; a cursor in `op_checkpoints` keyed by kind + scope resumes an interrupted or `--limit` run and is cleared when a scan completes; the same row carries the run id (written before the first applied item and passed to `apply` as `runId`), so a resumed run keeps the id that any authorization it granted is bound to; a kind may return a named per-item outcome (`RepairItemOutcome`), tallied in `outcomes` and `outcome_items`; a `spends: 'llm'` kind's plan reports `llm` (its paid-model estimate, null for an unpriced model under a user-set cap, and what is left under its own daily cap), and its result's `cost` adds `llm_usd` (the estimate on a dry run, the actual spend summed from each item's `llm_usd` on an apply) and `llm_cap_remaining_usd` (the smaller of the daily cap and the run allowance, less the spend), keys other kinds never carry; `maxLlmUsd` is the run's paid-model allowance: each item's `apply` gets what is left as `llmAllowanceUsd`, and once it is used up, or an item's own `llm_usd` estimate exceeds what is left, the run stops `budget_exhausted` before that item, naming spent and allowance, and rerunning the apply command resumes it (a dry run sums the per-item estimates of the items it would apply, so `--limit` lowers it); the core opens no budget tracker; `deadline` (epoch ms) stops the run with `time_budget` before the next item; an item outcome's `stop` ends the run after that item with its reason, message and fix; a kind's `report` hook adds `repaired`, `remaining`, `verification` (or refines `stopped`) once the run ends, and a plan's `scan` is copied to the result; stops before crossing 90% of the brain or principal lifetime-ID / receipt-byte caps with the `gbrain config set` value that finishes; a held writer stops with `gbrain sources writer status <source>`). `timeline.ts`: `scanTimelineHistory` (bounded id-order scan shared with the doctor; one stored-row read per page batch for the retraction check) and the materialize kind. `visibility.ts`: `planVisibilityRepair`, the tighten-only atom/concept backfill (atoms from `effectiveVisibility` of their origin, concepts from the strictest input over provenance edges and atoms' `concepts:`; no-lineage concepts are counted and left alone). `safe-chunks.ts`: a `publication: 'projection'` kind (no admission, zero lifetime-ID and receipt cost, no capacity stop) that re-seals markdown and code pages below the safe-chunk fence through `resealSafeChunks`, then embeds their NULL chunks unless `--no-embed`; code pages without a recorded path and other page kinds are residuals. The pending count is reported only by the doctor check `safe_index_pending`, which the post-upgrade recovery banner uses. `contextual-mode.ts`: a `publication: 'projection'` kind (#5621) that stamps `contextual_retrieval_mode` + `corpus_generation` on sealed live markdown pages with a NULL mode through `resolveImportContextualMode` (`src/core/import-contextual-mode.ts`, the resolver `importFromContent` also uses, strict source-row read), then under the page guard clears only vectors whose recorded embedding input the stamped convention no longer accepts (the #5553 rule) and re-embeds that page once unless `--no-embed`; unsealed pages are the `unsealed_projection` residual. `connector-checkpoints.ts`: a `publication: 'projection'` bookkeeping kind (#5686, `embeds: false`) that deletes connector checkpoint rows and retry pointers no registered source can load and that are older than 7 days, keeping rows a non-terminal request or recorded pending set references; brain-wide. `request-indexes.ts`: a `publication: 'projection'` brain-wide kind (#5762, `embeds: false`) that builds a missing online-built request index (`PERSISTENCE_REQUEST_ONLINE_INDEXES`: the managed sync checkpoint pair and the page purge's slug index) or drops an INVALID one and rebuilds it through `buildIndexOnline` (`src/core/schema-migrations/helpers.ts`: CONCURRENTLY on Postgres under the session's startup timeouts with no session SET, inline on PGLite, the result re-checked for validity, an index another session is still building is left alone); it clears `persistence_request_indexes`. `orphan-bindings.ts`: a projection bookkeeping kind (#5732) over `persistence/orphan-bindings.ts` that deletes persistence source bindings of a removed source or an earlier incarnation, brain-wide, keeping one a pending request of that incarnation references. `embedding-effects.ts`: a projection kind (#5629/#5734, `embeds: 'effect'`) over `persistence/embedding-settlement.ts`; each stale queued or failed embedding effect of a committed write is `reconciled` (the effect projection verifier passes), `superseded` (page deleted, or a newer revision of the same page owns its own effect), `retry_queued` (stale queued re-queued for the owner; failed granted the retry-effects allowance; an exhausted allowance gets one new bounded cycle under `embeddingGrantId(runId, effect)`, which a resumed run replays) or `blocked` with a reason; every change is a compare-and-set on state, attempts, execution token and recovery, and a changed candidate is `changed_since_preview`. Retry items count the whole retry budget in the embedding estimate. `registry.ts`: `REPAIR_REGISTRY` (one entry per `REPAIR_KINDS` name in `--all` order: handler, help summary, `embeds` — `effect` when the publication's embedding effect re-embeds each page outside the run, `inline` when the kind embeds in-process and honors `--no-embed`, `none` for bookkeeping kinds — `spends: 'llm'` for a kind that may call a paid chat model, and the doctor `checks` it clears), `repairMayEmbed` (embedding spend under the flags) and `repairMaySpend` (that or `spends: 'llm'`), `repairForCheck`, `repairApplyCommand` and `repairRunner`, the one trusted local runner that both `gbrain repair` and doctor remediation use (an applying runner resolves the CLI write wait once, before any kind runs, and puts it on the ctx as `writeWaitMs`, so every publication waits like other CLI writes and a malformed `GBRAIN_WRITE_WAIT_MS` refuses before a checkpoint; a preview never reads it) (its `run` takes `maxLlmUsd`; `repairRunner` and `repairSpec` take an optional `registry` of stub specs for tests, and production callers use the registered kinds); a new kind plugs in by adding its name to `REPAIR_KINDS` and one registry entry. A kind with `explicit_only` (`stale-atoms`, `extractor-facts`; the `extractor-facts.ts` stub refuses with `unavailable` until its fix wave 5 lane lands) runs only when named: `AUTO_REPAIR_REGISTRY` is the `--all`, no-kind and remediation set, `explicitRepairNotices` lists the rest as `explicit_kind_required` with `repairPreviewCommand`, and `runRepair` refuses an unnamed explicit-only kind (`explicitKindRequired`), so a supplied remediation step cannot run one. Explicit-only kinds and kinds with `preview_bound` (`fences`, which is not explicit-only and so also runs from `--all`, the remediation run and the maintenance cycle with a bare `--apply`) accept `--expect <hash>`; only explicit-only kinds accept `--include-ambiguous`; `--only`/`--skip`/`--slug` selections, `--no-llm` and `--max-usd` (only `spends: 'llm'` kinds; it only lowers their cap) are passed to `plan` as `RepairPlanOptions` and printed in the apply command; a plan's `preview_hash` is appended to its apply command, and its `listing` (every previewed item with its class) is printed by the dry run. `stale-atoms.ts` (#5770): live page-bound atoms (never `imported_from`, never `source_path`-only) whose source page is gone (`origin_gone`) or whose stripped 16-character `source_hash` differs from a source page that already completed an extraction at its current hash (`origin_changed`; managed evidence is the completed `managed-atoms` checkpoint via `managedAtomCompletedSql`, unmanaged evidence a non-managed atom at that hash). The preview saves the set with `saveApprovedSet`; `--apply --expect <hash>` loads it (`preview_changed` otherwise; `--apply` alone refuses with the filled commands), rechecks each atom (revision, class, origin, evidence) and reports `retired`, `changed_since_preview` or `file_conflict` (an uncoordinated edit of the atom file; its attempt-aware `repairRequestId` lets a later apply retry once the file is fixed). An approved set applies only under the source selection it was previewed with, and the apply's resume cursor is keyed by its approval hash. Managed brains admit one `managed_maintenance_retire_stale_atoms` request per atom bound to its revision (`prepareStaleAtomRetirement`, rechecked under the atom and origin page locks, no live origin needed); unmanaged brains soft-delete in one locked transaction. Both stamp `retired_by: stale-atoms`/`retired_at` and bump the origin page's `managed-atoms-generation` (clearing its page state and completed checkpoints, keeping the current hash for `origin_changed`), so a restored page is extracted again and `publishManagedAtoms` restores the retired atoms. Tests: `test/repair-explicit-only.test.ts`, `test/repair-stale-atoms.test.ts` and `test/journey-atoms-sync-race.test.ts` (PGLite and Postgres). Tests: `test/repair-command.test.ts`, `test/derived-visibility-repair.test.ts`, `test/safe-chunk-reseal.test.ts` (PGLite and Postgres), `test/repair-contextual-mode-5621.serial.test.ts` (PGLite and Postgres), `test/repair-flags.test.ts`, `test/persistence-request-indexes.test.ts`. `attribution-backfill.ts` (Foundations 1, F1b): an automatic `publication: 'projection'` bookkeeping kind (`embeds: 'none'`, no doctor check) that fills NULL write attribution only where exactly one committed request proves it: `pages.revision_*` and `page_versions.write_*` from the page mutation (or fenced `remember`) whose `outcome.revision` is the row's `knowledge_revision` (skipped, duplicate and observe-only requests prove nothing), and `facts.write_*` from the `remember` whose `outcome.id` names the fact with status `inserted` or `superseded`. The preview proofs and each batch run inside a short transaction with `enable_nestloop` off (the journal join on the outcome key has no index, and fresh attribution columns have no statistics), restoring the caller's setting before it ends. Items are batches of up to 1,000 ids per table in (table, id) cursor order; each batch re-runs the proof under `lockPageKeys` for its pages and commits on its own, so an interrupted run resumes after the last committed batch. Unproven NULL rows are the `unrecorded_<table>` residuals. Test: `test/write-attribution-read.test.ts`. `google-file-modes.ts`: an explicit-only (`explicit_only: true`), `publication: 'projection'` filesystem-only kind (`embeds: false`, no admission, no request ids) that plans one item per loose entry from `scanGoogleFileModes` (cursor phase = source index; the item carries root, relative path, kind and old mode) and applies `tightenGoogleEntry` (outcomes `tightened`, `already_private`, `skipped` with a reason); symlink, foreign-owner and wrong-type entries are `skipped_*` residuals. It is last in `REPAIR_KINDS`, so `--all` runs it after `embedding-effects`; registry check `google_file_modes`. Every run re-scans, so a rerun after `--limit` picks up exactly what is still loose.
- `src/core/rerank-audit.ts` — failure-only JSONL audit at `~/.gbrain/audit/rerank-failures-YYYY-Www.jsonl` (ISO-week rotation, mirrors `src/core/audit-slug-fallback.ts`). Exports `logRerankFailure({reason, model, query_hash, doc_count, error_summary})` + `readRecentRerankFailures(days)`. The `no_key` reason is written ONCE per process per model by the gateway itself (not per query by `applyReranker`): the provider key is absent, so calls are skipped without HTTP and results pass through unreranked; `auth` means key present but rejected; `unreachable` means no HTTP response at all (connection refused, DNS, reset; a stale `provider_base_urls` entry fails every call this way, Cat 40 R0), while `network` stays a provider 5xx. Deliberately no `logRerankSuccess`: writing once per tokenmax search is hot-path I/O churn AND success events leak query volume + timing into a local audit file. `gbrain doctor`'s `reranker_health` check (`doctor/checks/calibration.ts`) resolves enablement + model through `resolveSearchMode(loadSearchModeConfig)` — the plane search reranks with — and `rerankerReadiness` before reading the audit: readiness is evaluated against the DB-merged config plane (`loadConfigWithEngine`, so DB-plane provider keys and `provider_base_urls` self-host overrides count, exactly like the gateway the CLI configures): a brain with NO embedding provider (`isAvailable('embedding')` false on a configured gateway) is `ok` even when not ready — search runs keyword-only there and never reaches `applyReranker`, so there is nothing to fix; otherwise enabled-but-not-ready (key absent / unknown model) warns with the paste-ready fix; only audit rows for the RESOLVED model count (rows for any other model never make the live default warn or send the operator to verify the wrong key); `no_key` skip rows are informational once ready (those processes ran unreranked; a long-lived worker started before the key was added keeps skipping until restarted) and never outlive the fix as a warn; then the auth / payload / budget / unreachable (3+ rows: names the `provider_base_urls.<provider>` key) / transient / unknown ladders on the non-skip rows; disabled → ok (with an enable hint when the default is ready). Query text SHA-256-prefix-hashed (8 hex chars) for privacy. `GBRAIN_AUDIT_DIR` env override honored via the shared `resolveAuditDir()`.
- `src/core/repair/extractor-facts.ts` — `gbrain repair extractor-facts` (#5731), explicit-only and preview-bound. `classifyExtractorFacts` (read-only; also the doctor check's count) takes conversation-extractor facts with `expired_at` set and `row_num` NULL and classes each: `excluded` (page missing or deleted, `superseded_by` set, withdrawn, an active same-text fact on the page, or an earlier same-text candidate), `ambiguous` (unmanaged brain; no committed request of the page with `completed_at = expired_at`, compared in SQL as microsecond UTC text, which only a same-transaction completion satisfies on Postgres; a consumer at or above v0.60.11.0; or the page has ever held fence-projected facts) or `evidenced`. The preview lists every candidate, hashes them with the selection (`--include-ambiguous`) and saves one approved item per page (with its request id) through `preview-approval.ts`; the apply loads only that set, replays a still-pending request with the ctx's CLI write wait, skips pages whose request already committed or whose facts are active again, and restores each still-identical fact with a fresh `row_num` above the page's facts and fence rows. Managed brains publish one database-only `managed_maintenance_restore_extractor_facts` request per page (`submitDatabaseMaintenanceIntent`, dispatched by `prepareMaintenanceMutation` to `prepareExtractorFactsRestore`, which reclassifies under the page lock); unmanaged brains run the same restore in one locked transaction. Previews warn, naming the host, when a consumer older than this release published after `writer_version_cutoff`. On PGLite `now()` has millisecond resolution, so the same-transaction rule is millisecond-exact there.
- `src/core/repair/conversation-labels.ts` — `gbrain repair conversation-labels`, explicit-only, preview-bound and destructive (consent payload from the registry's `consentText`). `classifyLabelFacts` (read-only) takes active per-segment extractor facts (`source` exactly `cli:extract-conversation-facts`) on live pages with a bold `METADATA_LABELS` line and classes each `excluded` (page outcome stamped with `extractor_version`, withdrawn, superseded, named by another fact's `superseded_by`, referenced by `open_loops.fact_id`), `evidenced` (context carries `segment 1970-01-01`) or `ambiguous`. The preview decides each page's outcome with the current parser at no cost (`non_extractable`, `awaiting_reextraction`, `cleaned`), hashes it all, saves one approved item per page and prints the capped hand-off (`extract-conversation-facts --slugs … --dry-run`, then `--max-cost-usd`). The apply expires the approved ids still as previewed (appending `retired: conversation-labels <hash>` to the context), expires the completion marker and writes the stamped not-extractable outcome for a page still at the previewed parser input; approved pages apply in batches of `LABEL_BATCH_PAGES` (25): one database-only `managed_maintenance_conversation_label_retire` request per batch on `LABELS_ANCHOR_SLUG` on a managed brain (`prepareConversationLabelRetirement`, every page key locked, each page rechecked), one transaction per batch otherwise. No model calls. `countLabelFacts` is doctor `conversation_label_facts`' bounded count. Pinned by `test/repair-conversation-labels.test.ts` (+ Postgres arm) and `test/conversation-facts-retained-history.test.ts`.
diff --git a/docs/architecture/key-files/memory-purge.md b/docs/architecture/key-files/memory-purge.md
index 2108c98112..a7faedc090 100644
--- a/docs/architecture/key-files/memory-purge.md
+++ b/docs/architecture/key-files/memory-purge.md
@@ -4,16 +4,16 @@
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
User-facing contract: [expire versus purge](../../guides/memory-boundaries.md#purge).
-- `src/core/facts/purge.ts` — `submitPurgeFactMutation`, the handler of the owner-only `purge_fact` op (`gbrain forget <id> --purge`). Refuses every caller whose `ctx.remote !== false` with `trusted_local_only` (`purgeHostOnly`, actor user, the exact host command). `planFactPurge` (read-only) computes the scope: every fact row with the same `gbrain_fact_fingerprint` in the fact's source, visibility and subject (the fact's `entity_slug`, `'*'` with `all_subjects`), verbatim takes (`facts.consolidated_into` plus same-fingerprint takes on the subject's page), affected pages from `discoverWithdrawalTargets`, page_versions carrying the text, terminal request intents carrying it, derived rows from `derivation_inputs`, the fact's P8 review rows, and a `revision` digest. A dry run returns the receipt, `confirm_token` (fingerprint's first 8 hex) and `expected_revision`; a real run requires `confirm === token` and, when given, an unchanged revision. The journaled intent is `{id, reason, all_subjects, fact_hash}`, never claim text; replay by request id returns the stored outcome. One transaction in the global lock order: source `FOR UPDATE` (serializes with the guards' `FOR SHARE`), counters for the purge and every redacted request, admission, then inside `withCoordinatedWrite`: pending-publication refusal (`purge_blocked_pending_recovery`), intent redaction, page locks, derived rows hidden before evidence goes, `fact_purges`/`take_purges` tombstones, deletes (takes, review rows, open loops by fact id, take proposals by fingerprint, facts), core-notice base text nulled, page bodies rewritten through the purge overlay, chunks deleted, versions redacted in place, legacy `query_cache` cleared, and `withdrawal-mirror`/`git`/`embedding` effects with `mode: 'purge'` and `commit_subject: gbrain: purge fact <hash8>`. Chunks are rebuilt before acknowledging; `similar_active` is computed before deletion. Pinned by `test/purge-fact.test.ts` (both engines) and `test/forget-purge-cli.test.ts`.
+- `src/core/facts/purge.ts` — `submitPurgeFactMutation`, the handler of the owner-only `purge_fact` op (`gbrain forget <id> --purge`). Refuses every caller whose `ctx.remote !== false` with `trusted_local_only` (`purgeHostOnly`, actor user, the exact host command). `planFactPurge` (read-only) computes the scope: every fact row with the same `gbrain_fact_fingerprint` in the fact's source, visibility and subject (the fact's `entity_slug`, `'*'` with `all_subjects`), verbatim takes (`facts.consolidated_into` plus same-fingerprint takes on the subject's page), affected pages from `discoverWithdrawalTargets`, page_versions carrying the text, terminal request intents carrying it (`findRequestsCarrying` behind the `purge:carrying_lookup` seam; its 57014 is the typed `purge_lookup_timeout`, nothing planned or purged, pinned by `test/fact-purge-lookup-timeout-6511.test.ts`), derived rows from `derivation_inputs`, the fact's P8 review rows, and a `revision` digest. A dry run returns the receipt, `confirm_token` (fingerprint's first 8 hex) and `expected_revision`; a real run requires `confirm === token` and, when given, an unchanged revision. The journaled intent is `{id, reason, all_subjects, fact_hash}`, never claim text; replay by request id returns the stored outcome. One transaction in the global lock order: source `FOR UPDATE` (serializes with the guards' `FOR SHARE`), counters for the purge and every redacted request, admission, then inside `withCoordinatedWrite`: pending-publication refusal (`purge_blocked_pending_recovery`), intent redaction, page locks, derived rows hidden before evidence goes, `fact_purges`/`take_purges` tombstones, deletes (takes, review rows, open loops by fact id, take proposals by fingerprint, facts), core-notice base text nulled, page bodies rewritten through the purge overlay, chunks deleted, versions redacted in place, legacy `query_cache` cleared, and `withdrawal-mirror`/`git`/`embedding` effects with `mode: 'purge'` and `commit_subject: gbrain: purge fact <hash8>`. Chunks are rebuilt before acknowledging; `similar_active` is computed before deletion. Pinned by `test/purge-fact.test.ts` (both engines) and `test/forget-purge-cli.test.ts`.
- `src/core/facts/purge-verify.ts` — receipts and verification. `verifyFactPurge` runs one bounded adapter per store (row bound, per-statement `statement_timeout`, a total deadline; `__setPurgeProbeLimitsForTests`): swept stores report `deleted`, `incomplete` (still holds the claim) or `unverified` (bound hit); page-text stores report remaining text as `out_of_scope: source_prose`; every `probed_reported` inventory table is probed and listed; derived rows are `retained_inactive`; model-derived pages without edges are `derived_legacy: unverified`. On-disk: page files (`canonical_markdown`), a quarantined `<file>.tmp` carrying the claim is deleted, the facts write-failure log is reported. `gitResidualCommits` scans `git log --all -p -- <page paths>` output in-process (the pattern never enters argv; byte and time bounded) and lists commits; `OUT_OF_REACH_RESIDUALS` lead every receipt. The vector probe returns same-model neighbours as paraphrase candidates and is never a gate. `purgeCompletion` derives `committed | complete | incomplete` from effects (failed or parked = incomplete), a fingerprint probe and the receipt, with exit codes 10/0/75.
- `src/core/facts/purge-overlay.ts` — purge mode of the import overlay: `dropPurgedFenceRows` drops facts-fence rows matching `fact_purges` and takes-fence rows matching `take_purges` (the takes fence re-renders with its reservation rows plus the dropped numbers reserved, so a purged number is never reused; pinned by `test/purge-overlay-reservations.test.ts`) (subject = page slug; malformed fences left to the withdrawal diagnostics, which refuse a purged claim inside one). Called first by `preserveWithdrawnFenceRows`, so `import-file.ts` needs no change; the snapshot overlay (`page-state/snapshot.ts`) and export (`export-snapshot.ts`) carry purge tombstones as `PageWithdrawal.purged`, which `overlayWithdrawalBody` drops instead of striking.
- `src/core/facts/purge-schema.ts` — `MEMORY_PURGE_SCHEMA_SQL` (schema.sql fragment: `fact_purges`, `take_purges`, `page_purges` keyed `(source_id, content_hash)`, `derivation_inputs`, `needs_rederive`) and `MEMORY_PURGE_GUARD_SQL` (migration only): `facts_refuse_purged`, `takes_refuse_purged` and `pages_refuse_purged` raise `P0001 purged_content: …` (mapped to typed `purged_content` by `persistence/publication-failure.ts`) instead of skipping the row, whatever `expired_at` says. The pages guard has no column list so it never pins columns. `FACT_PURGE_LOOKUP_INDEX_SQL` (migration v231, CONCURRENTLY on Postgres) adds `fact_purges_subject_idx` (a page's own tombstones, the '*' lookup by fingerprint) and the partial `fact_purges_all_subjects_idx` (subject '*' only, for the snapshot marker count).
- `src/core/page-state/snapshot.ts` — a page snapshot lists only the page's own `fact_purges` tombstones; subject-'*' ones come back as `PageSnapshot.globalPurges` (count, latest `purged_at`, world-only flag; absent at count 0). `resolveGlobalPurges` turns the marker into purge withdrawals for the fence rows of whatever text is overlaid (stored page, incoming file in `page-prepare.ts`, `overlayCanonicalBodies`), on the caller's query. Reconcile pins/preimages and extract-atoms page-state hashing carry the marker, so a new '*' purge invalidates them and an artifact without it reads stale. Alias resolution: `readPageSnapshot` with `resolveAlias` first runs the exact-slug statement (an exact hit outranks every alias), then, on a miss or for `requireUnambiguous`, one `WITH chosen` statement whose candidates are a UNION ALL of the exact-slug probe and an alias-join probe (`slug_aliases` → `pages` on `(source_id, canonical_slug)`, `p.slug<>$1` keeps the branches disjoint so `count(*) OVER ()` still counts pages). #6281: never `slug=$1 OR EXISTS(alias)`, which read every page of every readable source; `page-snapshot-alias-plan.test.ts` pins fewer than 100 `pages` rows per statement from EXPLAIN on both engines.
- `src/core/facts/derivation-inputs.ts` — `recordDerivationInputs(tx, {table, id, sourceId}, inputs)`: complete derived-row → input edges, written by derivers in the deriving transaction (`write_origin` keeps only a display sample). `derivedRowsFrom` walks edges breadth-first (bounded, reports `truncated`); `hideDerivedRows` expires facts, deactivates takes, soft-deletes pages and upserts `needs_rederive`.
- `src/core/deletion-inventory.ts` — the deletion-target registry: every table with a text, JSON, bytes, array, lexeme or vector column, classed `swept`, `retained_inactive` or `out_of_scope` (`probed_reported` with probe columns, `text_free_ledger`, `secret_material`, `no_memory_text`), plus on-disk stores and out-of-reach residuals. `test/deletion-inventory.test.ts` fails on any unlisted text-bearing column of a fresh schema and pins the AGENTS.md "never promise physical erasure" line.
-- `src/core/persistence/intent-redaction.ts` — accounting-aware intent redaction: `findRequestsCarrying` (intent, outcome, error detail or message, compacted rows included) / `findRequestsForSlugs`, `redactRequestIntents` locks counters then request rows, refuses on a non-terminal or recovering request (unless `skipPending`), nulls `intent`/`error_message` and replaces every outcome or error-detail string carrying a needle with `"[purged]"` (`redactJson`), with compaction's terminal-byte accounting, so replay keeps returning the (redacted) stored outcome.
+- `src/core/persistence/intent-redaction.ts` — accounting-aware intent redaction: `findRequestsCarrying` (intent, outcome, error detail or message, compacted rows included; the fact purge's planning read) / `findRequestsForSlugs` (index-served by `persistence_requests_slug_intent`), the page purge's preparation-time journal census `sweepRequestsCarrying` (#6511: a keyset walk of the source's journal in `JOURNAL_SWEEP_CHUNK_ROWS` chunks, every needle in raw and JSON-escaped form against intent, outcome, error detail and message, compacted rows included, the purge's own row excluded, stopped by the claim clock between chunks and at `JOURNAL_SWEEP_MATCH_CAP`; returns the carrying ids, the ids pending at the scan, the `sequence` ceiling as text and `complete`) with `recheckRequestsCarrying` for the publication's bounded re-check of the tail past the ceiling and of the rows that were pending, `redactRequestIntents` locks counters then request rows, refuses on a non-terminal or recovering request (unless `skipPending`), nulls `intent`/`error_message` and replaces every outcome or error-detail string carrying a needle with `"[purged]"` (`redactJson`), with compaction's terminal-byte accounting, so replay keeps returning the (redacted) stored outcome.
- `src/core/persistence/purged-intent.ts` — `intentCarriesPurgedContent`: `completeWrite` (journal.ts) nulls the intent of any terminal request whose content (`fact`, `claim`, page fence rows, or the page's content hash) matches a subject-scoped purge tombstone, and of any refusal coded `purged_content`; a write refused for another reason, or committed as a no-op after the overlay dropped purged rows, keeps no copy. Only content-bearing intents are checked, and whether the source holds any tombstone is selected by completeWrite's terminal statement itself (`PURGE_PRESENCE_COLUMNS`), so the hook adds no statement to a write on a source without tombstones (#6007 budget). `purged_content` is a write error code, so receipts and the frozen verb path (wire `invalid_params`, canonical `purged_content`) keep it typed.
-- `src/core/persistence/page-purge.ts` — `purgePageInTransaction`, called by the `delete_page purge:true` apply in `page-prepare.ts`: records in `page_purges` the content hash of the page and of every retained version (up to 1000), each as imported and as purge-overlaid, so an older version is refused too; drops the decide rows, trust proposals, gate holds (by slug) and gate receipts naming the page or its rows and clears legacy `query_cache`; tombstones and deletes facts filed on the page, tombstones its takes, deletes take proposals, open loops, core notices and `files` rows, redacts finished intents for the slug, then deletes the page (FK cascades). `PURGE_RESIDUALS` names what stays out of reach. `finishPagePurge` deletes stored blobs after commit, lists any left by storage path, and attaches `receipt`, the store-by-store receipt from `verifyPagePurge` (same shape as the fact receipt: residuals first, every swept inventory store, other pages' prose naming a purged claim as `source_prose`); the page's claims used as needles live only in process memory, and a same-id replay returns the result built when the purge ran. `residuals` stays the prose string. `readPagePurgeTombstones` feeds `screenImportContent({ purgedPages })` from managed sync's freeze-time screen (`sync-screen.ts`, one read per run) and publication (`sync-prepare.ts`), which hold a matching file as `purged_content`; direct imports and `put_page` hit the pages guard instead; `listPagePurges` / `unpurgePage` (also clears the fact and take tombstones of the same request) back the owner-only ops. Pinned by `test/page-purge.test.ts`. #6368: a purge of a tombstone whose file matches `sync.exclude` (discovery's globs via `syncExcludePatterns` in `sync-discovery.ts`, matched relative to the source root) owns no file: `prepareFileTarget`'s `excludeTombstone` option returns no target, the purge is database-only and the receipt says `write_through.skipped: 'sync_excluded'`; the file is neither compared nor removed (an unchanged excluded file used to be deleted, an edited one refused forever). The apply re-reads the exclusion inside the publication transaction and refuses `source_changed` if it was removed meanwhile. Live-page purges and soft deletes are unchanged.
+- `src/core/persistence/page-purge.ts` — `purgePageInTransaction`, called by the `delete_page purge:true` apply in `page-prepare.ts`: records in `page_purges` the content hash of the page and of every retained version (up to 1000), each as imported and as purge-overlaid, so an older version is refused too; drops the decide rows, trust proposals, gate holds (by slug) and gate receipts naming the page or its rows and clears legacy `query_cache`; tombstones and deletes facts filed on the page, tombstones its takes, deletes take proposals, open loops, core notices and `files` rows, redacts finished intents for the slug and the carrying ids the preparation sweep found plus the publication's tail and pending re-check (#6511: `preparePagePurge` runs `readPurgeClaims` and `sweepRequestsCarrying` under the preparation budget at steps `purge_claims` / `purge_journal_sweep`, so the O(journal) substring scan is a charged `preparation_deadline` release and `preparation_stalled` at the attempt limit, never a transaction timeout; the lookups that stay inside the transaction go through `lookup`, which maps a 57014 to the terminal, non-retryable `purge_lookup_timeout` naming `gbrain repair request-indexes` only when `persistence_requests_slug_intent` is missing or INVALID; the receipt's `journal_sweep` reports `ceiling`, `scanned`, `tail`, `pending_rechecked` and `complete`), then deletes the page (FK cascades). `PURGE_RESIDUALS` names what stays out of reach. `finishPagePurge` deletes stored blobs after commit, lists any left by storage path, and attaches `receipt`, the store-by-store receipt from `verifyPagePurge` (same shape as the fact receipt: residuals first, every swept inventory store, other pages' prose naming a purged claim as `source_prose`); the page's claims used as needles live only in process memory, and a same-id replay returns the result built when the purge ran. `residuals` stays the prose string. `readPagePurgeTombstones` feeds `screenImportContent({ purgedPages })` from managed sync's freeze-time screen (`sync-screen.ts`, one read per run) and publication (`sync-prepare.ts`), which hold a matching file as `purged_content`; direct imports and `put_page` hit the pages guard instead; `listPagePurges` / `unpurgePage` (also clears the fact and take tombstones of the same request) back the owner-only ops. Pinned by `test/page-purge.test.ts` and `test/page-purge-journal-timeout-6511.test.ts` (both engines; seams `purge:*` in `fault-points.ts`). #6368: a purge of a tombstone whose file matches `sync.exclude` (discovery's globs via `syncExcludePatterns` in `sync-discovery.ts`, matched relative to the source root) owns no file: `prepareFileTarget`'s `excludeTombstone` option returns no target, the purge is database-only and the receipt says `write_through.skipped: 'sync_excluded'`; the file is neither compared nor removed (an unchanged excluded file used to be deleted, an edited one refused forever). The apply re-reads the exclusion inside the publication transaction and refuses `source_changed` if it was removed meanwhile. Live-page purges and soft deletes are unchanged.
- `src/core/ops/purge.ts` — `purge_fact`, `list_page_purges`, `unpurge_page`: admin scope, `cliOnly` (every MCP route gets `trusted_local_only`). The resident owner runs them only for its verified local CLI registration (`LOCAL_CLI_OWNER_OPERATIONS` in `persistence/ipc.ts`, checked in `persistence/provider.ts`).
- `src/commands/forget-purge.ts` + `src/commands/pages-purges.ts` — the CLI fronts. `runForgetPurge` always runs the dry run, then a typed token on a terminal or `--yes` plus `--request-id` without one; `--match` lists ids, `--status` polls completion; `PURGE_FAMILY_HELP` is the purge-family table shown by `gbrain forget --help`. `gbrain pages purges list` and `gbrain pages unpurge <slug>` run the page-tombstone ops as the trusted CLI.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index f49588dd3a..19b36ab996 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -2203,6 +2203,16 @@ More: [docs/guides/repair.md#projection-owner-resident](../../docs/guides/repair
More: [docs/guides/memory-boundaries.md#purge](../../docs/guides/memory-boundaries.md#purge)
+### purge_lookup_timeout
+
+<a id="purge_lookup_timeout"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A page purge's in-transaction journal lookup hit the publication transaction's statement budget, so the purge failed terminally; nothing was removed, tombstoned or redacted, and later writes to the source move again. | The lookup is deterministic on a large request table, not contention: retrying it as `database_contention` requeued the same purge forever and held every later write to its source behind it. The substring search for the page's claims now runs at preparation under the preparation budget; this code is for the lookups that still run inside the transaction (the slug lookup, the tail and pending re-checks, the locking read). | Do not assume the requested content was erased. If the receipt names the slug index as missing or INVALID, run gbrain repair request-indexes --apply first; then submit the purge again with a new request_id (a retry with the same id returns this failure). Run: gbrain repair request-indexes --json | host_admin | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/write-refusals.md#purge_lookup_timeout](../../docs/guides/write-refusals.md#purge_lookup_timeout)
+
### purged_content
<a id="purged_content"></a>
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 22f98dc7cb..cd65160a24 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -73,6 +73,7 @@ of making a duplicate.
| <a id="no_pricing"></a>`no_pricing` | `no_pricing` | A cost cap you set (`--max-cost`, `--max-usd`, `--max-cost-usd`, or an explicit cap in config such as `cycle.extract_atoms.budget_usd`) cannot be enforced, because gbrain has no price for the model the run was about to call. The run stops before that call. Under a default cap an unpriced model warns and runs instead. The message names the model, provider and kind, and JSON output carries the same guidance as fields: `code`, `model`, `provider`, `kind`, `units`, `lookup`, `register_command`, `register_scope` and `docs`. | Look up the provider's current price for the model, for example by searching the web for its pricing page. A chat model needs USD per 1M input tokens and USD per 1M output tokens; an embedding or reranker model needs USD per 1M tokens. On the brain host, run `gbrain pricing set <model> --input <usd> --output <usd> --source <pricing-page-url>` (or `--rate <usd>`), then retry. An agent connected over MCP cannot register prices: give the command to the brain's operator. See [registering a model price](../operations/spend-controls.md#registering-a-model-price). |
| <a id="managed_raw_upload"></a>raw upload on a managed brain | `writer_coordinator_required` | `gbrain files upload-raw` of a small (git-storage) file whose `.raw/` destination is inside a managed canonical worktree. The persistence coordinator does not publish raw files yet, so the worktree refuses writes from outside it; starting a `gbrain serve` owner does not change that. The refusal comes before anything is created: no `.raw/` directory and no `files` row. With no storage backend, `file_upload` for such a page no longer suggests `upload-raw`. | Configure `storage` (supabase, s3 or local) in the gbrain config, then run the printed `gbrain files upload <file> --page <slug>`; check it with `gbrain files list <slug>`. |
| <a id="timeline_rows_would_be_removed"></a>`timeline_rows_would_be_removed` | `timeline_rows_would_be_removed` | A remote `put_page` (or a `put_pages` entry) has no Timeline section at all — no `<!-- timeline -->` sentinel and no `## Timeline` or `## History` heading — and would delete dated entries the page has, including rows `add_timeline_entry` added. `put_page` content replaces the whole page, so the omission must be explicit. Nothing was written. A section that is present but empty is a deliberate delete and is not refused; a local `gbrain put` without `--expected-revision` keeps the rows instead. | Re-read with `get_page include_content:true`, keep the Timeline section and resubmit with a new `request_id`; to remove every dated entry on purpose, resubmit the same content with `drop_timeline: true` (on put_pages, per entry). A successful write that deletes rows reports `timeline_rows_removed {count, earliest, latest, warning, fix}` (dates only); `get_versions` then `revert_version` restores them as new rows. |
+| <a id="purge_lookup_timeout"></a>`purge_lookup_timeout` | `purge_lookup_timeout` | A page purge (`gbrain delete <slug> --purge`) ran one of the journal lookups that still execute inside its publication transaction (the lookup of stored intents for the slug, the re-check of requests admitted after its preparation scan or pending at that scan, the locking read of the requests to redact) and that statement hit the transaction's 5-second statement budget on a large `persistence_requests` table. The request failed terminally instead of being released as `database_contention` and claimed again: nothing of the page was removed or tombstoned, nothing in the journal was redacted, and later writes to the source move again. Do not assume the requested content was erased. The substring search for the page's claims no longer runs here: it runs at preparation in bounded keyset chunks under the preparation budget, and a sweep that outruns that budget twice ends [`preparation_stalled`](#preparation_stalled) instead. A committed purge's receipt reports `journal_sweep` (`scanned`, `ceiling`, `tail`, `pending_rechecked`, `complete`); `complete: false` means a cap was hit (the 10,000-match cap or the tail bound) and some requests were not tested. | If the receipt says the slug index `persistence_requests_slug_intent` is missing or INVALID, run `gbrain repair request-indexes --apply` (the `persistence_request_slug_intent_index` migration builds it online; the index serves the slug lookup, not the substring sweep), then submit the purge again with a new `request_id`. Otherwise submit it again with a new `request_id` (a retry with the same id returns this failure); if it times out again, report the request id with the `persistence_request_indexes` and `persistence_request_growth` entries of `gbrain doctor --json`. |
| <a id="preparation_stalled"></a>`preparation_stalled` | `preparation_stalled` | The write's owner could not finish *preparing* it. Every write has a preparation budget (`persistence.sync_preparation_ms` for a managed sync member, `persistence.maintenance_preparation_ms` for every other managed kind, 120 s each; `remember`, `put_page` and `edit_page` keep 30 s), the owner releases the claim at the budget and tries again, and a request cut off `persistence.max_preparation_attempts` times (default 2; a process killed mid-preparation counts too) is finished `failed` with this code instead of being claimed again and holding the rest of its root. The receipt names the last recorded step and what it was waiting on (`git`, `fs`, `db`, `pool` or `unknown`); while the write was still running, `gbrain sources writer status --json` showed the same on `claim.stall` (`preparation_overdue`). The rest of the root keeps publishing. A **managed sync member** (an import, delete or rename of a file) is also **held**: the sync turns the failed receipt into a `preparation_stalled` hold and carries on, so the file is not imported until it is retried. The file is fine; this is the write owner stalling (a database or pool wait, a hung step), never a frontmatter or fence problem, so no repair applies. The hold's `message` names the request and the step; a held deletion keeps its page. A stalled hold re-screens by itself only when the gbrain version changes; a run that stalls many files in a row stops with [`preparation_systemic`](#preparation_systemic) instead of holding them all. A **foreground write** (`put_page`, `edit_page`, `remember`) or a **maintenance write** (fact-fence adoption, maintenance page writes) gets the terminal receipt only. The deadlines sit behind `persistence.preparation_deadlines` (`false` restores the old behaviour, where only `remember`, `put_page` and `edit_page` had a 30 s budget). | Run `gbrain sources writer status --source <source> --json` (read-only: the step, its wait cause, the owner process and its gbrain version), fix what it names (restart or upgrade an owner that predates deadlines, free the pool, let the lock holder finish), then for a sync hold run `gbrain sources retry-held <source>` and the same `gbrain sync` with the same options (the hold's `fix.then.then` and `retry-held` print it, for example `gbrain sync --source <source> --no-pull --no-embed`). When that sync still has a backlog to finish, it finishes it first and re-screens the scheduled files in the same invocation (the drain yields at the checkpoint and discovers again), so one run of the printed command clears the hold. A foreground write needs a new `request_id`; the next maintenance run submits its write again. Runbook: [catch-up stuck / held N files](troubleshooting.md#catch-up-stuck). |
| <a id="write_outcome_unknown"></a>`write_outcome_unknown` | `write_outcome_unknown` | The database session dropped while the write was being admitted (a pooler reap, a failover, `pg_terminate_backend`), and it kept dropping through the re-reads, so whether the write was accepted is unknown (#6355). A single drop never reaches you: the admission attempt is re-run after 100, 300 and 900 ms, and every attempt begins by reading the retained `request_id`, so a re-run replays an admitted row instead of admitting again. Before this code existed the raw socket error (`write CONNECTION_CLOSED …`, `57P01`) reached the caller while the write went on to commit, and a receipt oracle took it for a refusal. | Read the request first: `gbrain write-request -- <request_id>` or `get_write_request { request_id }` (the error's `fix` names it). A committed or pending row means the write was accepted: replay the same `request_id` to wait for it. No row means it was not: submit it again with the same `request_id`. Never resubmit under a new `request_id` without that read. |
| <a id="fence_unrenderable"></a>`fence_unrenderable` | `fence_unrenderable` | A legacy fact row (an active `facts` row with no fence row number) was not adopted into its page's `## Facts` fence because the fence codec reads the rendered row back as something other than the stored fact: a whitespace-only claim comes back empty, `~~x~~` comes back struck, a literal `<br>` comes back as a line break, or another column changes. Surrounding whitespace and CRLF line endings are the one accepted difference: such a row is adopted and `facts.fact` takes the fence's text. A second legacy row whose normalized claim, source and visibility the page already carries is left too (`duplicate_claim`; a private and a world row with one text are two facts and both adopt). The cycle and the v0.32.2 migration print `FACTS_FENCE_FAILED: <slug> (fence_unrenderable: N row(s), <class>)`; doctor `fence_integrity` lists the pages, fact ids and reason classes under `unrenderable_legacy_facts` (never the claim text). The same code refuses a planned adoption whose rendered fence does not read back as its facts; that is a gbrain planning defect, not caller input. | Nothing to fix in the page: the rows stay active and searchable, nothing is lost, and their pages skip destructive fact reconciliation until the rows are adopted. Report the pages and reason classes with the gbrain version. Never `forget_fact` a row to clear the count. |
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 215c8b656f..5f909480c4 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -473,6 +473,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
// #6529 (GBRA-79). `since` is provisional: stamped at the current VERSION because a `since` past VERSION discloses on every fresh brain (goldens, notice tests); the integrator restamps both rows to the release (0.60.182.0 placeholder) at the merge slot.
{ since: '0.60.182.0', text: 'With `GBRAIN_EMBEDDING_MULTIMODAL=true`, managed sync now imports image files through the coordinated image importer (OCR text, image vector and `source_path` at import) instead of holding them as `managed_image_sync_unsupported`; existing image holds are re-screened and imported on the next `gbrain sync --source <id> --no-pull`. With it off, images stay held as before.' },
{ since: '0.60.182.0', text: 'On a multimodal install, plain `gbrain embed --stale` now runs the image sweep (`--images`) before its text pass and reports it as `images` in `--json`; `gbrain embed --stale --images` works on managed brains, finds an image page with no recorded `source_path` by its slug, and exits non-zero naming the path it tried when no candidate has a file (it used to exit 0); the folded sweep only reports fileless pages. Doctor gains `image_embedding_coverage`.' },
+ // wave 16 (GBRA-79). `since` is provisional at the current VERSION; the integrator restamps it to the merge-slot version.
+ { since: '0.60.183.0', text: 'A page purge (`gbrain delete <slug> --purge`) now searches the source\'s write journal for the page\'s claims at preparation, in bounded keyset chunks under the preparation budget (`persistence.maintenance_preparation_ms`), and its publication transaction only re-checks the requests admitted or settled since; the receipt reports `journal_sweep` (`scanned`, `ceiling`, `tail`, `pending_rechecked`, `complete`), and `complete: false` means a cap was hit and some requests were not tested. A purge whose remaining in-transaction lookup times out now ends `failed` with `purge_lookup_timeout` (nothing removed, tombstoned or redacted; later writes to the source move again) instead of being requeued as `database_contention` without bound, and a sweep that outruns its budget twice ends `preparation_stalled`; either failure needs a new request_id. A schema migration adds the request-table slug index (`gbrain repair request-indexes` rebuilds it).' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 0c8dad8811..925e8d648c 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -47,7 +47,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--mode', '--multimodal', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-rebase', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--mode', '--multimodal', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-rebase', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
@@ -72,7 +72,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],
'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],
'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],
- 'init': ['--access', '--acknowledge-managed', '--adopt', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--content-root', '--db-only', '--dest', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expansion-model', '--facts', '--fix', '--force', '--from-meetings', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--id', '--images', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--no-llm', '--no-pull', '--no-repair', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--reset', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--section', '--self-transfer', '--show-toplevel', '--skip-embed-check', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
+ 'init': ['--access', '--acknowledge-managed', '--adopt', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--content-root', '--db-only', '--dest', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expansion-model', '--facts', '--fix', '--force', '--from-meetings', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--id', '--images', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--no-llm', '--no-pull', '--no-repair', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--purge', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--reset', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--section', '--self-transfer', '--show-toplevel', '--skip-embed-check', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],
'jobs': ['--abbrev-ref', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-quiesced', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--grammar-diagnostics', '--group', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--purge', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 1d1834c163..dd83ba47ab 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -342,6 +342,12 @@ export const CODES = {
provenance_required: { class: 'caller', summary: "provenance is required and must be non-empty." },
publication_pending: { class: 'retryable', summary: "The catalog adoption is accepted but not fully committed." },
purge_blocked_pending_recovery: { class: 'retryable', summary: "A purge was refused because a pending, running or recovering write still needs the content it would remove; nothing was purged.", why: "Purge redacts stored write intents and rewrites pages; doing that under an unfinished publication or recovery would lose or resurrect content.", suggestion: 'Wait for the named write to finish or recover (gbrain write-request <id>), then retry the purge with the same request id.', docs: 'docs/guides/memory-boundaries.md#purge' },
+ purge_lookup_timeout: { class: 'caller', retryable: false, actor: 'host_admin',
+ summary: "A page purge's in-transaction journal lookup hit the publication transaction's statement budget, so the purge failed terminally; nothing was removed, tombstoned or redacted, and later writes to the source move again.",
+ why: "The lookup is deterministic on a large request table, not contention: retrying it as `database_contention` requeued the same purge forever and held every later write to its source behind it. The substring search for the page's claims now runs at preparation under the preparation budget; this code is for the lookups that still run inside the transaction (the slug lookup, the tail and pending re-checks, the locking read).",
+ docs: 'docs/guides/write-refusals.md#purge_lookup_timeout',
+ suggestion: 'Do not assume the requested content was erased. If the receipt names the slug index as missing or INVALID, run gbrain repair request-indexes --apply first; then submit the purge again with a new request_id (a retry with the same id returns this failure).',
+ fix: { argv: ['gbrain', 'repair', 'request-indexes', '--json'], consent: [], actor: 'host_admin', why: 'Previews the request-table indexes without changing anything; the purge receipt says whether the slug index is the cause.', requires_exclusive: false } },
purged_content: { class: 'caller', summary: "The content matches a purged fact, take or page in this source, so it was not saved.", why: "A purge leaves a text-free tombstone (the claim fingerprint or the page content hash) so stale files, re-syncs, reverts and re-extraction cannot bring purged content back.", suggestion: 'Do not retry the same content. Write it in new words if it is still true, or ask the user to clear the tombstone on the brain host (gbrain pages purges list, then gbrain pages unpurge <slug> for a page).', docs: 'docs/guides/memory-boundaries.md#purge' },
question_not_found: { class: 'caller', summary: "No pinned question has this id in the caller's scope; ids are source-qualified (default:questions/<slug>).", docs: 'docs/guides/pinned-questions.md#ids-and-scope' },
question_owner_only: { class: 'host_only', summary: "Pinned questions are owner-private: this connection cannot read private pages (or is slug-fenced or delegated), so the owner runs the command on the brain host.", docs: 'docs/guides/pinned-questions.md#who-can-see-pinned-questions' },
diff --git a/src/core/facts/purge.ts b/src/core/facts/purge.ts
index e5eeb0d8c3..fd246d7cc9 100644
--- a/src/core/facts/purge.ts
+++ b/src/core/facts/purge.ts
@@ -24,6 +24,7 @@ import type { BrainEngine } from '../engine.ts';
import type { OperationContext } from '../ops/contract.ts';
import { opError, OperationError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
+import { faultPoint } from '../persistence/fault-points.ts';
import { contentHash, rowToPage } from '../utils.ts';
import { discoverWithdrawalTargets, withdrawalDiscoveryFailure } from './withdrawal-discovery.ts';
import { dropPurgedFenceRows } from './purge-overlay.ts';
@@ -108,7 +109,15 @@ export async function planFactPurge(engine: BrainEngine, target: PurgeTarget, al
const pages = [...discovered, ...takePages.map(p => ({ ...p, page_id: Number(p.page_id) }))].sort((a, b) => a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0);
const [versions] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM page_versions v JOIN pages p ON p.id=v.page_id
WHERE p.source_id=$1 AND (strpos(lower(v.compiled_truth),$2)>0 OR strpos(lower(COALESCE(v.timeline,'')),$2)>0)`, [target.source_id, target.fact.toLowerCase()]);
- const requests = await findRequestsCarrying(engine, target.source_id, target.fact);
+ // #6511 [R5]: a statement timeout of this unindexable substring search is deterministic on a large journal, not contention: the typed code, not a retry.
+ const requests = await faultPoint('purge:carrying_lookup', { sourceId: target.source_id, operation: PURGE_OPERATION })
+ .then(() => findRequestsCarrying(engine, target.source_id, target.fact)).catch(error => {
+ if ((error as { code?: unknown } | null)?.code !== '57014') throw error;
+ throw opError('purge_lookup_timeout', 'This purge could not finish; nothing was purged. Do not assume the requested content was erased.',
+ `The lookup of historical write requests carrying fact ${target.id} in source ${target.source_id} exceeded its statement budget while the purge was planned, so no plan was made and nothing was removed, tombstoned or redacted. `
+ + 'Run the dry run again later (a smaller or compacted journal finishes it); if it times out again, report it with the persistence_request_indexes and persistence_request_growth entries of gbrain doctor --json.',
+ { fix: readFix('Lists the request-table indexes and their state, read-only.', { argv: ['gbrain', 'repair', 'request-indexes', '--json'] }) });
+ });
const inputs: DerivationRef[] = [...factIds.map(id => ({ table: 'facts', id })), ...takes.map(t => ({ table: 'takes', id: t.id }))];
const derived = await derivedRowsFrom(engine, inputs);
const [counts] = await engine.executeRaw<{ q: number; rp: number; dp: number }>(`SELECT
diff --git a/src/core/persistence/checkpoint-validation.ts b/src/core/persistence/checkpoint-validation.ts
index f33af01a87..88c45fe4ee 100644
--- a/src/core/persistence/checkpoint-validation.ts
+++ b/src/core/persistence/checkpoint-validation.ts
@@ -19,7 +19,7 @@
*/
import type { BrainEngine } from '../engine.ts';
import { opError } from '../ops/contract.ts';
-import { PERSISTENCE_SYNC_RUN_INDEXES } from './schema.ts';
+import { PERSISTENCE_REQUEST_ONLINE_INDEXES, PERSISTENCE_SYNC_RUN_INDEXES } from './schema.ts';
import { docsAnchor } from './connector-errors.ts';
import type { SyncProcessingOptions } from './sync-authority.ts';
import type { SyncCursorOptions } from './sync-prepare.ts';
@@ -67,9 +67,13 @@ export interface RequestIndexState {
progress?: { phase: string; blocks_done: number; blocks_total: number };
}
-/** A fresh read of the #5762 indexes: valid, missing, INVALID, or still being built by another session. */
-export async function readRequestIndexStates(engine: Pick<BrainEngine, 'executeRaw' | 'kind'>): Promise<RequestIndexState[]> {
- const names = PERSISTENCE_SYNC_RUN_INDEXES.map(index => index.name);
+/**
+ * A fresh read of the online-built request indexes (#5762's checkpoint pair and #6511's slug index by default): valid,
+ * missing, INVALID, or still being built by another session. The checkpoint timeout hint reads the pair it depends on.
+ */
+export async function readRequestIndexStates(engine: Pick<BrainEngine, 'executeRaw' | 'kind'>,
+ indexes: ReadonlyArray<{ name: string }> = PERSISTENCE_REQUEST_ONLINE_INDEXES): Promise<RequestIndexState[]> {
+ const names = indexes.map(index => index.name);
if (engine.kind !== 'postgres') {
const rows = await engine.executeRaw<{ name: string; present: boolean }>(
'SELECT n.name, to_regclass(n.name) IS NOT NULL AS present FROM unnest($1::text[]) AS n(name)', [names]);
@@ -126,5 +130,5 @@ export function formatCheckpointTimeoutHint(indexes: RequestIndexState[], input:
}
export async function checkpointTimeoutHint(engine: Pick<BrainEngine, 'executeRaw' | 'kind'>, input: Parameters<typeof formatCheckpointTimeoutHint>[1]): Promise<CheckpointTimeoutHint> {
- return formatCheckpointTimeoutHint(await readRequestIndexStates(engine), input);
+ return formatCheckpointTimeoutHint(await readRequestIndexStates(engine, PERSISTENCE_SYNC_RUN_INDEXES), input);
}
diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.ts
index ffcb8fa5a6..a1d9d6dad5 100644
--- a/src/core/persistence/fault-points.ts
+++ b/src/core/persistence/fault-points.ts
@@ -15,7 +15,11 @@ import type { WriteRequest } from './model.ts';
export type PublicationBoundary = Parameters<NonNullable<PublicationHooks['boundary']>>[0];
export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${EffectKind}:mid` | 'effect:embedding:settle'
| 'effect_recovery:before_clear' | 'publication_recovery:before_clear' | 'sync:mid_checkpoint' | 'sync:before_group_admission' | 'sync:mid_waiver_run' | 'consumer:prepared'
- | 'consumer:preparing' | 'lane:applied';
+ | 'consumer:preparing' | 'lane:applied'
+ // #6511: the page purge's in-transaction journal lookups (page-purge.ts `journalLookup`); a hook that throws a 57014 models a statement timeout there.
+ | 'purge:slug_lookup' | 'purge:tail_recheck' | 'purge:pending_recheck' | 'purge:redaction_read'
+ // #6511: before each keyset chunk of the preparation-time journal sweep (a stalling hook models a slow chunk), and the fact purge's planning read.
+ | 'purge:sweep_chunk' | 'purge:carrying_lookup';
/**
* `signal` (#6278, `consumer:preparing` only): the preparation's abort signal, so
* a stalling hook can model both the reporter's cases: a preparer that honours
diff --git a/src/core/persistence/intent-redaction.ts b/src/core/persistence/intent-redaction.ts
index 39e130907a..4fa41b9e40 100644
--- a/src/core/persistence/intent-redaction.ts
+++ b/src/core/persistence/intent-redaction.ts
@@ -15,16 +15,136 @@
*
* Replay keys on the stored `digest`, so a later retry of a redacted request
* returns its stored outcome without re-executing.
+ *
+ * #6511: the page purge no longer runs the needle search inside its 5 s
+ * publication transaction. `sweepRequestsCarrying` walks the source's journal
+ * in keyset chunks at preparation (bounded by the preparation budget: the
+ * clock between chunks, the server-side bound on Postgres), recording the
+ * sequence ceiling it scanned to and the non-terminal rows it saw;
+ * `recheckRequestsCarrying` then runs the same predicate inside the
+ * publication transaction over the tail past that ceiling and over those
+ * pending rows, so a carrying request admitted or settled after the scan is
+ * still redacted. `findRequestsCarrying` (one needle, one statement) stays
+ * the fact purge's planning read.
*/
import { opError } from '../ops/contract.ts';
import type { BrainEngine } from '../engine.ts';
+import { enterClaimStep, type ClaimPhaseClock } from './claim-phase.ts';
import { jsonBytes } from './digest.ts';
import { lockCounters } from './journal.ts';
import { isTerminal, principalKey, requestPrincipal, type WriteRequest } from './model.ts';
export interface IntentRedactionTarget { id: string; principal_kind: string; principal_id: string }
+/** Rows one keyset chunk of the journal sweep reads at a time. */
+export const JOURNAL_SWEEP_CHUNK_ROWS = 2000;
+/** The match cap `findRequestsCarrying` always had; a sweep that reaches it reports `complete: false`. */
+export const JOURNAL_SWEEP_MATCH_CAP = 10_000;
+
+/** Every form a claim takes inside the journal's text columns: lowercased raw, and lowercased as it appears inside a JSON string. */
+export function carryingNeedles(claims: readonly string[]): string[] {
+ const forms = claims.flatMap(claim => [claim.toLowerCase(), JSON.stringify(claim).slice(1, -1).toLowerCase()]);
+ return [...new Set(forms.filter(Boolean))];
+}
+
+interface SweepRow extends IntentRedactionTarget { sequence: string; pending: boolean; matched: boolean; chunk_rows: string; chunk_last: string | null }
+/**
+ * One chunk of the carrying predicate: the rows of `sourceId` with `after < sequence <= ceiling` (`ceiling` null: no upper
+ * bound), in sequence order, at most `limit`. The chunk is materialised once and each text column lowered once per row;
+ * only the rows that match a needle or are still pending come back, plus the chunk's row count and last scanned
+ * sequence (as text: bigint) so the caller continues past a chunk that matched nothing.
+ */
+async function sweepChunk(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, needles: readonly string[], after: string, ceiling: string | null, limit: number,
+ ids: readonly string[] | null = null, exclude: string | null = null): Promise<{ rows: Array<IntentRedactionTarget & { sequence: string; pending: boolean; matched: boolean }>; scanned: number; last: string | null }> {
+ const rows = await engine.executeRaw<SweepRow>(`WITH chunk AS MATERIALIZED (
+ SELECT id,principal_kind,principal_id,sequence,
+ (state IN ('queued','running','recovering') OR recovery IS NOT NULL) AS pending,
+ lower(COALESCE(intent::text,'')) AS i,lower(COALESCE(outcome::text,'')) AS o,lower(COALESCE(error_detail::text,'')) AS d,lower(COALESCE(error_message,'')) AS m
+ FROM persistence_requests WHERE source_id=$1 AND sequence>$2::bigint AND ($3::bigint IS NULL OR sequence<=$3::bigint)
+ AND ($6::uuid[] IS NULL OR id=ANY($6::uuid[])) AND ($7::uuid IS NULL OR id<>$7::uuid)
+ ORDER BY sequence LIMIT $5),
+ stats AS (SELECT count(*)::text AS chunk_rows,max(sequence)::text AS chunk_last FROM chunk),
+ tested AS (SELECT id,principal_kind,principal_id,sequence,pending,
+ EXISTS (SELECT 1 FROM unnest($4::text[]) AS n WHERE strpos(i,n)>0 OR strpos(o,n)>0 OR strpos(d,n)>0 OR strpos(m,n)>0) AS matched FROM chunk)
+ SELECT t.id::text AS id,t.principal_kind,t.principal_id,t.sequence::text AS sequence,t.pending,t.matched,s.chunk_rows,s.chunk_last
+ FROM tested t CROSS JOIN stats s WHERE t.matched OR t.pending
+ UNION ALL SELECT NULL,NULL,NULL,NULL,false,false,s.chunk_rows,s.chunk_last FROM stats s`,
+ [sourceId, after, ceiling, [...needles], limit, ids ? [...ids] : null, exclude]);
+ // Every row carries the chunk statistics; the sentinel row guarantees at least one.
+ const stats = rows[0]!;
+ return { rows: rows.filter(row => row.id !== null).map(({ id, principal_kind, principal_id, sequence, pending, matched }) => ({ id, principal_kind, principal_id, sequence, pending, matched })),
+ scanned: Number(stats.chunk_rows), last: stats.chunk_last };
+}
+
+export interface JournalSweep {
+ /** Terminal-at-scan requests carrying a needle (the publication redacts them under `FOR UPDATE`). */
+ targets: IntentRedactionTarget[];
+ /** Requests that were queued, running or recovering when the scan passed them; the publication tests them again. */
+ pendingAtScan: string[];
+ /** The highest sequence the scan covered (text: bigint); null when the source had no requests. */
+ ceiling: string | null;
+ scanned: number;
+ /** False when the match cap was hit: rows past it were not tested. */
+ complete: boolean;
+}
+/**
+ * The preparation-time census (#6511): every request of `sourceId` up to the sequence ceiling read at the start, in
+ * `JOURNAL_SWEEP_CHUNK_ROWS` keyset chunks, continuing from the last scanned row whether or not it matched. Between
+ * chunks the loop checks the claim clock itself, so on PGLite (no server-side bound) a sweep past its preparation
+ * budget ends with the budget's own `preparation_deadline` and the consumer releases the claim charged; on Postgres
+ * `boundedReads` ends the chunk statement at the same bound. Needles stay in memory; no text is returned.
+ */
+export async function sweepRequestsCarrying(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, claims: readonly string[],
+ opts: { clock?: ClaimPhaseClock; chunkRows?: number; matchCap?: number; onChunk?: () => Promise<void> | void; now?: () => number;
+ /** The purge's own request row (running while it scans): never a target, never pending. */ exclude?: string } = {}): Promise<JournalSweep> {
+ const needles = carryingNeedles(claims);
+ const chunkRows = opts.chunkRows ?? JOURNAL_SWEEP_CHUNK_ROWS, matchCap = opts.matchCap ?? JOURNAL_SWEEP_MATCH_CAP, now = opts.now ?? Date.now;
+ const [top] = await engine.executeRaw<{ ceiling: string | null }>('SELECT max(sequence)::text AS ceiling FROM persistence_requests WHERE source_id=$1', [sourceId]);
+ const ceiling = top?.ceiling ?? null;
+ const sweep: JournalSweep = { targets: [], pendingAtScan: [], ceiling, scanned: 0, complete: true };
+ if (ceiling === null || !needles.length) return sweep;
+ for (let after = '0'; ;) {
+ enterClaimStep(opts.clock, 'purge_journal_sweep', undefined, 'db');
+ if (opts.clock?.deadlineAt !== undefined && now() >= opts.clock.deadlineAt) throw journalSweepDeadline(opts.clock);
+ await opts.onChunk?.();
+ const chunk = await sweepChunk(engine, sourceId, needles, after, ceiling, chunkRows, null, opts.exclude ?? null);
+ sweep.scanned += chunk.scanned;
+ for (const row of chunk.rows) {
+ if (row.pending) sweep.pendingAtScan.push(row.id);
+ else if (row.matched) sweep.targets.push({ id: row.id, principal_kind: row.principal_kind, principal_id: row.principal_id });
+ }
+ if (sweep.targets.length >= matchCap) { sweep.targets.length = matchCap; sweep.complete = false; return sweep; }
+ if (chunk.scanned < chunkRows || chunk.last === null) return sweep;
+ after = chunk.last;
+ }
+}
+/** The budget's own abort reason, raised by the sweep loop between chunks when the clock has run out (`preparationAbortReason` reads `code`). */
+function journalSweepDeadline(clock: ClaimPhaseClock): Error {
+ return Object.assign(new Error(`The purge's journal sweep${clock.step ? ` at step ${clock.step}` : ''} reached its preparation budget between chunks.`), { code: 'preparation_deadline' });
+}
+
+export interface JournalRecheck { targets: IntentRedactionTarget[]; tail: number; pendingRechecked: number; complete: boolean }
+/**
+ * The publication-time reconciliation (#6511), inside the purge transaction: the same predicate over the tail the scan
+ * did not cover (`sequence > ceiling`, one bounded chunk; more rows than that leave `complete: false`) and over the rows
+ * that were pending at scan time (settled ones with a carrying outcome now redact; still-pending ones are left to
+ * `redactRequestIntents`' `skipPending`). Returns the ids to redact in addition to the sweep's.
+ */
+export async function recheckRequestsCarrying(tx: Pick<BrainEngine, 'executeRaw'>, sourceId: string, claims: readonly string[], sweep: Pick<JournalSweep, 'ceiling' | 'pendingAtScan'>,
+ opts: { tailRows?: number; beforePending?: () => Promise<void> | void; exclude?: string } = {}): Promise<JournalRecheck> {
+ const needles = carryingNeedles(claims);
+ const tailRows = opts.tailRows ?? JOURNAL_SWEEP_CHUNK_ROWS;
+ const targets = new Map<string, IntentRedactionTarget>();
+ if (!needles.length) return { targets: [], tail: 0, pendingRechecked: 0, complete: true };
+ const tail = await sweepChunk(tx, sourceId, needles, sweep.ceiling ?? '0', null, tailRows, null, opts.exclude ?? null);
+ for (const row of tail.rows) if (row.matched && !row.pending) targets.set(row.id, { id: row.id, principal_kind: row.principal_kind, principal_id: row.principal_id });
+ await opts.beforePending?.();
+ const pending = sweep.pendingAtScan.length ? await sweepChunk(tx, sourceId, needles, '0', null, sweep.pendingAtScan.length, sweep.pendingAtScan, opts.exclude ?? null) : { rows: [], scanned: 0, last: null };
+ for (const row of pending.rows) if (row.matched && !row.pending) targets.set(row.id, { id: row.id, principal_kind: row.principal_kind, principal_id: row.principal_id });
+ return { targets: [...targets.values()], tail: tail.scanned, pendingRechecked: pending.scanned, complete: tail.scanned < tailRows };
+}
+
/**
* Requests in `sourceId` whose stored intent, outcome or error text carries `claim`, bounded, compacted
* ones included (compaction keeps the outcome). Owner-only; never returns the text.
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index add3398501..9ae96e169a 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -57,7 +57,7 @@ import { fenceWhere } from '../fence-repair/refusal.ts';
import { pageFencesNormalized } from '../fence-repair/report.ts';
import { parseFenceRepairReceipt } from '../fence-repair/receipt.ts';
import { fenceRepairCommit } from './effect-model.ts';
-import { purgePageInTransaction } from './page-purge.ts';
+import { preparePagePurge, purgePageInTransaction, type PreparedPagePurge } from './page-purge.ts';
import { withTrustKeep } from './context.ts';
import { isFenceEditWrite, pageGateTrust, pageWriteTrust, recordAgentPageLowering, stampPageTrustMarker, storedPageTier } from '../trust/page-write.ts';
import { suppliedTrustMarkerView } from '../trust/channel.ts';
@@ -291,6 +291,34 @@ async function assertStillSyncExcluded(tx: BrainEngine, row: WriteRequest, exclu
`${excludedPath} was excluded from sync when the purge of ${row.slug} was prepared and is not any more, so nothing was purged. Run the purge again; it re-reads the exclusion.`, pageFix(row.source_id, row.slug));
}
+/** The `delete_page` preparation: soft delete, or purge with its journal sweep (#6511) run under the preparation budget. */
+async function prepareDeletePageMutation(engine: BrainEngine, row: WriteRequest, snapshot: PageSnapshot | null,
+ options: { activePack?: ParseOpts['activePack']; clock?: ClaimPhaseClock; allowMissingFile?: boolean }): Promise<PreparedMutation> {
+ const p = row.intent!, source = { sourceId: row.source_id }, clock = options.clock;
+ assertPurgeParams(p, row.authority.remote);
+ if (!snapshot) throw pageRefusal('page_not_found', 'Page not found.', row,
+ `Page ${row.slug} does not exist in source ${row.source_id}, so nothing was deleted. Check the slug and the source.`, pageFix(row.source_id, row.slug));
+ const observedRevision = snapshot.revision;
+ const purge = p.purge === true;
+ const noop = !purge && snapshot.page.deleted_at != null;
+ // Always-loaded core pages: a remote caller cannot delete one (owner-only).
+ if (!noop) { enterClaimStep(clock, 'core_guard', undefined, 'db'); await prepareCoreGuard(engine, { row, snapshot, incoming: null }); }
+ enterClaimStep(clock, 'file_target', undefined, 'fs');
+ // Tombstones still own their recorded artifact. Purge always attempts its
+ // removal before the guarded hard-delete and receipt commit; failure rolls
+ // back to the prior row, and replay survives the eventual absence of that row.
+ const { file, excludedPath } = await prepareDeleteFileTarget(engine, row, snapshot, purge, { allowMissing: purge || options.allowMissingFile, deleting: true, activePack: options.activePack, remote: row.authority.remote });
+ // #6511: the purge's journal sweep runs here, under the preparation budget, never inside the 5 s publication transaction.
+ const preparedPurge: PreparedPagePurge | null = purge ? await preparePagePurge(engine, row, snapshot, clock) : null;
+ return { observedRevision, noop, file, ...await pageDatabaseOnlyPublication(engine, row, file), ...(excludedPath !== null ? { databaseOnlyReason: 'sync_excluded' as const } : {}), apply: async tx => {
+ if (purge && excludedPath !== null) await assertStillSyncExcluded(tx, row, excludedPath);
+ if (preparedPurge) return purgePageInTransaction(tx, row, snapshot, preparedPurge);
+ if (!noop) { await tx.createVersion(row.slug, source); await tx.softDeletePage(row.slug, source); }
+ return { status: 'soft_deleted', slug: row.slug, source_id: row.source_id, noop,
+ recoverable_until: 'now + 72h via restore_page (remove immediately instead: gbrain delete <slug> --purge, local CLI only)' };
+ } };
+}
+
/**
* Providers and parsing run before the OS lock and before any publication transaction.
* `coordinated`: the caller publishes this mutation itself through the coordinator, whose
@@ -332,27 +360,7 @@ export async function preparePageMutation(unbounded: BrainEngine, row: WriteRequ
'Use capture --file PATH --slug SLUG for file input, or pass allow_empty:true with the expected revision to intentionally clear it.');
}
}
- if (row.operation === 'delete_page') {
- assertPurgeParams(p, row.authority.remote);
- if (!snapshot) throw pageRefusal('page_not_found', 'Page not found.', row,
- `Page ${row.slug} does not exist in source ${row.source_id}, so nothing was deleted. Check the slug and the source.`, pageFix(row.source_id, row.slug));
- const purge = p.purge === true;
- const noop = !purge && snapshot.page.deleted_at != null;
- // Always-loaded core pages: a remote caller cannot delete one (owner-only).
- if (!noop) { enterClaimStep(clock, 'core_guard', undefined, 'db'); await prepareCoreGuard(engine, { row, snapshot, incoming: null }); }
- enterClaimStep(clock, 'file_target', undefined, 'fs');
- // Tombstones still own their recorded artifact. Purge always attempts its
- // removal before the guarded hard-delete and receipt commit; failure rolls
- // back to the prior row, and replay survives the eventual absence of that row.
- const { file, excludedPath } = await prepareDeleteFileTarget(engine, row, snapshot, purge, { allowMissing: purge || options.allowMissingFile, deleting: true, activePack, remote: row.authority.remote });
- return { observedRevision, noop, file, ...await pageDatabaseOnlyPublication(engine, row, file), ...(excludedPath !== null ? { databaseOnlyReason: 'sync_excluded' as const } : {}), apply: async tx => {
- if (purge && excludedPath !== null) await assertStillSyncExcluded(tx, row, excludedPath);
- if (purge) return purgePageInTransaction(tx, row, snapshot);
- if (!noop) { await tx.createVersion(row.slug, source); await tx.softDeletePage(row.slug, source); }
- return { status: 'soft_deleted', slug: row.slug, source_id: row.source_id, noop,
- recoverable_until: 'now + 72h via restore_page (remove immediately instead: gbrain delete <slug> --purge, local CLI only)' };
- } };
- }
+ if (row.operation === 'delete_page') return prepareDeletePageMutation(engine, row, snapshot, { activePack, clock, allowMissingFile: options.allowMissingFile });
// #6188: a trusted local fence repair's receipt (admission refuses it from every other caller) rides the outcome and the file's commit.
const fenceRepair = row.operation === 'put_page' && !row.authority.remote ? parseFenceRepairReceipt(p.fence_repair) : null;
const fenceRepairOutcome = fenceRepair ? { fence_repair: fenceRepair } : {};
diff --git a/src/core/persistence/page-purge.ts b/src/core/persistence/page-purge.ts
index bc337606a4..f4d4722db8 100644
--- a/src/core/persistence/page-purge.ts
+++ b/src/core/persistence/page-purge.ts
@@ -14,14 +14,29 @@
* `page_purges` keeps (source_id, content_hash, slug): the pages guard raises
* typed `purged_content` when a page with that content hash is written again
* under any slug, until `gbrain pages unpurge <slug>` clears it.
+ *
+ * #6511: the search for historical requests carrying the page's claims is an
+ * O(journal) substring scan that no index serves, so it runs at preparation
+ * (`preparePagePurge`, under the preparation budget) and the publication
+ * transaction only reconciles the tail past the scanned ceiling and the rows
+ * that were pending at scan time (`recheckRequestsCarrying`). A statement
+ * timeout inside one of the remaining in-transaction lookups is deterministic
+ * on a large journal, not contention: it ends the request `failed` with the
+ * typed `purge_lookup_timeout` (the queue behind it moves) instead of being
+ * released as `database_contention` and retried without bound.
*/
import type { BrainEngine } from '../engine.ts';
import type { OperationContext } from '../ops/contract.ts';
-import { opError } from '../ops/contract.ts';
+import { opError, type OperationError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
import type { PageSnapshot } from '../page-state/types.ts';
import type { WriteRequest } from './model.ts';
-import { findRequestsCarrying, findRequestsForSlugs, redactRequestIntents } from './intent-redaction.ts';
+import { enterClaimStep, type ClaimPhaseClock } from './claim-phase.ts';
+import { PERSISTENCE_REQUEST_SLUG_INTENT_INDEX } from './schema.ts';
+import { readRequestIndexStates, REQUEST_INDEXES_REPAIR_COMMAND, type RequestIndexState } from './checkpoint-validation.ts';
+import { faultPoint } from './fault-points.ts';
+import { findRequestsForSlugs, recheckRequestsCarrying, redactRequestIntents, sweepRequestsCarrying, type JournalSweep } from './intent-redaction.ts';
import { dropPurgedFenceRows } from '../facts/purge-overlay.ts';
import { contentHash } from '../utils.ts';
@@ -44,8 +59,61 @@ const purgeContext = new Map<string, { needles: string[]; factIds: number[]; pag
const PURGE_CONTEXT_LIMIT = 64;
const purgeReceipts = new Map<string, { receipt: Record<string, unknown>; purge: Record<string, unknown> }>();
+/** The page's claims (facts filed on it, its takes) that the journal sweep searches for, bounded, trimmed, deduplicated. */
+async function readPurgeClaims(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, slug: string, pageId: number) {
+ const factRows = await engine.executeRaw<{ id: number; fact: string }>('SELECT id,fact FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 ORDER BY id LIMIT 1000', [sourceId, slug]);
+ const takeRows = await engine.executeRaw<{ id: number; claim: string }>('SELECT id,claim FROM takes WHERE page_id=$1 ORDER BY id LIMIT 1000', [pageId]);
+ const needles = [...new Set([...factRows.map(f => f.fact), ...takeRows.map(t => t.claim)].map(t => t.trim()).filter(t => t.length >= 8))].slice(0, 32);
+ return { factRows, takeRows, needles };
+}
+
+/** What the delete preparation hands the purge apply: the claims it searched for, the journal census, and the slug index's state for the failure hint. */
+export interface PreparedPagePurge { needles: string[]; sweep: JournalSweep; slugIndex: RequestIndexState['state'] }
+/**
+ * #6511: at preparation, before the root lock and outside any transaction: the page's claims, the slug index's state and
+ * the keyset journal sweep under the preparation budget (the clock between chunks; `boundedReads` on Postgres).
+ */
+export async function preparePagePurge(engine: BrainEngine, row: WriteRequest, snapshot: PageSnapshot, clock: ClaimPhaseClock | undefined): Promise<PreparedPagePurge> {
+ enterClaimStep(clock, 'purge_claims', undefined, 'db');
+ const { needles } = await readPurgeClaims(engine, row.source_id, snapshot.page.slug, snapshot.page.id);
+ const [slugIndex] = await readRequestIndexStates(engine, [PERSISTENCE_REQUEST_SLUG_INTENT_INDEX]);
+ const sweep = await sweepRequestsCarrying(engine, row.source_id, needles, { clock, exclude: row.id,
+ onChunk: () => faultPoint('purge:sweep_chunk', { requestId: row.request_id, sourceId: row.source_id, operation: row.operation }) });
+ return { needles, sweep, slugIndex: slugIndex?.state ?? 'missing' };
+}
+
+/** The in-transaction journal lookups a statement timeout ends as `purge_lookup_timeout` (also the purge's fault-point seams). */
+export type PurgeLookupPoint = 'slug_lookup' | 'tail_recheck' | 'pending_recheck' | 'redaction_read';
+const LOOKUP_LABEL: Record<PurgeLookupPoint, string> = { slug_lookup: 'lookup of stored intents for the slug', tail_recheck: 're-check of requests admitted after its preparation scan',
+ pending_recheck: 're-check of requests that were pending at its preparation scan', redaction_read: 'locking read of the requests to redact' };
+export const PURGE_LOOKUP_TIMEOUT_MESSAGE = 'This purge could not finish; later writes to the source can move again. Do not assume the requested content was erased.';
+/** [R6] The failure's `fix` names the index repair only when the slug index is missing or invalid; otherwise a fresh request id. */
+export function purgeLookupTimeout(row: Pick<WriteRequest, 'request_id' | 'slug' | 'source_id'>, point: PurgeLookupPoint, slugIndex: RequestIndexState['state']): OperationError {
+ const broken = slugIndex === 'missing' || slugIndex === 'invalid';
+ const next = broken
+ ? `The request-table slug index ${PERSISTENCE_REQUEST_SLUG_INTENT_INDEX.name} is ${slugIndex === 'invalid' ? 'INVALID' : 'missing'}: rebuild it (${REQUEST_INDEXES_REPAIR_COMMAND}), then submit the purge again with a new request_id.`
+ : 'Submit the purge again with a new request_id (a retry with the same id returns this failure); if it times out again, report the request and attach the persistence_request_indexes and persistence_request_growth entries of gbrain doctor --json.';
+ // The journal keeps code and message only, so the next step rides the message (the receipt is what `gbrain write-request` shows).
+ return opError('purge_lookup_timeout', `${PURGE_LOOKUP_TIMEOUT_MESSAGE} ${next}`,
+ `The purge's ${LOOKUP_LABEL[point]} (request ${row.request_id}, page ${row.slug} in source ${row.source_id}) exceeded the publication transaction's statement budget, so the transaction rolled back: `
+ + 'no row, file or tombstone of the page was removed and nothing in the journal was redacted.',
+ { fix: broken
+ ? { argv: ['gbrain', 'repair', 'request-indexes', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Previews the missing or invalid request-table indexes without changing anything.' }
+ : readFix(`Reads request ${row.request_id}'s durable receipt: its state and recorded error, read-only.`, { argv: ['gbrain', 'write-request', '--', row.request_id] }) });
+}
+/** Runs one in-transaction journal lookup behind its fault-point seam; a 57014 from it is the terminal typed failure, never transient contention. */
+async function journalLookup<T>(row: WriteRequest, point: PurgeLookupPoint, slugIndex: RequestIndexState['state'], fn: () => Promise<T>): Promise<T> {
+ try {
+ await faultPoint(`purge:${point}`, { requestId: row.request_id, sourceId: row.source_id, operation: row.operation });
+ return await fn();
+ } catch (error) {
+ if ((error as { code?: unknown } | null)?.code !== '57014') throw error;
+ throw purgeLookupTimeout(row, point, slugIndex);
+ }
+}
+
/** Inside the coordinated delete transaction, before the page row is deleted. */
-export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest, snapshot: PageSnapshot): Promise<Record<string, unknown>> {
+export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest, snapshot: PageSnapshot, prepared: PreparedPagePurge): Promise<Record<string, unknown>> {
const page = snapshot.page, sourceId = row.source_id, slug = page.slug;
const actor = `${row.principal_kind}:${row.principal_id}`;
const [stored] = await tx.executeRaw<{ content_hash: string | null }>('SELECT content_hash FROM pages WHERE id=$1', [page.id]);
@@ -71,10 +139,8 @@ export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest,
}
await tx.executeRaw(`INSERT INTO page_purges(source_id,content_hash,slug,request_id) SELECT $1,h,$3,$4::uuid FROM unnest($2::text[]) AS h
ON CONFLICT (source_id,content_hash) DO UPDATE SET slug=EXCLUDED.slug,request_id=EXCLUDED.request_id,purged_at=now()`, [sourceId, [...hashes], slug, row.id]);
- const factRows = await tx.executeRaw<{ id: number; fact: string }>('SELECT id,fact FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 ORDER BY id LIMIT 1000', [sourceId, slug]);
- const takeRows = await tx.executeRaw<{ id: number; claim: string }>('SELECT id,claim FROM takes WHERE page_id=$1 ORDER BY id LIMIT 1000', [page.id]);
+ const { factRows, takeRows, needles } = await readPurgeClaims(tx, sourceId, slug, page.id);
const factIds = factRows.map(f => Number(f.id)), takeIds = takeRows.map(t => Number(t.id));
- const needles = [...new Set([...factRows.map(f => f.fact), ...takeRows.map(t => t.claim)].map(t => t.trim()).filter(t => t.length >= 8))].slice(0, 32);
const count = async (sql: string, params: unknown[]) => (await tx.executeRaw(sql, params)).length;
const refs = factIds.map(String);
const removed: Record<string, number> = {
@@ -95,9 +161,15 @@ export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest,
removed.take_proposals = await count('DELETE FROM take_proposals WHERE source_id=$1 AND page_slug=$2 RETURNING 1', [sourceId, slug]);
removed.open_loops = await count('DELETE FROM open_loops WHERE source_id=$1 AND page_slug=$2 RETURNING 1', [sourceId, slug]);
removed.core_edit_notices = await count('DELETE FROM core_edit_notices WHERE source_id=$1 AND slug=$2 RETURNING 1', [sourceId, slug]);
- const carrying = needles.length ? (await Promise.all(needles.map(n => findRequestsCarrying(tx, sourceId, n)))).flat() : [];
- const requests = [...new Map([...await findRequestsForSlugs(tx, sourceId, [slug]), ...carrying].map(r => [r.id, r])).values()];
- removed.persistence_requests = await redactRequestIntents(tx, requests, row.id, { skipPending: true, needles });
+ // #6511 [R2]: the preparation sweep's targets, plus the tail past its ceiling and the rows pending at scan time, re-tested here.
+ const lookup = <T>(point: PurgeLookupPoint, fn: () => Promise<T>) => journalLookup(row, point, prepared.slugIndex, fn);
+ const recheck = await lookup('tail_recheck', () => recheckRequestsCarrying(tx, sourceId, needles, prepared.sweep,
+ { exclude: row.id, beforePending: () => faultPoint('purge:pending_recheck', { requestId: row.request_id, sourceId, operation: row.operation }) }));
+ const forSlug = await lookup('slug_lookup', () => findRequestsForSlugs(tx, sourceId, [slug]));
+ const requests = [...new Map([...forSlug, ...prepared.sweep.targets, ...recheck.targets].map(r => [r.id, r])).values()];
+ removed.persistence_requests = await lookup('redaction_read', () => redactRequestIntents(tx, requests, row.id, { skipPending: true, needles }));
+ const journalSweep = { scanned: prepared.sweep.scanned, ceiling: prepared.sweep.ceiling, tail: recheck.tail, pending_rechecked: recheck.pendingRechecked,
+ complete: prepared.sweep.complete && recheck.complete };
const files = await tx.executeRaw<{ storage_path: string }>(`DELETE FROM files WHERE (page_id=$1 OR (page_slug=$2 AND (source_id=$3 OR source_id IS NULL)))
RETURNING storage_path`, [page.id, slug, sourceId]);
removed.files = files.length;
@@ -111,7 +183,7 @@ export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest,
purgeContext.delete(key);
purgeContext.set(key, { needles, factIds, pageId: page.id, paths });
while (purgeContext.size > PURGE_CONTEXT_LIMIT) purgeContext.delete(purgeContext.keys().next().value!);
- return { status: 'purged', slug, source_id: sourceId, residuals: PURGE_RESIDUALS,
+ return { status: 'purged', slug, source_id: sourceId, residuals: PURGE_RESIDUALS, journal_sweep: journalSweep,
purge: { content_hash8: storedHash?.slice(0, 8) ?? null, tombstoned: hashes.size > 0, content_hashes_tombstoned: hashes.size, removed,
blobs: files.map(f => f.storage_path).filter(Boolean) } };
}
diff --git a/src/core/persistence/schema.ts b/src/core/persistence/schema.ts
index 851fed83d9..2cf1dca62f 100644
--- a/src/core/persistence/schema.ts
+++ b/src/core/persistence/schema.ts
@@ -18,6 +18,16 @@ export const PERSISTENCE_SYNC_RUN_INDEXES = [
{ name: 'persistence_requests_sync_run_open', sql: PERSISTENCE_SYNC_RUN_OPEN_INDEX_SQL },
{ name: 'persistence_requests_sync_run_committed', sql: PERSISTENCE_SYNC_RUN_COMMITTED_INDEX_SQL },
] as const;
+/**
+ * #6511: the page purge's lookup of stored intents for a slug (`findRequestsForSlugs`: source, slug, uncompacted rows
+ * with an intent) ran as a sequential scan of the request table inside the 5 s purge transaction. Postgres builds it
+ * CONCURRENTLY in the persistence_request_slug_intent_index migration (`transaction: false`); PGLite inline. `gbrain repair request-indexes` rebuilds it.
+ */
+export const PERSISTENCE_REQUEST_SLUG_INTENT_INDEX_SQL = `CREATE INDEX IF NOT EXISTS persistence_requests_slug_intent
+ ON persistence_requests(source_id,slug,sequence) WHERE intent IS NOT NULL AND NOT compacted`;
+export const PERSISTENCE_REQUEST_SLUG_INTENT_INDEX = { name: 'persistence_requests_slug_intent', table: 'persistence_requests', sql: PERSISTENCE_REQUEST_SLUG_INTENT_INDEX_SQL } as const;
+/** Every request-table index built online (a migration, then `gbrain repair request-indexes` and doctor `persistence_request_indexes`). */
+export const PERSISTENCE_REQUEST_ONLINE_INDEXES = [...PERSISTENCE_SYNC_RUN_INDEXES, PERSISTENCE_REQUEST_SLUG_INTENT_INDEX] as const;
/**
* #6317: the movement watermark (the newest committed receipt of a worktree)
* that `writer movement`, `data_moving` and doctor `managed_sync_not_moving`
@@ -85,6 +95,7 @@ export const PERSISTENCE_CONSUMERS_TABLE_SQL = `CREATE TABLE IF NOT EXISTS persi
/** Indexes the Postgres blob omits because a migration builds them CONCURRENTLY. */
export const POSTGRES_CONCURRENT_PERSISTENCE_INDEXES: ReadonlySet<string> = new Set([
PERSISTENCE_DATABASE_PENDING_INDEX_SQL, PERSISTENCE_SYNC_RUN_OPEN_INDEX_SQL, PERSISTENCE_SYNC_RUN_COMMITTED_INDEX_SQL, PERSISTENCE_SYNC_WATERMARK_INDEX_SQL, PERSISTENCE_COMPACTABLE_INDEX_SQL,
+ PERSISTENCE_REQUEST_SLUG_INTENT_INDEX_SQL,
]);
/** Durable infrastructure: never reconstruct or discard these rows during page reindexing. */
export const PERSISTENCE_SCHEMA_STATEMENTS = [
@@ -178,6 +189,7 @@ export const PERSISTENCE_SCHEMA_STATEMENTS = [
PERSISTENCE_SYNC_RUN_COMMITTED_INDEX_SQL,
PERSISTENCE_SYNC_WATERMARK_INDEX_SQL,
PERSISTENCE_COMPACTABLE_INDEX_SQL,
+ PERSISTENCE_REQUEST_SLUG_INTENT_INDEX_SQL,
`CREATE INDEX IF NOT EXISTS persistence_requests_principal ON persistence_requests(principal_kind,principal_id,sequence DESC)`,
`CREATE TABLE IF NOT EXISTS persistence_effects (
id bigserial PRIMARY KEY,
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index 0daa221e71..3a6e5e0d39 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -1333,6 +1333,8 @@ CREATE INDEX IF NOT EXISTS persistence_requests_sync_watermark
ON persistence_requests(worktree_id,source_incarnation,completed_at DESC) WHERE state='committed' AND COALESCE(intent->>'kind','') LIKE 'managed_sync_%';
CREATE INDEX IF NOT EXISTS persistence_requests_compactable
ON persistence_requests(completed_at) WHERE recovery IS NULL AND NOT compacted AND state IN ('committed','conflict','failed','cancelled');
+CREATE INDEX IF NOT EXISTS persistence_requests_slug_intent
+ ON persistence_requests(source_id,slug,sequence) WHERE intent IS NOT NULL AND NOT compacted;
CREATE INDEX IF NOT EXISTS persistence_requests_principal ON persistence_requests(principal_kind,principal_id,sequence DESC);
CREATE TABLE IF NOT EXISTS persistence_effects (
id bigserial PRIMARY KEY,
diff --git a/src/core/repair/request-indexes.ts b/src/core/repair/request-indexes.ts
index 1bde458d37..4cd9750a30 100644
--- a/src/core/repair/request-indexes.ts
+++ b/src/core/repair/request-indexes.ts
@@ -1,13 +1,14 @@
/**
- * `gbrain repair request-indexes` (#5762): create a missing managed sync
- * request index, or drop an INVALID one (an interrupted concurrent build) and
- * rebuild it, on a brain whose schema version is already current, where the
- * v179 migration never runs again. Postgres builds CONCURRENTLY, one index at
+ * `gbrain repair request-indexes` (#5762, #6511): create a missing online-built
+ * request index (the managed sync checkpoint pair, the purge slug index), or
+ * drop an INVALID one (an interrupted concurrent build) and rebuild it, on a
+ * brain whose schema version is already current, where the v179 and slug-index
+ * migrations never run again. Postgres builds CONCURRENTLY, one index at
* a time; PGLite builds inline. An index another session is still building is
* reported, never dropped. Brain-wide; no journal admission and no user data
* changes, so `--all` and doctor remediation include it.
*/
-import { PERSISTENCE_SYNC_RUN_INDEXES } from '../persistence/schema.ts';
+import { PERSISTENCE_REQUEST_ONLINE_INDEXES } from '../persistence/schema.ts';
import { readRequestIndexStates } from '../persistence/checkpoint-validation.ts';
import { buildIndexOnline } from '../schema-migrations/helpers.ts';
import type { RepairHandler, RepairItem } from './core.ts';
@@ -25,9 +26,9 @@ export const requestIndexesRepair: RepairHandler = {
return { items, residuals: { building: states.filter(index => index.state === 'building').length } };
},
async apply(ctx, item) {
- const index = PERSISTENCE_SYNC_RUN_INDEXES.find(candidate => candidate.name === item.slug);
+ const index = PERSISTENCE_REQUEST_ONLINE_INDEXES.find(candidate => candidate.name === item.slug);
if (!index) return false;
- const outcome = await buildIndexOnline(ctx.engine, 0, { ...index, table: 'persistence_requests' }, { notice: line => ctx.logger.info(line.trimEnd()) });
+ const outcome = await buildIndexOnline(ctx.engine, 0, { table: 'persistence_requests', ...index }, { notice: line => ctx.logger.info(line.trimEnd()) });
return outcome === 'created' || outcome === 'rebuilt';
},
};
diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts
index 2f887f8c54..e5b395aed4 100644
--- a/src/core/schema-migrations/latest.generated.ts
+++ b/src/core/schema-migrations/latest.generated.ts
@@ -4,4 +4,4 @@
// The highest schema migration version (migrate.ts LATEST_VERSION), importable without
// loading the migrations themselves.
-export const LATEST_SCHEMA_VERSION = 239;
+export const LATEST_SCHEMA_VERSION = 240;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index f2297d1e85..db63358ce4 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -240,6 +240,7 @@ import { v236 } from './v236-open-loops-counterparty-source.ts';
import { v237 } from './v237-facts-question-recall-indexes.ts';
import { v238 } from './v238-persistence-client-request-id.ts';
import { v239 } from './v239-extract-rollup-halt-reasons.ts';
+import { v240 } from './v240-persistence-request-slug-intent-index.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -478,4 +479,5 @@ export const MIGRATIONS: Migration[] = [
v237,
v238,
v239,
+ v240,
];
diff --git a/src/core/schema-migrations/v240-persistence-request-slug-intent-index.ts b/src/core/schema-migrations/v240-persistence-request-slug-intent-index.ts
new file mode 100644
index 0000000000..789933dc06
--- /dev/null
+++ b/src/core/schema-migrations/v240-persistence-request-slug-intent-index.ts
@@ -0,0 +1,25 @@
+import type { Migration } from './types.ts';
+import { PERSISTENCE_REQUEST_SLUG_INTENT_INDEX } from '../persistence/schema.ts';
+import { buildIndexOnline, migrationNotice } from './helpers.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// #6511 (GBRA-79 wave 16): the page purge's lookup of stored intents for its
+// slug (`findRequestsForSlugs`: source, slug, uncompacted rows with an intent)
+// had no index and ran as a sequential scan of the request table inside the
+// purge's 5 s publication transaction. Postgres builds the partial index
+// CONCURRENTLY outside a transaction, after dropping an INVALID leftover (the
+// blob omits it); PGLite builds it inline. `gbrain repair request-indexes`
+// runs the same helper on a brain whose schema is already current. DDL only:
+// no column, no backfill.
+export const v240: Migration = {
+ version: 240,
+ name: 'persistence_request_slug_intent_index',
+ idempotent: true,
+ transaction: false,
+ sql: '',
+ handler: async engine => {
+ await buildIndexOnline(engine, 240, PERSISTENCE_REQUEST_SLUG_INTENT_INDEX, { notice: migrationNotice });
+ },
+};
diff --git a/test/e2e/persistence-request-indexes-postgres.test.ts b/test/e2e/persistence-request-indexes-postgres.test.ts
index c32a322f42..9c87e7a359 100644
--- a/test/e2e/persistence-request-indexes-postgres.test.ts
+++ b/test/e2e/persistence-request-indexes-postgres.test.ts
@@ -10,7 +10,7 @@ import { claimWorktree, getWorktreeBinding } from '../../src/core/persistence/ow
import { performManagedSync } from '../../src/core/persistence/sync-run.ts';
import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
import { INCOMPLETE_SYNC_RECEIPT_SQL, readRequestIndexStates } from '../../src/core/persistence/checkpoint-validation.ts';
-import { PERSISTENCE_SYNC_RUN_INDEXES } from '../../src/core/persistence/schema.ts';
+import { PERSISTENCE_REQUEST_ONLINE_INDEXES, PERSISTENCE_SYNC_RUN_INDEXES } from '../../src/core/persistence/schema.ts';
import { SCHEMA_SQL } from '../../src/core/schema-embedded.generated.ts';
import { v179 } from '../../src/core/schema-migrations/v179-persistence-request-sync-run-indexes.ts';
import { requestIndexesCheck, requestGrowthCheck } from '../../src/commands/doctor/checks/persistence-requests.ts';
@@ -31,6 +31,9 @@ let close: () => Promise<void>;
const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SOURCE: undefined, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };
const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
const NAMES = PERSISTENCE_SYNC_RUN_INDEXES.map(index => index.name);
+// #6511 added the purge slug index to the online-built set; `readRequestIndexStates` lists it after the pair.
+const ALL_NAMES = PERSISTENCE_REQUEST_ONLINE_INDEXES.map(index => index.name);
+const states = async (names: readonly string[] = ALL_NAMES) => (await readRequestIndexStates(engine, names.map(name => ({ name })))).map(index => index.state);
const ctx = () => ({ engine, config: { engine: 'postgres' }, remote: false, dryRun: false, logger: { info() {}, warn() {}, error() {} } }) as unknown as OperationContext;
beforeAll(async () => {
@@ -92,10 +95,10 @@ test('#5762 on a 512k-row request table every probe is an index scan, and the fo
}), 300_000);
test('#5762 the Postgres blob never builds the indexes; v179 builds them concurrently, one at a time', async () => withEnv(env, async () => {
- for (const name of NAMES) expect(SCHEMA_SQL).not.toContain(name);
+ for (const name of ALL_NAMES) expect(SCHEMA_SQL).not.toContain(name);
for (const name of NAMES) await engine.executeRaw(`DROP INDEX IF EXISTS ${name}`);
await engine.runMigration(0, SCHEMA_SQL);
- expect((await readRequestIndexStates(engine)).map(index => index.state)).toEqual(['missing', 'missing']);
+ expect(await states(NAMES)).toEqual(['missing', 'missing']);
const statements: string[] = [];
const reserve = engine.withReservedConnection.bind(engine);
engine.withReservedConnection = (async (fn: Parameters<PostgresEngine['withReservedConnection']>[0]) => reserve(conn => fn({
@@ -104,23 +107,23 @@ test('#5762 the Postgres blob never builds the indexes; v179 builds them concurr
try { await v179.handler!(engine); } finally { engine.withReservedConnection = reserve; }
expect(statements.filter(sql => sql.startsWith('CREATE INDEX CONCURRENTLY IF NOT EXISTS')).map(sql => sql.split(/\s+/)[6])).toEqual(NAMES);
expect(statements.filter(sql => /^(SET|RESET)\b/i.test(sql))).toEqual([]);
- expect((await readRequestIndexStates(engine)).map(index => index.state)).toEqual(['valid', 'valid']);
+ expect(await states()).toEqual(['valid', 'valid', 'valid']);
}), 120_000);
test('#5762 gbrain repair request-indexes rebuilds a dropped and an INVALID index on a current schema; a second run is a no-op', async () => withEnv(env, async () => {
await engine.executeRaw('DROP INDEX persistence_requests_sync_run_open');
await engine.executeRaw("UPDATE pg_index SET indisvalid=false WHERE indexrelid='persistence_requests_sync_run_committed'::regclass");
- expect(await readRequestIndexStates(engine)).toEqual([{ name: NAMES[0], state: 'missing' }, { name: NAMES[1], state: 'invalid' }]);
+ expect(await readRequestIndexStates(engine)).toEqual([{ name: NAMES[0], state: 'missing' }, { name: NAMES[1], state: 'invalid' }, { name: ALL_NAMES[2], state: 'valid' }]);
const doctor = await requestIndexesCheck(engine);
expect(doctor).toMatchObject({ name: 'persistence_request_indexes', status: 'warn', details: { count: 2, command: 'gbrain repair request-indexes --apply' } });
expect(doctor.message).toContain('persistence_requests_sync_run_committed is INVALID');
const scope = await resolveRepairScope(engine);
const preview = await runRepair(ctx(), requestIndexesRepair, scope, { apply: false });
expect(preview).toMatchObject({ affected: 2, cost: { lifetime_ids: 0 }, apply_command: 'gbrain repair request-indexes --apply' });
- expect((await readRequestIndexStates(engine)).map(index => index.state)).toEqual(['missing', 'invalid']);
+ expect(await states()).toEqual(['missing', 'invalid', 'valid']);
const applied = await runRepair(ctx(), requestIndexesRepair, scope, { apply: true });
expect(applied).toMatchObject({ applied: 2, complete: true });
- expect((await readRequestIndexStates(engine)).map(index => index.state)).toEqual(['valid', 'valid']);
+ expect(await states()).toEqual(['valid', 'valid', 'valid']);
expect((await requestIndexesCheck(engine)).status).toBe('ok');
expect(await runRepair(ctx(), requestIndexesRepair, scope, { apply: true })).toMatchObject({ affected: 0, applied: 0, complete: true });
}), 120_000);
@@ -139,7 +142,7 @@ test('#5762 a build that leaves the index INVALID (a concurrent caller failed fi
try { await expect(buildIndexOnline(engine, 0, index)).rejects.toThrow(`Index ${index.name} is not valid after its concurrent build`); }
finally { engine.withReservedConnection = reserve; }
expect(await buildIndexOnline(engine, 0, index)).toBe('rebuilt');
- expect((await readRequestIndexStates(engine)).map(state => state.state)).toEqual(['valid', 'valid']);
+ expect(await states()).toEqual(['valid', 'valid', 'valid']);
}), 60_000);
test('#5762 recovery journey: a checkpoint timeout with a dropped index is fixed by the two printed commands', async () => withEnv(env, async () => {
diff --git a/test/fact-purge-lookup-timeout-6511.test.ts b/test/fact-purge-lookup-timeout-6511.test.ts
new file mode 100644
index 0000000000..5444a15421
--- /dev/null
+++ b/test/fact-purge-lookup-timeout-6511.test.ts
@@ -0,0 +1,100 @@
+/**
+ * #6511 (GBRA-79 wave 16, G3.1 [R5]): the fact purge's planning read of the
+ * historical journal (`findRequestsCarrying`, an unindexable substring search)
+ * can hit the statement budget on a large journal. That timeout is
+ * deterministic, not contention: the plan fails with the typed
+ * `purge_lookup_timeout`, nothing is purged, tombstoned or redacted, no page
+ * receipt is persisted for the dry run, and a following write to the source
+ * commits. Master: the raw 57014 escaped the handler as an untyped error.
+ *
+ * Semantic injection: `installFaultHook('purge:carrying_lookup')` makes the
+ * named read fail; no SQL substring. PGLite and, with DATABASE_URL, Postgres.
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operations, OperationError, type OperationContext } from '../src/core/operations.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { CODES } from '../src/core/error-registry.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const CLAIM = 'Door code is 4417';
+const page = (title: string) => `---\ntitle: ${title}\ntype: note\n---\n# ${title}\n\nProse about ${title}.\n\n## Facts\n\n<!--- gbrain:facts:begin -->
+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |
+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|
+| 1 | ${CLAIM} | fact | 1.0 | world | medium | 2026-01-01 | | chat | |
+<!--- gbrain:facts:end -->\n`;
+const op = (name: string) => operations.find(o => o.name === name)!;
+const timeout57014 = () => Object.assign(new Error('canceling statement due to statement timeout'), { code: '57014' });
+
+for (const backend of testBackends()) describe(`[${backend}] #6511 purge_fact planning lookup timeout`, () => {
+ let engine: BrainEngine;
+ let closePostgres: (() => Promise<void>) | undefined;
+ const home = mkdtempSync(join(tmpdir(), `gbrain-6511-fact-${backend}-`));
+ const context = (): OperationContext => ({ engine, config: { engine: backend, embedding_disabled: true } as never,
+ logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false, sourceId: 'default' });
+ const call = (name: string, params: Record<string, unknown>) => withEnv({ GBRAIN_HOME: home }, () => op(name).handler(context(), params)) as Promise<Record<string, any>>;
+ const count = async (sql: string, params: unknown[] = []) => Number((await engine.executeRaw<{ n: string }>(`SELECT count(*)::text AS n FROM ${sql}`, params))[0]!.n);
+ const snapshot = async () => ({
+ facts: await count('facts WHERE source_id=$1', ['default']), factPurges: await count('fact_purges'), pagePurges: await count('page_purges'),
+ requests: await count('persistence_requests'), carrying: await count("persistence_requests WHERE strpos(lower(intent::text), lower($1)) > 0", [CLAIM]),
+ });
+
+ beforeAll(async () => {
+ if (backend === 'pglite') { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }
+ else { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engine = pg.engine; closePostgres = pg.close; }
+ await importFromContent(engine, 'people/door', page('Door'), { noEmbed: true, sourceId: 'default' });
+ await runExtractFacts(engine, { slugs: ['people/door'] });
+ const carrier = await call('put_page', { slug: 'notes/door-carrier', content: `---\ntitle: Carrier\ntype: note\n---\nSomeone wrote: ${CLAIM}.\n`, request_id: randomUUID() });
+ expect(carrier.state).toBe('committed');
+ }, 120_000);
+ afterAll(async () => {
+ installFaultHook(undefined);
+ await disposePersistenceConsumer(engine); await engine.disconnect(); await closePostgres?.();
+ rmSync(home, { recursive: true, force: true });
+ }, 60_000);
+ afterEach(() => installFaultHook(undefined));
+
+ test('a statement timeout of the planning lookup is the typed purge_lookup_timeout; nothing is purged, no receipt is stored, the source keeps moving', async () => {
+ const [fact] = await engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE fact=$1 AND source_id=$2', [CLAIM, 'default']);
+ const before = await snapshot();
+ expect(before.carrying).toBeGreaterThan(0);
+ let seen = 0;
+ installFaultHook(point => { if (point === 'purge:carrying_lookup') { seen++; throw timeout57014(); } });
+ let error: OperationError | undefined;
+ try { await call('purge_fact', { id: Number(fact!.id), dry_run: true }); } catch (e) { error = e as OperationError; }
+ expect(error).toBeInstanceOf(OperationError);
+ expect(error!.code).toBe('purge_lookup_timeout');
+ expect(error!.message).toContain('could not finish');
+ expect(error!.message).toContain('Do not assume');
+ expect(error!.fix).toMatchObject({ argv: ['gbrain', 'repair', 'request-indexes', '--json'] });
+ expect(seen).toBe(1);
+ expect(await snapshot()).toEqual(before);
+ expect(await count("persistence_requests WHERE operation='purge_fact'")).toBe(0);
+ installFaultHook(undefined);
+ const dry = await call('purge_fact', { id: Number(fact!.id), dry_run: true });
+ expect(dry).toMatchObject({ dry_run: true, action: 'purge_fact' });
+ expect(await snapshot()).toEqual(before);
+ const written = await call('put_page', { slug: 'notes/after-timeout', content: '---\ntitle: After\ntype: note\n---\nStill moving.\n', request_id: randomUUID() });
+ expect(written.state).toBe('committed');
+ }, 60_000);
+
+ test('the error registry classifies purge_lookup_timeout as a non-retryable caller error the brain host administers', () => {
+ expect(CODES.purge_lookup_timeout).toMatchObject({ class: 'caller', retryable: false, actor: 'host_admin', docs: 'docs/guides/write-refusals.md#purge_lookup_timeout' });
+ });
+
+ test('any other failure of the planning lookup is rethrown untyped', async () => {
+ const [fact] = await engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE fact=$1 AND source_id=$2', [CLAIM, 'default']);
+ installFaultHook(point => { if (point === 'purge:carrying_lookup') throw Object.assign(new Error('connection reset'), { code: '08006' }); });
+ await expect(call('purge_fact', { id: Number(fact!.id), dry_run: true })).rejects.toThrow('connection reset');
+ });
+});
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index cbf296ad1e..5dc5212625 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -1176,6 +1176,7 @@
"persistence_requests_principal_kind_principal_id_request_id_key": "CREATE UNIQUE INDEX persistence_requests_principal_kind_principal_id_request_id_key ON public.persistence_requests USING btree (principal_kind, principal_id, request_id)",
"persistence_requests_recovery": "CREATE INDEX persistence_requests_recovery ON public.persistence_requests USING btree (worktree_id, sequence) WHERE (recovery IS NOT NULL)",
"persistence_requests_sequence_key": "CREATE UNIQUE INDEX persistence_requests_sequence_key ON public.persistence_requests USING btree (sequence)",
+ "persistence_requests_slug_intent": "CREATE INDEX persistence_requests_slug_intent ON public.persistence_requests USING btree (source_id, slug, sequence) WHERE ((intent IS NOT NULL) AND (NOT compacted))",
"persistence_requests_sync_run_committed": "CREATE INDEX persistence_requests_sync_run_committed ON public.persistence_requests USING btree (source_id, ((intent ->> 'runId'::text)), ((intent ->> 'index'::text))) WHERE ((state = 'committed'::text) AND (intent ? 'runId'::text))",
"persistence_requests_sync_run_open": "CREATE INDEX persistence_requests_sync_run_open ON public.persistence_requests USING btree (worktree_id, ((intent ->> 'runId'::text))) WHERE ((state <> 'committed'::text) AND ((intent ->> 'kind'::text) = ANY (ARRAY['managed_sync_import'::text, 'managed_sync_delete'::text])))",
"persistence_requests_sync_watermark": "CREATE INDEX persistence_requests_sync_watermark ON public.persistence_requests USING btree (worktree_id, source_incarnation, completed_at DESC) WHERE ((state = 'committed'::text) AND (COALESCE((intent ->> 'kind'::text), ''::text) ~~ 'managed_sync_%'::text))",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index 152c1ca406..c8bd028764 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -1176,6 +1176,7 @@
"persistence_requests_principal_kind_principal_id_request_id_key": "CREATE UNIQUE INDEX persistence_requests_principal_kind_principal_id_request_id_key ON public.persistence_requests USING btree (principal_kind, principal_id, request_id)",
"persistence_requests_recovery": "CREATE INDEX persistence_requests_recovery ON public.persistence_requests USING btree (worktree_id, sequence) WHERE (recovery IS NOT NULL)",
"persistence_requests_sequence_key": "CREATE UNIQUE INDEX persistence_requests_sequence_key ON public.persistence_requests USING btree (sequence)",
+ "persistence_requests_slug_intent": "CREATE INDEX persistence_requests_slug_intent ON public.persistence_requests USING btree (source_id, slug, sequence) WHERE ((intent IS NOT NULL) AND (NOT compacted))",
"persistence_requests_sync_run_committed": "CREATE INDEX persistence_requests_sync_run_committed ON public.persistence_requests USING btree (source_id, ((intent ->> 'runId'::text)), ((intent ->> 'index'::text))) WHERE ((state = 'committed'::text) AND (intent ? 'runId'::text))",
"persistence_requests_sync_run_open": "CREATE INDEX persistence_requests_sync_run_open ON public.persistence_requests USING btree (worktree_id, ((intent ->> 'runId'::text))) WHERE ((state <> 'committed'::text) AND ((intent ->> 'kind'::text) = ANY (ARRAY['managed_sync_import'::text, 'managed_sync_delete'::text])))",
"persistence_requests_sync_watermark": "CREATE INDEX persistence_requests_sync_watermark ON public.persistence_requests USING btree (worktree_id, source_incarnation, completed_at DESC) WHERE ((state = 'committed'::text) AND (COALESCE((intent ->> 'kind'::text), ''::text) ~~ 'managed_sync_%'::text))",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index e856bc2caa..c7a8d4b915 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -1172,6 +1172,7 @@
"persistence_requests_principal_kind_principal_id_request_id_key": "CREATE UNIQUE INDEX persistence_requests_principal_kind_principal_id_request_id_key ON public.persistence_requests USING btree (principal_kind, principal_id, request_id)",
"persistence_requests_recovery": "CREATE INDEX persistence_requests_recovery ON public.persistence_requests USING btree (worktree_id, sequence) WHERE (recovery IS NOT NULL)",
"persistence_requests_sequence_key": "CREATE UNIQUE INDEX persistence_requests_sequence_key ON public.persistence_requests USING btree (sequence)",
+ "persistence_requests_slug_intent": "CREATE INDEX persistence_requests_slug_intent ON public.persistence_requests USING btree (source_id, slug, sequence) WHERE ((intent IS NOT NULL) AND (NOT compacted))",
"persistence_requests_sync_run_committed": "CREATE INDEX persistence_requests_sync_run_committed ON public.persistence_requests USING btree (source_id, ((intent ->> 'runId'::text)), ((intent ->> 'index'::text))) WHERE ((state = 'committed'::text) AND (intent ? 'runId'::text))",
"persistence_requests_sync_run_open": "CREATE INDEX persistence_requests_sync_run_open ON public.persistence_requests USING btree (worktree_id, ((intent ->> 'runId'::text))) WHERE ((state <> 'committed'::text) AND ((intent ->> 'kind'::text) = ANY (ARRAY['managed_sync_import'::text, 'managed_sync_delete'::text])))",
"persistence_requests_sync_watermark": "CREATE INDEX persistence_requests_sync_watermark ON public.persistence_requests USING btree (worktree_id, source_incarnation, completed_at DESC) WHERE ((state = 'committed'::text) AND (COALESCE((intent ->> 'kind'::text), ''::text) ~~ 'managed_sync_%'::text))",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
index 0f36bcf4cf..c93c866c8c 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
@@ -835,6 +835,7 @@
"persistence_requests_principal_kind_principal_id_request_id_key": "CREATE UNIQUE INDEX persistence_requests_principal_kind_principal_id_request_id_key ON public.persistence_requests USING btree (principal_kind, principal_id, request_id)",
"persistence_requests_recovery": "CREATE INDEX persistence_requests_recovery ON public.persistence_requests USING btree (worktree_id, sequence) WHERE (recovery IS NOT NULL)",
"persistence_requests_sequence_key": "CREATE UNIQUE INDEX persistence_requests_sequence_key ON public.persistence_requests USING btree (sequence)",
+ "persistence_requests_slug_intent": "CREATE INDEX persistence_requests_slug_intent ON public.persistence_requests USING btree (source_id, slug, sequence) WHERE ((intent IS NOT NULL) AND (NOT compacted))",
"persistence_requests_sync_run_committed": "CREATE INDEX persistence_requests_sync_run_committed ON public.persistence_requests USING btree (source_id, ((intent ->> 'runId'::text)), ((intent ->> 'index'::text))) WHERE ((state = 'committed'::text) AND (intent ? 'runId'::text))",
"persistence_requests_sync_run_open": "CREATE INDEX persistence_requests_sync_run_open ON public.persistence_requests USING btree (worktree_id, ((intent ->> 'runId'::text))) WHERE ((state <> 'committed'::text) AND ((intent ->> 'kind'::text) = ANY (ARRAY['managed_sync_import'::text, 'managed_sync_delete'::text])))",
"persistence_requests_sync_watermark": "CREATE INDEX persistence_requests_sync_watermark ON public.persistence_requests USING btree (worktree_id, source_incarnation, completed_at DESC) WHERE ((state = 'committed'::text) AND (COALESCE((intent ->> 'kind'::text), ''::text) ~~ 'managed_sync_%'::text))",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
index 00ecc19cf1..f7b112bfce 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
@@ -835,6 +835,7 @@
"persistence_requests_principal_kind_principal_id_request_id_key": "CREATE UNIQUE INDEX persistence_requests_principal_kind_principal_id_request_id_key ON public.persistence_requests USING btree (principal_kind, principal_id, request_id)",
"persistence_requests_recovery": "CREATE INDEX persistence_requests_recovery ON public.persistence_requests USING btree (worktree_id, sequence) WHERE (recovery IS NOT NULL)",
"persistence_requests_sequence_key": "CREATE UNIQUE INDEX persistence_requests_sequence_key ON public.persistence_requests USING btree (sequence)",
+ "persistence_requests_slug_intent": "CREATE INDEX persistence_requests_slug_intent ON public.persistence_requests USING btree (source_id, slug, sequence) WHERE ((intent IS NOT NULL) AND (NOT compacted))",
"persistence_requests_sync_run_committed": "CREATE INDEX persistence_requests_sync_run_committed ON public.persistence_requests USING btree (source_id, ((intent ->> 'runId'::text)), ((intent ->> 'index'::text))) WHERE ((state = 'committed'::text) AND (intent ? 'runId'::text))",
"persistence_requests_sync_run_open": "CREATE INDEX persistence_requests_sync_run_open ON public.persistence_requests USING btree (worktree_id, ((intent ->> 'runId'::text))) WHERE ((state <> 'committed'::text) AND ((intent ->> 'kind'::text) = ANY (ARRAY['managed_sync_import'::text, 'managed_sync_delete'::text])))",
"persistence_requests_sync_watermark": "CREATE INDEX persistence_requests_sync_watermark ON public.persistence_requests USING btree (worktree_id, source_incarnation, completed_at DESC) WHERE ((state = 'committed'::text) AND (COALESCE((intent ->> 'kind'::text), ''::text) ~~ 'managed_sync_%'::text))",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
index 113a0c3928..2238fcb87a 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
@@ -834,6 +834,7 @@
"persistence_requests_principal_kind_principal_id_request_id_key": "CREATE UNIQUE INDEX persistence_requests_principal_kind_principal_id_request_id_key ON public.persistence_requests USING btree (principal_kind, principal_id, request_id)",
"persistence_requests_recovery": "CREATE INDEX persistence_requests_recovery ON public.persistence_requests USING btree (worktree_id, sequence) WHERE (recovery IS NOT NULL)",
"persistence_requests_sequence_key": "CREATE UNIQUE INDEX persistence_requests_sequence_key ON public.persistence_requests USING btree (sequence)",
+ "persistence_requests_slug_intent": "CREATE INDEX persistence_requests_slug_intent ON public.persistence_requests USING btree (source_id, slug, sequence) WHERE ((intent IS NOT NULL) AND (NOT compacted))",
"persistence_requests_sync_run_committed": "CREATE INDEX persistence_requests_sync_run_committed ON public.persistence_requests USING btree (source_id, ((intent ->> 'runId'::text)), ((intent ->> 'index'::text))) WHERE ((state = 'committed'::text) AND (intent ? 'runId'::text))",
"persistence_requests_sync_run_open": "CREATE INDEX persistence_requests_sync_run_open ON public.persistence_requests USING btree (worktree_id, ((intent ->> 'runId'::text))) WHERE ((state <> 'committed'::text) AND ((intent ->> 'kind'::text) = ANY (ARRAY['managed_sync_import'::text, 'managed_sync_delete'::text])))",
"persistence_requests_sync_watermark": "CREATE INDEX persistence_requests_sync_watermark ON public.persistence_requests USING btree (worktree_id, source_incarnation, completed_at DESC) WHERE ((state = 'committed'::text) AND (COALESCE((intent ->> 'kind'::text), ''::text) ~~ 'managed_sync_%'::text))",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
index 203128b796..a4fd9193ff 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@ -1180,6 +1180,7 @@
"persistence_requests_principal_kind_principal_id_request_id_key": "CREATE UNIQUE INDEX persistence_requests_principal_kind_principal_id_request_id_key ON public.persistence_requests USING btree (principal_kind, principal_id, request_id)",
"persistence_requests_recovery": "CREATE INDEX persistence_requests_recovery ON public.persistence_requests USING btree (worktree_id, sequence) WHERE (recovery IS NOT NULL)",
"persistence_requests_sequence_key": "CREATE UNIQUE INDEX persistence_requests_sequence_key ON public.persistence_requests USING btree (sequence)",
+ "persistence_requests_slug_intent": "CREATE INDEX persistence_requests_slug_intent ON public.persistence_requests USING btree (source_id, slug, sequence) WHERE ((intent IS NOT NULL) AND (NOT compacted))",
"persistence_requests_sync_run_committed": "CREATE INDEX persistence_requests_sync_run_committed ON public.persistence_requests USING btree (source_id, ((intent ->> 'runId'::text)), ((intent ->> 'index'::text))) WHERE ((state = 'committed'::text) AND (intent ? 'runId'::text))",
"persistence_requests_sync_run_open": "CREATE INDEX persistence_requests_sync_run_open ON public.persistence_requests USING btree (worktree_id, ((intent ->> 'runId'::text))) WHERE ((state <> 'committed'::text) AND ((intent ->> 'kind'::text) = ANY (ARRAY['managed_sync_import'::text, 'managed_sync_delete'::text])))",
"persistence_requests_sync_watermark": "CREATE INDEX persistence_requests_sync_watermark ON public.persistence_requests USING btree (worktree_id, source_incarnation, completed_at DESC) WHERE ((state = 'committed'::text) AND (COALESCE((intent ->> 'kind'::text), ''::text) ~~ 'managed_sync_%'::text))",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
index b932210248..e1c91042fc 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@ -1180,6 +1180,7 @@
"persistence_requests_principal_kind_principal_id_request_id_key": "CREATE UNIQUE INDEX persistence_requests_principal_kind_principal_id_request_id_key ON public.persistence_requests USING btree (principal_kind, principal_id, request_id)",
"persistence_requests_recovery": "CREATE INDEX persistence_requests_recovery ON public.persistence_requests USING btree (worktree_id, sequence) WHERE (recovery IS NOT NULL)",
"persistence_requests_sequence_key": "CREATE UNIQUE INDEX persistence_requests_sequence_key ON public.persistence_requests USING btree (sequence)",
+ "persistence_requests_slug_intent": "CREATE INDEX persistence_requests_slug_intent ON public.persistence_requests USING btree (source_id, slug, sequence) WHERE ((intent IS NOT NULL) AND (NOT compacted))",
"persistence_requests_sync_run_committed": "CREATE INDEX persistence_requests_sync_run_committed ON public.persistence_requests USING btree (source_id, ((intent ->> 'runId'::text)), ((intent ->> 'index'::text))) WHERE ((state = 'committed'::text) AND (intent ? 'runId'::text))",
"persistence_requests_sync_run_open": "CREATE INDEX persistence_requests_sync_run_open ON public.persistence_requests USING btree (worktree_id, ((intent ->> 'runId'::text))) WHERE ((state <> 'committed'::text) AND ((intent ->> 'kind'::text) = ANY (ARRAY['managed_sync_import'::text, 'managed_sync_delete'::text])))",
"persistence_requests_sync_watermark": "CREATE INDEX persistence_requests_sync_watermark ON public.persistence_requests USING btree (worktree_id, source_incarnation, completed_at DESC) WHERE ((state = 'committed'::text) AND (COALESCE((intent ->> 'kind'::text), ''::text) ~~ 'managed_sync_%'::text))",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
index 241f39db24..7434efbb96 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@ -1176,6 +1176,7 @@
"persistence_requests_principal_kind_principal_id_request_id_key": "CREATE UNIQUE INDEX persistence_requests_principal_kind_principal_id_request_id_key ON public.persistence_requests USING btree (principal_kind, principal_id, request_id)",
"persistence_requests_recovery": "CREATE INDEX persistence_requests_recovery ON public.persistence_requests USING btree (worktree_id, sequence) WHERE (recovery IS NOT NULL)",
"persistence_requests_sequence_key": "CREATE UNIQUE INDEX persistence_requests_sequence_key ON public.persistence_requests USING btree (sequence)",
+ "persistence_requests_slug_intent": "CREATE INDEX persistence_requests_slug_intent ON public.persistence_requests USING btree (source_id, slug, sequence) WHERE ((intent IS NOT NULL) AND (NOT compacted))",
"persistence_requests_sync_run_committed": "CREATE INDEX persistence_requests_sync_run_committed ON public.persistence_requests USING btree (source_id, ((intent ->> 'runId'::text)), ((intent ->> 'index'::text))) WHERE ((state = 'committed'::text) AND (intent ? 'runId'::text))",
"persistence_requests_sync_run_open": "CREATE INDEX persistence_requests_sync_run_open ON public.persistence_requests USING btree (worktree_id, ((intent ->> 'runId'::text))) WHERE ((state <> 'committed'::text) AND ((intent ->> 'kind'::text) = ANY (ARRAY['managed_sync_import'::text, 'managed_sync_delete'::text])))",
"persistence_requests_sync_watermark": "CREATE INDEX persistence_requests_sync_watermark ON public.persistence_requests USING btree (worktree_id, source_incarnation, completed_at DESC) WHERE ((state = 'committed'::text) AND (COALESCE((intent ->> 'kind'::text), ''::text) ~~ 'managed_sync_%'::text))",
diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.json
index f87f23f40d..8b1b102485 100644
--- a/test/fixtures/goldens/doctor/content-pglite-json.json
+++ b/test/fixtures/goldens/doctor/content-pglite-json.json
@@ -832,6 +832,10 @@
{
"name": "persistence_requests_sync_run_committed",
"state": "valid"
+ },
+ {
+ "name": "persistence_requests_slug_intent",
+ "state": "valid"
}
],
"repair": "request-indexes"
diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
index 984b9d0131..94fd53fbef 100644
--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
@@ -860,6 +860,10 @@
{
"name": "persistence_requests_sync_run_committed",
"state": "valid"
+ },
+ {
+ "name": "persistence_requests_slug_intent",
+ "state": "valid"
}
],
"repair": "request-indexes"
@@ -3939,6 +3943,10 @@
{
"name": "persistence_requests_sync_run_committed",
"state": "valid"
+ },
+ {
+ "name": "persistence_requests_slug_intent",
+ "state": "valid"
}
],
"repair": "request-indexes"
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index e5514a7b78..34dcb9fcb2 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -772,6 +772,10 @@
{
"name": "persistence_requests_sync_run_committed",
"state": "valid"
+ },
+ {
+ "name": "persistence_requests_slug_intent",
+ "state": "valid"
}
],
"repair": "request-indexes"
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index 436d9a5e97..2d1c03dc48 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -791,6 +791,10 @@
{
"name": "persistence_requests_sync_run_committed",
"state": "valid"
+ },
+ {
+ "name": "persistence_requests_slug_intent",
+ "state": "valid"
}
],
"repair": "request-indexes"
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 61543b7033..267b9c23f6 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -6123,7 +6123,7 @@
{
"kind": "class",
"members": [
- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_branch_unborn\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"merge_recommended\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"pending_writes\" | \"persistence_write_stall\" | \"schema_lock_blocked\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"question_not_found\" | \"question_owner_only\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"search_offset_over_cap\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
+ "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_branch_unborn\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"merge_recommended\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"pending_writes\" | \"persistence_write_stall\" | \"schema_lock_blocked\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"question_not_found\" | \"question_owner_only\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"search_offset_over_cap\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
"canonicalCode: string",
"cause?: unknown",
"code: ErrorCode",
diff --git a/test/migration-persistence-request-slug-index.test.ts b/test/migration-persistence-request-slug-index.test.ts
new file mode 100644
index 0000000000..c2d7e70a10
--- /dev/null
+++ b/test/migration-persistence-request-slug-index.test.ts
@@ -0,0 +1,143 @@
+/**
+ * #6511 (GBRA-79 wave 16, G3.1 [R4]): the migration that builds the purge's
+ * slug index on the request table (`persistence_requests_slug_intent`) has the
+ * v179 shape: `transaction: false`, an empty `sql`, a handler that runs
+ * `buildIndexOnline` (CONCURRENTLY on Postgres, inline on PGLite). DDL only:
+ * no `ALTER TABLE … ADD COLUMN` (DECISIONS.md D2 keeps the cap column out).
+ * The Postgres schema blob omits the index; PGLite's blob carries it, so a fresh
+ * PGLite brain needs no build. `gbrain repair request-indexes` rebuilds a
+ * dropped (both engines) or INVALID (Postgres) index on a current schema, and a
+ * concurrent writer keeps committing while the Postgres build runs.
+ *
+ * The migration is found by its name, never by its number: the number is
+ * provisional until the merge slot (GBRA-81 carries a sibling).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { PostgresEngine } from '../src/core/postgres-engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { readRequestIndexStates } from '../src/core/persistence/checkpoint-validation.ts';
+import { PERSISTENCE_REQUEST_ONLINE_INDEXES, PERSISTENCE_REQUEST_SLUG_INTENT_INDEX, POSTGRES_CONCURRENT_PERSISTENCE_INDEXES } from '../src/core/persistence/schema.ts';
+import { PGLITE_SCHEMA_SQL } from '../src/core/pglite-schema.generated.ts';
+import { SCHEMA_SQL } from '../src/core/schema-embedded.generated.ts';
+import { MIGRATIONS } from '../src/core/schema-migrations/registry.generated.ts';
+import { LATEST_SCHEMA_VERSION } from '../src/core/schema-migrations/latest.generated.ts';
+import { runRepair, resolveRepairScope } from '../src/core/repair/core.ts';
+import { requestIndexesRepair } from '../src/core/repair/request-indexes.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const INDEX = PERSISTENCE_REQUEST_SLUG_INTENT_INDEX;
+const migration = MIGRATIONS.find(m => m.name === 'persistence_request_slug_intent_index');
+
+describe('#6511 the slug index migration module', () => {
+ test('is registered once, as the latest migration, in the v179 online-index shape', () => {
+ expect(MIGRATIONS.filter(m => m.name === 'persistence_request_slug_intent_index')).toHaveLength(1);
+ expect(migration).toMatchObject({ idempotent: true, transaction: false, sql: '' });
+ expect(migration!.version).toBe(LATEST_SCHEMA_VERSION);
+ expect(typeof migration!.handler).toBe('function');
+ });
+ test('is DDL only: an index on the request table, no column and no backfill', () => {
+ expect(INDEX.sql).toMatch(/^CREATE INDEX IF NOT EXISTS persistence_requests_slug_intent\s+ON persistence_requests\(source_id,slug,sequence\) WHERE intent IS NOT NULL AND NOT compacted$/);
+ expect(INDEX.sql).not.toMatch(/ALTER TABLE|ADD COLUMN|UPDATE /i);
+ expect(migration!.sql).not.toMatch(/ALTER TABLE|ADD COLUMN/i);
+ });
+ test('the Postgres blob omits the index (the migration builds it CONCURRENTLY); the PGLite blob carries it', () => {
+ expect(POSTGRES_CONCURRENT_PERSISTENCE_INDEXES.has(INDEX.sql)).toBe(true);
+ expect(SCHEMA_SQL).not.toContain(INDEX.name);
+ expect(PGLITE_SCHEMA_SQL).toContain(INDEX.name);
+ expect(PERSISTENCE_REQUEST_ONLINE_INDEXES.map(index => index.name)).toContain(INDEX.name);
+ });
+});
+
+for (const backend of testBackends()) describe(`[${backend}] #6511 the slug index on a brain`, () => {
+ let engine: BrainEngine;
+ let closePostgres: (() => Promise<void>) | undefined;
+ const ctx = () => ({ engine, config: { engine: backend }, remote: false, dryRun: false, logger: { info() {}, warn() {}, error() {} } }) as unknown as OperationContext;
+ const state = async () => (await readRequestIndexStates(engine, [INDEX]))[0]!.state;
+ const explain = async (slug: string) => JSON.stringify(await engine.executeRaw(
+ `EXPLAIN (FORMAT JSON) SELECT id::text FROM persistence_requests WHERE source_id=$1 AND slug=ANY($2::text[]) AND NOT compacted AND intent IS NOT NULL ORDER BY sequence LIMIT 10000`,
+ ['default', [slug]]));
+
+ beforeAll(async () => {
+ if (backend === 'pglite') { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }
+ else { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engine = pg.engine; closePostgres = pg.close; }
+ }, 120_000);
+ afterAll(async () => { await engine.disconnect(); await closePostgres?.(); }, 60_000);
+
+ test('a current brain has the index valid; the migration handler is a no-op on it', async () => {
+ expect(await state()).toBe('valid');
+ await migration!.handler!(engine);
+ expect(await state()).toBe('valid');
+ });
+
+ test('a dropped index is rebuilt by the migration handler and by gbrain repair request-indexes; a second repair is a no-op', async () => {
+ await engine.executeRaw(`DROP INDEX ${INDEX.name}`);
+ expect(await state()).toBe('missing');
+ await migration!.handler!(engine);
+ expect(await state()).toBe('valid');
+ await engine.executeRaw(`DROP INDEX ${INDEX.name}`);
+ const scope = await resolveRepairScope(engine);
+ const preview = await runRepair(ctx(), requestIndexesRepair, scope, { apply: false });
+ expect(preview).toMatchObject({ affected: 1, apply_command: 'gbrain repair request-indexes --apply' });
+ expect(await state()).toBe('missing');
+ expect(await runRepair(ctx(), requestIndexesRepair, scope, { apply: true })).toMatchObject({ applied: 1, complete: true });
+ expect(await state()).toBe('valid');
+ expect(await runRepair(ctx(), requestIndexesRepair, scope, { apply: true })).toMatchObject({ affected: 0, applied: 0, complete: true });
+ }, 60_000);
+
+ if (backend === 'postgres') {
+ test('the purge slug lookup is served by the index on a wide request table, and was a sequential scan without it', async () => {
+ await engine.executeRaw(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,digest,intent,authority,intent_bytes,terminal_reservation,state)
+ SELECT 'local_cli','seed',gen_random_uuid(),'put_page','default',(SELECT incarnation FROM sources WHERE id='default'),'seed-'||g,'d',jsonb_build_object('kind','put_page','n',g),'{}'::jsonb,1,64,'committed'
+ FROM generate_series(1,50000) g`);
+ await engine.executeRaw('ANALYZE persistence_requests');
+ expect(await explain('seed-7')).toContain(INDEX.name);
+ await engine.executeRaw(`DROP INDEX ${INDEX.name}`);
+ expect(await explain('seed-7')).toContain('Seq Scan');
+ await migration!.handler!(engine);
+ expect(await explain('seed-7')).toContain(INDEX.name);
+ }, 120_000);
+
+ test('an INVALID index (an interrupted concurrent build) is dropped and rebuilt; the build is CONCURRENTLY outside a transaction and sets nothing on the session', async () => {
+ const pg = engine as PostgresEngine;
+ await pg.executeRaw(`UPDATE pg_index SET indisvalid=false WHERE indexrelid='${INDEX.name}'::regclass`);
+ expect(await state()).toBe('invalid');
+ const statements: string[] = [];
+ const reserve = pg.withReservedConnection.bind(pg);
+ pg.withReservedConnection = (async (fn: Parameters<PostgresEngine['withReservedConnection']>[0]) => reserve(conn => fn({
+ executeRaw: async (sql: string, params?: unknown[]) => { statements.push(sql); return conn.executeRaw(sql, params); },
+ }))) as PostgresEngine['withReservedConnection'];
+ try { await migration!.handler!(pg); } finally { pg.withReservedConnection = reserve; }
+ expect(statements.filter(sql => sql.startsWith('CREATE INDEX CONCURRENTLY IF NOT EXISTS')).map(sql => sql.split(/\s+/)[6])).toEqual([INDEX.name]);
+ expect(statements.filter(sql => /^(SET|RESET|BEGIN)\b/i.test(sql))).toEqual([]);
+ expect(await state()).toBe('valid');
+ }, 60_000);
+
+ test('a writer committing request rows during the concurrent build is never blocked', async () => {
+ const pg = engine as PostgresEngine;
+ await pg.executeRaw(`DROP INDEX ${INDEX.name}`);
+ let stop = false, committed = 0;
+ const writer = (async () => {
+ while (!stop) {
+ await pg.executeRaw(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,digest,intent,authority,intent_bytes,terminal_reservation,state)
+ VALUES('local_cli','writer',$1::uuid,'put_page','default',(SELECT incarnation FROM sources WHERE id='default'),$2,'d','{"kind":"put_page"}'::jsonb,'{}'::jsonb,1,32,'committed')`, [randomUUID(), `live-${committed}`]);
+ committed++;
+ }
+ })();
+ const reserve = pg.withReservedConnection.bind(pg);
+ // The build holds its connection a while so the writer provably overlaps it.
+ pg.withReservedConnection = (async (fn: Parameters<PostgresEngine['withReservedConnection']>[0]) => reserve(async conn => {
+ await conn.executeRaw('SELECT pg_sleep(0.5)');
+ return fn(conn);
+ })) as PostgresEngine['withReservedConnection'];
+ const before = committed;
+ try { await migration!.handler!(pg); } finally { pg.withReservedConnection = reserve; stop = true; await writer; }
+ expect(committed).toBeGreaterThan(before);
+ expect(await state()).toBe('valid');
+ expect(await explain('live-1')).toContain(INDEX.name);
+ }, 60_000);
+ }
+});
diff --git a/test/page-purge-journal-timeout-6511.test.ts b/test/page-purge-journal-timeout-6511.test.ts
new file mode 100644
index 0000000000..9dbc7213de
--- /dev/null
+++ b/test/page-purge-journal-timeout-6511.test.ts
@@ -0,0 +1,438 @@
+/**
+ * #6511 (GBRA-79 wave 16, G3.1): a page purge's historical-request lookup
+ * used to run as an O(journal) substring scan inside the 5 s publication
+ * transaction, and its statement timeout (57014) was classified as
+ * transient contention with no attempt cap, so the request oscillated
+ * queued <-> running forever and FIFO held every later write to its source.
+ *
+ * Protects (fail-first against master):
+ * - [R1 a] a statement timeout inside any of the purge's remaining in-transaction
+ * lookups (slug lookup, tail re-check, pending re-check, locking read) ends the
+ * request `failed`/`purge_lookup_timeout` on the FIRST claim, with the failed
+ * receipt retained, nothing removed or tombstoned, a following write to the
+ * source committing, a same-id retry returning the terminal failure and a new
+ * request_id admitted. Master: `write_pending`, the row left `queued` with
+ * `database_contention` after several claims, no `journal_sweep` on any receipt.
+ * - [R1 b] a journal sweep that outruns the preparation budget is a charged
+ * `preparation_deadline` release, then `preparation_stalled` at the attempt
+ * limit; the sweep loop checks the claim clock itself between chunks (PGLite
+ * has no server-side bound) and on Postgres the bounded read's 57014 is the
+ * same deadline.
+ * - [R1 c] both recovery arms: a database-only page and a worktree-backed page,
+ * with the canonical bytes byte-identical after the terminal failure.
+ * - [R2] the preparation sweep records a sequence ceiling and the rows pending
+ * at scan; the publication re-checks the tail and those rows, so a carrying
+ * request admitted-then-cancelled after the scan, or settled after it, is
+ * still redacted; a request still queued at publication is left in place;
+ * `journal_sweep.complete` is false when a cap is hit, never swallowed.
+ * - [R3] the keyset sweep: continuation past empty chunks, matches beyond the
+ * second chunk, compacted outcomes, error_detail and raw error_message
+ * matches, JSON-escaped needles, another source untouched, bigint sequences
+ * carried as text, the match cap.
+ * - [R6] the failure names `repair request-indexes` only when the slug index is
+ * missing or invalid.
+ *
+ * Why existing coverage misses it: test/page-purge.test.ts pins what a purge
+ * removes, never a lookup failure or the journal census boundary.
+ * Semantic injection: `installFaultHook` on the purge's named seams, never an
+ * SQL substring. Runs on PGLite and, with DATABASE_URL, on Postgres.
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operations, OperationError, type OperationContext } from '../src/core/operations.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { installFaultHook, type FaultDetail, type FaultPoint } from '../src/core/persistence/fault-points.ts';
+import { boundedReads, PreparationDeadlineError } from '../src/core/persistence/bounded-reads.ts';
+import { startClaimPhase } from '../src/core/persistence/claim-phase.ts';
+import { cancelWriteRequest } from '../src/core/persistence/control.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { JOURNAL_SWEEP_CHUNK_ROWS, JOURNAL_SWEEP_MATCH_CAP, sweepRequestsCarrying } from '../src/core/persistence/intent-redaction.ts';
+import { PERSISTENCE_REQUEST_SLUG_INTENT_INDEX } from '../src/core/persistence/schema.ts';
+import { resetWriteSwitches } from '../src/core/persistence/switches.ts';
+import { buildIndexOnline } from '../src/core/schema-migrations/helpers.ts';
+import { assertConservation } from '../scripts/persistence/harness.ts';
+import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const backends = testBackends();
+const CLAIM = 'Deploy key lives in vault-a';
+const page = (title: string, claim = CLAIM) => `---\ntitle: ${title}\ntype: note\n---\n# ${title}\n\nBody of ${title}.\n\n## Facts\n\n<!--- gbrain:facts:begin -->
+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |
+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|
+| 1 | ${claim} | fact | 1.0 | world | medium | 2026-01-01 | | chat | |
+<!--- gbrain:facts:end -->\n`;
+const op = (name: string) => operations.find(o => o.name === name)!;
+const timeout57014 = () => Object.assign(new Error('canceling statement due to statement timeout'), { code: '57014' });
+type Row = { state: string; error_code: string | null; error_message: string | null; blocked_reason: string | null; preparation_attempts: number; has_recovery: boolean; intent: unknown; outcome: unknown; compacted: boolean };
+
+for (const backend of backends) describe(`[${backend}] #6511 page purge journal lookups`, () => {
+ let engine: BrainEngine;
+ let closePostgres: (() => Promise<void>) | undefined;
+ const home = mkdtempSync(join(tmpdir(), `gbrain-6511-${backend}-`));
+ let n = 0;
+ const context = (): OperationContext => ({ engine, config: { engine: backend, embedding_disabled: true } as never,
+ logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false, sourceId: 'default' });
+ const call = (name: string, params: Record<string, unknown>) => withEnv({ GBRAIN_HOME: home }, () => op(name).handler(context(), params)) as Promise<Record<string, any>>;
+ const row = async (requestId: string): Promise<Row> => (await engine.executeRaw<Row>(`SELECT state,error_code,error_message,blocked_reason,preparation_attempts,
+ recovery IS NOT NULL AS has_recovery,intent,outcome,compacted FROM persistence_requests WHERE request_id=$1::uuid`, [requestId]))[0]!;
+ const count = async (sql: string, params: unknown[] = []) => Number((await engine.executeRaw<{ n: string }>(`SELECT count(*)::text AS n FROM ${sql}`, params))[0]!.n);
+ const revision = async (slug: string) => (await engine.readPageSnapshot(slug, { sourceId: 'default', includeDeleted: true }))!.revision;
+ /** A page with one extracted fact (the purge's needle) and a committed write of another page carrying the claim. */
+ async function seed(prefix: string): Promise<{ slug: string; carrier: string; carrierRequest: string }> {
+ const slug = `${prefix}/leaked-${++n}`, carrier = `${prefix}/mentions-${n}`;
+ await importFromContent(engine, slug, page(`Leaked ${n}`), { noEmbed: true, sourceId: 'default' });
+ await runExtractFacts(engine, { slugs: [slug] });
+ expect(await count('facts WHERE source_id=$1 AND source_markdown_slug=$2', ['default', slug])).toBe(1);
+ const carrierRequest = randomUUID();
+ const written = await call('put_page', { slug: carrier, content: `---\ntitle: Mentions ${n}\ntype: note\n---\nSomeone wrote: ${CLAIM}.\n`, request_id: carrierRequest });
+ expect(written.state).toBe('committed');
+ return { slug, carrier, carrierRequest };
+ }
+ async function purge(slug: string, requestId = randomUUID()) {
+ return call('delete_page', { slug, purge: true, request_id: requestId, expected_revision: await revision(slug) });
+ }
+ async function failure(fn: () => Promise<unknown>): Promise<OperationError> {
+ try { await fn(); } catch (error) { expect(error).toBeInstanceOf(OperationError); return error as OperationError; }
+ throw new Error('expected a refusal');
+ }
+ /** Installs a hook on the named seam for the named request; counts the request's preparation claims. */
+ function arm(points: Partial<Record<FaultPoint, (detail: FaultDetail) => Promise<void> | void>>, requestId: string) {
+ const claims: string[] = [];
+ installFaultHook(async (point, detail) => {
+ if (detail.requestId !== requestId) return;
+ if (point === 'consumer:preparing') claims.push(point);
+ await points[point]?.(detail);
+ });
+ return { claims };
+ }
+
+ beforeAll(async () => {
+ if (backend === 'pglite') { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }
+ else { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engine = pg.engine; closePostgres = pg.close; }
+ }, 120_000);
+ afterAll(async () => {
+ installFaultHook(undefined);
+ await disposePersistenceConsumer(engine); await engine.disconnect(); await closePostgres?.();
+ rmSync(home, { recursive: true, force: true });
+ }, 60_000);
+ afterEach(async () => { installFaultHook(undefined); await disposePersistenceConsumer(engine); });
+
+ const points: Array<'slug_lookup' | 'tail_recheck' | 'pending_recheck' | 'redaction_read'> = ['slug_lookup', 'tail_recheck', 'pending_recheck', 'redaction_read'];
+ for (const point of points) test(`[R1 a] a statement timeout at the ${point} ends the purge failed/purge_lookup_timeout on the first claim; the source keeps moving`, async () => {
+ const { slug, carrier, carrierRequest } = await seed('db');
+ const before = { page: await engine.readPageSnapshot(slug, { sourceId: 'default', includeDeleted: true }), carrierIntent: (await row(carrierRequest)).intent,
+ facts: await count('facts WHERE source_id=$1', ['default']), pagePurges: await count('page_purges'), factPurges: await count('fact_purges') };
+ const requestId = randomUUID();
+ const { claims } = arm({ [`purge:${point}`]: () => { throw timeout57014(); } }, requestId);
+ const error = await failure(() => purge(slug, requestId));
+ expect(error.code).toBe('purge_lookup_timeout');
+ expect(error.message).toContain('could not finish');
+ expect(error.message).toContain('Do not assume the requested content was erased');
+ expect(error.writeRequest?.state).toBe('failed');
+ expect(claims).toHaveLength(1);
+ const failed = await row(requestId);
+ expect(failed).toMatchObject({ state: 'failed', error_code: 'purge_lookup_timeout', preparation_attempts: 0, has_recovery: false });
+ expect(failed.error_message).toContain('could not finish');
+ // Nothing of the page, its facts, its tombstones or the journal changed.
+ expect(await engine.readPageSnapshot(slug, { sourceId: 'default', includeDeleted: true })).toEqual(before.page);
+ expect(await count('facts WHERE source_id=$1', ['default'])).toBe(before.facts);
+ expect(await count('page_purges')).toBe(before.pagePurges);
+ expect(await count('fact_purges')).toBe(before.factPurges);
+ expect((await row(carrierRequest)).intent).toEqual(before.carrierIntent);
+ // The same request id replays the terminal failure; the queue behind it moves; a new request id is admitted.
+ const replay = await failure(() => purge(slug, requestId));
+ expect(replay.writeRequest).toEqual(error.writeRequest);
+ const next = await call('put_page', { slug: `db/after-${n}`, content: `---\ntitle: After ${n}\ntype: note\n---\nMoves again.\n`, request_id: randomUUID() });
+ expect(next.state).toBe('committed');
+ installFaultHook(undefined);
+ const purged = await purge(slug);
+ expect(purged).toMatchObject({ status: 'purged', state: 'committed', journal_sweep: { complete: true, tail: 0, pending_rechecked: 0 } });
+ expect(Number(purged.journal_sweep.scanned)).toBeGreaterThanOrEqual(1);
+ expect(typeof purged.journal_sweep.ceiling).toBe('string');
+ expect((await row(carrierRequest))).toMatchObject({ intent: null, compacted: true });
+ expect(await engine.readPageSnapshot(carrier, { sourceId: 'default' })).not.toBeNull();
+ await assertConservation(engine);
+ }, 60_000);
+
+ test('[R6] the failure names the index repair only while the slug index is missing or INVALID', async () => {
+ const { slug } = await seed('hint');
+ await engine.executeRaw(`DROP INDEX IF EXISTS ${PERSISTENCE_REQUEST_SLUG_INTENT_INDEX.name}`);
+ try {
+ const missingId = randomUUID();
+ arm({ 'purge:slug_lookup': () => { throw timeout57014(); } }, missingId);
+ const missing = await failure(() => purge(slug, missingId));
+ expect(missing.code).toBe('purge_lookup_timeout');
+ expect(missing.message).toContain('repair request-indexes');
+ expect(missing.message).toContain(`${PERSISTENCE_REQUEST_SLUG_INTENT_INDEX.name} is missing`);
+ // The journal keeps code and message only: the hint must be in the durable receipt, not only on the thrown error's fix.
+ expect((await row(missingId)).error_message).toContain('repair request-indexes');
+ } finally {
+ await disposePersistenceConsumer(engine);
+ expect(await buildIndexOnline(engine, 0, PERSISTENCE_REQUEST_SLUG_INTENT_INDEX)).toBe('created');
+ }
+ const validId = randomUUID();
+ arm({ 'purge:slug_lookup': () => { throw timeout57014(); } }, validId);
+ const valid = await failure(() => purge(slug, validId));
+ expect(valid.code).toBe('purge_lookup_timeout');
+ expect(valid.message).not.toContain('repair request-indexes');
+ expect(valid.message).toContain('new request_id');
+ expect((await row(validId)).error_message).not.toContain('repair request-indexes');
+ }, 60_000);
+
+ test('[R1 b] a sweep that outruns the preparation budget is a charged preparation_deadline release, then preparation_stalled at the limit; the source keeps moving', async () => {
+ const { slug } = await seed('budget');
+ await engine.setConfig('persistence.maintenance_preparation_ms', '1000');
+ resetWriteSwitches();
+ try {
+ const requestId = randomUUID();
+ const seen: Row[] = [];
+ const { claims } = arm({
+ 'consumer:preparing': async () => { seen.push(await row(requestId)); },
+ 'purge:sweep_chunk': () => Bun.sleep(1_600),
+ }, requestId);
+ const error = await failure(() => purge(slug, requestId));
+ expect(error.code).toBe('preparation_stalled');
+ expect(error.message).toContain('submit the write again with a new request_id');
+ expect(claims).toHaveLength(2);
+ // The second claim saw the first attempt's charged release.
+ expect(seen[1]).toMatchObject({ state: 'running', preparation_attempts: 1 });
+ expect(await row(requestId)).toMatchObject({ state: 'failed', error_code: 'preparation_stalled', preparation_attempts: 2, has_recovery: false });
+ expect(await engine.readPageSnapshot(slug, { sourceId: 'default' })).not.toBeNull();
+ installFaultHook(undefined);
+ await disposePersistenceConsumer(engine);
+ const next = await call('put_page', { slug: `budget/after-${n}`, content: `---\ntitle: After ${n}\ntype: note\n---\nMoves again.\n`, request_id: randomUUID() });
+ expect(next.state).toBe('committed');
+ await assertConservation(engine);
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw("DELETE FROM config WHERE key='persistence.maintenance_preparation_ms'");
+ resetWriteSwitches();
+ }
+ }, 60_000);
+
+ test('[R1 b] the sweep loop ends at the claim clock between chunks, without a server-side bound', async () => {
+ await seed('clock');
+ let statements = 0;
+ const counting = new Proxy(engine, { get(target, key) {
+ if (key === 'executeRaw') return (sql: string, params?: unknown[]) => { if (sql.includes('WITH chunk AS MATERIALIZED')) statements++; return target.executeRaw(sql, params); };
+ const value = Reflect.get(target, key, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ const start = Date.now();
+ const clock = startClaimPhase(start, undefined, 10_000);
+ let ticks = 0;
+ // The first check passes; every later one reads a clock past the deadline.
+ const now = () => ++ticks === 1 ? start : start + 20_000;
+ const error = await sweepRequestsCarrying(counting, 'default', [CLAIM], { clock, chunkRows: 1, now }).then(() => null, (e: unknown) => e as { code?: string; message: string });
+ expect(error?.code).toBe('preparation_deadline');
+ expect(error?.message).toContain('reached its preparation budget between chunks');
+ expect(statements).toBe(1);
+ }, 60_000);
+
+ if (backend === 'postgres') test('[R1 b] on Postgres a bounded chunk read the server ends is the same deadline', async () => {
+ await seed('bounded');
+ await engine.executeRaw(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,digest,intent,authority,state,
+ intent_bytes,terminal_reservation,outcome,completed_at)
+ SELECT 'local_cli','seed-bounded',gen_random_uuid(),'put_page','default',(SELECT incarnation FROM sources WHERE id='default'),'bounded/row-'||g,'d',
+ jsonb_build_object('content',repeat('filler text ',200)),'{}'::jsonb,'committed',0,0,'{}'::jsonb,now() FROM generate_series(1,4000) g`);
+ const clock = startClaimPhase(Date.now(), undefined, 1);
+ const bounded = boundedReads(engine, clock);
+ const error = await sweepRequestsCarrying(bounded, 'default', [CLAIM], { now: () => 0 }).then(() => null, (e: unknown) => e);
+ expect(error).toBeInstanceOf(PreparationDeadlineError);
+ expect((error as PreparationDeadlineError).code).toBe('preparation_deadline');
+ expect((error as PreparationDeadlineError).sqlstate).toBe('57014');
+ await engine.executeRaw("DELETE FROM persistence_requests WHERE principal_id='seed-bounded'");
+ }, 60_000);
+
+ test('[R2] a carrying request admitted and cancelled after the preparation scan is redacted by the tail re-check; one still queued is left in place', async () => {
+ const { slug } = await seed('race');
+ const [principal] = await engine.executeRaw<{ principal_kind: string; principal_id: string }>("SELECT principal_kind,principal_id FROM persistence_requests WHERE slug=$1", [slug.replace('leaked', 'mentions')]);
+ const requestId = randomUUID();
+ const cancelledId = randomUUID(), queuedId = randomUUID();
+ let queuedWrite: Promise<Record<string, any>> | null = null;
+ arm({ 'consumer:prepared': async () => {
+ // Both admitted after the scan completed, so neither is in the sweep's id list; both carry the claim in their intent.
+ // wait_ms: 0 reports the admitted write as pending (a thrown write_pending) and leaves it queued behind this purge.
+ const admitted = await call('put_page', { slug: `race/cancelled-${n}`, content: `---\ntitle: C\ntype: note\n---\nLate: ${CLAIM}.\n`, request_id: cancelledId, wait_ms: 0 }).catch(error => error as OperationError);
+ expect((admitted as OperationError).code).toBe('write_pending');
+ expect((await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE request_id=$1::uuid', [cancelledId]))[0]!.state).toBe('queued');
+ const cancelled = await cancelWriteRequest(engine, { kind: principal.principal_kind as never, id: principal.principal_id }, cancelledId);
+ expect(cancelled?.state).toBe('cancelled');
+ queuedWrite = call('put_page', { slug: `race/queued-${n}`, content: `---\ntitle: Q\ntype: note\n---\nLater: ${CLAIM}.\n`, request_id: queuedId });
+ await Bun.sleep(50);
+ expect((await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE request_id=$1::uuid', [queuedId]))[0]!.state).toBe('queued');
+ } }, requestId);
+ const purged = await purge(slug, requestId);
+ expect(purged).toMatchObject({ status: 'purged', state: 'committed' });
+ expect(purged.journal_sweep.tail).toBeGreaterThanOrEqual(2);
+ expect(purged.journal_sweep.complete).toBe(true);
+ const cancelled = await row(cancelledId);
+ expect(cancelled).toMatchObject({ state: 'cancelled', intent: null, compacted: true, error_message: null });
+ expect(JSON.stringify(cancelled.outcome ?? {}).toLowerCase()).not.toContain(CLAIM.toLowerCase());
+ installFaultHook(undefined);
+ const later = await queuedWrite!;
+ expect(later.state).toBe('committed');
+ expect(JSON.stringify((await row(queuedId)).intent)).toContain(CLAIM);
+ await assertConservation(engine);
+ }, 60_000);
+
+ test('[R2] a request pending at the scan that settles with a carrying outcome is redacted by the pending re-check', async () => {
+ const { slug } = await seed('pending');
+ const [principal] = await engine.executeRaw<{ principal_kind: string; principal_id: string }>("SELECT principal_kind,principal_id FROM persistence_requests WHERE slug=$1", [slug.replace('leaked', 'mentions')]);
+ // A request of another owner's worktree: never claimable here, never blocking, but a pending row of this source at scan time.
+ const [worktree] = await engine.executeRaw<{ id: string }>("INSERT INTO persistence_worktrees(owner_host_id,state) VALUES (gen_random_uuid(),'active') RETURNING id::text AS id");
+ const pendingId = randomUUID();
+ await engine.executeRaw(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,worktree_id,digest,intent,authority,state,intent_bytes,terminal_reservation)
+ VALUES ($1,$2,$3::uuid,'put_page','default',(SELECT incarnation FROM sources WHERE id='default'),'pending/other',$4::uuid,'d','{}'::jsonb,'{}'::jsonb,'queued',0,0)`,
+ [principal.principal_kind, principal.principal_id, pendingId, worktree.id]);
+ await engine.executeRaw("UPDATE persistence_counters SET lifetime_ids=lifetime_ids+1,outstanding_count=outstanding_count+1 WHERE key IN ('brain',$1)", [`principal:${principal.principal_kind}:${principal.principal_id}`]);
+ const requestId = randomUUID();
+ arm({ 'consumer:prepared': async () => {
+ await engine.executeRaw(`UPDATE persistence_requests SET state='committed',outcome=$2::text::jsonb,completed_at=now() WHERE request_id=$1::uuid`, [pendingId, JSON.stringify({ echoed: `Outcome carries ${CLAIM}` })]);
+ await engine.executeRaw("UPDATE persistence_counters SET outstanding_count=outstanding_count-1 WHERE key IN ('brain',$1)", [`principal:${principal.principal_kind}:${principal.principal_id}`]);
+ } }, requestId);
+ const purged = await purge(slug, requestId);
+ expect(purged).toMatchObject({ status: 'purged', state: 'committed', journal_sweep: { pending_rechecked: 1, complete: true } });
+ const settled = await row(pendingId);
+ expect(settled).toMatchObject({ state: 'committed', compacted: true, outcome: { echoed: '[purged]' } });
+ await assertConservation(engine);
+ }, 60_000);
+
+ test('[R2] the receipt reports complete:false when the tail past the ceiling exceeds its bound', async () => {
+ const { slug } = await seed('tail');
+ const requestId = randomUUID();
+ arm({ 'consumer:prepared': async () => {
+ await engine.executeRaw(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,digest,intent,authority,state,intent_bytes,terminal_reservation,completed_at)
+ SELECT 'local_cli','seed-tail',gen_random_uuid(),'put_page','default',(SELECT incarnation FROM sources WHERE id='default'),'tail/row-'||g,'d','{}'::jsonb,'{}'::jsonb,'committed',0,0,now()
+ FROM generate_series(1,$1::int) g`, [JOURNAL_SWEEP_CHUNK_ROWS + 1]);
+ } }, requestId);
+ const purged = await purge(slug, requestId);
+ expect(purged).toMatchObject({ status: 'purged', state: 'committed', journal_sweep: { tail: JOURNAL_SWEEP_CHUNK_ROWS, complete: false } });
+ await engine.executeRaw("DELETE FROM persistence_requests WHERE principal_id='seed-tail'");
+ }, 60_000);
+
+ test('[R3] the keyset sweep walks every chunk, matches every text column in raw and JSON-escaped form, and leaves other sources alone', async () => {
+ const incarnation = "(SELECT incarnation FROM sources WHERE id='default')";
+ const seedRow = (slug: string, columns: { intent?: unknown; outcome?: unknown; error_detail?: unknown; error_message?: string; compacted?: boolean; source?: string }) =>
+ engine.executeRaw(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,digest,intent,authority,state,
+ intent_bytes,terminal_reservation,outcome,error_detail,error_message,compacted,completed_at)
+ VALUES ('local_cli','seed-keyset',gen_random_uuid(),'put_page',$1,${incarnation},$2,'d',$3::text::jsonb,'{}'::jsonb,'committed',0,0,$4::text::jsonb,$5::text::jsonb,$6,$7,now()) RETURNING id::text AS id`,
+ [columns.source ?? 'default', slug, columns.intent === undefined ? null : JSON.stringify(columns.intent), columns.outcome === undefined ? null : JSON.stringify(columns.outcome),
+ columns.error_detail === undefined ? null : JSON.stringify(columns.error_detail), columns.error_message ?? null, columns.compacted ?? false]).then(rows => (rows[0] as { id: string }).id);
+ const quoted = 'He said "vault\\a" twice';
+ const expected: string[] = [];
+ try {
+ // Two full chunks that match nothing, then the carrying rows past row 4,000 (an empty-match chunk precedes them).
+ await engine.executeRaw(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,digest,intent,authority,state,intent_bytes,terminal_reservation,completed_at)
+ SELECT 'local_cli','seed-keyset',gen_random_uuid(),'put_page','default',${incarnation},'keyset/row-'||g,'d','{"content":"nothing here"}'::jsonb,'{}'::jsonb,'committed',0,0,now()
+ FROM generate_series(1,$1::int) g`, [2 * JOURNAL_SWEEP_CHUNK_ROWS]);
+ expected.push(await seedRow('keyset/intent', { intent: { content: `says ${CLAIM.toUpperCase()} loudly` } }));
+ expected.push(await seedRow('keyset/outcome-compacted', { outcome: { echoed: CLAIM }, compacted: true }));
+ expected.push(await seedRow('keyset/error-detail', { error_detail: { reason: `because ${CLAIM}` } }));
+ expected.push(await seedRow('keyset/error-message', { error_message: `refused: ${quoted}` }));
+ expected.push(await seedRow('keyset/quoted-json', { intent: { content: quoted } }));
+ const foreign = await seedRow('keyset/foreign', { intent: { content: CLAIM }, source: 'gstack' });
+ const unrelated = await seedRow('keyset/unrelated', { intent: { content: 'nothing' }, outcome: { echoed: 'nothing' } });
+ const sweep = await sweepRequestsCarrying(engine, 'default', [CLAIM, quoted]);
+ expect(sweep.targets.map(t => t.id).sort()).toEqual([...expected].sort());
+ expect(sweep.targets.map(t => t.id)).not.toContain(foreign);
+ expect(sweep.targets.map(t => t.id)).not.toContain(unrelated);
+ expect(sweep.complete).toBe(true);
+ expect(sweep.pendingAtScan).toEqual([]);
+ expect(sweep.scanned).toBe(await count("persistence_requests WHERE source_id='default'"));
+ expect(typeof sweep.ceiling).toBe('string');
+ expect(sweep.ceiling).toBe((await engine.executeRaw<{ s: string }>("SELECT max(sequence)::text AS s FROM persistence_requests WHERE source_id='default'"))[0]!.s);
+ // A quoted claim: the raw form appears only in the text column (error_message), the JSON-escaped form only inside a JSON column.
+ const both = await sweepRequestsCarrying(engine, 'default', ['"vault\\a"']);
+ expect(both.targets.map(t => t.id).sort()).toEqual([expected[3]!, expected[4]!].sort());
+ // The escaped form alone is not searched raw: a needle that only matches when escaped finds only the JSON row.
+ const escapedOnly = await sweepRequestsCarrying(engine, 'default', ['said "vault']);
+ expect(escapedOnly.targets.map(t => t.id).sort()).toEqual([expected[3]!, expected[4]!].sort());
+ expect((await engine.executeRaw<{ n: string }>(`SELECT count(*)::text AS n FROM persistence_requests WHERE strpos(lower(intent::text),'said "vault')>0`))[0]!.n).toBe('0');
+ // The match cap: more carrying rows than the cap leave complete:false with exactly the cap collected.
+ const capped = await sweepRequestsCarrying(engine, 'default', [CLAIM], { matchCap: 2 });
+ expect(capped.targets).toHaveLength(2);
+ expect(capped.complete).toBe(false);
+ } finally { await engine.executeRaw("DELETE FROM persistence_requests WHERE principal_id='seed-keyset'"); }
+ }, 120_000);
+
+ test('[R3] the real match cap leaves complete:false and exactly the cap collected', async () => {
+ await engine.executeRaw(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,digest,intent,authority,state,intent_bytes,terminal_reservation,completed_at)
+ SELECT 'local_cli','seed-cap',gen_random_uuid(),'put_page','default',(SELECT incarnation FROM sources WHERE id='default'),'cap/row-'||g,'d',$2::text::jsonb,'{}'::jsonb,'committed',0,0,now()
+ FROM generate_series(1,$1::int) g`, [JOURNAL_SWEEP_MATCH_CAP + 1, JSON.stringify({ content: CLAIM })]);
+ try {
+ const sweep = await sweepRequestsCarrying(engine, 'default', [CLAIM]);
+ expect(sweep.targets).toHaveLength(JOURNAL_SWEEP_MATCH_CAP);
+ expect(sweep.complete).toBe(false);
+ } finally { await engine.executeRaw("DELETE FROM persistence_requests WHERE principal_id='seed-cap'"); }
+ }, 120_000);
+
+ describe('worktree-backed page', () => {
+ let brainDir: string;
+ const sourceId = `wt-${randomUUID().slice(0, 8)}`;
+ const wt = (): OperationContext => ({ ...context(), sourceId });
+ const callWt = (name: string, params: Record<string, unknown>) => withEnv({ GBRAIN_HOME: home }, () => op(name).handler(wt(), params)) as Promise<Record<string, any>>;
+ beforeAll(async () => {
+ brainDir = mkdtempSync(join(home, 'brain-'));
+ await disposePersistenceConsumer(engine);
+ // A source this host owns explicitly (the automatic first-write claim is PGLite's single-host convenience).
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, brainDir]);
+ await withEnv({ GBRAIN_HOME: home }, () => claimWorktree(engine, sourceId, brainDir));
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ _resetWriteThroughCacheForTest();
+ });
+ afterAll(async () => { await disposePersistenceConsumer(engine); _resetWriteThroughCacheForTest(); });
+ for (const present of [true, false]) test(`[R1 c] the worktree arm (file ${present ? 'present' : 'already removed'}): the terminal failure recovers the canonical state byte-identically and keeps the failed receipt`, async () => {
+ const slug = `wt/leaked-${++n}`;
+ // A coordinated write on the managed source: the page, its canonical file and (after extraction) its fact.
+ const written = await callWt('put_page', { slug, source_id: sourceId, content: page(`Worktree ${n}`), request_id: randomUUID() });
+ expect(written).toMatchObject({ state: 'committed', write_through: { written: true } });
+ await disposePersistenceConsumer(engine);
+ await runExtractFacts(engine, { slugs: [slug], sourceId });
+ expect(await count('facts WHERE source_id=$1 AND source_markdown_slug=$2', [sourceId, slug])).toBe(1);
+ const path = join(brainDir, `${slug}.md`);
+ expect(existsSync(path)).toBe(true);
+ const bytes = readFileSync(path);
+ if (!present) rmSync(path);
+ const before = { page: await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true }), facts: await count('facts WHERE source_id=$1', [sourceId]), pagePurges: await count('page_purges') };
+ const requestId = randomUUID();
+ let removedDuringPublication: boolean | null = null;
+ const { claims } = arm({ 'purge:slug_lookup': () => { removedDuringPublication = !existsSync(path); throw timeout57014(); } }, requestId);
+ const purgeWt = async (id = randomUUID()) => callWt('delete_page', { slug, purge: true, request_id: id, source_id: sourceId,
+ expected_revision: (await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true }))!.revision });
+ const error = await failure(() => purgeWt(requestId));
+ expect(error.code).toBe('purge_lookup_timeout');
+ expect(error.writeRequest?.state).toBe('failed');
+ expect(claims).toHaveLength(1);
+ if (present) {
+ // The file was removed by the publication and restored by the recovery route; its bytes are the prior bytes.
+ expect(removedDuringPublication as boolean | null).toBe(true);
+ expect(readFileSync(path).equals(bytes)).toBe(true);
+ } else expect(existsSync(path)).toBe(false);
+ const failed = await row(requestId);
+ expect(failed).toMatchObject({ state: 'failed', error_code: 'purge_lookup_timeout', has_recovery: false });
+ expect(await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true })).toEqual(before.page);
+ expect(await count('facts WHERE source_id=$1', [sourceId])).toBe(before.facts);
+ expect(await count('page_purges')).toBe(before.pagePurges);
+ expect(await count('persistence_requests WHERE recovery IS NOT NULL')).toBe(0);
+ installFaultHook(undefined);
+ await disposePersistenceConsumer(engine);
+ const next = await callWt('put_page', { slug: `wt/after-${n}`, source_id: sourceId, content: `---\ntitle: After ${n}\ntype: note\n---\nMoves again.\n`, request_id: randomUUID() });
+ expect(next).toMatchObject({ state: 'committed', write_through: { written: true } });
+ const purged = await purgeWt();
+ expect(purged).toMatchObject({ status: 'purged', state: 'committed', write_through: { written: true } });
+ expect(existsSync(path)).toBe(false);
+ await assertConservation(engine);
+ }, 60_000);
+ });
+});
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 62207336c5..641b2eac68 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -35,6 +35,7 @@ test/extract-all-stamp-intersection.serial.test.ts
test/extract-endpoint-revision.serial.test.ts
test/extract-entities-managed.test.ts
test/extract-timeline-from-meetings-managed.test.ts
+test/fact-purge-lookup-timeout-6511.test.ts
test/fence-repair-receipts.test.ts
test/frontmatter-reserved-keys-6454.test.ts
test/graduation-copy.test.ts
@@ -76,9 +77,11 @@ test/managed-sync-pinned-reads.test.ts
test/managed-sync-preparation-stalled-holds.test.ts
test/managed-sync-row-parity.test.ts
test/managed-sync-stale-group-head.test.ts
+test/migration-persistence-request-slug-index.test.ts
test/owner-refusal.test.ts
test/pack-relation-direction-engine.test.ts
test/page-embedding-install-batch.test.ts
+test/page-purge-journal-timeout-6511.test.ts
test/page-state-engine.test.ts
test/persistence-bounded-read-session.test.ts
test/persistence-commit-durability.test.ts