Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(purge): one journal sweep per purge batch, tail-only sweeps past its watermark, purge runs capped to free write capacity (#6884)

garrytanad170f87f33a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bc12ea3d03..eb12f54df3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,24 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased] - 2026-10-17
+
+**A batch of page purges no longer holds a source's write queue for hours (#6884).** Each page purge used to read and case-fold the whole write journal to find old requests that still carried the page's claims, so on a journal of about 540k requests one purge took about 20 minutes and a nightly purge batch blocked ordinary writes for about 2.8 hours. Now one sweep serves a batch of queued purges, later purges read only the rows added since, and the purge run stops submitting when the writer's queue is full instead of failing thousands of pages.
+
+### What you'd see
+
+| Situation | Before | Now |
+|---|---|---|
+| N purges queued for one source | N full journal sweeps; each receipt's `journal_sweep.scanned` equals the journal size | one sweep for up to 32 queued purges; the others scan only the rows added since (`journal_sweep.batch`, `journal_sweep.watermark`) |
+| `gbrain dream --phase purge` / `gbrain pages purge-deleted` with more expired pages than free queue room | thousands of `queue_capacity` failures, `managed_purge_failed`, each failure counted toward parking the page | submits only while the writer has room (background runs stop at `persistence.capacity.background_pause_pct`); the rest is `write_capacity_deferred` / `capacity_deferred`, the phase warns, the next run picks it up |
+
+### For contributors
+
+- `sweepRequestsForGroups` (`src/core/persistence/intent-redaction.ts`) runs the #6511 census once for several needle groups; `after` starts past an earlier ceiling.
+- The batch cache lives in process memory in `src/core/persistence/page-purge.ts` (`sweepForPurge`); the journal still never stores claims. No schema change and no compaction default changed.
+- `readOutstandingRoom` (`src/core/persistence/journal.ts`) reads the tighter of the principal's and the brain's outstanding caps.
+- Tests: `test/page-purge-batch-sweep-6884.test.ts` (PGLite and Postgres), `test/purge-deleted-capacity-6884.test.ts`.
+
## [0.60.278.0] - 2026-10-17
**A stuck upgrade queue drains, held embeddings say what they need, and doctor and status answer in bounded time (#6803, #6847).** Four things got better for anyone whose brain grew big or went through the recent upgrades. Image pages that an old upgrade left queued (and missing from search) can now be put back with one keyless command when gbrain already knows they're safe, and the rest are counted and named instead of hidden. Large pages waiting for your embedding approval are reported everywhere with one exact command to approve them, and that command now works on free local embedding models too. `gbrain doctor --json` and `gbrain sync --status` stop running for minutes on a large brain. And the "un-extracted edges" nudge after a sync now agrees with doctor and names the command that actually finishes the job.
diff --git a/docs/architecture/key-files/memory-purge.md b/docs/architecture/key-files/memory-purge.md
index 456ab4638b..c79047fbae 100644
--- a/docs/architecture/key-files/memory-purge.md
+++ b/docs/architecture/key-files/memory-purge.md
@@ -13,14 +13,14 @@ User-facing contract: [expire versus purge](../../guides/memory-boundaries.md#pu
- `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; 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/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`; #6884: `sweepRequestsForGroups` runs it once for several needle groups, each row read and lowered once and every hit attributed to the groups carrying that needle, the match cap per group, and `after` starts past an earlier ceiling) 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, the page's `page_aliases` and the `slug_aliases` redirects whose `canonical_slug` is the page (#6619; a redirect from this slug to another page stays; counted in `removed` and checked by slug in the receipt), 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/persistence/page-purge.ts` — #6884: `preparePagePurge` takes its census from `sweepForPurge`: a purge an earlier batch sweep covered for all of its current claims scans only the tail past that sweep's ceiling (`journal_sweep.watermark`); otherwise it sweeps once for its own claims and those of the next queued purges of the source (up to `PURGE_SWEEP_BATCH_MEMBERS`, `PURGE_SWEEP_BATCH_NEEDLES` claim forms) and caches each member's result in process memory (never in the journal; `journal_sweep.batch` counts the purges one sweep covered). Rows a member's cached census saw as pending, the leader's own row included, are re-tested at publication. Tests: `test/page-purge-batch-sweep-6884.test.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, the page's `page_aliases` and the `slug_aliases` redirects whose `canonical_slug` is the page (#6619; a redirect from this slug to another page stays; counted in `removed` and checked by slug in the receipt), 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.
- Withdrawn-claim refusal on `remember` (`persistence/memory-mutations.ts`, `memory-prepare.ts`) — admission refuses a withdrawn claim (`fact_withdrawn`, `FACT_WITHDRAWN_MESSAGE`/`_SUGGESTION` in `src/core/facts/withdrawal.ts`) before a request exists, and preparation re-checks it; `writeFailureDiagnostic` allowlists that prefix, so a failed receipt and `get_write_request` name it. `replaces` accepts a target saved without an entity (links it by supersession). Test: `test/remember-withdrawn-claim.test.ts`. (R1, Cat 40 Hard.) The refusal carries an additive `withdrawn` object (`factWithdrawnRefusal` in `facts/single-prepare.ts`, from `fact_withdrawals` only: the named entity's row over `all_entities`, then the newest, omitted when the caller cannot read the forgotten rows); `withdrawalFailureDetail`/`withdrawnFromDetail` in `facts/withdrawal.ts` keep it in the failed receipt's `error_detail` for `get_write_request` and replay. Tests: `test/withdrawn-detail.test.ts`, `test/e2e/withdrawn-detail-postgres.test.ts`.
-- `src/core/persistence/purge-deleted.ts` — `purgeDeletedPagesCoordinated` backs the cycle `purge` phase, the purge job, `purge_deleted_pages` and `gbrain pages purge-deleted`. Unmanaged brains keep the engine bulk delete; a managed brain purges each tombstone older than the window (skipping archived sources, which the source lifecycle purges) through `delete_page` with `purge: true` and the internal `retention: true` bound to its revision (retention is not an owner purge; see [belief ledger](belief-ledger.md)). Writer state is read once per run (`writerOnboardingPreflight`): a source whose writer is `recovery_required` submits nothing and its tombstones are listed in `blocked` as `writer_not_active` (counted in `inactive`). Revision races are deferred to the next run; a parked tombstone (`purge-parks.ts`) is skipped as `purge_parked` (counted in `parked`) unless `retryParked`, and any other failure is listed in `blocked` and sets `error`. `selectPurgeCandidates` is the one eligibility selector (preview, consent, `purge_deleted_pages` op, run); `purgePhaseStatus`/`purgePhaseNote` shape the cycle purge phase (fail on `error`, warn on `writer_not_active` or parked). Tests: `test/managed-writers-w3.test.ts`, `test/purge-deleted-parks.test.ts`.
+- `src/core/persistence/purge-deleted.ts` — `purgeDeletedPagesCoordinated` backs the cycle `purge` phase, the purge job, `purge_deleted_pages` and `gbrain pages purge-deleted`. Unmanaged brains keep the engine bulk delete; a managed brain purges each tombstone older than the window (skipping archived sources, which the source lifecycle purges) through `delete_page` with `purge: true` and the internal `retention: true` bound to its revision (retention is not an owner purge; see [belief ledger](belief-ledger.md)). Writer state is read once per run (`writerOnboardingPreflight`): a source whose writer is `recovery_required` submits nothing and its tombstones are listed in `blocked` as `writer_not_active` (counted in `inactive`). Revision races are deferred to the next run; a parked tombstone (`purge-parks.ts`) is skipped as `purge_parked` (counted in `parked`) unless `retryParked`, and any other failure is listed in `blocked` and sets `error`. `selectPurgeCandidates` is the one eligibility selector (preview, consent, `purge_deleted_pages` op, run); #6884: the run submits only while the writer has outstanding-request room (`readOutstandingRoom` in `journal.ts`, at `persistence.capacity.background_pause_pct` of the cap for a background run); the rest, and the rest after a `queue_capacity` refusal, is `blocked` as `write_capacity_deferred` and counted in `capacity_deferred`, never a failure or a park. `purgePhaseStatus`/`purgePhaseNote` shape the cycle purge phase (fail on `error`, warn on `writer_not_active`, parked or capacity-deferred). Tests: `test/managed-writers-w3.test.ts`, `test/purge-deleted-parks.test.ts`, `test/purge-deleted-capacity-6884.test.ts`.
- `src/core/persistence/purge-parks.ts` — #6741 C: per-tombstone purge parks in op_checkpoints (op `purge-deleted-park`, key source+slug+deleted_at, so a re-deleted page starts fresh); park at `PURGE_PARK_LIMIT` (5) non-deferral failures, a success clears it, and parks of a source seen inactive rearm the first run its writer is active again (`notePurgeSourceWriter`). `purgeStaleCheckpoints` exempts the op; `prunePurgeParks` drops parks whose tombstone is gone. Tests: `test/purge-deleted-parks.test.ts`.
diff --git a/src/commands/pages.ts b/src/commands/pages.ts
index f6273047bc..fcc9f9acd8 100644
--- a/src/commands/pages.ts
+++ b/src/commands/pages.ts
@@ -81,7 +81,7 @@ async function runPurgeDeleted(engine: BrainEngine, args: string[]): Promise<voi
const result = await purgeDeletedPagesCoordinated(engine, olderThanHours, { retryParked });
if (json) {
console.log(JSON.stringify({ older_than_hours: olderThanHours, count: result.count, slugs: result.slugs,
- ...(result.blocked.length ? { blocked: result.blocked } : {}) }, null, 2));
+ ...(result.capacity_deferred ? { capacity_deferred: result.capacity_deferred } : {}), ...(result.blocked.length ? { blocked: result.blocked } : {}) }, null, 2));
if (result.error) setCliExitVerdict(1);
return;
}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index caeb961f14..ae2357024d 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -764,6 +764,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.278.0', text: '`gbrain embed --stale` and the embed-backfill job report `budget_limited` (pages held for approval or at their per-page cap, by source) and print one line instead of saying nothing; it is never a failure. Doctor `partial_embedding` is its own entry (`--only oversized_pages` no longer emits it) and its fix is a per-source approve, `gbrain embed --held --source <id> --max-usd <N>` with a concrete N, with every other source in `details.by_source`. `gbrain embed --held --dry-run` lists every source and exits 0 on a multi-source brain; `--held --max-usd` without `--source` there refuses with `invalid_params`. Receipts name `gbrain embed --held --dry-run --source <id>` instead of `gbrain reindex --held`, which does not exist.' },
{ since: '0.60.278.0', text: 'An explicit `--max-usd N` on `gbrain embed --slugs` or `--held` now releases a held page on a free embedding provider too (#6847); it used to reprint the hold. Free-recipe models cost $0 in the per-page ledger, printed approve commands carry a concrete N (a paid N includes the 1.5x headroom and $0.25 floor), a free provider\'s approve asks for no paid or egress consent, and an approval when embeddings cannot run or the paid model has no price is refused before the hold is released. `--yes` still never releases a hold.' },
{ since: '0.60.278.0', text: '`gbrain extract --stale --source <id>` now refuses with `invalid_params` naming `--source-id <id>` instead of running brain-wide; `--source fs` exits 2 `invalid_params` (it exited 1), and `--source db` refuses as ambiguous when a source is named `db`. Rendered extract fixes pin `--source-id`. The end-of-sync extraction nudge stays silent when doctor `links_extraction_lag` would not warn (attendance-blocked meetings no longer count), names both `gbrain extract --stale` and `gbrain extract --stale --catch-up` with estimates, and becomes a run-it-yourself step above two minutes; `extract --stale` JSON gains `actionable`, `attendance_blocked`, `mention_due` and `complete`; the per-source "still owe extraction" line counts only pages that sync imported; and an owner-delegated plain `extract --stale` keeps the 30-minute budget (`--catch-up` is carried through).' },
+ // #6884 (GBRA-117): `since` is a placeholder equal to the branch's VERSION, restamped when the merge slot is called.
+ { since: '0.60.278.0', text: 'A batch of page purges no longer reads the whole write journal once per page: the first queued purge of a source sweeps once for its own claims and those of the purges queued behind it, and each of those scans only the journal rows added since. Purge receipts\' `journal_sweep` gains `batch` (how many purges that sweep covered) and `watermark` (the sequence a purge started past; null when it swept from the start). A purge whose claims changed since the batch sweep sweeps on its own as before.' },
+ { since: '0.60.278.0', text: 'The managed purge (autopilot purge phase, the purge job and `gbrain pages purge-deleted`) submits only while the writer has outstanding-request room (a background run stops at `persistence.capacity.background_pause_pct` of the cap). The rest is reported as `write_capacity_deferred` and counted in `capacity_deferred` (cycle: `purged_pages_capacity_deferred`, phase status warn) and is submitted by the next run, where it used to fail each page with `queue_capacity` (`managed_purge_failed`) and count each failure toward parking it.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/cycle.ts b/src/core/cycle.ts
index 7cf3811601..a4e34edb10 100644
--- a/src/core/cycle.ts
+++ b/src/core/cycle.ts
@@ -1811,7 +1811,7 @@ async function runPhasePurge(engine: BrainEngine, dryRun: boolean): Promise<Phas
details: {
purged_sources_count: purgedSources.length,
purged_sources_blocked: purgeResult.blocked,
- purged_pages_count: purgedPages.count, purged_pages_blocked: purgedPages.blocked, purged_pages_deferred: purgedPages.deferred,
+ purged_pages_count: purgedPages.count, purged_pages_blocked: purgedPages.blocked, purged_pages_deferred: purgedPages.deferred, purged_pages_capacity_deferred: purgedPages.capacity_deferred,
purged_orphan_clones_count: purgedClones.count,
purged_orphan_clone_names: purgedClones.names,
purged_sources: purgedSources,
diff --git a/src/core/persistence/intent-redaction.ts b/src/core/persistence/intent-redaction.ts
index 4bd4db0afb..fc7fbbac16 100644
--- a/src/core/persistence/intent-redaction.ts
+++ b/src/core/persistence/intent-redaction.ts
@@ -26,6 +26,12 @@
* 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.
+ *
+ * #6884: `sweepRequestsForGroups` runs that census once for several needle
+ * groups (the queued purges of a batch), reading and lowering each journal
+ * row once and attributing every hit to the groups whose needles it carries;
+ * `after` starts a sweep past an earlier sweep's ceiling, so a purge whose
+ * claims an earlier batch sweep already covered scans only the tail.
*/
import { opError } from '../ops/contract.ts';
@@ -48,15 +54,17 @@ export function carryingNeedles(claims: readonly string[]): string[] {
return [...new Set(forms.filter(Boolean))];
}
-interface SweepRow extends IntentRedactionTarget { sequence: string; pending: boolean; matched: boolean; chunk_rows: string; chunk_last: string | null }
+interface SweepRow extends IntentRedactionTarget { sequence: string; pending: boolean; hits: number[] | null; chunk_rows: string; chunk_last: string | null }
+type ChunkRow = IntentRedactionTarget & { sequence: string; pending: boolean; matched: boolean; hits: number[] };
/**
* 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.
+ * only the rows that match a needle or are still pending come back, with the 0-based indexes of the needles each carries
+ * (`hits`), 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 }> {
+ ids: readonly string[] | null = null, exclude: string | null = null): Promise<{ rows: ChunkRow[]; 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,
@@ -66,14 +74,16 @@ async function sweepChunk(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: str
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`,
+ ARRAY(SELECT (n.ord-1)::int FROM unnest($4::text[]) WITH ORDINALITY AS n(v,ord)
+ WHERE strpos(i,n.v)>0 OR strpos(o,n.v)>0 OR strpos(d,n.v)>0 OR strpos(m,n.v)>0 ORDER BY n.ord) AS hits FROM chunk)
+ SELECT t.id::text AS id,t.principal_kind,t.principal_id,t.sequence::text AS sequence,t.pending,t.hits,s.chunk_rows,s.chunk_last
+ FROM tested t CROSS JOIN stats s WHERE cardinality(t.hits)>0 OR t.pending
+ UNION ALL SELECT NULL,NULL,NULL,NULL,false,NULL::int[],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 })),
+ return { rows: rows.filter(row => row.id !== null).map(({ id, principal_kind, principal_id, sequence, pending, hits }) => ({ id, principal_kind, principal_id, sequence, pending,
+ matched: (hits?.length ?? 0) > 0, hits: (hits ?? []).map(Number) })),
scanned: Number(stats.chunk_rows), last: stats.chunk_last };
}
@@ -87,6 +97,10 @@ export interface JournalSweep {
scanned: number;
/** False when the match cap was hit: rows past it were not tested. */
complete: boolean;
+ /** #6884: the sequence this sweep started past (an earlier batch sweep's ceiling); null when it scanned from the start. */
+ watermark?: string | null;
+ /** #6884: how many purges the journal sweep this result comes from covered (1: this purge alone). */
+ batch?: number;
}
/**
* The preparation-time census (#6511): every request of `sourceId` up to the sequence ceiling read at the start, in
@@ -96,26 +110,63 @@ export interface JournalSweep {
* `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);
+ opts: SweepOptions = {}): Promise<JournalSweep> {
+ return (await sweepRequestsForGroups(engine, sourceId, [{ key: '', claims }], opts)).get('')!;
+}
+
+export interface SweepOptions {
+ 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;
+ /** #6884: start past this sequence (an earlier sweep's ceiling): only the tail is read. */ after?: string;
+}
+/**
+ * #6884: one census for several needle groups. Each journal row is read and lowered once and tested against the union of
+ * the groups' needles; a hit counts for every group carrying that needle, and a pending row is pending for every group.
+ * The match cap applies per group: a group that reaches it stops collecting (`complete: false`) and the sweep ends once
+ * no group is collecting.
+ */
+export async function sweepRequestsForGroups(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, groups: ReadonlyArray<{ key: string; claims: readonly string[] }>,
+ opts: SweepOptions = {}): Promise<Map<string, JournalSweep>> {
const chunkRows = opts.chunkRows ?? JOURNAL_SWEEP_CHUNK_ROWS, matchCap = opts.matchCap ?? JOURNAL_SWEEP_MATCH_CAP, now = opts.now ?? Date.now;
+ const needles: string[] = [], owners: Array<Set<string>> = [];
+ for (const group of groups) for (const needle of carryingNeedles(group.claims)) {
+ let at = needles.indexOf(needle);
+ if (at < 0) { at = needles.push(needle) - 1; owners.push(new Set()); }
+ owners[at]!.add(group.key);
+ }
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'; ;) {
+ let scanned = 0;
+ const sweeps = new Map(groups.map(group => [group.key, { targets: [] as IntentRedactionTarget[], pendingAtScan: [] as string[], ceiling, scanned: 0, complete: true,
+ ...(opts.after !== undefined ? { watermark: opts.after } : {}) }]));
+ const collecting = new Set(groups.filter(group => carryingNeedles(group.claims).length).map(group => group.key));
+ const stopped = new Set<string>();
+ const finish = () => { for (const [key, sweep] of sweeps) if (!stopped.has(key)) sweep.scanned = scanned; return sweeps; };
+ if (ceiling === null || !needles.length || (opts.after !== undefined && BigInt(opts.after) >= BigInt(ceiling))) return finish();
+ for (let after = opts.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;
+ 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 });
+ const target = { id: row.id, principal_kind: row.principal_kind, principal_id: row.principal_id };
+ const hit = new Set(row.hits.flatMap(i => [...owners[i] ?? []]));
+ for (const key of collecting) {
+ if (row.pending) sweeps.get(key)!.pendingAtScan.push(row.id);
+ else if (hit.has(key)) sweeps.get(key)!.targets.push(target);
+ }
+ }
+ for (const key of [...collecting]) {
+ const sweep = sweeps.get(key)!;
+ if (sweep.targets.length < matchCap) continue;
+ sweep.targets.length = matchCap;
+ sweep.complete = false;
+ sweep.scanned = scanned;
+ collecting.delete(key);
+ stopped.add(key);
}
- if (sweep.targets.length >= matchCap) { sweep.targets.length = matchCap; sweep.complete = false; return sweep; }
- if (chunk.scanned < chunkRows || chunk.last === null) return sweep;
+ if (!collecting.size || chunk.scanned < chunkRows || chunk.last === null) return finish();
after = chunk.last;
}
}
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index 22a8459330..10e5b22f6e 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -171,6 +171,21 @@ export async function assertWriteHeadroom(engine: SqlEngine, principal: Principa
}
}
}
+/**
+ * #6884: how many more requests `principal` can have outstanding before the tighter of its own and the brain's
+ * outstanding caps, each taken at `share` (a background run stops at the pause line), with that cap's counts.
+ */
+export async function readOutstandingRoom(engine: SqlEngine, principal: Principal, share = 1): Promise<{ room: number; scope: 'brain' | 'principal'; used: number; limit: number }> {
+ const limits = await readJournalLimits(engine);
+ const rows = await engine.executeRaw<{ key: string; outstanding_count: number | string }>('SELECT key,outstanding_count FROM persistence_counters WHERE key=ANY($1::text[])',
+ [['brain', principalKey(principal)]]);
+ const room = (scope: 'brain' | 'principal', key: string, cap: number) => {
+ const used = Number(rows.find(row => row.key === key)?.outstanding_count ?? 0), limit = Math.floor(cap * share);
+ return { room: limit - used, scope, used, limit };
+ };
+ const brain = room('brain', 'brain', limits.brainOutstanding), own = room('principal', principalKey(principal), limits.principalOutstanding);
+ return brain.room < own.room ? brain : own;
+}
/** Creates and locks the counter rows in key order: two statements for any number of keys (#5984 round-trip diet). */
/** Creates missing counter rows; takes no lock on existing ones. Keys sorted. */
export const ENSURE_COUNTERS_SQL = 'INSERT INTO persistence_counters(key) SELECT k FROM unnest($1::text[]) WITH ORDINALITY AS u(k,n) ORDER BY n ON CONFLICT DO NOTHING';
diff --git a/src/core/persistence/page-purge.ts b/src/core/persistence/page-purge.ts
index c3886bd4b1..97d7863051 100644
--- a/src/core/persistence/page-purge.ts
+++ b/src/core/persistence/page-purge.ts
@@ -24,6 +24,12 @@
* 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.
+ *
+ * #6884: that sweep read and lowered the whole journal once per purged page,
+ * so a batch of purges cost N full sweeps. A preparation now sweeps once for
+ * its own claims and those of the next queued purges of the source
+ * (`sweepForPurge`), and each of those finds its census cached here and
+ * scans only the tail past that sweep's ceiling (the source's watermark).
*/
import type { BrainEngine } from '../engine.ts';
@@ -36,7 +42,8 @@ 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 { carryingNeedles, findRequestsForSlugs, JOURNAL_SWEEP_MATCH_CAP, recheckRequestsCarrying, redactRequestIntents, sweepRequestsCarrying, sweepRequestsForGroups,
+ type JournalSweep } from './intent-redaction.ts';
import { dropPurgedFenceRows } from '../facts/purge-overlay.ts';
import { derivedRowsFrom, hideDerivedRows } from '../facts/derivation-inputs.ts';
import { contentHash } from '../utils.ts';
@@ -73,6 +80,67 @@ async function readPurgeClaims(engine: Pick<BrainEngine, 'executeRaw'>, sourceId
return { factRows, takeRows, needles };
}
+/** #6884: how many queued purges of the source one preparation's journal sweep covers at most, this one included. */
+export const PURGE_SWEEP_BATCH_MEMBERS = 32;
+/** #6884: the most claim forms one batch sweep tests per journal row; members past it sweep on their own. */
+export const PURGE_SWEEP_BATCH_NEEDLES = 256;
+/** A member's census is cached only up to this many targets, and this process caches at most this many members. */
+const PURGE_SWEEP_CACHE_TARGETS = 1000;
+const PURGE_SWEEP_CACHE_LIMIT = 128;
+/**
+ * #6884: what a batch sweep found for each queued purge it covered, keyed by that purge's request row id, in this process
+ * only (like `purgeContext`, the journal must never hold the claims): the claim forms searched for and the census up to
+ * the sweep's ceiling. Rows at or below the ceiling that were terminal stay as the sweep saw them (a terminal row's text
+ * only shrinks, by compaction or redaction); rows that were pending, the leader's own row included, are re-tested at
+ * publication; rows past it are the member's tail.
+ */
+const batchSweeps = new Map<string, { sourceId: string; forms: Set<string>; sweep: JournalSweep }>();
+
+/**
+ * #6884: the purge's census. A purge a batch sweep already covered for all of its current claims scans only the tail past
+ * that sweep's ceiling; otherwise it sweeps once for its own claims and those of the next queued purges of the source
+ * (in queue order, bounded by member count and claim forms) and caches each member's result.
+ */
+async function sweepForPurge(engine: BrainEngine, row: WriteRequest, claims: string[], clock: ClaimPhaseClock | undefined): Promise<JournalSweep> {
+ const onChunk = () => faultPoint('purge:sweep_chunk', { requestId: row.request_id, sourceId: row.source_id, operation: row.operation });
+ const forms = carryingNeedles(claims);
+ const cached = batchSweeps.get(row.id);
+ if (cached && cached.sourceId === row.source_id && forms.every(form => cached.forms.has(form))) {
+ const tail = await sweepRequestsCarrying(engine, row.source_id, claims, { clock, exclude: row.id, after: cached.sweep.ceiling ?? '0', onChunk });
+ const targets = [...new Map([...cached.sweep.targets, ...tail.targets].map(t => [t.id, t])).values()];
+ const complete = cached.sweep.complete && tail.complete && targets.length <= JOURNAL_SWEEP_MATCH_CAP;
+ return { targets: targets.slice(0, JOURNAL_SWEEP_MATCH_CAP), pendingAtScan: [...new Set([...cached.sweep.pendingAtScan, ...tail.pendingAtScan])].filter(id => id !== row.id),
+ ceiling: tail.ceiling, scanned: tail.scanned, complete, watermark: cached.sweep.ceiling, batch: cached.sweep.batch ?? 1 };
+ }
+ const groups = [{ key: row.id, claims }], memberForms = new Map<string, Set<string>>();
+ enterClaimStep(clock, 'purge_batch', undefined, 'db');
+ const queued = forms.length ? await engine.executeRaw<{ id: string; slug: string }>(`SELECT id::text AS id,slug FROM persistence_requests
+ WHERE state='queued' AND source_id=$1 AND sequence>$2::bigint AND operation='delete_page' AND intent->>'purge'='true' ORDER BY sequence LIMIT $3`,
+ [row.source_id, String(row.sequence), PURGE_SWEEP_BATCH_MEMBERS - 1]) : [];
+ let budget = forms.length;
+ for (const member of queued) {
+ const [page] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', [row.source_id, member.slug]);
+ if (!page) continue;
+ const memberClaims = (await readPurgeClaims(engine, row.source_id, member.slug, Number(page.id))).needles;
+ const memberNeedles = carryingNeedles(memberClaims);
+ if (!memberNeedles.length) continue;
+ if (budget + memberNeedles.length > PURGE_SWEEP_BATCH_NEEDLES) break;
+ budget += memberNeedles.length;
+ groups.push({ key: member.id, claims: memberClaims });
+ memberForms.set(member.id, new Set(memberNeedles));
+ }
+ const sweeps = await sweepRequestsForGroups(engine, row.source_id, groups, { clock, exclude: row.id, onChunk });
+ for (const [id, memberNeedles] of memberForms) {
+ const sweep = sweeps.get(id)!;
+ if (!sweep.complete || sweep.targets.length > PURGE_SWEEP_CACHE_TARGETS) continue;
+ batchSweeps.delete(id);
+ // The leader was running when the sweep passed it (excluded from the scan), so for every member it is a pending row.
+ batchSweeps.set(id, { sourceId: row.source_id, forms: memberNeedles, sweep: { ...sweep, pendingAtScan: [...sweep.pendingAtScan.filter(p => p !== id), row.id], batch: groups.length } });
+ }
+ while (batchSweeps.size > PURGE_SWEEP_CACHE_LIMIT) batchSweeps.delete(batchSweeps.keys().next().value!);
+ return { ...sweeps.get(row.id)!, watermark: null, batch: groups.length };
+}
+
/** 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'];
@@ -103,8 +171,7 @@ export async function preparePagePurge(engine: BrainEngine, row: WriteRequest, s
enterClaimStep(clock, 'purge_claims', undefined, 'db');
const { needles, factRows, takeRows } = 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 }) });
+ const sweep = await sweepForPurge(engine, row, needles, clock);
const retention = row.intent?.retention === true;
const ledger = await sourceHasBeliefEvents(engine, row.source_id);
const derived = ledger && !retention ? [...(await derivedStreamSlugs(engine, row.source_id, (await derivedRowsFrom(engine, [{ table: 'pages', id: snapshot.page.id },
@@ -227,8 +294,8 @@ export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest,
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 journalSweep = { scanned: prepared.sweep.scanned, ceiling: prepared.sweep.ceiling, watermark: prepared.sweep.watermark ?? null, batch: prepared.sweep.batch ?? 1,
+ 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;
diff --git a/src/core/persistence/purge-deleted.ts b/src/core/persistence/purge-deleted.ts
index 6ce8e54330..269997218a 100644
--- a/src/core/persistence/purge-deleted.ts
+++ b/src/core/persistence/purge-deleted.ts
@@ -4,7 +4,10 @@ import { loadConfig } from '../config.ts';
import type { OperationContext } from '../ops/contract.ts';
import { requireConsent, type ConsentRequest } from '../consent.ts';
import { managedPersistenceEnabled } from './ownership.ts';
-import { submitPageMutation } from './page-mutations.ts';
+import { requestPrincipalForContext, submitPageMutation } from './page-mutations.ts';
+import { readOutstandingRoom } from './journal.ts';
+import { isWriteCapacityWait } from './admission-retry.ts';
+import { readBackgroundPauseShare, resolveAdmissionOrigin } from './admission-origin.ts';
import { withBeliefBatch } from '../belief/ledger.ts';
import { markBeliefCommits } from '../belief/append.ts';
import { linkStreamSlugs } from './page-purge.ts';
@@ -28,6 +31,11 @@ export interface DeletedPagePurge {
inactive: number;
/** #6741 C: tombstones not submitted after PURGE_PARK_LIMIT failures (in `blocked`, code `purge_parked`); doctor purge_parked_pages names them. */
parked: number;
+ /**
+ * #6884: tombstones not submitted because the writer's outstanding-request capacity was in use (in `blocked`, code
+ * `write_capacity_deferred`); the next run submits them. Never a failure and never a park.
+ */
+ capacity_deferred: number;
/** Present when `failed > 0`, so the caller cannot report success. */
error?: { class: string; code: string; message: string };
}
@@ -159,14 +167,15 @@ export async function selectPurgeCandidates(engine: BrainEngine, olderThanHours:
return selection;
}
-/** #6741 C: the cycle purge phase's status: a coordinator failure fails it; a source in recovery or a parked page warns. */
+/** #6741 C: the cycle purge phase's status: a coordinator failure fails it; a source in recovery, a parked page or a capacity deferral (#6884) warns. */
export function purgePhaseStatus(result: DeletedPagePurge): 'ok' | 'warn' | 'fail' {
- return result.error ? 'fail' : result.inactive || result.parked ? 'warn' : 'ok';
+ return result.error ? 'fail' : result.inactive || result.parked || result.capacity_deferred ? 'warn' : 'ok';
}
/** The purge phase summary's note on the pages it did not submit (empty when there are none). */
export function purgePhaseNote(result: DeletedPagePurge): string {
- const parts = [result.inactive ? `${result.inactive} waiting on a writer in recovery` : '', result.parked ? `${result.parked} parked (gbrain doctor: purge_parked_pages)` : ''].filter(Boolean);
+ const parts = [result.inactive ? `${result.inactive} waiting on a writer in recovery` : '', result.parked ? `${result.parked} parked (gbrain doctor: purge_parked_pages)` : '',
+ result.capacity_deferred ? `${result.capacity_deferred} deferred to the next run (write capacity in use)` : ''].filter(Boolean);
return parts.length ? ` (${parts.join(', ')})` : '';
}
@@ -183,12 +192,17 @@ export function purgePhaseNote(result: DeletedPagePurge): string {
* recovery and skips a tombstone that failed PURGE_PARK_LIMIT times (parked,
* purge-parks.ts); `retryParked` (`gbrain pages purge-deleted --retry-parked`)
* gives each parked tombstone the cutoff selects one more attempt.
+ *
+ * #6884: the run submits only while the writer has outstanding-request room
+ * (at the background pause line for a background run), so a large backlog
+ * no longer turns into thousands of `queue_capacity` failures and parks
+ * ahead of interactive writes; the rest is `capacity_deferred` to the next run.
*/
export async function purgeDeletedPagesCoordinated(engine: BrainEngine, olderThanHours: number, opts: { retryParked?: boolean } = {}): Promise<DeletedPagePurge> {
if (!await managedPersistenceEnabled(engine)) {
const recorded = await expireRecordedTombstones(engine, olderThanHours);
const result = await engine.purgeDeletedPages(olderThanHours);
- return { slugs: [...recorded, ...result.slugs], count: recorded.length + result.count, blocked: [], deferred: 0, failed: 0, inactive: 0, parked: 0 };
+ return { slugs: [...recorded, ...result.slugs], count: recorded.length + result.count, blocked: [], deferred: 0, failed: 0, inactive: 0, parked: 0, capacity_deferred: 0 };
}
const selection = await selectPurgeCandidates(engine, olderThanHours, opts);
for (const [sourceId, active] of Object.entries(selection.writers)) await notePurgeSourceWriter(engine, sourceId, active);
@@ -196,20 +210,33 @@ export async function purgeDeletedPagesCoordinated(engine: BrainEngine, olderTha
const config = loadConfig() ?? { engine: engine.kind };
const slugs: string[] = [];
const blocked: DeletedPagePurge['blocked'] = [...selection.blocked];
- let deferred = 0, failed = 0;
- for (const row of selection.candidates) {
+ let deferred = 0, failed = 0, capacityDeferred = 0;
+ const share = resolveAdmissionOrigin() === 'background' ? await readBackgroundPauseShare(engine) : 1;
+ let principal: Awaited<ReturnType<typeof requestPrincipalForContext>> | undefined;
+ for (const [index, row] of selection.candidates.entries()) {
+ const deferRest = (reason: string) => {
+ for (const rest of selection.candidates.slice(index)) blocked.push({ source_id: rest.source_id, slug: rest.slug, code: 'write_capacity_deferred', reason });
+ capacityDeferred = selection.candidates.length - index;
+ };
try {
+ const ctx: OperationContext = { engine, config, remote: false, sourceId: row.source_id, dryRun: false,
+ logger: { info() {}, warn() {}, error() {} } };
+ principal ??= await requestPrincipalForContext(ctx);
+ const room = await readOutstandingRoom(engine, principal, share);
+ if (room.room <= 0) {
+ deferRest(`Not submitted: ${room.used} ${room.scope} outstanding write requests are in use, and this run submits only below ${room.limit}${share < 1 ? ` (a background run stops at ${Math.round(share * 100)}% of the cap, persistence.capacity.background_pause_pct)` : ''}; the next run submits it.`);
+ break;
+ }
const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
if (!snapshot?.page.deleted_at) continue;
// Restored and deleted again since the scan: its recovery window restarted.
if (new Date(snapshot.page.deleted_at).getTime() >= new Date(row.cutoff).getTime()) { deferred++; continue; }
- const ctx: OperationContext = { engine, config, remote: false, sourceId: row.source_id, dryRun: false,
- logger: { info() {}, warn() {}, error() {} } };
await submitPageMutation(ctx, { operation: 'delete_page', params: { slug: row.slug, source_id: row.source_id,
purge: true, retention: true, expected_revision: snapshot.revision, request_id: randomUUID() } });
slugs.push(row.slug);
if (row.park) await clearPurgePark(engine, row.key);
} catch (error) {
+ if (isWriteCapacityWait(error)) { deferRest(`Not submitted: ${error.message}; the next run submits it.`); break; }
const code = typeof (error as { code?: unknown })?.code === 'string' ? (error as { code: string }).code : null;
const reason = error instanceof Error ? error.message : String(error);
if (code && DEFERRAL_CODES.has(code)) deferred++;
@@ -217,10 +244,10 @@ export async function purgeDeletedPagesCoordinated(engine: BrainEngine, olderTha
blocked.push({ source_id: row.source_id, slug: row.slug, code, reason });
}
}
- const failures = blocked.filter(b => !b.code || !DEFERRAL_CODES.has(b.code) && b.code !== 'writer_not_active' && b.code !== 'purge_parked');
+ const failures = blocked.filter(b => !b.code || !DEFERRAL_CODES.has(b.code) && b.code !== 'writer_not_active' && b.code !== 'purge_parked' && b.code !== 'write_capacity_deferred');
const error = failed > 0 ? { class: 'ManagedPurgeFailed', code: 'managed_purge_failed',
message: `${failed} expired page(s) could not be purged through the coordinator: ${failures.slice(0, 3)
.map(b => `${b.source_id}/${b.slug}: ${b.reason}`).join('; ')}` } : undefined;
const parked = selection.parked.filter(park => !park.retried).length;
- return { slugs, count: slugs.length, blocked, deferred, failed, inactive: selection.inactive, parked, ...(error ? { error } : {}) };
+ return { slugs, count: slugs.length, blocked, deferred, failed, inactive: selection.inactive, parked, capacity_deferred: capacityDeferred, ...(error ? { error } : {}) };
}
diff --git a/test/page-purge-batch-sweep-6884.test.ts b/test/page-purge-batch-sweep-6884.test.ts
new file mode 100644
index 0000000000..3ecf074508
--- /dev/null
+++ b/test/page-purge-batch-sweep-6884.test.ts
@@ -0,0 +1,213 @@
+/**
+ * #6884: a page purge's journal sweep (#6511) read and lowered the whole write
+ * journal once per purged page, so a batch of N purges cost N full sweeps and
+ * a nightly purge phase held the source's FIFO queue for hours.
+ *
+ * Protects (fail-first against master):
+ * - [B1] one sweep per batch: the first queued purge sweeps once for its own
+ * claims and those of the purges queued behind it (`journal_sweep.batch`),
+ * and each of those scans only the tail past that sweep's ceiling
+ * (`journal_sweep.watermark`), so the batch's total `scanned` stays near
+ * one journal instead of N. Master: no `batch`/`watermark`, and every
+ * receipt's `scanned` is the whole journal.
+ * - [B1] redaction stays complete for every member: its carriers below the
+ * watermark (from the batch sweep), a carrier admitted and cancelled after
+ * the batch sweep (the member's tail), and a row pending at the batch sweep
+ * that settles with a carrying outcome before the member publishes.
+ * - [B2] a member whose claims changed since the batch sweep does not reuse it:
+ * it sweeps from the start, so a carrier of its new claim below the old
+ * ceiling is still redacted.
+ * - [B3] `sweepRequestsForGroups` attributes each hit to the groups whose
+ * needles it carries, caps each group on its own, and `after` reads only
+ * the rows past it.
+ *
+ * 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 { 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, type FaultPoint } from '../src/core/persistence/fault-points.ts';
+import { cancelWriteRequest } from '../src/core/persistence/control.ts';
+import { JOURNAL_SWEEP_CHUNK_ROWS, sweepRequestsForGroups } from '../src/core/persistence/intent-redaction.ts';
+import { assertConservation } from '../scripts/persistence/harness.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 page = (title: string, claim: string) => `---\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 FILLER = 2 * JOURNAL_SWEEP_CHUNK_ROWS + 500;
+type Row = { state: string; intent: unknown; outcome: unknown; compacted: boolean };
+
+for (const backend of backends) describe(`[${backend}] #6884 page purge batch sweep`, () => {
+ let engine: BrainEngine;
+ let closePostgres: (() => Promise<void>) | undefined;
+ const home = mkdtempSync(join(tmpdir(), `gbrain-6884-${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,intent,outcome,compacted FROM persistence_requests WHERE request_id=$1::uuid', [requestId]))[0]!;
+ const revision = async (slug: string) => (await engine.readPageSnapshot(slug, { sourceId: 'default', includeDeleted: true }))!.revision;
+ const purge = async (slug: string, requestId: string) => call('delete_page', { slug, purge: true, request_id: requestId, expected_revision: await revision(slug) });
+ /** A page with one extracted fact (the purge's claim) and a committed write of another page carrying it. */
+ async function seed(prefix: string): Promise<{ slug: string; claim: string; carrierRequest: string }> {
+ const i = ++n, slug = `${prefix}/leaked-${i}`, claim = `Batch secret ${i} lives in vault-${randomUUID().slice(0, 8)}`;
+ await importFromContent(engine, slug, page(`Leaked ${i}`, claim), { noEmbed: true, sourceId: 'default' });
+ await runExtractFacts(engine, { slugs: [slug] });
+ const carrierRequest = randomUUID();
+ const written = await call('put_page', { slug: `${prefix}/mentions-${i}`, content: `---\ntitle: Mentions ${i}\ntype: note\n---\nSomeone wrote: ${claim}.\n`, request_id: carrierRequest });
+ expect(written.state).toBe('committed');
+ return { slug, claim, carrierRequest };
+ }
+ /** Terminal journal rows that carry nothing: the bulk a full sweep has to read. */
+ const fill = () => 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-6884',gen_random_uuid(),'put_page','default',(SELECT incarnation FROM sources WHERE id='default'),'filler/row-'||g,'d',
+ jsonb_build_object('content','filler body '||g),'{}'::jsonb,'committed',0,0,now() FROM generate_series(1,$1::int) g`, [FILLER]);
+ const unfill = () => engine.executeRaw("DELETE FROM persistence_requests WHERE principal_id='seed-6884'");
+ /** One hook per (seam, request): fires for the named request only. */
+ function arm(hooks: Array<{ point: FaultPoint; requestId: string; fn: () => Promise<void> | void; once?: boolean }>) {
+ const fired = new Set<number>();
+ installFaultHook(async (point, detail) => {
+ for (const [i, hook] of hooks.entries()) {
+ if (hook.point !== point || hook.requestId !== detail.requestId || (hook.once && fired.has(i))) continue;
+ fired.add(i);
+ await hook.fn();
+ }
+ });
+ }
+ async function untilQueued(requestIds: string[]): Promise<void> {
+ for (const deadline = Date.now() + 15_000; Date.now() < deadline; await Bun.sleep(25)) {
+ const rows = await engine.executeRaw<{ n: string }>("SELECT count(*)::text AS n FROM persistence_requests WHERE request_id=ANY($1::uuid[]) AND state='queued'", [requestIds]);
+ if (Number(rows[0]!.n) === requestIds.length) return;
+ }
+ throw new Error('the batch members were not queued in time');
+ }
+ /** A request of another owner's worktree: never claimable here, but a pending row of this source while the batch sweeps. */
+ async function foreignPending(principal: { principal_kind: string; principal_id: string }): Promise<string> {
+ 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 id = 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, id, 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}`]);
+ return id;
+ }
+ async function settle(principal: { principal_kind: string; principal_id: string }, requestId: string, outcome: unknown): Promise<void> {
+ await engine.executeRaw("UPDATE persistence_requests SET state='committed',outcome=$2::text::jsonb,completed_at=now() WHERE request_id=$1::uuid", [requestId, JSON.stringify(outcome)]);
+ await engine.executeRaw("UPDATE persistence_counters SET outstanding_count=outstanding_count-1 WHERE key IN ('brain',$1)", [`principal:${principal.principal_kind}:${principal.principal_id}`]);
+ }
+ const principalOf = async (requestId: string) => (await engine.executeRaw<{ principal_kind: string; principal_id: string }>(
+ 'SELECT principal_kind,principal_id FROM persistence_requests WHERE request_id=$1::uuid', [requestId]))[0]!;
+
+ 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); await unfill(); });
+
+ test('[B1] a batch of queued purges sweeps the journal once; each later member scans only the tail and still redacts every carrier', async () => {
+ const seeds = [await seed('batch'), await seed('batch'), await seed('batch'), await seed('batch')];
+ const principal = await principalOf(seeds[0]!.carrierRequest);
+ const pendingId = await foreignPending(principal);
+ await fill();
+ const ids = seeds.map(() => randomUUID()), tailId = randomUUID();
+ let members: Array<Promise<Record<string, any>>> = [];
+ arm([
+ // The leader waits at its claim until the other purges are queued behind it.
+ { point: 'consumer:preparing', requestId: ids[0]!, once: true, fn: async () => {
+ members = seeds.slice(1).map((s, i) => purge(s.slug, ids[i + 1]!));
+ await untilQueued(ids.slice(1));
+ } },
+ // After the batch sweep read its ceiling: a carrier of member 1's claim admitted and cancelled (terminal, past the ceiling).
+ { point: 'purge:sweep_chunk', requestId: ids[0]!, once: true, fn: async () => {
+ const admitted = await call('put_page', { slug: `batch/late-${n}`, content: `---\ntitle: Late\ntype: note\n---\nLate: ${seeds[1]!.claim}.\n`, request_id: tailId, wait_ms: 0 })
+ .catch(error => error as OperationError);
+ expect((admitted as OperationError).code).toBe('write_pending');
+ expect((await cancelWriteRequest(engine, { kind: principal.principal_kind as never, id: principal.principal_id }, tailId))?.state).toBe('cancelled');
+ } },
+ // A row pending at the batch sweep (below the watermark) settles carrying member 2's claim before member 2 publishes.
+ { point: 'consumer:prepared', requestId: ids[2]!, once: true, fn: () => settle(principal, pendingId, { echoed: `Outcome carries ${seeds[2]!.claim}` }) },
+ ]);
+ const leader = await purge(seeds[0]!.slug, ids[0]!);
+ const receipts = [leader, ...await Promise.all(members)];
+ for (const receipt of receipts) expect(receipt).toMatchObject({ status: 'purged', state: 'committed', journal_sweep: { batch: 4, complete: true } });
+ expect(leader.journal_sweep.watermark).toBeNull();
+ expect(leader.journal_sweep.scanned).toBeGreaterThan(FILLER);
+ for (const member of receipts.slice(1)) {
+ expect(member.journal_sweep.watermark).toBe(leader.journal_sweep.ceiling);
+ expect(member.journal_sweep.scanned).toBeLessThan(50);
+ }
+ const total = receipts.reduce((sum, receipt) => sum + Number(receipt.journal_sweep.scanned), 0);
+ expect(total).toBeLessThan(leader.journal_sweep.scanned + 200);
+ for (const s of seeds) expect(await row(s.carrierRequest)).toMatchObject({ intent: null, compacted: true });
+ expect(await row(tailId)).toMatchObject({ state: 'cancelled', intent: null, compacted: true });
+ expect(await row(pendingId)).toMatchObject({ state: 'committed', compacted: true, outcome: { echoed: '[purged]' } });
+ await unfill();
+ await assertConservation(engine);
+ }, 120_000);
+
+ test('[B2] a member whose claims changed since the batch sweep sweeps from the start and redacts a carrier of its new claim below the old ceiling', async () => {
+ const seeds = [await seed('changed'), await seed('changed')];
+ const changed = `Rotated secret now lives in vault-${randomUUID().slice(0, 8)}`;
+ const lateCarrier = randomUUID();
+ expect((await call('put_page', { slug: `changed/rotated-${n}`, content: `---\ntitle: Rotated\ntype: note\n---\nNoted: ${changed}.\n`, request_id: lateCarrier })).state).toBe('committed');
+ await fill();
+ const ids = [randomUUID(), randomUUID()];
+ let member: Promise<Record<string, any>> | undefined;
+ arm([
+ { point: 'consumer:preparing', requestId: ids[0]!, once: true, fn: async () => { member = purge(seeds[1]!.slug, ids[1]!); await untilQueued([ids[1]!]); } },
+ // After the batch sweep: member 1's fact now states another claim, which the batch never searched for.
+ { point: 'consumer:prepared', requestId: ids[0]!, once: true, fn: async () => {
+ await engine.executeRaw('UPDATE facts SET fact=$3 WHERE source_id=$1 AND source_markdown_slug=$2', ['default', seeds[1]!.slug, changed]);
+ } },
+ ]);
+ const leader = await purge(seeds[0]!.slug, ids[0]!);
+ const second = await member!;
+ expect(leader).toMatchObject({ status: 'purged', journal_sweep: { batch: 2, watermark: null } });
+ expect(second).toMatchObject({ status: 'purged', state: 'committed', journal_sweep: { watermark: null, complete: true } });
+ expect(second.journal_sweep.scanned).toBeGreaterThan(FILLER);
+ expect(await row(lateCarrier)).toMatchObject({ intent: null, compacted: true });
+ }, 120_000);
+
+ test('[B3] the group sweep attributes hits per group, caps each group on its own, and reads only past its watermark', async () => {
+ const incarnation = "(SELECT incarnation FROM sources WHERE id='default')";
+ const insert = (text: string) => engine.executeRaw<{ id: string; sequence: string }>(`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)
+ VALUES ('local_cli','seed-6884',gen_random_uuid(),'put_page','default',${incarnation},'groups/row','d',$1::text::jsonb,'{}'::jsonb,'committed',0,0,now())
+ RETURNING id::text AS id,sequence::text AS sequence`, [JSON.stringify({ content: text })]).then(rows => rows[0]!);
+ const alpha = `Alpha secret ${randomUUID()}`, beta = `Beta secret ${randomUUID()}`;
+ const a1 = await insert(`one ${alpha}`), both = await insert(`${alpha} and ${beta}`), b1 = await insert(`one ${beta}`), a2 = await insert(`two ${alpha}`);
+ const sweeps = await sweepRequestsForGroups(engine, 'default', [{ key: 'a', claims: [alpha] }, { key: 'b', claims: [beta] }, { key: 'none', claims: [] }]);
+ expect(sweeps.get('a')!.targets.map(t => t.id)).toEqual([a1.id, both.id, a2.id]);
+ expect(sweeps.get('b')!.targets.map(t => t.id)).toEqual([both.id, b1.id]);
+ expect(sweeps.get('none')!.targets).toEqual([]);
+ expect(sweeps.get('a')!.complete && sweeps.get('b')!.complete).toBe(true);
+ // Group a reaches the cap on its second hit and stops; group b keeps collecting to the end.
+ const capped = await sweepRequestsForGroups(engine, 'default', [{ key: 'a', claims: [alpha] }, { key: 'b', claims: [`one ${beta}`] }], { matchCap: 2, chunkRows: 1 });
+ expect(capped.get('a')).toMatchObject({ complete: false, targets: [{ id: a1.id }, { id: both.id }] });
+ expect(capped.get('b')).toMatchObject({ complete: true, targets: [{ id: b1.id }] });
+ expect(capped.get('b')!.scanned).toBeGreaterThan(capped.get('a')!.scanned);
+ const tail = await sweepRequestsForGroups(engine, 'default', [{ key: 'a', claims: [alpha] }], { after: b1.sequence });
+ expect(tail.get('a')).toMatchObject({ watermark: b1.sequence, scanned: 1, targets: [{ id: a2.id }], complete: true });
+ }, 60_000);
+});
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index d046d9fec5..370d2bc2b6 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -132,6 +132,7 @@ test/page-embedding-budget.test.ts
test/page-embedding-content-validity.test.ts
test/page-embedding-install-batch.test.ts
test/page-prepare-shared-origin-6517.test.ts
+test/page-purge-batch-sweep-6884.test.ts
test/page-purge-journal-timeout-6511.test.ts
test/page-state-engine.test.ts
test/persistence-background-pause.test.ts
diff --git a/test/purge-deleted-capacity-6884.test.ts b/test/purge-deleted-capacity-6884.test.ts
new file mode 100644
index 0000000000..6c25025e0f
--- /dev/null
+++ b/test/purge-deleted-capacity-6884.test.ts
@@ -0,0 +1,125 @@
+/**
+ * #6884: the managed purge (`gbrain pages purge-deleted`, the cycle purge
+ * phase, the Minion job) submitted every expired tombstone whatever the
+ * writer's outstanding-request room, so a large backlog became thousands of
+ * `queue_capacity` failures, each recorded toward a park, while the admitted
+ * purges sat ahead of interactive writes.
+ *
+ * Protects (fail-first against master): a run submits only while the writer
+ * has outstanding room; the rest is `capacity_deferred` (blocked code
+ * `write_capacity_deferred`), never a failure, never a park and never a
+ * permanent request id, and the phase warns instead of failing; a background
+ * run stops at `persistence.capacity.background_pause_pct` of the cap while
+ * an interactive run uses the whole cap; freed room is used by the next run.
+ * Master: `failed` per tombstone, `managed_purge_failed`, a park record each.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { OperationContext } from '../src/core/operations.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { requestPrincipalForContext, submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { purgeDeletedPagesCoordinated, purgePhaseNote, purgePhaseStatus } from '../src/core/persistence/purge-deleted.ts';
+import { readPurgeParks } from '../src/core/persistence/purge-parks.ts';
+import { withAdmissionOrigin } from '../src/core/persistence/admission-origin.ts';
+import { principalKey } from '../src/core/persistence/model.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const SOURCE = 'purge-capacity';
+const SLUGS = ['notes/expired-a', 'notes/expired-b', 'notes/expired-c'];
+let engine: PGLiteEngine;
+let dir: string;
+let key: string;
+
+const env = () => ({ GBRAIN_HOME: join(dir, 'home'), GBRAIN_SOURCE: undefined, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined,
+ OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined });
+const ctx = (): OperationContext => ({ engine, sourceId: SOURCE, remote: false, dryRun: false, logger: { info() {}, warn() {}, error() {} },
+ config: { engine: engine.kind, embedding_disabled: true } as never });
+
+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);
+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); });
+
+beforeEach(async () => {
+ await disposePersistenceConsumer(engine);
+ await resetPgliteState(engine);
+ dir = mkdtempSync(join(tmpdir(), 'gb-purge-capacity-'));
+ const root = join(dir, 'brain');
+ mkdirSync(root);
+ await withEnv(env(), async () => {
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [SOURCE, root]);
+ await engine.setConfig('sync.write_through', 'true');
+ await claimWorktree(engine, SOURCE, root);
+ for (const slug of SLUGS) {
+ await submitPageMutation(ctx(), { operation: 'put_page', params: { slug, content: `---\ntitle: ${slug}\ntype: note\n---\nGone soon.`, request_id: randomUUID() } });
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId: SOURCE });
+ await submitPageMutation(ctx(), { operation: 'delete_page', params: { slug, expected_revision: snapshot!.revision, request_id: randomUUID() } });
+ }
+ await engine.executeRaw("UPDATE pages SET deleted_at=now() - interval '100 hours' WHERE source_id=$1", [SOURCE]);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ key = principalKey(await requestPrincipalForContext(ctx()));
+ });
+});
+afterEach(async () => { await disposePersistenceConsumer(engine); rmSync(dir, { recursive: true, force: true }); });
+
+const purge = () => withEnv(env(), () => purgeDeletedPagesCoordinated(engine, 72));
+const purgeRequests = async () => (await engine.executeRaw(`SELECT 1 FROM persistence_requests WHERE source_id=$1 AND operation='delete_page' AND intent->>'purge'='true'`, [SOURCE])).length;
+const lifetimeIds = async () => Number((await engine.executeRaw<{ n: string }>("SELECT lifetime_ids::text AS n FROM persistence_counters WHERE key='brain'"))[0]?.n ?? 0);
+const tombstones = async () => (await engine.executeRaw('SELECT 1 FROM pages WHERE source_id=$1', [SOURCE])).length;
+/** Outstanding requests of the purge's own principal held by another owner's worktree (never claimable here). */
+async function occupy(count: number): Promise<string[]> {
+ 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 [kind, id] = [key.split(':')[1]!, key.split(':').slice(2).join(':')];
+ const ids: string[] = [];
+ for (let i = 0; i < count; i++) {
+ const requestId = 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',$4,(SELECT incarnation FROM sources WHERE id=$4),'held/'||$3,$5::uuid,'d','{}'::jsonb,'{}'::jsonb,'queued',0,0)`, [kind, id, requestId, SOURCE, worktree!.id]);
+ ids.push(requestId);
+ }
+ await engine.executeRaw("UPDATE persistence_counters SET lifetime_ids=lifetime_ids+$2,outstanding_count=outstanding_count+$2 WHERE key IN ('brain',$1)", [key, count]);
+ return ids;
+}
+async function release(requestId: string): Promise<void> {
+ await engine.executeRaw("UPDATE persistence_requests SET state='committed',completed_at=now() WHERE request_id=$1::uuid", [requestId]);
+ await engine.executeRaw("UPDATE persistence_counters SET outstanding_count=outstanding_count-1 WHERE key IN ('brain',$1)", [key]);
+}
+
+describe('#6884 managed purge capped to the free write capacity', () => {
+ // A caller that sets no origin is background (admission-origin.ts), so this run stops at 80% of the cap of 3, i.e. below 2.
+ test('no outstanding room: every tombstone is deferred, nothing fails, parks or takes a request id; freed room is used by the next run', async () => {
+ await engine.setConfig('persistence.limits.principal_outstanding', '3');
+ const held = await occupy(3);
+ const ids = await lifetimeIds();
+ const deferred = await purge();
+ expect(deferred).toMatchObject({ count: 0, failed: 0, capacity_deferred: 3, parked: 0 });
+ expect(deferred.error).toBeUndefined();
+ expect(deferred.blocked.map(b => b.code)).toEqual(['write_capacity_deferred', 'write_capacity_deferred', 'write_capacity_deferred']);
+ expect(deferred.blocked[0]!.reason).toContain('3 principal outstanding write requests are in use, and this run submits only below 2');
+ expect(purgePhaseStatus(deferred)).toBe('warn');
+ expect(purgePhaseNote(deferred)).toContain('3 deferred to the next run');
+ expect(await purgeRequests()).toBe(0);
+ expect(await lifetimeIds()).toBe(ids);
+ expect((await readPurgeParks(engine)).size).toBe(0);
+ await release(held[0]!);
+ await release(held[1]!);
+ const next = await purge();
+ expect(next).toMatchObject({ count: 3, failed: 0, capacity_deferred: 0 });
+ expect(await tombstones()).toBe(0);
+ }, 60_000);
+
+ test('a background run stops at the pause line of the outstanding cap; an interactive run uses the rest', async () => {
+ await engine.setConfig('persistence.limits.principal_outstanding', '10');
+ await occupy(8);
+ const background = await withAdmissionOrigin('background', () => purge());
+ expect(background).toMatchObject({ count: 0, failed: 0, capacity_deferred: 3 });
+ expect(background.blocked[0]!.reason).toContain('a background run stops at 80% of the cap');
+ expect(await purgeRequests()).toBe(0);
+ const interactive = await withAdmissionOrigin('interactive', () => purge());
+ expect(interactive).toMatchObject({ count: 3, failed: 0, capacity_deferred: 0 });
+ }, 60_000);
+});