Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): write_interrupted is a held page; interruption charge is atomic; a cancelled shared read charges no member
garrytan1cee2bd3d92d
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 7954e931b0..20a055f052 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -3894,7 +3894,7 @@ Reasons: `override`, `standing_instruction`, `exfiltration`, `credential`, `dete| 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 |+| 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 held sync file needs gbrain sources retry-held <id> and the same sync. 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)diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.mdindex 0fb05f2b78..fa933e41d6 100644--- a/docs/guides/sync-unblock-runbook.md+++ b/docs/guides/sync-unblock-runbook.md@@ -111,6 +111,7 @@ Every hold and error has three fields, from one table| `concurrent_write` | page | reconcile | yes | always: the file and the database page diverge || `file_drift` | page | reconcile | yes | always: the page changed in the database since its file was last imported || `preparation_stalled` | page | retry, upgrade | no | 3 failed attempts over 24 h, or writer status names a step that never finishes |+| `write_interrupted` | page | retry | no | 3 failed attempts over 24 h: gbrain sources writer status --source <source> --json (read-only) names the load on the write owner || `invalid_fence` | page | repair | no | the fence repair preview offers no plan (a manual reason) || `invalid_frontmatter` | page | repair | no | the repair preview needs an interpretation (--include-ambiguous) || `frontmatter_slug_conflict` | page | repair | no | the lane recorded why it could not decide |@@ -140,7 +141,6 @@ Every hold and error has three fields, from one table| `sync_incomplete` | page | retry | no | never: an unfinished cursor resumes with the same command || `connection_lost` | connection | retry | no | three reruns in a row end connection_lost (the database is unreachable from this host) || `database_contention` | connection | retry | no | three reruns in a row stop on it |-| `write_interrupted` | connection | retry | no | a rerun ends write_interrupted on the same entry again: gbrain sources writer status --source <source> --json (read-only) names the load on the write owner || `write_capacity` | connection | retry | no | writer status shows the cap held by requests that never settle || `write_capacity_backpressure` | connection | retry | no | reason lifetime_ids (request ids never free, so only the host raise lifts it), or the pause outlasts a day || `capacity_paused` | connection | retry | no | reason lifetime_ids (only the host raise resumes it), or the same pause after the raise |@@ -217,6 +217,11 @@ it and kept going; the receipt lists the hold (`held`, `held_count`) and- `preparation_stalled`: the write owner, not the file, stalled;`gbrain sources writer status --source <id> --json` names the step.`unblock --apply` schedules the re-screen.+- `write_interrupted`: the database ended the file's statements (SQLSTATE+ 57014, a statement timeout or cancel) at every attempt, so the file is held+ and the rest of the source syncs. Writer status names the load on the write+ owner; reduce it, then `gbrain sources retry-held <id>` (or+ `unblock --apply`) and the same sync.- `invalid_fence` and `frontmatter_slug_conflict`: the content-repair laneclears them. Managed sync drops a `slug:` line naming no page or file(#6865). `unblock --apply` runs it on the held paths now; the maintenancediff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex bbc519c5af..41c6f5517c 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -98,7 +98,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; a run that stops on it is resumable (`gbrain sync status` class `connection`, safe action `retry`, [runbook row](sync-unblock-runbook.md)). 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_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 is held like [`preparation_stalled`](#write_interrupted-hold): the run moves past it and the rest of the source lands, `gbrain sync status` lists the hold (class `page`, safe action `retry`, [runbook row](sync-unblock-runbook.md)), and `gbrain sources retry-held` re-admits it. Only the database ending the write's own statement counts: a group's shared read the database cancels charges no member, and the charge commits with the claim's release, so a crash between them never counts it twice. 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; for a held sync file, run `gbrain sources retry-held <source>` and the same sync with its options. 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. |@@ -207,6 +207,7 @@ with each file and fix the ones that need no guessing."*| <a id="concurrent_write"></a>`concurrent_write` | Managed sync was importing a newer Git version of the file while a database-only write (write-through off, a sandboxed or derived write) committed a different version of the same page, so the two diverge (#6194). The proof is the page's revision itself: it was written by a committed non-sync request for that page. Neither version was overwritten: the page keeps the database version, the file is held and the rest of the source syncs. Since #6340 a page that moved with no such request to name is held the same way (the hold records `page_revision` and `expected_revision` instead of a competing request), and so is a page that changed, was deleted or was re-bound in the database between the manifest freeze and the entry's turn; a page that still holds exactly what the file would import is re-bound to its new revision and passed. | `gbrain sources status <source>` names the page and the competing request. Preview with `gbrain sources reconcile <source> <slug> --preview`, decide with the user which content wins, apply the resolved preview, then `gbrain sources retry-held <source>` and `gbrain sync --source <source> --no-pull` re-screen the file. A new commit of the file re-screens it too. || <a id="file_drift"></a>`file_drift` | Managed sync would have imported a file over a database version of its page that sync never saw (#6712). Every import records its provenance (the bytes left on disk, the page revision it wrote, the parser); a page that moved since that record (a database-only write, write-through off) while its file did not change, or, in a tree walk (first sync, `--full`, an unreachable checkpoint), a page whose file and revision both moved or that has no usable record (an upgraded brain: none, a pre-PR 0 record, a partial one), is imported only when the import changes nothing, a sync request wrote its current revision, or its writer's write-through wrote that revision to the file. Otherwise the file is held, the page keeps the database version and the rest of the source syncs. The hold names `sides` (`database`, `both`, `unknown`) and the database request that wrote the page when there was one. Pages under `storage.keep_db` prefixes are never held: the entry is skipped and the keep_db worker reconciles the page from the database. Holds of this code never escalate; with `sync.holds=fail` the run stops with `file_drift` instead of holding. | `gbrain sources status <source>` names the page. Preview `gbrain repair file-drift --source <source> --slug <slug> --prefer database` (keep the database copy, rewrite the file) or `--prefer file` (import the file), decide with the user, apply it with the plan hash, then `gbrain sync --source <source> --no-pull`. A changed file or page revision re-screens the hold by itself. || <a id="parser_regression"></a>`parser_regression` | With `GBRAIN_SYNC_PARSER_REGRESSION=hold`, a file whose exact bytes imported under an earlier gbrain is now refused. This is a gbrain bug. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version. After a fixed gbrain is installed, `gbrain sources retry-held <source>` and then `gbrain sync --source <source> --no-pull` re-screen it. |+| <a id="write_interrupted-hold"></a>`write_interrupted` | The database ended this file's statements (a statement timeout or cancel) at every attempt, so the sync held the file and kept going. The file is fine: no repair applies, and it is not imported until it is retried. Full reference: [`write_interrupted`](#write_interrupted). | `gbrain sources writer status --source <source> --json` (read-only) names the load on the write owner; reduce it, then `gbrain sources retry-held <source>` and the same sync with its options. || <a id="preparation_stalled-hold"></a>`preparation_stalled` | The write for this file could not finish *preparing* within its attempt limit, so the sync held the file and kept going. The file is fine: no repair applies, and it is not imported until it is retried. Full reference: [`preparation_stalled`](#preparation_stalled). | `gbrain sources writer status --source <source> --json` (read-only), fix what it names, then `gbrain sources retry-held <source>` and the same sync with its options. Runbook: [catch-up stuck / held N files](troubleshooting.md#catch-up-stuck). || <a id="worktree_dirty"></a>`worktree_dirty` | The working tree holds uncommitted bytes for this file that match neither the pinned commit nor the current page (an agent mid-edit on a live checkout), and importing the pinned version would discard them (#6340). Before this release the refusal (`source_changed` / `pinned_git_worktree_conflict`) stopped the whole run; now the file is held, the local edit is untouched and the rest of the source syncs. The hold keeps the pinned blob (`meta.blob_oid`) and a hash of the working bytes, counts `meta.attempts` each time the same file is held again, and a page held three times is reported `needs_human` by `gbrain sync status`. Bytes that are **committed at HEAD** past the pinned target are not a conflict at all: sync imports them as HEAD has them and the later pin..HEAD diff re-imports the same bytes as a no-op. Since 0.60.179.0 (#6513) the same hold covers a pinned import whose canonical correction (a fixable fence, reflowed frontmatter) would rewrite a file that holds newer uncommitted bytes: that refusal used to block the cursor with no exit, because `--retry-failed` replays the same pin against the same bytes, `sources refresh` refuses `sync_in_progress` on the unfinished cursor and `--acknowledge-managed` refuses `cursor_unfinished`. Working-tree bytes that already *are* the correction (gbrain's own writeback, published before the request that carried it settled) are not a conflict either: the page imports and the file is left as it is. | Commit the edit (or restore the file), then `gbrain sync unblock --source <source> --apply` re-screens every held file that is now committed and prints the sync to run (`gbrain sources retry-held <source>` does the same for all holds). A later commit that changes the file re-screens it on its own. Never discard or normalize the local bytes. Runbook: [sync unblock](sync-unblock-runbook.md). || <a id="sync_parser_regression"></a>`sync_parser_regression` | Sync stopped without advancing because it would hold a file whose exact bytes imported before (default `GBRAIN_SYNC_PARSER_REGRESSION=stop`). This is a gbrain bug, not a content problem. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version, then `gbrain sync --source <source> --no-pull`. To keep syncing meanwhile, `gbrain config set sync.parser_regression hold` (ask the user). |diff --git a/llms-full.txt b/llms-full.txtindex 8d20cda9ab..bf8a3dc4d6 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -7497,6 +7497,7 @@ Every hold and error has three fields, from one table| `concurrent_write` | page | reconcile | yes | always: the file and the database page diverge || `file_drift` | page | reconcile | yes | always: the page changed in the database since its file was last imported || `preparation_stalled` | page | retry, upgrade | no | 3 failed attempts over 24 h, or writer status names a step that never finishes |+| `write_interrupted` | page | retry | no | 3 failed attempts over 24 h: gbrain sources writer status --source <source> --json (read-only) names the load on the write owner || `invalid_fence` | page | repair | no | the fence repair preview offers no plan (a manual reason) || `invalid_frontmatter` | page | repair | no | the repair preview needs an interpretation (--include-ambiguous) || `frontmatter_slug_conflict` | page | repair | no | the lane recorded why it could not decide |@@ -7526,7 +7527,6 @@ Every hold and error has three fields, from one table| `sync_incomplete` | page | retry | no | never: an unfinished cursor resumes with the same command || `connection_lost` | connection | retry | no | three reruns in a row end connection_lost (the database is unreachable from this host) || `database_contention` | connection | retry | no | three reruns in a row stop on it |-| `write_interrupted` | connection | retry | no | a rerun ends write_interrupted on the same entry again: gbrain sources writer status --source <source> --json (read-only) names the load on the write owner || `write_capacity` | connection | retry | no | writer status shows the cap held by requests that never settle || `write_capacity_backpressure` | connection | retry | no | reason lifetime_ids (request ids never free, so only the host raise lifts it), or the pause outlasts a day || `capacity_paused` | connection | retry | no | reason lifetime_ids (only the host raise resumes it), or the same pause after the raise |@@ -7603,6 +7603,11 @@ it and kept going; the receipt lists the hold (`held`, `held_count`) and- `preparation_stalled`: the write owner, not the file, stalled;`gbrain sources writer status --source <id> --json` names the step.`unblock --apply` schedules the re-screen.+- `write_interrupted`: the database ended the file's statements (SQLSTATE+ 57014, a statement timeout or cancel) at every attempt, so the file is held+ and the rest of the source syncs. Writer status names the load on the write+ owner; reduce it, then `gbrain sources retry-held <id>` (or+ `unblock --apply`) and the same sync.- `invalid_fence` and `frontmatter_slug_conflict`: the content-repair laneclears them. Managed sync drops a `slug:` line naming no page or file(#6865). `unblock --apply` runs it on the held paths now; the maintenancediff --git a/src/commands/sources-retry-held.ts b/src/commands/sources-retry-held.tsindex 906ab07a49..5dbd5b6c5c 100644--- a/src/commands/sources-retry-held.ts+++ b/src/commands/sources-retry-held.ts@@ -26,7 +26,7 @@ import type { Action } from '../core/agent-output.ts';import { OperationError } from '../core/ops/contract.ts';import { managedBrain, readAllSourceHolds, readHoldRetryKeys, requestHoldRetry, writeHeldRetryPointer } from '../core/connectors/item-holds-store.ts';import { isConnectorSourceKind } from '../core/persistence/connector-identity.ts';-import { fenceAutoRepairFor, holdRepairSteps, readGitHoldRetryPaths, readGitSourceHolds, requestGitHoldRetry, type GitHoldRecord } from '../core/persistence/sync-holds.ts';+import { outOfAttemptsHold, fenceAutoRepairFor, holdRepairSteps, readGitHoldRetryPaths, readGitSourceHolds, requestGitHoldRetry, type GitHoldRecord } from '../core/persistence/sync-holds.ts';import { readManagedSyncBacklog } from '../core/persistence/sync-drain.ts';import type { FenceAutoRepair } from '../core/fence-repair/hold-fix.ts';import { companyBrainProfile } from '../core/company-brain/policy.ts';@@ -71,7 +71,7 @@ export async function gitFollowUpSync(engine: BrainEngine, sourceId: string, helif (!await managedBrain(engine)) return ['gbrain', 'sync', '--source', sourceId];const [backlog] = await readManagedSyncBacklog(engine, [sourceId]).catch(() => []);if (backlog) return ['gbrain', 'sync', ...backlog.resume_args];- const stalled = held.find(record => record.code === 'preparation_stalled' && record.meta.stall?.sync_argv?.length);+ const stalled = held.find(record => outOfAttemptsHold(record.code) && record.meta.stall?.sync_argv?.length);return ['gbrain', 'sync', ...(stalled?.meta.stall?.sync_argv ?? ['--source', sourceId, '--no-pull'])];}@@ -98,7 +98,7 @@ function gitNextStep(sourceId: string, dryRun: boolean, scheduled: Scheduled): {why: `Schedules a re-screen of ${count} held file(s) on the next sync of ${sourceId}; nothing runs now.` } };const fences = scheduled.items.filter(item => item.code === 'invalid_fence').length;const concurrent = scheduled.items.filter(item => item.code === 'concurrent_write').length;- const stalled = scheduled.items.filter(item => item.code === 'preparation_stalled').length;+ const stalled = scheduled.items.filter(item => outOfAttemptsHold(item.code)).length;const dirty = scheduled.items.filter(item => item.code === 'worktree_dirty').length;const drift = scheduled.items.filter(item => item.code === 'file_drift').length;return { text: `${count} held file(s) scheduled for a re-screen; none has run yet. ${automatic} Run it now with: ${sync}, then verify with: gbrain sources status ${sourceId}. `diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 59d4aee5df..7f009f8e74 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -891,7 +891,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }// Large pages switch-on flip (Wave B PR 2 follow-up). `since` is stamped, with SEGMENTED_WRITER_FLOOR, at the merge slot.{ since: 'TBD', text: 'Pages over 1 MiB are now stored in segments: `pages.segmented_storage` is on by default. Reading a window, outline or chunk context of a large page costs the size of the window, not the page, and a rewrite re-indexes only the segments that changed. A page can be up to 256 MiB on Postgres and 128 MiB on PGLite (`pages.max_bytes` lowers it). `put_page`, `put_pages` and `capture` content and `gbrain put` stdin stay limited to 24 MiB per call, so a larger page comes in by `gbrain import` or `gbrain sync` of its file: on a source backed by files only from the file\'s own place in the checkout, which is never rewritten; a database-only source takes it by import. Pages at or under 1 MiB are stored exactly as before. `gbrain config set pages.segmented_storage off` stores new pages inline up to 24 MiB again; pages already stored in segments stay readable. The writer hold now counts any gbrain older than this release, v0.60.290.0 included (its withdrawal mirror leaves a large page\'s file unchanged and its search build can overlap another\'s): while one wrote in the last 7 days, new pages stay inline and doctor `segmented_storage` names the host to upgrade.' },{ since: 'TBD', text: 'With `pages.segmented_storage` on, a withdrawal (`forget`, `forget_fact`, `purge_fact`) now rewrites the canonical file of a page stored in segments on a source backed by files, as it rewrites an inline page\'s: the file loses the withdrawn or purged row, its bytes are those `gbrain export` writes for the page, and the withdrawal\'s Git effect commits it. The file is streamed from the segments into its staging file one segment at a time, and its recovery record names that staging file by path and SHA-256 instead of holding the file; the file\'s prior bytes are read in pieces too. A streamed staging file (this mirror\'s, or `restore_page`\'s for a page over 24 MiB) is written under an in-progress name and renamed once complete, so one a crash cut short is discarded and written again instead of blocking the source\'s worktree with `unexpected_staging_bytes`. Before, the withdrawal-mirror and Git effects passed such a page by (`skipped` reason `page_body_segmented`) and its file kept the withdrawn text. The content gate\'s markers (`embed_skip`, `content_flag`, `quarantine`), which the database stores and the file does not, are now set aside when a page stored in segments is compared with its file, as they are for an inline page; before, any rewrite of a marked page\'s file (a withdrawal, delete, restore or tag change) was skipped or refused as `file_database_drift`.' },- { 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, and a run that stops on it is resumable (`gbrain sync status` shows class `connection`, safe action `retry`, no person needed; a rerun on the same entry ending it again names the read-only `gbrain sources writer status`). `persistence.preparation_deadlines false` turns the counting off with the deadlines.' },+ { 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 holds the file and moves on (`gbrain sync status` lists the hold with class `page`, safe action `retry`, and the read-only `gbrain sources writer status` diagnosis), and `gbrain sources retry-held` re-admits it. A shared read of a group the database cancels charges no member, and the charge commits with the release of the claim, so a crash between them never counts an interruption twice. `persistence.preparation_deadlines false` turns the counting off with the deadlines.' },{ since: 'TBD', text: 'Upgrading builds the index `ingest_log_marked_idx` (migration v257): on Postgres online (`CREATE INDEX CONCURRENTLY`; reads and writes go on while it builds), on PGLite as a plain build that holds writes until it ends. It took 0.4 s for 1M `ingest_log` rows on Postgres and 0.5 s on PGLite. The segmented storage writer hold now judges every recent import, sync or connector run and resident process by its version, including those of a gbrain that already records reading segmented pages (v0.60.290.0), and the index keeps that read to the last 7 days of the log: 600 buffers on a 1M-row log, where a scan reads the whole table.' },];diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 55b2bc6ae2..eb2e5c6db3 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -642,7 +642,7 @@ export const CODES = {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.',+ 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 held sync file needs gbrain sources retry-held <id> and the same sync. 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.",diff --git a/src/core/persistence/bounded-reads.ts b/src/core/persistence/bounded-reads.tsindex e3a5f388e7..cbc0507286 100644--- a/src/core/persistence/bounded-reads.ts+++ b/src/core/persistence/bounded-reads.ts@@ -64,6 +64,21 @@ export function isStatementTimeout(error: unknown): error is { code: string } {return typeof code === 'string' && DEADLINE_SQLSTATES.has(code);}+const SHARED_READ = Symbol('gbrain.shared-read');+/**+ * Flip lane C: the failure of a read several preparations share (group-publish.ts `preparationReads`), handed to every member+ * waiting on it. It ran without any member's bound, so it is no member's own statement: a bounded member never reads it as+ * its deadline, and the coordinator never charges it as the member's interruption. The SQLSTATE stays, so a transient+ * one still releases the member uncounted.+ */+export function sharedReadFailure(error: unknown): unknown {+ if (!(error instanceof Error)) return error;+ return Object.assign(new Error(error.message, { cause: error }), { code: (error as { code?: unknown }).code, [SHARED_READ]: true });+}+export function isSharedReadFailure(error: unknown): boolean {+ return typeof error === 'object' && error !== null && (error as { [SHARED_READ]?: true })[SHARED_READ] === true;+}+/** The engine a preparer reads through: raw statements bounded by the clock's remaining budget, everything else untouched. */export function boundedReads(engine: BrainEngine, clock: ClaimPhaseClock | undefined): BrainEngine {const deadlineAt = clock?.deadlineAt;@@ -83,7 +98,7 @@ export function boundedReads(engine: BrainEngine, clock: ClaimPhaseClock | undef} catch (error) {// A connection the engine discarded after the budget's cancel (a pooler that never completed the round-trip) is the deadline too.const discarded = isConnectionEnd(error) && (clock!.signal?.aborted || Date.now() >= deadlineAt);- if (!isStatementTimeout(error) && !discarded) throw error;+ if (isSharedReadFailure(error) || (!isStatementTimeout(error) && !discarded)) throw error;if (clock!.signal?.aborted) throw clock!.signal.reason;throw new PreparationDeadlineError(clock!.step, (error as { code: string }).code, error);}diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex 70679fa536..7aa664ad26 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -17,6 +17,7 @@ import { chargePreparationAttempt, clearResolvedRecovery, completeWrite, getWritimport type { WaitingOn } from './claim-phase.ts';import { preparationKind } from './preparation-budget.ts';import { readWriteSwitchSnapshot } from './switches.ts';+import { isSharedReadFailure } from './bounded-reads.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';@@ -210,11 +211,13 @@ export function transientDatabaseFailure(error: unknown): boolean {* 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 {+ // A group's shared read (`sharedReadFailure`) is no member's own statement.+ if (isSharedReadFailure(error)) return 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.'+ ? `The file is held and the rest of the source syncs; reduce the load, then gbrain sources retry-held ${row.source_id} and the same gbrain sync with the same options.`: '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. `@@ -222,19 +225,29 @@ function writeInterruptedFailure(row: WriteRequest, sqlstate: string, attempts: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).+ * Flip lane C: the limit an interruption (`writeInterruption`) is charged against, persistence.max_preparation_attempts.+ * Null when the failure is not an interruption, the `preparation_deadlines` switch is off (nothing is counted, as+ * before), or the database cannot be read (the claim is then released uncounted).*/-async function chargedInterruption(engine: BrainEngine, row: WriteRequest, error: unknown): Promise<PublicationFailure | null> {+async function interruptionCharge(engine: BrainEngine, error: unknown): Promise<{ sqlstate: string; limit: number } | null> {const sqlstate = writeInterruption(error);if (!sqlstate) return null;try {const { switches, preparation } = await readWriteSwitchSnapshot(engine);- if (!switches.preparation_deadlines) return null;+ return switches.preparation_deadlines ? { sqlstate, limit: preparation.maxAttempts } : null;+ } catch { return null; }+}+/**+ * Flip lane C: the recovery route's charge, returning the terminal `write_interrupted` failure once the count reaches the+ * limit. It runs in its own statement before `markRecovering`: the request already holds its recovery record, which the+ * expired-owner sweep never takes, so a crash in between leaves the one charge for the owner's recovery to finish.+ */+async function chargedInterruption(engine: BrainEngine, row: WriteRequest, error: unknown): Promise<PublicationFailure | null> {+ const charge = await interruptionCharge(engine, error);+ if (!charge) return null;+ try {const attempts = await chargePreparationAttempt(engine, row);- return attempts >= preparation.maxAttempts ? writeInterruptedFailure(row, sqlstate, attempts, preparation.maxAttempts) : null;+ return attempts >= charge.limit ? writeInterruptedFailure(row, charge.sqlstate, attempts, charge.limit) : null;} catch { return null; }}/**@@ -288,8 +301,21 @@ export async function finishPreparationStalled(engine: BrainEngine, row: WriteReexport 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 charge = await interruptionCharge(engine, error);+ if (charge) {+ // Flip lane C: charged in the transaction that releases or finishes the claim. A crash before it commits leaves the claim+ // uncharged (the expired-owner sweep charges a preparing claim once), after it the charged outcome; never both.+ const done = await engine.transaction(async tx => {+ const attempts = await chargePreparationAttempt(tx, row);+ if (attempts >= charge.limit) return completeWrite(tx, row, 'failed', {}, withAttempt(writeInterruptedFailure(row, charge.sqlstate, attempts, charge.limit), stage));+ await releaseUnpublishedClaim(tx, row, 'database_contention');+ return null;+ }).then(outcome => ({ outcome }), () => null);+ if (done) {+ await faultPoint('persistence:interruption_charged', { requestId: row.request_id, writeId: row.id, sourceId: row.source_id, operation: row.operation });+ return done.outcome ?? (await getWriteRequestById(engine, row.id))!;+ }+ }const failure = withAttempt(requestError(error), stage);if (mayReprepare(row, failure) || transientDatabaseFailure(error)) {await releaseUnpublishedClaim(engine, row, transientDatabaseFailure(error) ? 'database_contention' : 'revision_changed_repreparing');diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.tsindex bb90315c74..7fedf40815 100644--- a/src/core/persistence/fault-points.ts+++ b/src/core/persistence/fault-points.ts@@ -20,6 +20,8 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect// before the recovery transaction renames it.| 'effect_recovery:before_stage' | 'effect_recovery:staged' | 'sync:mid_checkpoint' | 'sync:before_group_admission' | 'sync:mid_waiver_run' | 'sync:prescreened' | 'consumer:prepared'| 'consumer:preparing' | 'lane:applied'+ // Flip lane C: after a statement-cancelled (57014) write's attempt is charged, before its claim is released or finished.+ | 'persistence:interruption_charged'// Before each claim attempt of the consumer, a FIFO claim or a lane head's: a stalling hook keeps this process from starting// another request or lane group meanwhile, while the requests it already holds run on.| 'consumer:claiming'diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.tsindex 2fc9370bb4..9e12aa2637 100644--- a/src/core/persistence/group-publish.ts+++ b/src/core/persistence/group-publish.ts@@ -59,6 +59,7 @@ import { withFilesystemPublication } from './filesystem-guard.ts';import { isWriteTargetContained } from '../path-confine.ts';import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';import { isStreamedContent } from './large-file.ts';+import { sharedReadFailure } from './bounded-reads.ts';import { decoratePublicationOutcome, finishPreparationStalled, finishUnpublishedFailure, pageRecoveryRecord, persistenceFileHash, preparationAbortReason, publicationPostimage, publishMutation,publishPersistenceFile, recoverPublication, type PreparedMutation } from './coordinator.ts';import { pipelined } from '../page-state/transactions.ts';@@ -170,7 +171,8 @@ export function preparationReads(engine: BrainEngine, imports?: ImportGroupReadsconst reads = new Map<string, Promise<unknown>>();const once = <T>(id: string, read: () => Promise<T>): Promise<T> => {let value = reads.get(id) as Promise<T> | undefined;- if (!value) { value = read(); reads.set(id, value); value.catch(() => reads.delete(id)); }+ // Flip lane C: a failed shared read is no member's own statement (`sharedReadFailure`): nobody is charged for it.+ if (!value) { value = read().catch(error => { throw sharedReadFailure(error); }); reads.set(id, value); value.catch(() => reads.delete(id)); }return value;};return new Proxy(engine, { get(target, key) {diff --git a/src/core/persistence/held-reads.ts b/src/core/persistence/held-reads.tsindex d0ea874a2b..e6487109c7 100644--- a/src/core/persistence/held-reads.ts+++ b/src/core/persistence/held-reads.ts@@ -21,7 +21,7 @@import type { BrainEngine } from '../engine.ts';import type { Action, Notice } from '../agent-output.ts';import { ALL_SOURCES } from '../source-id.ts';-import { GIT_HOLD_OP, GIT_HOLD_SUMMARY_OP, contentRepairArgv, fenceAutoRepairFor, gitHoldDocs, gitHoldFix, holdRepairSteps, type GitHoldCode, type GitHoldReason, type GitHoldRecord, type HoldRepairRoute } from './sync-holds.ts';+import { outOfAttemptsHold, GIT_HOLD_OP, GIT_HOLD_SUMMARY_OP, contentRepairArgv, fenceAutoRepairFor, gitHoldDocs, gitHoldFix, holdRepairSteps, type GitHoldCode, type GitHoldReason, type GitHoldRecord, type HoldRepairRoute } from './sync-holds.ts';import { fenceHoldLocation, fenceHoldRelay, type FenceAutoRepair, type FenceHoldLocation } from '../fence-repair/hold-fix.ts';type Exec = Pick<BrainEngine, 'executeRaw'>;@@ -156,7 +156,7 @@ export function hostOperatorFix(sources: ReadonlyArray<{ source_id: string; rout/** The route of one hold record. */export function recordRoute(record: Pick<GitHoldRecord, 'code'>): HoldRepairRoute {return record.code === 'invalid_fence' ? { fences: 1, others: 0 } : record.code === 'concurrent_write' ? { fences: 0, others: 0, concurrent: 1 }- : record.code === 'preparation_stalled' ? { fences: 0, others: 0, stalled: 1 } : record.code === 'worktree_dirty' ? { fences: 0, others: 0, dirty: 1 } : record.code === 'file_drift' ? { fences: 0, others: 0, drift: 1 }+ : outOfAttemptsHold(record.code) ? { fences: 0, others: 0, stalled: 1 } : record.code === 'worktree_dirty' ? { fences: 0, others: 0, dirty: 1 } : record.code === 'file_drift' ? { fences: 0, others: 0, drift: 1 }: record.code === 'frontmatter_slug_conflict' ? { fences: 0, others: 0, slug_conflicts: 1 } : { fences: 0, others: 1 };}@@ -169,7 +169,7 @@ export function recordRoute(record: Pick<GitHoldRecord, 'code'>): HoldRepairRoutexport function fileHeldField(held: HeldPage, remote: boolean): FileHeld {const { record } = held;const fence = record.code === 'invalid_fence';- const stalled = record.code === 'preparation_stalled';+ const stalled = outOfAttemptsHold(record.code);const why = `The canonical file of this page is held (${record.code}${record.meta.reason ? `, ${record.meta.reason}` : ''}): sync cannot import its newer version, so this page shows its last good revision `+ `and is read-only for put_page until ${fence ? 'the file is repaired' : stalled ? 'the brain host operator fixes the write owner and re-screens the file' : 'the brain host operator repairs the file'}.`;const fix = !remote ? gitHoldFix(record, held.fenceAuto)diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.tsindex b0d03893e3..ef879133c5 100644--- a/src/core/persistence/sync-fault-class.ts+++ b/src/core/persistence/sync-fault-class.ts@@ -59,6 +59,11 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [human_reason: 'The database page moved since sync last imported its file, and importing would replace it; a person chooses which version wins (gbrain repair file-drift --source <source> --slug <slug> --prefer database|file previews it and writes nothing until applied).' },{ code: 'preparation_stalled', class: 'page', safe_actions: ['retry', 'upgrade'], needs_human: false,escalate: `${ESCALATE_AFTER}, or writer status names a step that never finishes`, human_reason: 'The write owner cannot finish preparing this file; writer status names the step, fix or report it.' },+ // Flip lane C: the database ended the write's statements (SQLSTATE 57014) persistence.max_preparation_attempts times; like+ // preparation_stalled the write ran out of attempts, so the entry is held and the run goes on.+ { code: 'write_interrupted', class: 'page', safe_actions: ['retry'], needs_human: false,+ escalate: `${ESCALATE_AFTER}: gbrain sources writer status --source <source> --json (read-only) names the load on the write owner`,+ human_reason: 'The database keeps ending this file\'s statements before they finish; writer status names the load on the write owner. Reduce it, then gbrain sources retry-held and the same sync.' },{ code: 'invalid_fence', class: 'page', safe_actions: ['repair'], needs_human: false, escalate: 'the fence repair preview offers no plan (a manual reason)', human_reason: 'Edit the facts or takes table the hold names and commit.' },{ code: 'invalid_frontmatter', class: 'page', safe_actions: ['repair'], needs_human: false, escalate: 'the repair preview needs an interpretation (--include-ambiguous)', human_reason: 'Approve the proposed frontmatter fix or edit the file.' },{ code: 'frontmatter_slug_conflict', class: 'page', safe_actions: ['repair'], needs_human: false, escalate: 'the lane recorded why it could not decide', human_reason: 'The content-repair lane could not clear the hold; its recorded verdict names the page, edit or setting.' },@@ -104,9 +109,6 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [// Connection class: transport only; the cursor and manifest stand.{ code: 'connection_lost', class: 'connection', safe_actions: ['retry'], needs_human: false, escalate: 'three reruns in a row end connection_lost (the database is unreachable from this host)' },{ code: 'database_contention', class: 'connection', safe_actions: ['retry'], needs_human: false, escalate: 'three reruns in a row stop on it' },- // The database ended a write's statements (SQLSTATE 57014) persistence.max_preparation_attempts times; the run re-freezes the entry in place.- { code: 'write_interrupted', class: 'connection', safe_actions: ['retry'], needs_human: false,- escalate: 'a rerun ends write_interrupted on the same entry again: gbrain sources writer status --source <source> --json (read-only) names the load on the write owner' },{ code: 'write_capacity', class: 'connection', safe_actions: ['retry'], needs_human: false, escalate: 'writer status shows the cap held by requests that never settle' },// #6696 (A5): a background sync paused near a cumulative cap; interactive writes keep the rest and the pause lifts as capacity returns.{ code: 'write_capacity_backpressure', class: 'connection', safe_actions: ['retry'], needs_human: false,diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.tsindex d4392aad8c..b694b4aa21 100644--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@ -69,7 +69,14 @@ export const GIT_HOLD_ESCALATE_MIN_SCREENED = 40;type Exec = Pick<BrainEngine, 'executeRaw'>;export type GitHoldCode = ContentRefusal['code'] | 'rename_held' | 'parser_regression' | 'managed_image_sync_unsupported' | 'concurrent_write' | 'preparation_stalled' | 'worktree_dirty' | 'file_drift'- | 'legacy_slug_conflict';+ | 'legacy_slug_conflict' | 'write_interrupted';+/**+ * Flip lane C: the holds of a write that ran out of attempts, its preparation never settling (`preparation_stalled`)+ * or its statements ended by the database every time (`write_interrupted`). The file is not the problem: they route to+ * writer status and a re-screen, never a file repair.+ */+export const OUT_OF_ATTEMPTS_HOLDS: ReadonlySet<string> = new Set(['preparation_stalled', 'write_interrupted']);+export const outOfAttemptsHold = (code: string | null | undefined): boolean => OUT_OF_ATTEMPTS_HOLDS.has(code ?? '');/** #6278: what the owner recorded about a preparation it gave up on (step names and vocabulary only, never content). */export interface PreparationStallMeta {request_id: string;@@ -256,7 +263,7 @@ const staleWeight = (record: Pick<GitHoldRecord, 'page_id'> | null) => record &&const imageWeight = (record: Pick<GitHoldRecord, 'code'> | null) => record?.code === 'managed_image_sync_unsupported' ? 1 : 0;const fenceWeight = (record: Pick<GitHoldRecord, 'code'> | null) => record?.code === 'invalid_fence' ? 1 : 0;const concurrentWeight = (record: Pick<GitHoldRecord, 'code'> | null) => record?.code === 'concurrent_write' ? 1 : 0;-const stalledWeight = (record: Pick<GitHoldRecord, 'code'> | null) => record?.code === 'preparation_stalled' ? 1 : 0;+const stalledWeight = (record: Pick<GitHoldRecord, 'code'> | null) => outOfAttemptsHold(record?.code) ? 1 : 0;const dirtyWeight = (record: Pick<GitHoldRecord, 'code'> | null) => record?.code === 'worktree_dirty' ? 1 : 0;const driftWeight = (record: Pick<GitHoldRecord, 'code'> | null) => record?.code === 'file_drift' ? 1 : 0;const weightsOf = (record: Pick<GitHoldRecord, 'code' | 'page_id'>, sign = 1): SummaryWeights => ({ stale: sign * staleWeight(record), images: sign * imageWeight(record),@@ -500,11 +507,11 @@ export async function holdBasisMoved(engine: Pick<BrainEngine, 'executeRaw'>, soexport function holdRescreenDue(record: Pick<GitHoldRecord, 'code' | 'meta'>, retried: boolean): boolean {return retried || ['frontmatter_slug_conflict', 'file_too_large', 'rename_held', 'parser_regression', 'content_rejected', 'write_gate_rejected', 'purged_content', 'legacy_slug_conflict'].includes(record.code)// #6712: a transient hold (the write owner stalled, not the file) is retried by every sync until it has been held HOLD_ATTEMPTS_NEEDS_HUMAN times.- || (record.code === 'preparation_stalled' && (record.meta.attempts ?? 1) < HOLD_ATTEMPTS_NEEDS_HUMAN)+ || (outOfAttemptsHold(record.code) && (record.meta.attempts ?? 1) < HOLD_ATTEMPTS_NEEDS_HUMAN)|| (record.code === 'managed_image_sync_unsupported' && isMultimodalEnabled())|| record.meta.recovery_version < RECOVERY_VERSION|| (record.code === 'invalid_fence' && (record.meta.fence_version ?? 0) < FENCE_VERSION)- || (record.code === 'preparation_stalled' && record.meta.stall?.gbrain_version !== VERSION);+ || (outOfAttemptsHold(record.code) && record.meta.stall?.gbrain_version !== VERSION);}/**@@ -641,20 +648,24 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'cwhy: `Re-screens ${record.path} after the repair (a changed file or page revision re-screens it by itself).` },verify };}- case 'preparation_stalled': {+ case 'preparation_stalled':+ case 'write_interrupted': {const stall = record.meta.stall;const steps = stalledHoldSteps(source, stall?.sync_argv);const where = stall?.step ? ` at step ${stall.step}${stall.waiting_on && stall.waiting_on !== 'unknown' ? ` (waiting on ${stall.waiting_on})` : ''}` : '';const verify = { argv: ['gbrain', 'sources', 'status', source, '--json'] };- return { argv: steps.status, consent: [], actor: 'agent', requires_exclusive: false, docs: 'docs/guides/write-refusals.md#preparation_stalled',- why: `${record.path} is held because its ${record.meta.deleted ? 'deletion' : 'import'} could not finish preparing${where}: the write owner gave up after `- + `${stall?.attempts ?? 'the allowed'} attempt(s) (request ${stall?.request_id ?? '(unknown)'}) and the rest of the source kept syncing. The file itself is not the problem, so no `- + `frontmatter or fence repair applies. Writer status (read-only) shows the owner process, its gbrain version and any write still stuck; fix what it names or upgrade `+ const interrupted = record.code === 'write_interrupted';+ const kind = record.meta.deleted ? 'deletion' : 'import';+ const cause = interrupted ? `the database ended its ${kind}'s statements before they finished (a statement timeout or cancel) ${stall?.attempts ?? 'the allowed number of'} time(s)`+ : `its ${kind} could not finish preparing${where}: the write owner gave up after ${stall?.attempts ?? 'the allowed'} attempt(s)`;+ return { argv: steps.status, consent: [], actor: 'agent', requires_exclusive: false, docs: gitHoldDocs(record.code),+ why: `${record.path} is held because ${cause} (request ${stall?.request_id ?? '(unknown)'}) and the rest of the source kept syncing. The file itself is not the problem, so no `+ + `frontmatter or fence repair applies. Writer status (read-only) shows the owner process, its gbrain version${interrupted ? ', the load on its pool' : ''} and any write still stuck; fix what it names or upgrade `+ `gbrain, then schedule the re-screen and rerun the same sync.`,then: { argv: steps.retry, consent: [], actor: 'agent', requires_exclusive: false, verify,why: `Schedules ${record.path} for a re-screen on the next sync of ${source}; nothing runs now.`,then: { argv: steps.sync, consent: [], actor: 'agent', requires_exclusive: false, verify,- why: `Re-imports ${record.path} with the run's own options (a different sync command would start another cursor); a preparation that stalls again is held again without blocking the rest.` } },+ why: `Re-imports ${record.path} with the run's own options (a different sync command would start another cursor); a write that runs out of attempts again is held again without blocking the rest.` } },verify };}case 'file_too_large':@@ -716,7 +727,7 @@ export function gitHoldDocs(code: GitHoldCode, reason?: GitHoldReason, meta?: Piif (code === 'invalid_fence') return reason && reason in FENCE_REASONS ? FENCE_REASONS[reason as FenceReason].docs : 'docs/guides/write-refusals.md#invalid_fence';// #6377: a judged slug conflict points at its verdict's anchor.if (code === 'frontmatter_slug_conflict') return contentHoldDocs(meta?.content_repair);- if (code === 'preparation_stalled') return 'docs/guides/write-refusals.md#preparation_stalled';+ if (outOfAttemptsHold(code)) return `docs/guides/write-refusals.md#${code}`;if (code === 'worktree_dirty') return 'docs/guides/write-refusals.md#worktree_dirty';return `docs/guides/write-refusals.md#${reason ? `${code}-${reason}` : code}`;}diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex a8cb0fdc0d..b4119dfa78 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -60,7 +60,7 @@ import { pipelined } from '../page-state/transactions.ts';import { withCoordinatedWrite } from './context.ts';import { principalAttribution } from './attribution.ts';import { recordSyncRunTrend } from '../fence-repair/census-store.ts';-import { addFencesNormalized, addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, heldGitPaths, fencesNormalizedReport, holdsEscalated, readGitHoldRetryPaths, readGitSourceHolds, readSyncHoldPolicy, recordSyncConversion, releaseDiscoveredHolds, recoveredReport, requestGitHoldRetry, writeGitHold, type FencesTally, type GitHoldCode, type SyncHoldPolicy } from './sync-holds.ts';+import { outOfAttemptsHold, addFencesNormalized, addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, heldGitPaths, fencesNormalizedReport, holdsEscalated, readGitHoldRetryPaths, readGitSourceHolds, readSyncHoldPolicy, recordSyncConversion, releaseDiscoveredHolds, recoveredReport, requestGitHoldRetry, writeGitHold, type FencesTally, type GitHoldCode, type SyncHoldPolicy } from './sync-holds.ts';import { withScreeningPaths } from './screening-paths.ts';import { withBoundedReadSession } from './bounded-reads.ts';import { receiptClass, recordedStop, replaysContentRefusal, replaysUnchangedRefusal, resumableStop, stopRecorded } from './sync-stop-class.ts';@@ -564,7 +564,7 @@ const heldWrite = (held: Cursor, hold: HeldEntry, observedAt: string) => (tx: Br/** #6278: the terminal code an owner stamps on a request whose preparation never settled within its attempts (Lane A, consumer.ts). */export const PREPARATION_STALLED = 'preparation_stalled';-const preparationStalled = (row: Pick<WriteRequest, 'state' | 'error_code'>) => row.state === 'failed' && row.error_code === PREPARATION_STALLED;+const preparationStalled = (row: Pick<WriteRequest, 'state' | 'error_code'>) => row.state === 'failed' && outOfAttemptsHold(row.error_code);/** The run's page requests, as `persistence_requests_sync_run_open` indexes them. */const SYNC_PAGE_KINDS_SQL = "intent->>'kind' IN ('managed_sync_import','managed_sync_delete')";/** The `gbrain sync` arguments a hold or receipt prints to resume this cursor with its own options. */@@ -681,7 +681,7 @@ async function convertBlockedCursor(engine: BrainEngine, blocked: Cursor, key: sconst base: Cursor = { ...withoutPending(blocked), convertedFromFailed: converted }; delete base.breaker;const again = await freezeEntry(engine, at(base), key, assertActive, run);const rescreen = ((await readGitSourceHolds(engine, { sourceIds: [blocked.sourceId], runId: blocked.runId }))[0]?.holds ?? [])- .filter(hold => hold.code === PREPARATION_STALLED).map(hold => hold.path);+ .filter(hold => outOfAttemptsHold(hold.code)).map(hold => hold.path);const inTx = async (tx: BrainEngine) => {if (rescreen.length) await requestGitHoldRetry(tx, blocked.sourceId, blocked.incarnation, rescreen);if ('hold' in again) await heldWrite(blocked, again.hold, run.observedAt!)(tx);diff --git a/src/core/persistence/sync-screen.ts b/src/core/persistence/sync-screen.tsindex f7f1159099..7c02b678fa 100644--- a/src/core/persistence/sync-screen.ts+++ b/src/core/persistence/sync-screen.ts@@ -157,18 +157,21 @@ export function preparationStallMeta(receipt: Pick<WriteRequest, 'request_id' |/*** #6278: the hold a `managed_sync_import` or `managed_sync_delete` member earns* when its owner finished it `failed` with `preparation_stalled` (the- * preparation never settled within its attempts). The file is not the+ * preparation never settled within its attempts) or, flip lane C,+ * `write_interrupted` (the database ended its statements every attempt). The file is not the* problem, so the hold carries the receipt's step and wait cause and routes* to writer status, then `sources retry-held` and the same sync. A delete* hold has no content (`upstream_version` null) and is marked `deleted`, so* discovery leaves it alone until a retry or a gbrain change.*/export function preparationStalledHold(entry: Pick<SyncEntry, 'path' | 'sourcePath' | 'working' | 'renameFrom' | 'renameHeld' | 'action'>, slug: string, pageId: number | null,- receipt: Pick<WriteRequest, 'request_id' | 'error_detail'>, content: string | null, blobOid: string | null | undefined, syncArgv: string[]): HeldEntry {+ receipt: Pick<WriteRequest, 'request_id' | 'error_code' | 'error_detail'>, content: string | null, blobOid: string | null | undefined, syncArgv: string[]): HeldEntry {const stall = preparationStallMeta(receipt, syncArgv);const where = stall.step ? ` at step ${stall.step}` : '';- const held = heldEntry(entry, slug, pageId, { code: 'preparation_stalled',- message: `${entry.path}: its ${entry.action === 'delete' ? 'deletion' : 'import'} could not finish preparing${where} (request ${receipt.request_id}), so it is held and the rest of the source synced. `+ const kind = entry.action === 'delete' ? 'deletion' : 'import';+ const interrupted = receipt.error_code === 'write_interrupted';+ const held = heldEntry(entry, slug, pageId, { code: interrupted ? 'write_interrupted' : 'preparation_stalled',+ message: `${entry.path}: ${interrupted ? `the database ended its ${kind}'s statements before they finished every time` : `its ${kind} could not finish preparing${where}`} (request ${receipt.request_id}), so it is held and the rest of the source synced. `+ `Inspect the writer with gbrain sources writer status, then gbrain sources retry-held and the same sync.` }, content, blobOid ? { oid: blobOid } : null);return { ...held, meta: { ...held.meta, stall, ...(entry.action === 'delete' ? { deleted: true as const } : {}) } };}diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.tsindex 424ecbfe24..da0743ae2c 100644--- a/src/core/persistence/sync-status.ts+++ b/src/core/persistence/sync-status.ts@@ -27,7 +27,7 @@ import type { BrainEngine } from '../engine.ts';import type { Action } from '../agent-output.ts';import { managedSyncResumeArgs } from '../sync-reconcile.ts';import { readManagedSyncFailures, type ManagedSyncFailure } from './sync-failures.ts';-import { fenceAutoRepairFor, gitHoldFix, holdEscalation, noteHoldEdit, readGitSourceHolds, recordHoldAttempt, requestGitHoldRetry, type GitHoldRecord } from './sync-holds.ts';+import { outOfAttemptsHold, fenceAutoRepairFor, gitHoldFix, holdEscalation, noteHoldEdit, readGitSourceHolds, recordHoldAttempt, requestGitHoldRetry, type GitHoldRecord } from './sync-holds.ts';import type { FenceAutoRepair } from '../fence-repair/hold-fix.ts';import { classifySyncFault, HOLD_ATTEMPTS_NEEDS_HUMAN, type SyncFaultVerdict } from './sync-fault-class.ts';import { CONTENT_REPAIR_KINDS, contentHoldDisposition, runContentLane, type ContentHoldDisposition } from '../repair/content-lane.ts';@@ -547,7 +547,7 @@ export async function unblockSync(engine: BrainEngine, sourceId: string, opts: Uapplied.push({ path: hold.path, slug: hold.slug, code: hold.code, action: 'retry_when_clean', detail: `committed at HEAD as blob ${committed.oid.slice(0, 12)}; scheduled for a re-screen` });continue;}- if (hold.code === 'preparation_stalled') {+ if (outOfAttemptsHold(hold.code)) {applied.push({ path: hold.path, slug: hold.slug, code: hold.code, action: 'retry', detail: `attempt ${(hold.meta.attempts ?? 1) + 1} of ${HOLD_ATTEMPTS_NEEDS_HUMAN}; scheduled for a re-screen` });continue;}diff --git a/src/core/persistence/terminal-classify.ts b/src/core/persistence/terminal-classify.tsindex 43680f6140..9602dcd357 100644--- a/src/core/persistence/terminal-classify.ts+++ b/src/core/persistence/terminal-classify.ts@@ -296,7 +296,6 @@ function route(input: TerminalInput): Partial_ {why: 'The page changed after the caller read it. Read the current revision and resubmit against it with a new request id.',verify: { argv: failuresArgv(source) } } };}- if (code === 'write_interrupted') return fromTable('transport', code, origin, syncRetry(source, 'The database ended this write\'s statements until its preparation limit; a sync re-freezes the entry under a new request.'));if (FAULT_CODES.has(code)) return fromTable('sync_fault', code, origin, faultAction(code, input), null, input.error_message);const entry = (CODES as Record<string, { class: string } | undefined>)[code];if (!entry) return diagnosis(input, code, origin, `The write ended with code ${code}, which this build does not know.`);diff --git a/test/persistence-write-interrupted.test.ts b/test/persistence-write-interrupted.test.tsindex abb048642a..7ea8e4bcb8 100644--- a/test/persistence-write-interrupted.test.ts+++ b/test/persistence-write-interrupted.test.ts@@ -15,9 +15,13 @@* 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.- * A managed sync member that ends `write_interrupted` is a transient connection-class fault (SYNC_FAULT_TABLE): the- * run re-freezes it in place under a fresh request (STOPS_PER_ENTRY times in a row), then stops resumable with- * `retry` and an escalation naming the read-only `gbrain sources writer status`, never "Unknown code" for a person.+ * A managed sync member that ends `write_interrupted` is a page-class hold, like `preparation_stalled` (SYNC_FAULT_TABLE):+ * the run moves past it and the rest of the source lands; sync status lists the hold with the read-only+ * `gbrain sources writer status` as its fix, and `gbrain sources retry-held` re-admits it.+ * The charge is atomic with the claim's release or failure: a crash right after it (the+ * `persistence:interruption_charged` seam) leaves no claim for the expired-owner sweep to charge again, so the one+ * promised re-preparation survives. A group's shared read (preparationReads) the database cancelled is no member's own+ * statement: no member is charged, and a bounded member never reads it as its own deadline.* 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.@@ -36,8 +40,13 @@ 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 { classifySyncFault } from '../src/core/persistence/sync-fault-class.ts';-import { performManagedSync, STOPS_PER_ENTRY } from '../src/core/persistence/sync-run.ts';-import { readSyncStatus, unblockSync } from '../src/core/persistence/sync-status.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { readSyncStatus } from '../src/core/persistence/sync-status.ts';+import { retryHeld } from '../src/commands/sources-retry-held.ts';+import { boundedReads, PreparationDeadlineError } from '../src/core/persistence/bounded-reads.ts';+import { startClaimPhase } from '../src/core/persistence/claim-phase.ts';+import { preparationAbortReason } from '../src/core/persistence/coordinator.ts';+import { preparationReads } from '../src/core/persistence/group-publish.ts';import { receiptClass, resumableStop } from '../src/core/persistence/sync-stop-class.ts';import { classifyRecordedFault } from '../src/core/persistence/terminal-classify.ts';import type { WriteRequest } from '../src/core/persistence/model.ts';@@ -51,15 +60,34 @@ const interruption = (code: string) => Object.assign(new Error(code === '57014'const page = (title: string) => `---\ntitle: ${title}\ntype: note\n---\n# ${title}\n\nBody of ${title}.\n`;const WRITER_STATUS = 'gbrain sources writer status';-test('write_interrupted is a transient connection fault whose escalation names the read-only writer status', () => {- expect(classifySyncFault({ code: 'write_interrupted' })).toEqual({ class: 'connection', safe_actions: ['retry'], needs_human: false });- expect(classifyRecordedFault({ source_id: 'notes', code: 'write_interrupted', slug: 'a' })).toMatchObject({ category: 'transport', public_category: 'transient',- class: 'connection', safe_actions: ['retry'], needs_human: false, escalate: expect.stringContaining(WRITER_STATUS) });+test('write_interrupted is a page-class hold whose escalation names the read-only writer status', () => {+ expect(classifySyncFault({ code: 'write_interrupted' })).toEqual({ class: 'page', safe_actions: ['retry'], needs_human: false });+ expect(classifyRecordedFault({ source_id: 'notes', code: 'write_interrupted', slug: 'a' })).toMatchObject({ category: 'sync_fault', public_category: 'transient',+ class: 'page', safe_actions: ['retry'], needs_human: false, escalate: expect.stringContaining(WRITER_STATUS) });const receipt = { request_id: randomUUID(), source_id: 'notes', slug: 'a', operation: 'put_page', state: 'failed', error_code: 'write_interrupted',error_message: 'The database ended this write\'s statements 2 time(s).', error_detail: { origin: 'database_interruption', sqlstate: '57014', attempts: 2, limit: 2 },recovery: null, blocked_reason: null, compacted: false, publication_started: false, intent: { kind: 'managed_sync_import' } } as unknown as WriteRequest;- expect(receiptClass(receipt)).toBe('transport');- expect(resumableStop(receipt)).toBe(true);+ expect(receiptClass(receipt)).toBe('page');+ expect(resumableStop(receipt)).toBe(false);+});++const STABLE_READ = 'SELECT local_path FROM sources WHERE id=$1';+/** Two group members' views of one shared read the database cancelled (57014), as preparationReads hands them out. */+async function sharedReadFailures(): Promise<unknown[]> {+ const engine = { kind: 'postgres', executeRaw: async () => { throw interruption('57014'); }, getConfig: async () => null } as unknown as BrainEngine;+ const shared = preparationReads(engine);+ const members = [startClaimPhase(Date.now(), new AbortController().signal, 10_000), startClaimPhase(Date.now(), new AbortController().signal, 10_000)];+ return Promise.all(members.map(clock => boundedReads(shared, clock).executeRaw(STABLE_READ, ['default']).then(() => null, (error: unknown) => error)));+}++test('a shared read the database cancelled is no member\'s own deadline: each member sees a transient database failure', async () => {+ const failures = await sharedReadFailures();+ expect(failures).toHaveLength(2);+ for (const failure of failures) {+ expect(failure).not.toBeInstanceOf(PreparationDeadlineError);+ expect(preparationAbortReason(failure)).toBeNull();+ expect((failure as { code?: string }).code).toBe('57014');+ }});type Row = { state: string; error_code: string | null; error_message: string | null; error_detail: Record<string, unknown> | null; preparation_attempts: number; has_recovery: boolean };@@ -146,7 +174,7 @@ for (const backend of testBackends()) describe(`[${backend}] transient publicatiexpect(await row(requestId)).toMatchObject({ state: 'committed' });}, 120_000);- test('a managed sync entry that ends write_interrupted is re-frozen in place, then stops resumable with a retry', async () => withEnv({ GBRAIN_HOME: home,+ test('a managed sync entry that ends write_interrupted is held: the rest of the source lands, and retry-held re-admits it', async () => withEnv({ GBRAIN_HOME: home,GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SOURCE: undefined, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined }, async () => {const id = `wi-${randomUUID().slice(0, 8)}`, root = join(home, id);const git = (...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });@@ -169,26 +197,69 @@ for (const backend of testBackends()) describe(`[${backend}] transient publicati}if (point === 'publication:before_commit' && pageA.has(detail.requestId)) throw interruption('57014');});- const result = await performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true });- installFaultHook(undefined);- expect(result).toMatchObject({ status: 'blocked_by_failures', failureCodes: [{ code: 'write_interrupted', count: 1 }] });- const requests = await engine.executeRaw<{ state: string; error_code: string | null; preparation_attempts: number }>(- "SELECT state,error_code,preparation_attempts FROM persistence_requests WHERE source_id=$1 AND slug='a' ORDER BY sequence", [id]);- expect(requests).toEqual(Array.from({ length: STOPS_PER_ENTRY + 1 }, () => ({ state: 'failed', error_code: 'write_interrupted', preparation_attempts: 2 })));+ const sync = () => performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true });+ const first = await sync();+ expect(first.status).not.toBe('blocked_by_failures');+ expect(await engine.readPageSnapshot('b', { sourceId: id })).not.toBeNull();expect(await engine.readPageSnapshot('a', { sourceId: id })).toBeNull();- const status = await readSyncStatus(engine, id);- expect(status.last_error).toMatchObject({ code: 'write_interrupted', category: 'transport', public_category: 'transient', class: 'connection',- safe_actions: ['retry'], needs_human: false });- expect(status).toMatchObject({ state: 'resumable', needs_human: false });- expect(status.next?.argv?.slice(0, 2)).toEqual(['gbrain', 'sync']);- expect(status.next?.user_message).toBeUndefined();- expect((await unblockSync(engine, id, { apply: false })).refused).toEqual([]);- // The cause gone, the same sync converges.- expect((await performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true })).status).not.toBe('blocked_by_failures');+ // One request for `a`, never re-frozen in place: its two preparations, then the hold.+ const requests = async () => engine.executeRaw<{ state: string; error_code: string | null; preparation_attempts: number }>(+ "SELECT state,error_code,preparation_attempts FROM persistence_requests WHERE source_id=$1 AND slug='a' ORDER BY sequence", [id]);+ expect(await requests()).toEqual([{ state: 'failed', error_code: 'write_interrupted', preparation_attempts: 2 }]);+ const writerStatus = ['gbrain', 'sources', 'writer', 'status', '--source', id, '--json'];+ const held = await readSyncStatus(engine, id);+ expect(held.last_error).toBeNull();+ expect(held.needs_human).toBe(false);+ expect(held.holds).toEqual([expect.objectContaining({ path: 'a.md', code: 'write_interrupted', class: 'page', needs_human: false,+ fix: expect.objectContaining({ argv: writerStatus }) })]);+ // A second run with the cause still there makes no worse: it ends without blocking and `a` stays held.+ expect((await sync()).status).not.toBe('blocked_by_failures');+ expect((await readSyncStatus(engine, id)).holds).toEqual([expect.objectContaining({ path: 'a.md', code: 'write_interrupted' })]);+ // The cause gone, retry-held re-admits the entry and the same sync imports it.+ installFaultHook(undefined);+ await retryHeld(engine, id);+ expect((await sync()).status).not.toBe('blocked_by_failures');expect(await engine.readPageSnapshot('a', { sourceId: id })).not.toBeNull();- expect(await engine.readPageSnapshot('b', { sourceId: id })).not.toBeNull();+ expect((await readSyncStatus(engine, id)).holds).toEqual([]);}), 300_000);+ test('a crash right after an interruption is charged costs exactly one attempt: the claim it leaves is not charged again', async () => {+ const slug = `db/crash-${++n}`, requestId = randomUUID();+ const claims = { n: 0, attempts: [] as number[] };+ let crashed = false;+ installFaultHook(async (point, detail) => {+ if (detail.requestId !== requestId) return;+ if (point === 'consumer:preparing') {+ claims.n++;+ claims.attempts.push((await row(requestId)).preparation_attempts);+ if (claims.n === 1) throw interruption('57014');+ }+ // The owner dies here: nothing after the seam runs, and the claim it held lapses.+ if (point === 'persistence:interruption_charged' && !crashed) { crashed = true; throw new Error('owner died (probe)'); }+ });+ const pending = call({ slug, content: page(`Crash ${n}`), request_id: requestId }).catch(error => error as { code?: string });+ while (!crashed) await new Promise(resolve => setTimeout(resolve, 20));+ await engine.executeRaw("UPDATE persistence_requests SET claim_expires_at=now()-interval '1 second' WHERE request_id=$1::uuid AND state='running'", [requestId]);+ expect(await pending).toMatchObject({ state: 'committed' });+ expect(claims.n).toBe(2);+ expect(claims.attempts).toEqual([0, 1]);+ }, 120_000);++ test('a group\'s shared read the database cancelled charges no member: the member is released uncounted and commits', async () => {+ const [shared] = await sharedReadFailures();+ const slug = `db/shared-${++n}`, requestId = randomUUID();+ const claims = { n: 0, attempts: [] as number[] };+ installFaultHook(async (point, detail) => {+ if (detail.requestId !== requestId || point !== 'consumer:preparing') return;+ claims.n++;+ claims.attempts.push((await row(requestId)).preparation_attempts);+ if (claims.n <= 3) throw shared;+ });+ expect(await call({ slug, content: page(`Shared ${n}`), request_id: requestId })).toMatchObject({ state: 'committed' });+ expect(claims.n).toBe(4);+ expect(claims.attempts).toEqual([0, 0, 0, 0]);+ }, 120_000);+describe('worktree-backed page', () => {let brainDir: string;const sourceId = `wt-${randomUUID().slice(0, 8)}`;