Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): seal decision out of the publication tx; bound statement-cancel re-preparations

garrytanee691a387b1a
diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.md
index efb10e86e9..1eba082a92 100644
--- a/docs/architecture/key-files/persistence-stalls.md
+++ b/docs/architecture/key-files/persistence-stalls.md
@@ -24,7 +24,7 @@ owner (`owner_wedged_here`), movement surfaces (`data_moving`, doctor
- `src/core/persistence/bounded-reads.ts` — #6278 (plan item 1.4): a preparation read that can wait on a relation lock ends at the budget on the server. Phase 0 (`docs/eval/managed-sync-stall-repro.md`) showed that through a transaction-mode pooler gbrain's `statement_timeout` startup parameter is dropped, so a preparation read outside the publication transaction had no server-side bound; an `ACCESS EXCLUSIVE` lock on `pages` held elsewhere pinned the member's origin check and its connection until the lock lifted, and with the budget alone the released member's statement kept running as a zombie that blocked its root until the ceiling. `boundedReads(engine, clock)` is the engine view every preparer reads through (`prepareManagedSyncMutation` and its helpers, `preparePageMutation`, `prepareFactFenceAdoption`, the sync's out-of-consumer preparations): each unmemoized raw statement runs with `executeRaw`'s `timeoutMs` set to the clock's remaining budget (`ClaimPhaseClock.deadlineAt`, set by `startClaimPhase(now, signal, budgetMs)`) and the clock's signal, which ends only the wait for a free connection. On Postgres `timeoutMs` runs the statement on a reserved connection as `BEGIN; SET LOCAL statement_timeout; <statement>; COMMIT` in one pipelined round trip, so the bound holds through the pooler and `SET LOCAL` ends with it; inside a transaction and on PGLite the option is ignored. A statement the server ends (57014, or a 55P03 raised by a shorter session `lock_timeout`) surfaces as the member's own `preparation_deadline` (`PreparationDeadlineError`, or the signal's reason once it aborted), which `preparationAbortReason` classifies as the deadline: the consumer and the group route handle it as the deadline even inside the budget (charged release, `preparation_stalled` at the limit, the group cut like the timer), never as a `storage_error` receipt or an uncharged release. The memo rule holds: `preparationReads` answers a bounded read once with the member's bound and signal dropped. Engine helpers that bypass `executeRaw` (`readPageSnapshot`, the import pipeline) stay under the consumer's race and the ceiling. Tests: `test/persistence-bounded-reads.test.ts`, `test/e2e/persistence-preparation-lock-wait-postgres.test.ts` (a real lock held in another session), the server-ended cases in `test/persistence-consumer-scheduling.test.ts` and `test/e2e/persistence-group-deadline-postgres.test.ts`. GBRA-75 wave 9: `withBoundedReadSession` gives a waiver screen (`unchangedSyncImport`) one reserved ordinary-pool connection (a long-hold permit; none left, or PGLite, runs the screen as before) on which its bounded reads share one transaction: `BEGIN; SET LOCAL statement_timeout` once, `COMMIT` when the screen settles. The bound stays per statement on the server: it is set again in the read's pipeline once the bound in force differs from the read's own by more than `BOUNDED_SESSION_SLACK_MS` (25 ms). A waiver run (`waiveRun` in `sync-run.ts`) opens one session for all its screens, and a screen inside it joins it. Session reads are named prepared statements (`ReservedConnection.executeRaw` `prepare`, ANDed with the connection option as `runUnsafe` does). A failed read rolls back and the reads it aborted (25P02) run again in a new transaction; a read after the screen settled takes the per-read path. Test: `test/persistence-bounded-read-session.test.ts` (real lock wait and no remaining statement on Postgres).
- `src/core/persistence/owner-refusal.ts` — #6278: the `owner_unavailable` reasons matrix. `checkOwner(binding, incarnation, hostId)` names the first failing condition in a fixed order (`binding_missing`, `incarnation_changed`, `host_mismatch`, `transfer_in_progress` for a `draining` worktree, `clone_in_progress` for `recovering`, `local_path_missing`, `coordination_path_missing`) or returns the usable `ActiveOwnerBinding`; `ownerRefusal` gives each reason its message, `why`, actor, fix (always the read-only `gbrain sources writer status --source <id> --json`, with the same verify; `actor: provider` so the two in-progress reasons render `next: wait` with a 30 s delay, `host_admin` for the rest) and `retryable` (`host_mismatch` false at the site, carried by `OperationError.retryable`); `ownerUnavailableError` is the thrown form. `host_mismatch` prints both host ids' first 8 characters and, when `remote` is false, the `host.json` path this process read; nothing here claims or transfers ownership. Used by `maintenancePreflight`, `loadFenceSource` and `managedRepairRoot`; the registry's `owner_unavailable.reasons` and the `FENCE_REASONS` owner entries carry the same vocabulary. Tests: `test/owner-refusal.test.ts` (matrix, every preflight condition on a claimed worktree, the HTTP envelope without a local path), `test/fence-repair-reasons.test.ts`.
- `src/core/persistence/repair-busy.ts` — #6278: the busy set a repair must not write while a managed sync runs. `loadRepairBusySet(engine, sourceId, incarnation)` returns the paths and slugs named by queued, running and recovering requests and terminal rows with an open recovery (both rename endpoints included) plus, for every unfinished `managed-sync` cursor of the incarnation, the entries of its frozen `managed-sync-manifest` from the cursor's index on (a path with a `sync-hold` record is left out: the sync retries a held file only when its bytes change); it never throws and fails closed (`unknown` set, so `repairBusy` answers true for everything) when a query fails or a cursor's manifest is missing. `repairBusyMessage` is the hold text, `repairBusyError` the `sync_in_progress` refusal (`reason` `candidate_in_flight` or `busy_set_unreadable`) `submitManagedFileRepair` raises at admission. Tests: `test/repair-busy.test.ts`, `test/repair-fences.test.ts`, `test/repair-fences-during-catchup.test.ts` (Postgres: `test/e2e/repair-fences-during-catchup-postgres.test.ts`).
-- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement, + the 5 s #6650 dead-owner scan, mirroring the claim, recovery, expired-claim, effect, projection (inline rows windowed by `projection-window.ts`) and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Every claimed write has a preparation budget (`preparation-budget.ts`): `execute` races the preparation against it (`startPreparation`), so the claim is released with `blocked_reason` `preparation_deadline` and one counted attempt at the budget even when the preparer ignores its signal, and a late result never publishes (the execution-token fence). A request already at `persistence.max_preparation_attempts` is finished `failed` with `preparation_stalled` at claim without preparing again, and the release that reaches the limit finishes it there (`coordinator.ts` `finishPreparationStalled`; a waiting `awaitWrite` caller gets the terminal receipt, foreground writes included); a preparer's rejection on the consumer's own abort (its reason, an `AbortError` or a cancelled statement, `preparationAbortReason`) is a release, never a receipt. The expired-claim sweep (Postgres, and PGLite's `releaseAbandonedClaims`) charges one attempt for a claim stamped `preparing` (a process killed mid-preparation); `claim_lost`, `consumer_stopping` and `group_member_waiting` never charge, and a commit resets the counter. The #5373 root barrier for an abandoned preparation ends at `persistence.preparation_ceiling_ms` measured from the claim: the root is freed, the counter is pinned at the limit (an overrun proves cancellation is ignored, so the next claim fails the request `preparation_stalled`) and the zombie stays in `status().outlived_ceiling`; at the per-process cap (`zombieCap`, default 1) the consumer claims nothing more and `status().restart_required` is true. `stop()` gives abandoned preparations `ABANDONED_STOP_GRACE_MS` (5 s) after aborting them instead of waiting forever. The fault point `consumer:preparing` sits inside the budget, `status()` reports `preparation_policy` and `abandoned_preparations`, and the stderr line carries `phase=preparation reason=deadline_exceeded | preparation_stalled | ceiling_exceeded`. With the `preparation_deadlines` switch off only `remember` and intent-less `put_page`/`edit_page` keep the 30 s budget, the old unbounded wait applies and no attempt is counted. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `claimableWriteSql` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (PGLite, 1,000 pages: ~9.5 ms mean, ~18 ms p99 per page). On PGLite the first full tick releases claims last written before this process started (`releaseAbandonedClaims` in `effect-journal.ts`: running effects and unpublished requests without a recovery record), since the datastore admits one process and those owners have exited; Postgres keeps lease expiry (requests 30 s, effects 2 minutes); a provably dead owner's claim goes in 5 s (#6650). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`. With `requestsOnly` (engine graduation's drain) the effect, projection, topology and maintenance workers never start; claim, recovery, expired-claim and publication run as usual and `stop()` remains the barrier. Both the single route and the grouped/lane route (`executeClaimedGroup` in `group-publish.ts`) prepare under a claim lease (`claim-lease.ts`: a renewal every `renewalIntervalMs`, default 10 s, each bounded by `phaseMs`); the claim is lost the first time a renewal says it is gone, throws or overruns, and `whileHeld` stops waiting on the preparation at that moment (the single route also aborts it). The claims still ours are released unpublished with `claim_lost` (token-fenced, so a consumer that took one over keeps it); the abandoned preparation is never published and keeps its root or lane slot until it settles or the ceiling passes, while the consumer slot frees at once. Renewals are never awaited on the way out: `stop()` drains in-flight renewals and gives abandoned preparations their grace before engine close. Tests: `test/persistence-claim-lease.test.ts`, `test/e2e/persistence-consumer-claim-loss.test.ts`, `test/persistence-preparation-kill-accounting.test.ts`, `test/e2e/persistence-preparation-deadline.e2e.test.ts`. #6355: `onLane` lends its warm lane's transaction through a wrapper that notes a connection loss (`isConnectionLoss`); in `finally` a lost lane is released and `idleLaneRetryAt` set a minute out, whatever `run` returned or threw (admission turns the loss into `write_outcome_unknown` or succeeds on the pool, so the catch alone never saw it), because the dead reservation answers every later statement with "Connection is no longer owned" (`test/persistence-consumer-lane-loss.test.ts`).
+- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement, + the 5 s #6650 dead-owner scan, mirroring the claim, recovery, expired-claim, effect, projection (inline rows windowed by `projection-window.ts`) and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Every claimed write has a preparation budget (`preparation-budget.ts`): `execute` races the preparation against it (`startPreparation`), so the claim is released with `blocked_reason` `preparation_deadline` and one counted attempt at the budget even when the preparer ignores its signal, and a late result never publishes (the execution-token fence). A request already at `persistence.max_preparation_attempts` is finished `failed` with `preparation_stalled` at claim without preparing again, and the release that reaches the limit finishes it there (`coordinator.ts` `finishPreparationStalled`; a waiting `awaitWrite` caller gets the terminal receipt, foreground writes included); a preparer's rejection on the consumer's own abort (its reason, an `AbortError` or a cancelled statement, `preparationAbortReason`) is a release, never a receipt. The expired-claim sweep (Postgres, and PGLite's `releaseAbandonedClaims`) charges one attempt for a claim stamped `preparing` (a process killed mid-preparation); `claim_lost`, `consumer_stopping` and `group_member_waiting` never charge, and a commit resets the counter. A statement the database ended with 57014 (statement timeout or cancel: `coordinator.ts` `writeInterruption`) is charged too, in `finishUnpublishedFailure` and in `publishMutation`'s recovery route, and at the limit ends the request `failed` with `write_interrupted` instead of a `database_contention` release; contention with other transactions (55P03, 40001, 40P01), a dropped connection or a restarting database is never charged (`test/persistence-write-interrupted.test.ts`). The #5373 root barrier for an abandoned preparation ends at `persistence.preparation_ceiling_ms` measured from the claim: the root is freed, the counter is pinned at the limit (an overrun proves cancellation is ignored, so the next claim fails the request `preparation_stalled`) and the zombie stays in `status().outlived_ceiling`; at the per-process cap (`zombieCap`, default 1) the consumer claims nothing more and `status().restart_required` is true. `stop()` gives abandoned preparations `ABANDONED_STOP_GRACE_MS` (5 s) after aborting them instead of waiting forever. The fault point `consumer:preparing` sits inside the budget, `status()` reports `preparation_policy` and `abandoned_preparations`, and the stderr line carries `phase=preparation reason=deadline_exceeded | preparation_stalled | ceiling_exceeded`. With the `preparation_deadlines` switch off only `remember` and intent-less `put_page`/`edit_page` keep the 30 s budget, the old unbounded wait applies and no attempt is counted. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `claimableWriteSql` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (PGLite, 1,000 pages: ~9.5 ms mean, ~18 ms p99 per page). On PGLite the first full tick releases claims last written before this process started (`releaseAbandonedClaims` in `effect-journal.ts`: running effects and unpublished requests without a recovery record), since the datastore admits one process and those owners have exited; Postgres keeps lease expiry (requests 30 s, effects 2 minutes); a provably dead owner's claim goes in 5 s (#6650). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`. With `requestsOnly` (engine graduation's drain) the effect, projection, topology and maintenance workers never start; claim, recovery, expired-claim and publication run as usual and `stop()` remains the barrier. Both the single route and the grouped/lane route (`executeClaimedGroup` in `group-publish.ts`) prepare under a claim lease (`claim-lease.ts`: a renewal every `renewalIntervalMs`, default 10 s, each bounded by `phaseMs`); the claim is lost the first time a renewal says it is gone, throws or overruns, and `whileHeld` stops waiting on the preparation at that moment (the single route also aborts it). The claims still ours are released unpublished with `claim_lost` (token-fenced, so a consumer that took one over keeps it); the abandoned preparation is never published and keeps its root or lane slot until it settles or the ceiling passes, while the consumer slot frees at once. Renewals are never awaited on the way out: `stop()` drains in-flight renewals and gives abandoned preparations their grace before engine close. Tests: `test/persistence-claim-lease.test.ts`, `test/e2e/persistence-consumer-claim-loss.test.ts`, `test/persistence-preparation-kill-accounting.test.ts`, `test/e2e/persistence-preparation-deadline.e2e.test.ts`. #6355: `onLane` lends its warm lane's transaction through a wrapper that notes a connection loss (`isConnectionLoss`); in `finally` a lost lane is released and `idleLaneRetryAt` set a minute out, whatever `run` returned or threw (admission turns the loss into `write_outcome_unknown` or succeeds on the pool, so the catch alone never saw it), because the dead reservation answers every later statement with "Connection is no longer owned" (`test/persistence-consumer-lane-loss.test.ts`).
- **`src/core/persistence/sync-group.ts`** + **`group-publish.ts`** — #5984 bulk publication for draining managed Postgres syncs. `sync-group.ts` resolves bulk settings (`--no-bulk` > `GBRAIN_SYNC_BULK` > `sync.bulk` > on; `sync.bulk_size` 16, `sync.bulk_max_txn_ms` 15 s; PGLite off), sizes the next group from the last group's admission-to-commit time per member, freezes followers (four at a time, stopping at a rename, company plan, overtaken or waived entry, or #6712 a slug or page id shared with a member in flight or held, `dependencyKeys`) and admits a group in one transaction (`admitWriteGroupInTransaction`, which keeps one request row, ID and digest per page and replays priors). `sync-run.ts` keeps the head in `pending` and all members in the cursor's `group` (members carry `intent.group` = the head's request ID), waits for the last member and advances over the committed prefix; a terminal failure becomes the pending entry (settled by fault class; later members stay in the window, #6712), a still-pending member returns `writer_pending`. Any caller finishes an existing group; only a drain forms one. #6075: when another owner loop already admitted the group's head on the single path with the head's pre-group intent (the intent minus the `group`/`lane` keys `formGroup` adds, `groupedIntent`/`ungroupedIntent`), `groupStep` drops the group and the single path takes that request, and the never-admitted followers are frozen again; a different intent under the head's request ID still refuses `idempotency_conflict`. The single path's ENG-A7 admission guard compares the stored pending intent as well as its request ID, so a pass that read the head before a drain grouped it re-reads the cursor instead of admitting the stale intent, and an `idempotency_conflict` against a head the group admitted first re-reads the cursor too (`test/managed-sync-stale-group-head.test.ts`). The consumer claims a head's directly following queued members (`claimGroupFollowers`, never past an unfinished non-member) and `executeClaimedGroup` prepares four at a time, then `publishGroup` publishes them in one transaction: one worktree lock, ownership guard and coordinated write (each member set as the attributed actor with `setMemberAttribution`), per-member authorization, preimage read, sync validation (its source-wide part shared per transaction), apply (which reads the postimage the receipt and effects use), effects and receipt; `completeGroup` then reads every member's effect bytes, and pipelines the counter lock with one `UPDATE ... FROM unnest(...) RETURNING` that checks each member's claim and terminal reservation and releases the counters (a short `RETURNING` throws, so the single path reports each member's own code). #6712: each member keeps its own fate (sync groups keep claim 64, width four, ordered release, `syncGroup`): a failed preparation settles before the rest publish as a group; a sync member its lane group's transaction refused settles alone, the rest requeue (`settleCulprit`); other failures roll back and members publish singly. Sync validation accepts a group member through the cursor's `group`. #6007: the pages of one `put_pages` batch (`intent.page_batch.id`; the group key is `journal.ts` `publicationGroupKey`) and the files of one managed import batch (`intent.import_batch`, key `import:`, grouped on PGLite too; `independentGroup` names both) also publish as groups of at most `PAGE_BATCH_GROUP_MAX` (8) pages, prepared all at once, files included: one transaction records every member's recovery record (`prepareRecoveries`) before any file is touched, the publication transaction marks the members `publication_started`, publishes each member's file before its apply and re-arms the batch's mention links once after every member completes (`reconcileFinishedBatch`), and one transaction clears the records after commit (`clearResolvedRecoveries`). A single foreground page write publishes here too, as a group of one (core-persistence-continued.md, `switches.ts` entry). Within that transaction the source's local path, the owner's host binding and config values are read once per group (source membership and the writer registration are already memoized per transaction by `transactionMemo`). On failure every file the group published is restored by `recoverPublication`, which requeues those claims; the fallback claims them back in order (`reclaimReleasedWrite`) and publishes the members singly. Each member has its own preparation budget (#6278): `executeClaimedGroup` marks a wave durably (`markDispatched`) and starts each member's clock when the wave dispatches it, so a follower waiting behind four others is never charged; the lease renews the mutable set of members still held (`renewGroupClaims` stamps each member's own phase), so releasing one member never reads as a lost group lease. When member k's budget passes, nothing later is dispatched, the in-flight suffix is aborted, k is released `preparation_deadline` (charged; finished `preparation_stalled` when that reaches the limit) and the later members `group_member_waiting` (not charged), and the contiguous prepared prefix 0..k-1 publishes (singly when shorter than two; under lanes in the original group's key order). A `put_pages` batch group releases only k, `laneFallback` keeps the expired member's reason, and an abandoned member's preparation goes to the consumer with its clock, so the root waits for it until it settles or the ceiling. A member's signal reaches its preparer through its clock (`enterClaimStep`), never as a blanket statement signal: `preparationReads` and `groupReads` answer one read for every member (GBRA-75 wave 10: `preparationReads` answers `getConfig` from one `getAllConfig` per group; an import group's members also read their own `{ sourceId, includeDeleted: true }` snapshot from one batch and coalesce `findDuplicatePage` into one `findDuplicatePages` statement through `import-reads.ts`, and the group's preparation runs inside `withScreeningPaths`; publication's `validate`/`checkPaths` run after it, unmemoized) and skip their memo for a signalled statement, so a member that must give up on a shared read races its own signal against the shared promise (pinned by `test/persistence-preparation-memo-rule.test.ts`). A commit resets `preparation_attempts` (`completeGroup`). Tests: `test/managed-sync-bulk.test.ts`, `test/e2e/put-pages-group-postgres.test.ts`, `test/e2e/persistence-group-deadline-postgres.test.ts`.
- `src/core/persistence/identity.ts` — local writer and host identity. GBRA-75 wave 7: `localHostId` / `localHostIdentity` / `existingLocalHostId` share one cache of the validated `host.json`, keyed on the path (recomputed from `persistenceHome()` on every call, so a `GBRAIN_HOME` change misses) plus `statSync(bigint)` dev, ino, mtimeNs, ctimeNs and size. ENOENT is a miss (`existingLocalHostId` never mints); any other stat error reads uncached, so `writer_identity_invalid` still throws on every call; an invalid document is never cached; a file modified under 2 s ago is read but not cached (same-size rewrites inside one timestamp tick). `scripts/persistence/harness.ts` `selectFixtureHost` (rename over the path) stays correct. Tests: `test/persistence-host-identity-cache.test.ts`.
- `src/core/persistence/consumer-heartbeat.ts` — #6317 (B1a, B3): the probe and heartbeat behind one full consumer per host. `consumerIdentity()` is this process's `{pid, nonce, pid_ns}` (a random per-process nonce, the `/proc/self/ns/pid` inode where readable), so a reused pid after a container restart is a new row; every `owner_pid === process.pid` check compares the nonce too. `startConsumerHeartbeat(engine, row, opts)` renews this process's `persistence_consumers` row every 10 s on its own single-flight timer through `executeRawDirect` (independent of claim renewal: an idle `serve` holds no claim), carrying kind (`claimOwner().kind`), mode (`probing|full|waiter_only|promoted`), `restart_required`, the age of the oldest abandoned root barrier, the pool gauge `{checked_out, max, waiters}`, `host_json_path`, `persistence_home`, `minted_under` and the build; each renewal deletes rows not renewed for 90 s in the same CTE, and a failed write is logged once and never stops the consumer. #6650: rows carry `boot_id`, `process_start` (v243); the probe and `electOwner` skip rows `consumerRowProvablyDead` proves dead (Linux: same boot and pid ns, pid gone/reused). `probeLiveFullConsumer(engine, hostId, self)` is the database-only probe (never a socket: the persistence IPC socket exists only on PGLite): a row of a resident kind (`serve`, `sync`, `jobs`, `autopilot`, `mcp`), mode `full`, not this process, renewed within 30 s, not `restart_required` and not wedged (no root barrier older than `persistence.preparation_ceiling_ms`), on an `active` binding. `listHostConsumers(engine, hostId)` feeds `writer status --json` `host.consumers` and doctor. The consumer mode machine in `consumer.ts` (`probing` → `full` or `waiter_only` → `promoted` → back to `waiter_only` after three healthy owner ticks) consumes the probe on every tick; `startPersistenceConsumer` in `service.ts` stays synchronous and returns the waiter-only seam (`WaiterOnlyConsumer` behind `PersistenceConsumerLike`: `wake()` no-op, settlement listeners kept, `holds()` false, `status()` `waiter_only` with the owner pid) when the probe finds an owner and `persistence.single_consumer` is on. A `serve` always starts full; short-lived kinds (`put`, `import`, `dream`, `cycle`, `sources`, `cli`) keep their own consumer; PGLite is inert.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index a668aa8a71..8aa2a48606 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -3878,6 +3878,16 @@ Reasons: `override`, `standing_instruction`, `exfiltration`, `credential`, `dete
Reasons: `override`, `standing_instruction`, `exfiltration`, `credential`, `detector_error`.
+### write_interrupted
+
+<a id="write_interrupted"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The database ended this managed write's statements (SQLSTATE 57014, a statement timeout or cancel) persistence.max_preparation_attempts times (default 2), so the owner finished it failed instead of preparing it again; nothing was published. | Each cancelled statement throws the write's preparation away, and a write whose work outlasts the bound every time (a large page publishing under a 5 s statement bound on a loaded host) used to be released as database_contention and prepared again, its whole body streamed again, without limit. These cancellations now count with cut-off preparations. Contention with other transactions (lock timeout, serialization failure, deadlock), a dropped connection and a restarting database are never counted. The receipt names the attempts, the limit and the SQLSTATE. | Inspect the owner with gbrain sources writer status --source <id> --json (read-only), then submit the write again with a new request_id once the database is less loaded; a managed sync freezes the file again on its next run. If the same write ends this way again, report its request id with gbrain doctor --json. Run: gbrain sources writer status --source '{source_id}' --json | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/write-refusals.md#write_interrupted](../../docs/guides/write-refusals.md#write_interrupted)
+
### write_outcome_unknown
<a id="write_outcome_unknown"></a>
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index e12bfcf553..416dc9e535 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -97,6 +97,7 @@ of making a duplicate.
| <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="purge_mirror_unwritable"></a>`purge_mirror_unwritable` | `purge_mirror_unwritable` | A fact or page purge appends a text-free `intent` line to the purge mirror (`<brain home>/.gbrain/purge-events.jsonl`) and fsyncs it before it commits, so a later restore of an older backup can replay the purge. The mirror could not be written (a directory in its place, a read-only home, a full disk), so the purge was refused: nothing was removed, tombstoned or redacted. Do not assume the requested content was erased. | Make the mirror a writable regular file owned by the brain's user (mode 0600), then run the purge again with a new `request_id`. |
| <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_interrupted"></a>`write_interrupted` | `write_interrupted` | The database ended this managed write's own statements (SQLSTATE `57014`, a statement timeout or cancel) at preparation or inside its publication transaction, and the request reached `persistence.max_preparation_attempts` (default 2) counted attempts, so the owner finished it `failed` instead of preparing it again. Nothing was published: a worktree-backed write's canonical file is restored before the failure is recorded. Each interruption throws the preparation away, so it counts with the preparations cut off at their deadline ([`preparation_stalled`](#preparation_stalled)); before, a write the database ended every time (a large page publishing under the 5-second statement bound on a loaded host) was released as `database_contention` and prepared again, its whole body streamed again, without limit. Contention with other transactions (`55P03` lock timeout, `40001` serialization failure, `40P01` deadlock) is still released as `database_contention` uncounted, and a dropped connection or a database that is restarting or out of connections is never counted. The receipt's message and owner-only `error_detail` name the attempts, the limit and the SQLSTATE (`sqlstate`, public). A managed sync member re-freezes in place under a fresh request, at most three times in a row per run. With `persistence.preparation_deadlines` off nothing is counted, as before. | Run `gbrain sources writer status --source <source> --json` (read-only: the owner, its pool, what its writes wait on), then submit the write again with a new `request_id` once the database is less loaded; a managed sync freezes the file again on its next run. If the same write ends this way again, report its request id with `gbrain doctor --json`. Do not raise `persistence.max_preparation_attempts` to get past it. |
| <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="page_body_segmented"></a>`page_body_segmented` | `page_body_segmented` (a memory verb: `invalid_params` with `write_error: page_body_segmented`) | The target page stores its body in segments (a page over 1 MiB written while `pages.segmented_storage` was on), and this write needs the whole body as one string: `remember` against an entity page over 24 MiB (named, or inferred from the fact), and the other whole-body writers listed under [page_body_segmented](windowed-reads.md#page_body_segmented). It refused before changing anything and is not retryable. | For `remember`, save the claim without an entity (`infer_entity: false`); remembering it with `entity` once that page accepts fact rows replaces that copy. Otherwise edit the page's file and sync it, or read it with `get_page` `body: "auto"`. |
| <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. The planner runs the publisher's own read-back check on the whole rendered fence first, so such a page is reported as unadoptable (class `whole_fence`) instead of being submitted. A managed adoption refused in the last day is not resubmitted: the cycle reports it as class `prior_refusal` with the refused request id (`gbrain write-request -- <id>` reads it), and a direct `submitFactFenceAdoption` call refuses with `The same fact-fence adoption was already refused.`. It is retried a day after the refusal, or at once by a build whose adoption planner revision changed. Unadopted rows hold only their own page: the phantom-redirect pass skips a phantom that owns one and redirects the others. Before v0.60.218.0 the planner could reuse a leftover fence row (one with no database owner) whose visibility differed from the legacy fact's. On a managed brain the publisher refused that page here every cycle, so no private fact was published as world. An unmanaged brain had no such check: it fenced the fact into the leftover row, and the same cycle's reconcile copied that row's visibility into the fact, so a private fact could become world. The current planner never reuses a leftover row for a fact with a different visibility unless the fact is private, and re-renders a reused row from the fact. To count what an older build left in the writer table, run the read-only `scripts/diagnose/fence-adoption-census.sql` on the brain host against the brain's Postgres database (its header shows the `psql` command). | 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 43632f4b29..033d1b9a9d 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -882,6 +882,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.287.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.287.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.' },
{ since: '0.60.288.0', text: 'On a managed brain `gbrain sync --dry-run --json` adds a `convergence` object: a read-only shadow of the level-triggered sync (#6712 PR 4a) that classifies every path of the source the way the coming pass will (matched, import, held, drift and the other classes, each tagged with who acts: none, owner or repair), with predicted file_drift decisions after a read-only screen, `legacy_unverified` counts, deletes with the mass-delete valve verdict and up to 20 sample paths per class. `--redact-paths` turns the sample paths into sha256 prefixes and drops slugs, so the counts can be shared. `gbrain sync status --detail --json` adds the same object (`convergence`, `dry_run: true`) and `convergence_read`; a plain `sync status` skips that heavy read. Nothing is written or admitted, existing keys keep their meaning, and sync behaves exactly as before.' },
+ // Flip lane C (segmented storage switch-on): transient publication failures are bounded.
+ { since: 'TBD', text: 'A managed write whose statements the database ends with a statement timeout or cancel (SQLSTATE 57014, at preparation or inside its publication transaction) now counts each such interruption against `persistence.max_preparation_attempts` (default 2), together with preparations cut off at their deadline, and at the limit ends `failed` with `write_interrupted` (the receipt names the attempts, the limit and the SQLSTATE; a worktree-backed write restores its file first) instead of being released as `database_contention` and prepared again without limit. A single interruption still re-prepares and commits; a lock timeout, serialization failure or deadlock (contention with other writers), a dropped connection or a restarting database is never counted. A foreground write needs a new `request_id`; a managed sync re-freezes the file in place. `persistence.preparation_deadlines false` turns the counting off with the deadlines.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index dee6cb469c..779c4813a4 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -637,6 +637,12 @@ export const CODES = {
write_claim_lost: { class: 'retryable', summary: "Execution claim changed before publication." },
write_gate_rejected: { class: 'caller', summary: "The write gate refused external instruction-like content because the operator set `write_gate.external_mode` to `reject`.", why: "Text from an untrusted source that reads like an instruction to an agent (an override, a standing rule, an exfiltration or credential request) is refused instead of held under that setting, so nothing was written. The same content refuses on every retry.", reasons: ['override', 'standing_instruction', 'exfiltration', 'credential', 'detector_error'], suggestion: 'Tell the user the content was refused; whether to accept it or switch `write_gate.external_mode` back to `quarantine` is their decision.' },
write_held: { class: 'consent', summary: "The write gate held this content for the owner's review instead of saving it as memory.", why: "Content from an untrusted source read like an instruction to an agent, so it was quarantined in the write-gate holding table. It is not searchable or recalled until the owner releases it; retrying the same write only re-opens the same hold.", reasons: ['override', 'standing_instruction', 'exfiltration', 'credential', 'detector_error'], actor: 'user', exit: 3, suggestion: 'Do not retry. Tell the user what was held and give them the release command from the fix; releasing is their decision.' },
+ write_interrupted: { class: 'retryable', retryable: false, actor: 'agent',
+ summary: "The database ended this managed write's statements (SQLSTATE 57014, a statement timeout or cancel) persistence.max_preparation_attempts times (default 2), so the owner finished it failed instead of preparing it again; nothing was published.",
+ why: "Each cancelled statement throws the write's preparation away, and a write whose work outlasts the bound every time (a large page publishing under a 5 s statement bound on a loaded host) used to be released as database_contention and prepared again, its whole body streamed again, without limit. These cancellations now count with cut-off preparations. Contention with other transactions (lock timeout, serialization failure, deadlock), a dropped connection and a restarting database are never counted. The receipt names the attempts, the limit and the SQLSTATE.",
+ docs: 'docs/guides/write-refusals.md#write_interrupted',
+ suggestion: 'Inspect the owner with gbrain sources writer status --source <id> --json (read-only), then submit the write again with a new request_id once the database is less loaded; a managed sync freezes the file again on its next run. If the same write ends this way again, report its request id with gbrain doctor --json.',
+ fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: 'Read-only: the owner process, its pool and what its writes wait on.', requires_exclusive: false } },
write_outcome_unknown: { class: 'retryable', retryable: false, actor: 'agent',
summary: "The database connection dropped while a write was being admitted, and it kept dropping through the re-reads, so whether the write was accepted is unknown.",
why: "A session that closes under an admission (a pooler reap, a failover, pg_terminate_backend) leaves the transaction either committed or rolled back with no way to tell from the lost socket. gbrain re-runs the attempt, which starts by reading the retained request_id, so a single drop resolves by itself; this code means the database stayed unreachable through those re-reads. Before #6355 the raw socket error reached the caller, and a receipt oracle took it for a refusal while the write committed.",
diff --git a/src/core/page-body/ingest.ts b/src/core/page-body/ingest.ts
index 8569a152ad..3c03786d87 100644
--- a/src/core/page-body/ingest.ts
+++ b/src/core/page-body/ingest.ts
@@ -35,6 +35,7 @@ import { loadFenceChunkOverlay } from '../eligibility/fence-overlay.ts';
import { withdrawalFenceBlocks } from '../facts/withdrawal-overlay.ts';
import { overlaySegmentText, readBodyLedger, type BodyLedger } from './segment-ledger.ts';
import { assertGenerationTiles } from './body-tiling.ts';
+import { hasStaleChunks } from './projection.ts';
const utf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
@@ -89,6 +90,11 @@ export interface PreparedSegmentedBody {
retireChunkOccurrences: number[];
/** Occurrences of the new generation that have no chunk rows after staging (a create without `createChunks`: all, chunked after publication). */
unchunked: number;
+ /**
+ * The live generation stores chunk rows it does not hold (an earlier write's deferred retirement), so the publication
+ * leaves the page unsealed. Read here, not in the publication transaction: the probe walks every occurrence of the page.
+ */
+ priorStale: boolean;
body: SegmentedBodyColumns;
/** No manifest row changed: the write changes metadata only. */
bodyUnchanged: boolean;
@@ -321,7 +327,7 @@ async function stageBody(engine: BrainEngine, input: SegmentedBodyInput, staging
if (createChunks) await stageOccurrenceChunks(engine, { pageId: 0, sourceId: input.sourceId, slug: input.slug, generation: newGeneration, occurrences: rows,
title: input.title, frontmatter: input.frontmatter, flags: body.body_flags, chunking: input.chunking, retiredOccurrences: [], hold: createChunks.chunks });
return { stagingId, expectedGeneration, newGeneration, createRows: rows, createChunks, closeOccurrences: [], retireChunkOccurrences: [],
- unchunked: createChunks ? 0 : rows.length, body, bodyUnchanged: false, rows: { texts, manifest: rows.length, chunks: createChunks?.chunks.length ?? 0 }, stagedChunkIndexes: [] };
+ unchunked: createChunks ? 0 : rows.length, priorStale: false, body, bodyUnchanged: false, rows: { texts, manifest: rows.length, chunks: createChunks?.chunks.length ?? 0 }, stagedChunkIndexes: [] };
}
if (changed.length) await writes(exec => exec.stageManifestRows(changed));
await faultPoint('segmented:manifest_staged', { sourceId: input.sourceId });
@@ -332,8 +338,9 @@ async function stageBody(engine: BrainEngine, input: SegmentedBodyInput, staging
await faultPoint('segmented:chunks_staged', { sourceId: input.sourceId });
const kept = new Set(rows.filter((_, i) => matched[i]).map(row => row.occurrenceId));
retireChunkOccurrences.push(...chunkable.filter(row => kept.has(row.occurrenceId)).map(row => row.occurrenceId));
+ const priorStale = !!live && await hasStaleChunks(engine, live.id, expectedGeneration, liveRows.map(row => Number(row.occurrenceId)));
return { stagingId, expectedGeneration, newGeneration, createRows: null, createChunks: null, closeOccurrences, retireChunkOccurrences,
- unchunked: input.chunking.quarantined ? 0 : chunkable.length - chunks.occurrences, body,
+ unchunked: input.chunking.quarantined ? 0 : chunkable.length - chunks.occurrences, priorStale, body,
bodyUnchanged: changed.length === 0 && retireChunkOccurrences.length === 0, rows: { texts, manifest: changed.length, chunks: chunks.rows },
stagedChunkIndexes: chunks.indexes };
}
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 2d26ca529a..70679fa536 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -16,6 +16,7 @@ import { acquireWorktree, getWorktreeBinding, guardOwnership, type WorktreeBindi
import { chargePreparationAttempt, clearResolvedRecovery, completeWrite, getWriteRequestById, lockCounters, markRecovering, prepareRecovery, releaseUnpublishedClaim } from './journal.ts';
import type { WaitingOn } from './claim-phase.ts';
import { preparationKind } from './preparation-budget.ts';
+import { readWriteSwitchSnapshot } from './switches.ts';
import { isTerminal, principalKey, requestPrincipal, recoveryFiles, type FileRecoveryRecord, type RecoveryRecord, type WriteRequest } from './model.ts';
import { isLockOpenFailure, noteLockOpenFailure, type NativeLockHandle } from './native-lock.ts';
import { withCoordinatedWrite } from './context.ts';
@@ -201,6 +202,41 @@ export function transientDatabaseFailure(error: unknown): boolean {
return ['40001','40P01','55P03','57014','53300','57P01','57P02','57P03','08000','08003','08006','08001','08004',
'ECONNRESET','ECONNREFUSED','ETIMEDOUT','CONNECTION_CLOSED','CONNECTION_ENDED'].includes(String((error as {code?:string})?.code));
}
+/**
+ * The SQLSTATE of a transient failure that ended this write's own statement while the database stayed up (57014: a
+ * statement timeout or cancel), else null. It throws the preparation away and recurs while the write's work outlasts
+ * its bound, so it is charged like a cut-off preparation (`chargedInterruption`). Contention with other transactions
+ * (a lock timeout, a serialization failure, a deadlock) clears when they finish, and a lost connection or a database
+ * shutting down or out of connections is not the write's doing: neither is charged, so a restart never fails a write.
+ */
+function writeInterruption(error: unknown): string | null {
+ return String((error as {code?:string})?.code) === '57014' ? '57014' : null;
+}
+function writeInterruptedFailure(row: WriteRequest, sqlstate: string, attempts: number, limit: number): PublicationFailure {
+ const fix = preparationKind(row) === 'sync'
+ ? 'The next gbrain sync of the source freezes the file again under a new request.'
+ : 'Submit the write again with a new request_id once the database is less loaded.';
+ return { code: 'write_interrupted',
+ message: `The database ended this write's statements ${attempts} time(s) (SQLSTATE ${sqlstate}, a statement timeout or cancel), the limit of persistence.max_preparation_attempts (${limit}); it is not prepared again. `
+ + `Run gbrain sources writer status --source ${row.source_id} --json to see the load on the owner. ${fix}`,
+ detail: { origin: 'database_interruption', sqlstate, attempts, limit } as unknown as PublicationFailureDetail };
+}
+/**
+ * Flip lane C: charges an interruption (`writeInterruption`) to the claim this owner holds and returns the terminal
+ * `write_interrupted` failure once the count reaches persistence.max_preparation_attempts. Null when the failure is
+ * not an interruption, the `preparation_deadlines` switch is off (nothing is counted, as before), the count is below
+ * the limit, or the database cannot be read (the claim is then released uncounted).
+ */
+async function chargedInterruption(engine: BrainEngine, row: WriteRequest, error: unknown): Promise<PublicationFailure | null> {
+ const sqlstate = writeInterruption(error);
+ if (!sqlstate) return null;
+ try {
+ const { switches, preparation } = await readWriteSwitchSnapshot(engine);
+ if (!switches.preparation_deadlines) return null;
+ const attempts = await chargePreparationAttempt(engine, row);
+ return attempts >= preparation.maxAttempts ? writeInterruptedFailure(row, sqlstate, attempts, preparation.maxAttempts) : null;
+ } catch { return null; }
+}
/**
* #6278: the reasons a consumer aborts a preparation with. An error that is
* that abort (the reason itself, an AbortError, or the Postgres cancel the
@@ -252,6 +288,8 @@ export async function finishPreparationStalled(engine: BrainEngine, row: WriteRe
export async function finishUnpublishedFailure(engine: BrainEngine, row: WriteRequest, error: unknown,
stage: PublicationStage = 'publication'): Promise<WriteRequest> {
+ const interrupted = await chargedInterruption(engine, row, error);
+ if (interrupted) return engine.transaction(tx => completeWrite(tx, row, 'failed', {}, withAttempt(interrupted, stage)));
const failure = withAttempt(requestError(error), stage);
if (mayReprepare(row, failure) || transientDatabaseFailure(error)) {
await releaseUnpublishedClaim(engine, row, transientDatabaseFailure(error) ? 'database_contention' : 'revision_changed_repreparing');
@@ -522,8 +560,9 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
if (recovery) {
// Even a rejected prepare can retain a journal record; do not leave that
// record unaccounted or let a sibling publication bypass its recovery.
- const failure = !transactionBodyCompleted && !mayReprepare(row, requestError(error)) && !transientDatabaseFailure(error)
- ? withAttempt(requestError(error), published ? 'after_file_publication' : 'publication') : undefined;
+ const interrupted = transactionBodyCompleted ? null : await chargedInterruption(engine, row, error);
+ const failure = interrupted || (!transactionBodyCompleted && !mayReprepare(row, requestError(error)) && !transientDatabaseFailure(error))
+ ? withAttempt(interrupted ?? requestError(error), published ? 'after_file_publication' : 'publication') : undefined;
try { await markRecovering(engine, row, failure ? 'publication_failed' : published ? 'commit_outcome_uncertain' : 'publication_not_started', failure); }
catch { /* database outage: durable recovery record remains discoverable */ }
if (lock) {
diff --git a/src/core/persistence/segmented-apply.ts b/src/core/persistence/segmented-apply.ts
index 044e42efc0..0a878f88b7 100644
--- a/src/core/persistence/segmented-apply.ts
+++ b/src/core/persistence/segmented-apply.ts
@@ -25,7 +25,7 @@ import type { PageSnapshot } from '../page-state/types.ts';
import type { JsonObject, SegmentedPageMeta } from '../page-body/types.ts';
import type { PreparedSegmentedBody, SegmentChunkingContext, SegmentedLivePage, SegmentedStagingOwner } from '../page-body/ingest.ts';
import { materializeSegmentedBody, prepareSegmentedBody, segmentWriteScope, stringBodyFlags, stringRegion } from '../page-body/ingest.ts';
-import { buildSegmentedProjection, hasStaleChunks, liveOccurrenceIds } from '../page-body/projection.ts';
+import { buildSegmentedProjection } from '../page-body/projection.ts';
import { maintenanceAttribution } from './attribution.ts';
import { readPageBodyPolicy, chooseBodyStorage, SEGMENTED_DEMOTE_AT_OR_BELOW_BYTES, type PageBodyPolicy } from '../page-body/limits.ts';
import { SEGMENTED_CHUNKER_VERSION } from '../page-body/segment-chunks.ts';
@@ -179,9 +179,10 @@ export async function applySegmentedBody(tx: BrainEngine, input: SegmentedApplyI
await faultPoint('segmented:flipped', { sourceId: input.sourceId });
await tx.setBodyStagingState(prepared.stagingId, 'committed', { commitRequestId: input.requestId ?? null });
const chunked = prepared.createRows ? createChunks !== null : prepared.unchunked === 0;
- // The flip retires only the occurrences this write closes: rows an earlier write's deferred retirement left keep the page unsealed.
- const complete = chunked && !flip.retireDeferred
- && !await hasStaleChunks(tx, pageId, prepared.newGeneration, await liveOccurrenceIds(tx, pageId, prepared.newGeneration));
+ // The flip retires only the occurrences this write closes: rows an earlier write's deferred retirement left keep the page
+ // unsealed. Preparation read them (`priorStale`); while the generation it read is live no stale row is added, since a
+ // projection chunks only occurrences without rows and this flip retires every occurrence the preparation chunked again.
+ const complete = chunked && !flip.retireDeferred && !prepared.priorStale;
return { pageId, complete, retireDeferred: flip.retireDeferred };
}
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 39bc666743..5e011ca024 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -6393,7 +6393,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\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"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\" | \"page_body_segmented\" | \"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\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"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_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"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\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"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\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"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_drift\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"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\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"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\" | \"ipc_path_too_long\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"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_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"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\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_read_incomplete\" | \"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\" | \"result_too_large\" | \"revision_changed\" | \"revision_unavailable\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"serve_build_drift\" | \"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\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"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_drain_lease_held\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"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_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"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\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"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\" | \"page_body_segmented\" | \"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\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"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_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"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\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"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\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"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_drift\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"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\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"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\" | \"ipc_path_too_long\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"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_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"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\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_read_incomplete\" | \"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\" | \"result_too_large\" | \"revision_changed\" | \"revision_unavailable\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"serve_build_drift\" | \"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\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"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_drain_lease_held\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"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_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"write_interrupted\" | \"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/large-pages/publication-seal-bounded.test.ts b/test/large-pages/publication-seal-bounded.test.ts
new file mode 100644
index 0000000000..15b8ef3748
--- /dev/null
+++ b/test/large-pages/publication-seal-bounded.test.ts
@@ -0,0 +1,134 @@
+/**
+ * The seal decision of a segmented write's publication reads no more than the write's own delta (flip lane C).
+ *
+ * 1. Protects: applySegmentedBody decides whether the publication seals the page (every occurrence chunked, no stale
+ * chunk row stored) without reading the page: the stale-row probe (projection.ts STALE_CHUNKS_SQL, one index walk
+ * over every occurrence of the page plus every row of each live one) and the live manifest read run in preparation,
+ * and the publication transaction only reads what the write staged. A small edit near the end of a 2 MiB and an
+ * 8 MiB page still seals in its publication, and its new text is a keyword hit at once.
+ * 2. Fails when: the probe runs inside the publication transaction, where its cost grows with the page and
+ * declareDurablePersistence's 5 s statement_timeout can end it on a loaded host (57014), so the whole write is
+ * prepared again; or when the publication stops sealing (the post-commit projection is lost here, so only the
+ * publication can seal).
+ * 3. Existing coverage: second-write-deferred-retire.test.ts keeps a page whose earlier write deferred its retirement
+ * unsealed; chunk-retirement-plan.test.ts bounds the probe itself.
+ * 4. Work is EXPLAIN (ANALYZE, FORMAT JSON) of each content_chunks / page_body_manifest statement the publication
+ * transaction issues (inside a savepoint rolled back before the real statement runs): rows produced plus rows
+ * removed by filters, times loops, summed over plan nodes. Counts, never time. Runs on PGLite, and on Postgres
+ * when DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } 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 { importFromFile } from '../../src/core/import-file.ts';
+import { readPageBodyPolicy } from '../../src/core/page-body/limits.ts';
+import { installFaultHook } from '../../src/core/persistence/fault-points.ts';
+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { conversationPage } from '../helpers/conversation-page.ts';
+import { segmentedPageRow } from '../helpers/segmented-page-checks.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-publication-seal-'));
+const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };
+afterAll(() => { rmSync(home, { recursive: true, force: true }); });
+const PROJECTION_PAGE_READ = "FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL AND body_storage='segmented'";
+
+interface PlanNode { 'Actual Rows'?: number; 'Actual Loops'?: number; 'Rows Removed by Filter'?: number; 'Rows Removed by Index Recheck'?: number; Plans?: PlanNode[] }
+interface StatementWork { sql: string; rows: number }
+
+function rowsExamined(node: PlanNode): number {
+ const loops = node['Actual Loops'] ?? 1;
+ const own = ((node['Actual Rows'] ?? 0) + (node['Rows Removed by Filter'] ?? 0) + (node['Rows Removed by Index Recheck'] ?? 0)) * loops;
+ return own + (node.Plans ?? []).reduce((n, child) => n + rowsExamined(child), 0);
+}
+
+/** `tx` with each content_chunks / page_body_manifest statement measured first, in a savepoint rolled back before it runs. */
+function measuredTx(tx: BrainEngine, log: StatementWork[]): BrainEngine {
+ return new Proxy(tx, { get(target, prop) {
+ if (prop === 'executeRaw') return async (sql: string, params?: unknown[], opts?: unknown) => {
+ if (/content_chunks|page_body_manifest/.test(sql)) {
+ await target.executeRaw('SAVEPOINT plan_probe');
+ const [row] = await target.executeRaw<Record<string, unknown>>(`EXPLAIN (ANALYZE, FORMAT JSON) ${sql}`, params);
+ await target.executeRaw('ROLLBACK TO SAVEPOINT plan_probe');
+ const raw = Object.values(row!)[0];
+ const plan = (typeof raw === 'string' ? JSON.parse(raw) : raw) as Array<{ Plan: PlanNode }>;
+ log.push({ sql: sql.replace(/\s+/g, ' ').slice(0, 100), rows: rowsExamined(plan[0]!.Plan) });
+ }
+ return target.executeRaw(sql, params, opts as never);
+ };
+ const value = Reflect.get(target, prop, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+}
+
+/**
+ * The engine whose publication transaction (the one the generation flip runs in, `segmented:flipped`) has its statements
+ * measured into `publication`, and whose post-commit projection is lost (its page read throws), so only the publication seals.
+ */
+function measuredWrite(engine: BrainEngine, publication: StatementWork[]): BrainEngine {
+ return new Proxy(engine, { get(target, prop) {
+ if (prop === 'executeRaw') return (sql: string, params?: unknown[], opts?: unknown) => sql.includes(PROJECTION_PAGE_READ)
+ ? Promise.reject(new Error('projection lost (probe)')) : target.executeRaw(sql, params, opts as never);
+ if (prop === 'transaction') return (fn: (tx: BrainEngine) => Promise<unknown>, opts?: unknown) => target.transaction(async tx => {
+ const log: StatementWork[] = [];
+ let flipped = false;
+ installFaultHook(point => { if (point === 'segmented:flipped') flipped = true; });
+ try {
+ const out = await fn(measuredTx(tx, log));
+ if (flipped) publication.push(...log);
+ return out;
+ } finally { installFaultHook(undefined); }
+ }, opts as never);
+ const value = Reflect.get(target, prop, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+}
+
+for (const kind of testBackends()) describe(`a segmented write's publication reads its delta, not the page (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ beforeAll(async () => withEnv(env, async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); close = () => engine.disconnect(); }
+ await registerLocalWriter(engine, 'cli');
+ await engine.setConfig('pages.segmented_storage', 'on');
+ }), 120_000);
+ afterAll(async () => withEnv(env, async () => { await disposePersistenceConsumer(engine); await close?.(); }));
+
+ const found = async (slug: string, word: string) => (await engine.searchKeyword(word, { limit: 10 })).filter(r => r.slug === slug).length;
+
+ for (const mib of [2, 8]) test(`an edit near the end of a ${mib} MiB page seals in its publication, reading only what it staged`, async () => withEnv(env, async () => {
+ const v0 = conversationPage(mib * 1024 * 1024, { seed: 61, needles: [{ at: 0.95, word: 'tailmarkerquokka' }] });
+ const file = join(home, `page-${mib}.md`);
+ const slug = `notes/publication-seal-${mib}`;
+ const write = async (on: BrainEngine) => expect(await importFromFile(on, file, `${slug}.md`, { noEmbed: true, bodyPolicy: await readPageBodyPolicy(engine) }))
+ .toMatchObject({ status: 'imported' });
+ writeFileSync(file, v0);
+ await write(engine);
+ const before = await segmentedPageRow(engine, slug);
+ expect(before.text_projection_revision).toBe(before.knowledge_revision);
+
+ writeFileSync(file, v0.replace('tailmarkerquokka', 'tailmarkerwalrus'));
+ const publication: StatementWork[] = [];
+ await write(measuredWrite(engine, publication));
+
+ const page = await segmentedPageRow(engine, slug);
+ expect(page.text_projection_revision).toBe(page.knowledge_revision);
+ expect(await found(slug, 'tailmarkerwalrus')).toBeGreaterThan(0);
+ expect(await found(slug, 'tailmarkerquokka')).toBe(0);
+ const generation = Number(page.body_generation);
+ const [{ staged }] = await engine.executeRaw<{ staged: number }>(`SELECT
+ (SELECT count(*)::int FROM content_chunks WHERE page_id=$1 AND body_generation=$2) + (SELECT count(*)::int FROM page_body_manifest WHERE page_id=$1 AND gen_from=$2) AS staged`,
+ [page.id, generation]);
+ const [{ pageRows }] = await engine.executeRaw<{ pageRows: number }>('SELECT count(*)::int AS "pageRows" FROM content_chunks WHERE page_id=$1', [page.id]);
+ expect(pageRows).toBeGreaterThan(4 * staged);
+ const work = publication.reduce((n, statement) => n + statement.rows, 0);
+ expect(work, JSON.stringify(publication)).toBeLessThanOrEqual(staged);
+ }), 600_000);
+});
diff --git a/test/persistence-write-interrupted.test.ts b/test/persistence-write-interrupted.test.ts
new file mode 100644
index 0000000000..c87d887e44
--- /dev/null
+++ b/test/persistence-write-interrupted.test.ts
@@ -0,0 +1,162 @@
+/**
+ * Flip lane C (4): a write whose statements the database keeps ending is failed after a bound, not prepared forever.
+ *
+ * 1. Protects: a statement the database ended while it stayed up (57014, a statement timeout or cancel of this write's
+ * own work) is charged to the request's preparation_attempts like a preparation cut off at its deadline; at
+ * persistence.max_preparation_attempts the request ends `failed`/`write_interrupted` (the receipt names the
+ * attempts, the limit and the SQLSTATE) instead of being released as `database_contention` and prepared again. A
+ * single interruption still re-prepares and commits. Contention with other transactions (55P03 lock timeout, 40P01
+ * deadlock) and a dropped connection or restarting database (CONNECTION_CLOSED, 57P01) are never counted, so a
+ * Postgres restart never fails a write.
+ * Both publication arms: a database-only page (released or failed in place) and a worktree-backed page (the
+ * recovery route restores the canonical file before the failure is recorded).
+ * 2. Fails when: the transient branch of finishUnpublishedFailure / publishMutation's recovery route releases every
+ * interruption uncounted (master: a large segmented write cancelled by the publication's 5 s statement_timeout on a
+ * loaded host is prepared again, its whole body streamed again, without limit), or when contention or a connection loss is counted.
+ * 3. Existing coverage: page-purge-journal-timeout-6511.test.ts bounds the purge's own lookups only;
+ * persistence-preparation-deadline tests bound preparation deadlines, never a publication's interruptions.
+ * 4. Semantic injection: installFaultHook on the publication's before_commit seam (inside the publication transaction),
+ * throwing an error carrying the SQLSTATE, for every publication of the claims the test names. Counts claims, never
+ * time. 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, type OperationContext } from '../src/core/operations.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { resetWriteSwitches } from '../src/core/persistence/switches.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 op = (name: string) => operations.find(o => o.name === name)!;
+const interruption = (code: string) => Object.assign(new Error(code === '57014' ? 'canceling statement due to statement timeout' : `database interruption ${code}`), { code });
+const page = (title: string) => `---\ntitle: ${title}\ntype: note\n---\n# ${title}\n\nBody of ${title}.\n`;
+type Row = { state: string; error_code: string | null; error_message: string | null; error_detail: Record<string, unknown> | null; preparation_attempts: number; has_recovery: boolean };
+
+for (const backend of testBackends()) describe(`[${backend}] transient publication failures are bounded`, () => {
+ let engine: BrainEngine;
+ let closePostgres: (() => Promise<void>) | undefined;
+ const home = mkdtempSync(join(tmpdir(), `gbrain-write-interrupted-${backend}-`));
+ let n = 0;
+ const context = (sourceId = 'default'): OperationContext => ({ engine, config: { engine: backend, embedding_disabled: true } as never,
+ logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false, sourceId });
+ const call = (params: Record<string, unknown>, sourceId = 'default') => withEnv({ GBRAIN_HOME: home },
+ () => op('put_page').handler(context(sourceId), { wait_ms: 20_000, ...params })) as Promise<Record<string, any>>;
+ const row = async (requestId: string): Promise<Row> => (await engine.executeRaw<Row>(`SELECT state,error_code,error_message,error_detail,preparation_attempts,
+ recovery IS NOT NULL AS has_recovery FROM persistence_requests WHERE request_id=$1::uuid`, [requestId]))[0]!;
+
+ /**
+ * Every publication of the request's claims numbered in `failing` (1-based, counted at `consumer:preparing`) throws
+ * `error()` at its before_commit seam, inside the publication transaction. Returns the claim count and the request's
+ * preparation_attempts as each claim began (a commit resets the counter, so it is read while the request runs).
+ */
+ function interrupt(requestId: string, failing: (claim: number) => boolean, error: () => Error) {
+ const claims = { n: 0, attempts: [] as number[] };
+ installFaultHook(async (point, detail) => {
+ if (detail.requestId !== requestId) return;
+ if (point === 'consumer:preparing') {
+ claims.n++;
+ claims.attempts.push((await row(requestId)).preparation_attempts);
+ return;
+ }
+ if (point === 'publication:before_commit' && failing(claims.n)) throw error();
+ });
+ 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);
+ await engine.executeRaw("DELETE FROM config WHERE key='persistence.max_preparation_attempts'");
+ resetWriteSwitches();
+ });
+
+ test('a write cancelled at every publication ends write_interrupted after exactly max_preparation_attempts preparations', async () => {
+ const slug = `db/interrupted-${++n}`, requestId = randomUUID();
+ const claims = interrupt(requestId, () => true, () => interruption('57014'));
+ const outcome = await call({ slug, content: page(`Interrupted ${n}`), request_id: requestId }).catch(error => error as { code?: string });
+ installFaultHook(undefined);
+ expect(claims.n).toBe(2);
+ expect((outcome as { code?: string }).code).toBe('write_interrupted');
+ const failed = await row(requestId);
+ expect(failed).toMatchObject({ state: 'failed', error_code: 'write_interrupted', preparation_attempts: 2, has_recovery: false });
+ expect(failed.error_message).toContain('2 time(s)');
+ expect(failed.error_message).toContain('57014');
+ expect(failed.error_detail).toMatchObject({ origin: 'database_interruption', attempts: 2, limit: 2, sqlstate: '57014' });
+ expect(await engine.readPageSnapshot(slug, { sourceId: 'default' })).toBeNull();
+ // The source keeps moving: the next write commits.
+ expect(await call({ slug: `db/after-${n}`, content: page(`After ${n}`), request_id: randomUUID() })).toMatchObject({ state: 'committed' });
+ }, 120_000);
+
+ test('a single interruption re-prepares once, is counted and commits', async () => {
+ const slug = `db/once-${++n}`, requestId = randomUUID();
+ const claims = interrupt(requestId, claim => claim === 1, () => interruption('57014'));
+ expect(await call({ slug, content: page(`Once ${n}`), request_id: requestId })).toMatchObject({ state: 'committed' });
+ expect(claims.n).toBe(2);
+ expect(claims.attempts).toEqual([0, 1]);
+ expect(await row(requestId)).toMatchObject({ state: 'committed' });
+ }, 120_000);
+
+ for (const code of ['CONNECTION_CLOSED', '57P01', '55P03', '40P01']) test(`a dropped connection or contention (${code}) is never counted: past the limit the write still commits`, async () => {
+ const slug = `db/connection-${++n}`, requestId = randomUUID();
+ const claims = interrupt(requestId, claim => claim <= 3, () => interruption(code));
+ expect(await call({ slug, content: page(`Connection ${n}`), request_id: requestId })).toMatchObject({ state: 'committed' });
+ expect(claims.n).toBe(4);
+ expect(claims.attempts).toEqual([0, 0, 0, 0]);
+ expect(await row(requestId)).toMatchObject({ state: 'committed' });
+ }, 120_000);
+
+ describe('worktree-backed page', () => {
+ let brainDir: string;
+ const sourceId = `wt-${randomUUID().slice(0, 8)}`;
+ beforeAll(async () => {
+ brainDir = mkdtempSync(join(home, 'brain-'));
+ await disposePersistenceConsumer(engine);
+ 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(); });
+
+ test('the limit follows max_preparation_attempts, and the recovery route restores the canonical file before the failure', async () => {
+ const slug = `wt/interrupted-${++n}`;
+ expect(await call({ slug, content: page(`Prior ${n}`), request_id: randomUUID() }, sourceId)).toMatchObject({ state: 'committed', write_through: { written: true } });
+ const path = join(brainDir, `${slug}.md`);
+ const bytes = readFileSync(path);
+ const before = await engine.readPageSnapshot(slug, { sourceId });
+ await engine.setConfig('persistence.max_preparation_attempts', '3');
+ resetWriteSwitches();
+ const requestId = randomUUID();
+ const claims = interrupt(requestId, () => true, () => interruption('57014'));
+ const outcome = await call({ slug, content: page(`Next ${n}`), request_id: requestId, expected_revision: before!.revision }, sourceId).catch(error => error as { code?: string });
+ installFaultHook(undefined);
+ expect(claims.n).toBe(3);
+ expect((outcome as { code?: string }).code).toBe('write_interrupted');
+ expect(await row(requestId)).toMatchObject({ state: 'failed', error_code: 'write_interrupted', preparation_attempts: 3, has_recovery: false,
+ error_detail: expect.objectContaining({ attempts: 3, limit: 3, sqlstate: '57014' }) });
+ expect(existsSync(path)).toBe(true);
+ expect(readFileSync(path).equals(bytes)).toBe(true);
+ expect(await engine.readPageSnapshot(slug, { sourceId })).toEqual(before);
+ expect(Number((await engine.executeRaw<{ n: string }>('SELECT count(*)::text AS n FROM persistence_requests WHERE recovery IS NOT NULL'))[0]!.n)).toBe(0);
+ }, 120_000);
+ });
+});