Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): retry-held re-screens run in the same drain as the backlog; a write-capacity refusal waits instead of killing the pass (#6278 lane B7)

garrytan9e20864e3935
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2cbb7987ec..f9db08301d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -36,7 +36,8 @@ gbrain doctor --only fence_integrity --json # legacy fact rows th
| `gbrain sync` | The file is held as `preparation_stalled` (a held deletion keeps its page), the rest of the source imports and the checkpoint advances. Nothing repairs it: `gbrain sources status`, `retry-held` and doctor `git_held_files` point at writer status, then `retry-held` and the same sync. A stalled hold re-screens by itself when gbrain is upgraded. |
| A run that stalls many files | More than `sync.hold_escalate_count` / `sync.hold_escalate_pct` of the screened imports, or five in a row with no page committed between them, stops the run `blocked` / `preparation_systemic` (exit 1) with the last step, not a pile of holds. The next run re-freezes the stopped file and re-screens the files that run held. |
| `writer status` and doctor `persistence_write_stall` | A running write shows its `step`, how long it has been there, what it waits on (`git`, `fs`, `db`, `pool`, or `unknown` when nothing observed it) and the owner process (kind, pid, gbrain version). Past its budget, `claim.stall` reads `preparation_overdue`. |
-| The sync's progress line | `stalled <N>s on <step>` instead of an ETA that assumes nothing is stuck. `drain_stalled` now fires on a claim that is only being renewed (it never could before), allowing a live preparation its budget plus 30 s. |
+| The sync's progress line | `stalled <N>s on <step>` instead of an ETA that assumes nothing is stuck. `drain_stalled` now fires on a claim that is only being renewed (it never could before), allowing a live preparation its budget plus 30 s. While another writer's requests fill the write cap it prints `waiting for write capacity (N outstanding of M)`, and after 30 s the run stops `blocked` / `write_capacity` with `next` instead of dying with `queue_capacity`. |
+| `gbrain sources retry-held` with a backlog | The printed sync finishes the backlog and re-screens the scheduled files in the same run, so one command clears a `preparation_stalled` hold. |
| A preparation that ignores cancellation | The owner frees the root at `persistence.preparation_ceiling_ms` (600 s), and the request's next claim finishes it `preparation_stalled`. An owner that holds one such stuck preparation stops claiming and logs `restart_required`. A sync whose own process still holds a preparation past its budget plus 30 s exits `resumable` / `preparation_abandoned` (exit 0, safe to rerun), which also ends the stuck work. |
| A preparation read blocked on a table lock | Through a transaction-mode pooler (Supavisor, PgBouncer), gbrain's `statement_timeout` never reached the server, so a read waiting on an exclusive lock on `pages` (an index build, a migration, `VACUUM FULL`) waited forever while the claim kept renewing. Preparation reads now run with a transaction-local `statement_timeout` equal to the remaining budget, so the server ends the wait at the budget and the member is released `preparation_deadline` with nothing left running. Doctor's new `persistence_session_timeouts` check reports a pooler that drops the session timeout. |
| Fact-fence adoption | A legacy fact with surrounding whitespace or CRLF line endings adopts under its own id, and `facts.fact` takes the trimmed, LF text the fence holds. A fact the fence would change further (whitespace-only, `~~x~~`, a literal `<br>`), or one the page already carries, stays as it is, active and searchable, and shows as `FACTS_FENCE_FAILED: <slug> (fence_unrenderable: ...)` and in doctor `fence_integrity`. |
@@ -60,6 +61,8 @@ gbrain doctor --only fence_integrity --json # legacy fact rows th
- Writer status and doctor: blockers carry `operation`, `intent_kind`, `preparation_attempts`, the claim's step, `waiting_on`, `budget_ms`, owner and `claim.stall`; the result carries `preparation_policy`. `preparation_deadline` and `preparation_stalled` have next actions. `preparation_stalled` and `fence_unrenderable` are registered codes (`gbrain errors <code>`), and `docs/guides/write-refusals.md` is one reference for both.
- Sync holds: a `managed_sync_import` or `managed_sync_delete` member finished `preparation_stalled` is held (import by its bytes, delete as a delete hold, rename with its endpoints) in the run and at the next run's start. Both hold paths now write behind a narrowed gate: the failed entry's admitted suffix is cancelled first, then the hold waits only for requests naming that entry's page (slug, page id, path, origin, rename endpoints), where it used to wait for every unfinished request on the source, so a stuck write or a stream of maintenance writes no longer keeps every fence hold pending. The waiver and origin-equivalence preparations that run on the feeder race the same sync budget and fail open.
- Drain: the no-progress detector keys on state, blocked reason and the head claim's phase and step, not on lease columns every renewal bumps; `preparation_abandoned` and `preparation_systemic` join the stop reasons with their `next` commands and docs. `gbrain sources retry-held` and every hold fix print the sync with the run's own options (`managedSyncResumeArgs`).
+- `sources retry-held` against a backlog: the printed sync used to finish the unfinished cursor and report `synced` with the scheduled re-screens untouched (only a fresh discovery reads the schedule), so a `preparation_stalled` hold survived the documented route. A pass that finishes its cursor while re-screens are scheduled now yields (`writer_yield`) and the drain's next pass discovers and takes them, so one run of the printed command clears the hold; the drain report sums the runs it finished. Discovery consumes the schedule in the same transaction as the fresh cursor save (a kill between them can neither lose it nor leave a stale copy) and consumes every scheduled path, including ones already in the manifest or no longer eligible.
+- A sync admission refused for write capacity (`queue_capacity`: other writers' requests, such as a fact-adoption queue on the same `local_cli` principal, hold `persistence.limits.principal_outstanding`) no longer escapes the drain as an uncaught exit with no summary and a failure-ledger row naming `--retry-failed`. The drain retries with backoff, prints `waiting for write capacity (N outstanding of M)`, and past its 30 s no-progress window ends `blocked` / `write_capacity` (new stop reason; `drain.capacity` carries the counts) with `next` pointing at writer status. The refusal's `detail` carries `outstanding=N limit=M`; cumulative caps are unchanged.
- Facts: `planUnfencedFacts` uses the fence codec as its oracle (`adoptableClaim`), writes the parsed text back with the row number on the managed and unmanaged paths, and records rows it leaves alone as typed `UnadoptableFactRecord`s (never the claim text). `prepareFactFenceAdoption` refuses a planning mismatch with the registered `fence_unrenderable`. `submitMaintenance` scans every content-carrying intent with the canonical projection's fence check. `extract_facts` skips only the pages that still hold unadopted rows; doctor `fence_integrity` counts `unrenderable_legacy_facts` with `next: report`.
- Bounded reads: `executeRaw(sql, params, { timeoutMs })` on Postgres pipelines `BEGIN; SET LOCAL statement_timeout; <statement>; COMMIT` as one round trip (`postgres-engine/bounded-statement.ts`); `boundedReads(engine, clock)` (`persistence/bounded-reads.ts`) gives every preparer's unmemoized raw read the remaining budget and the claim's signal, and a `57014`/`55P03` from such a read is the deadline (charged release, `preparation_stalled` at the limit), never `storage_error`. New doctor wave check `persistence_session_timeouts` (`session_timeouts_not_applied`).
- Docs: write-refusals (`preparation_stalled`, `fence_unrenderable`, drain stops), live-sync timing knobs, the troubleshooting runbook "catch-up stuck / held N files" and symptom row, the repair guide's preparation route, `docs/ENGINES.md` log reasons, `AGENTS.md`, and KEY_FILES entries.
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index 4aa0c86e9d..07d0bfb59f 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -28,7 +28,7 @@ Connector ingestion, item holds, checkpoint validation and the single-write fast
- `src/core/persistence/canonical-projections.ts` — installs the facts, takes and timeline projections of a canonical page body inside its publication transaction. Rows written by the conversation fact extractor (`cli:extract-conversation-facts*`) share the page coordinate without a fence and are never expired as rows that left it (#1928 parity with the extract_facts reconcile), so republishing a conversation keeps its extracted facts until their own replay replaces them. Preparation takes the caller's prior snapshot and writer class and pins the stored timeline rows and take row numbers. Writer classes: `editing` (revision-bound `put_page`, reconcile with an approved body decision), `preserving` (`put_page` without a revision, reconcile, connectors), `file` (managed sync of file edits and managed import) and `immutable` (company-brain imports). One pure decision table (`timelineRowAction`) maps each row state (`in_body`, `drifted`, `removed`, `removed_marked`, `database_only`) to `refresh_detail`, `delete`, `keep` or `materialize`: database-only rows are materialized by `editing` and `preserving` writers and kept by the others; #6226 rows the older citation reading filed for either body are `superseded` (deleted by every writer) or, carrying their own detail, `superseded_annotated` (kept, never materialized); a materialized bullet the new body drops is deleted by `editing`/`file`, rendered again by `preserving` and kept DB-side by `immutable`. `materializeTimeline` runs during preparation, before the body is imported, digested and rendered, and appends each round-trippable row after existing bullets in date-then-id order as a marked bullet (`timeline-marker.ts`); `renderMaterializedBullet` requires render-then-extract to return exactly the tuple and normalized detail, so backlink receipts, empty or delimiter-bearing sources are kept and never rendered. `pendingTimelineRows` counts materializable and kept rows for the repair and doctor. Deletes and detail refreshes match the pinned id, tuple and detail, so rows changed after preparation are untouched. Fence refusals are typed `invalid_fence` (`fence-repair/refusal.ts`): `compileCanonicalProjections`, the validation-only entry, refuses the first defect `scanCanonicalFences` finds (repeated marker, any strict-parser warning, a row number used twice on the page) with wire `invalid_params`; a new fence row whose number belongs to a database-only take refuses as `stored_row_collision` with wire `take_row_collision`. When the prior takes fence does not parse, the page's stored `takes.row_num` count as prior canonical rows (TE1), so a row Tier 1 normalized updates its take instead of colliding. `unrecordedCanonicalTimeline` returns the body's canonical tuples with no stored row under the normalized key (managed `extract --stale` inserts only these), and `materializedHistoryRanges` locates marker lines whose hash matches the bullet after it, plus that bullet's indented detail (the dream verifier's history exemption). Tests: `test/canonical-projection-history.test.ts`, `test/timeline-materialize.test.ts` (PGLite and Postgres). A write that would drop rows held by a fence quoted in markdown code (readers project nothing from it) is refused as `invalid_fence` / `quoted_fence_rows` instead of deleting them. Pinned by `test/fence-marker-projection.test.ts`. #5969 (D3): an ordinary `put_page` / `put_pages` intent carries a `TimelineWritePolicy` (`timeline-omission.ts`) that changes only the rows the writer saw (`removed`, `removed_marked`): an explicitly empty section deletes them for every writer class; an omitted section keeps them for a local preserving writer (`materialize`) and deletes them with `drop_timeline`; maintenance, reconcile and file writers pass no policy. The pinned timeline `DELETE` returns what it removed, and the projection closure returns `{ timelineRowsRemoved: { count, earliest, latest } }` counting only `removed`/`removed_marked` rows it actually deleted (a row changed after preparation is neither deleted nor counted); `timelineRowsToRemove` judges the same set ahead of publication. #6259: a quarantined page (gate `quarantine` marker) projects no facts or takes (timeline rows still project); rows projected before it was quarantined stay as they are.
- `src/core/persistence/timeline-omission.ts` — #5969 (D3): `timelineSectionOf` reads a put_page body's Timeline section from the caller's raw content before normalization (`omitted`: no timeline sentinel and no `## Timeline`/`## History` heading outside code; `emptied`: a section with no entries; `present`). Admission (`page-mutations.ts`) records it on the intent as `timeline_section` (a caller-sent value is stripped; failed-writes replay passes the stored one through `submitPageMutation`'s `timelineSection`). `assertTimelineNotOmitted` refuses a remote omission that would delete rows with `timeline_rows_would_be_removed` (fix: `get_page include_content:true`, then the `drop_timeline: true` retry) before admission and again during preparation; `timelineWritePolicy` builds the projection policy. Successful deletes surface as the receipt's `timeline_rows_removed` advisory (`page-advisories.ts`, dates only), copied onto `put_pages` entries (`page-batch.ts`, which accepts `drop_timeline` per entry).
-- `src/core/persistence/admission-retry.ts` — bounded retries for database-confirmed admission transaction aborts. Each retry reuses the UUID and normalized intent, rechecks guarded authority and reserves quota only on commitment. Standalone journal admission uses 100ms lock waits within the five-second retry budget to retain queue position behind short counter transactions; backoff occurs after rollback releases the connection so counter contention leaves pool capacity for reads. Ambiguous connection/commit errors are never classified as confirmed rollback. Real counter-lock, sustained-queue progress, read-capacity and after-insert rollback tests live in `test/persistence-journal.test.ts`. Withdrawal retries wrap its whole source-exclusive transaction with its existing lock policy; `admitWriteInTransaction` never backs off inside an existing unit of work. `test/persistence-withdrawal-retry.test.ts` verifies guard release, complete rollback and bounded contention.
+- `src/core/persistence/admission-retry.ts` — bounded retries for database-confirmed admission transaction aborts. Each retry reuses the UUID and normalized intent, rechecks guarded authority and reserves quota only on commitment. Standalone journal admission uses 100ms lock waits within the five-second retry budget to retain queue position behind short counter transactions; backoff occurs after rollback releases the connection so counter contention leaves pool capacity for reads. Ambiguous connection/commit errors are never classified as confirmed rollback. Real counter-lock, sustained-queue progress, read-capacity and after-insert rollback tests live in `test/persistence-journal.test.ts`. Withdrawal retries wrap its whole source-exclusive transaction with its existing lock policy; `admitWriteInTransaction` never backs off inside an existing unit of work. `test/persistence-withdrawal-retry.test.ts` verifies guard release, complete rollback and bounded contention. #6278 (B7): also the outstanding-request cap's `detail` format (`outstandingCapacityDetail`, `outstanding=N limit=M`, stamped by `journal.ts` `capacityError`) and its readers `isWriteCapacityWait` / `outstandingCapacityOf`, which the managed drain and `sync-run.ts`'s failure ledger use to tell a refusal that clears by itself from a cumulative cap.
- `src/core/persistence/health.ts` — pure advisory age/reason/action policy shared by receipts and trusted diagnostics. The nested public contract is optional, validated and explicitly allowlisted; thresholds are 30/120 seconds and polls 1/5/30 seconds. The journal batches at most 100 authorized receipts into one projected root query with a 500ms caller budget, retaining one in-flight query per engine until settlement. Database-only pending lookups use a partial source-incarnation/sequence index shared by both engines. Synchronous service reads coalesce only for the same request ID, retain at most four unresolved reads per engine until settlement, and permit cancellation only by the read's initiating waiter or shutdown. No health observation changes authority or durable state. Real authenticated legacy/OAuth recovery and the synthetic three-client import live in `test/e2e/persistence-http-liveness.test.ts`.
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index 5542337186..8e9b33f8ef 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -14,11 +14,11 @@
- `src/core/persistence/{maintenance,root-registry,filesystem-guard,writer-guard-schema}.ts` — fail-closed legacy writer coverage: durable private refusal records and shared refusal-only root markers work before PGLite connect, resolve symlink ancestors, and retain stale roots conservatively. An unchanged per-tick refresh writes nothing: the registry directory and records are chmodded only when their mode differs and the directory is fsynced only when a record changed (`root-registry-idle-chmod-5297.test.ts`). The selected PGLite path is registered at connect/init and source claim refresh, so managed reinit refuses even offline; unmanaged backup acquires the stable sibling native lock through rename. SQL guards include free-text aliases and canonical source sync checkpoints; an update that changes only embedding, telemetry or write-attribution columns of facts/takes is a physical projection and passes without the coordinator. `docs/architecture/canonical-writers.tsv` is the finite writer census; `canonical-writer-inventory.test.ts` rejects unreviewed additions, and `persistence-writer-fences.test.ts`/`pglite-maintenance-fence.test.ts` exercise real engines, competing processes and separate homes.
-- **`src/core/persistence/sync-discovery.ts`** + **`sync-origin.ts`** — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision snapshots. Reserved skillpack paths (`skills/` at any depth and `skillpack.json`, `src/core/skill-reserved-paths.ts`) never enter discovery: the shared skill publisher owns them and `managedImportContent` refuses them, so a seeded pack cannot block a sync. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Under `source-root` mode a stored `<scope>/<path>` origin (the Git-root form older write-through minted from the slug, recognized because `<path>` names the page slug) is accepted as `<path>` at discovery, freeze, preparation and the page-origin query, and an import rewrites it in place; when both readings name existing files the stored origin refuses with `detail: ambiguous_source_path`. A genuine origin mismatch refuses with `detail: sync_origin_mismatch` and the filled paths. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Deleting a file that no page records as its origin (for example a skipped slug twin) while its slug's page keeps another origin commits an explicit no-op receipt (`unownedDeletion`, outcome reason `unowned_deleted_path`) that preserves that live page or tombstone; freeze and publication re-prove that no page owns the path and that the file is still absent. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten. Active Git holds of the source are re-screened when their blob or working bytes changed, the file left, a `sources retry-held` request names them, the hold predates the current `RECOVERY_VERSION`, or the code is `frontmatter_slug_conflict`, `file_too_large`, `rename_held` or `parser_regression`; holds of now-excluded paths are released at the checkpoint. A held rename destination (or a held path renamed again) carries the hold's `renameFrom` when the old page is unchanged, else `renameHeld` (held as `rename_held` / `rename_source_changed`), and a full walk never deletes an origin a hold's `rename_from` names. Imports whose origin has no page claim their slug together: a live page whose own file is still in the tree keeps the slug, otherwise the file named like the slug (else the first path) wins, and the losers leave the manifest and are reported as `slugCollisions` (the library path's `slug_collision` skip) instead of failing the run. A winner whose slug is held by a page with a vanished or deleted origin takes that page over (`renameFrom`, same slug). A Git-detected rename to an unoccupied slug becomes one import carrying `renameFrom` in place of a delete plus a create. Origins for one slug that differ only by case or separator spelling refuse, except a case-only respelling whose old file the same sync removes. Code files keep exact per-origin identity. On Windows a path containing `:` is reported in `SyncDiscovery.fileRefusals` (code `colon_slug_windows_write_through`, with its filled `gbrain sync --source <id> --no-pull` hint) and kept out of the run and its origin checks, so one such file no longer fails the whole sync (#5032).
-- **`src/core/persistence/sync-drain.ts`** — #5984: drains a managed sync in one invocation. `runDrain` re-enters the single-pass `performManagedSync` (which keeps returning `partial / writer_pending | writer_yield`) until the cursor is done, the caller's signal stops it, a strict registered run deadline is about 15 s away (`forward-progress.ts` `registerRunDeadline`, set by `cli.ts` when it arms the sync watchdog), a writer head needs intervention (`recovery_required`, `owner_unavailable`, unexpected bytes), or the no-progress detector sees the awaited request and its worktree head unchanged for 30 s and 3 passes with nothing claimable here. It retries only `worktree_refreshing` (its `retry_after_ms`), `database_contention`, connection errors and statement timeouts (3 attempts). Every page commit notes forward progress, so the progress-aware watchdog never stops a progressing drain. The result carries `drain: { outcome: synced | resumable | blocked, stop_reason, written, waived, remaining, rate_pages_per_min, eta_seconds, stall }`; `drainNext` builds `next` for the CLI from the shared `syncResumeCommand` (`sync-reconcile.ts`). The CLI (`sync/run.ts` single source, `--all`, `--watch`) sets `SyncOpts.drain`; the PGLite owner delegate uses `runDrain` over IPC; jobs, serve, the cycle, `sync-administration.ts` and `worktree-refresh.ts` keep their own loops. `readManagedSyncBacklog` reads unfinished cursors' `progress` window (stamped by `sync-run.ts` on each advance, reset per drain) for `gbrain doctor` (`managed_sync_backlog`) and `sources status`, with `resume_args` built by `sync-reconcile.ts` `managedSyncResumeArgs`. #6278: the no-progress fingerprint keys on state, blocked reason, head id/state and the head claim's phase/step/since (`drainClaimOf`), never on lease columns, so a renewed-forever claim reads as no progress; a live preparation is allowed its budget plus `STALL_GRACE_MS` (budgets read from `persistence.*_preparation_ms` / `preparation_ceiling_ms`), a lapsed claim keeps the plain window (`stall.cause: owner_missing`), a preparation this process's pid owns past its allowance ends `resumable` / `preparation_abandoned`, and `SyncResult.breaker` ends `blocked` / `preparation_systemic`; `stall` carries `phase`, `step`, `waiting_on`, `cause`, and a timer prints `stalled <N>s on <step>` while nothing commits: between passes from the fingerprint's claim, inside a pass (a grouped publish parked in preparation never returns to the loop) from `StallProbe.head`, a 2 s-bounded read of the source's oldest running (else queued) request that prints nothing when no write is unfinished (B6). Tests: `test/sync-drain.test.ts`, `test/sync-drain-claims.test.ts`, `test/managed-sync-drain.test.ts`.
+- **`src/core/persistence/sync-discovery.ts`** + **`sync-origin.ts`** — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision snapshots. Reserved skillpack paths (`skills/` at any depth and `skillpack.json`, `src/core/skill-reserved-paths.ts`) never enter discovery: the shared skill publisher owns them and `managedImportContent` refuses them, so a seeded pack cannot block a sync. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Under `source-root` mode a stored `<scope>/<path>` origin (the Git-root form older write-through minted from the slug, recognized because `<path>` names the page slug) is accepted as `<path>` at discovery, freeze, preparation and the page-origin query, and an import rewrites it in place; when both readings name existing files the stored origin refuses with `detail: ambiguous_source_path`. A genuine origin mismatch refuses with `detail: sync_origin_mismatch` and the filled paths. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Deleting a file that no page records as its origin (for example a skipped slug twin) while its slug's page keeps another origin commits an explicit no-op receipt (`unownedDeletion`, outcome reason `unowned_deleted_path`) that preserves that live page or tombstone; freeze and publication re-prove that no page owns the path and that the file is still absent. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten. Active Git holds of the source are re-screened when their blob or working bytes changed, the file left, a `sources retry-held` request names them, the hold predates the current `RECOVERY_VERSION`, or the code is `frontmatter_slug_conflict`, `file_too_large`, `rename_held` or `parser_regression`; holds of now-excluded paths are released at the checkpoint. #6278 (B7): `retryTaken` lists every scheduled path the discovery read (screened as an entry, as a candidate, or no longer eligible); `sync-run.ts` clears them in the transaction that saves the fresh cursor. A held rename destination (or a held path renamed again) carries the hold's `renameFrom` when the old page is unchanged, else `renameHeld` (held as `rename_held` / `rename_source_changed`), and a full walk never deletes an origin a hold's `rename_from` names. Imports whose origin has no page claim their slug together: a live page whose own file is still in the tree keeps the slug, otherwise the file named like the slug (else the first path) wins, and the losers leave the manifest and are reported as `slugCollisions` (the library path's `slug_collision` skip) instead of failing the run. A winner whose slug is held by a page with a vanished or deleted origin takes that page over (`renameFrom`, same slug). A Git-detected rename to an unoccupied slug becomes one import carrying `renameFrom` in place of a delete plus a create. Origins for one slug that differ only by case or separator spelling refuse, except a case-only respelling whose old file the same sync removes. Code files keep exact per-origin identity. On Windows a path containing `:` is reported in `SyncDiscovery.fileRefusals` (code `colon_slug_windows_write_through`, with its filled `gbrain sync --source <id> --no-pull` hint) and kept out of the run and its origin checks, so one such file no longer fails the whole sync (#5032).
+- **`src/core/persistence/sync-drain.ts`** — #5984: drains a managed sync in one invocation. `runDrain` re-enters the single-pass `performManagedSync` (which keeps returning `partial / writer_pending | writer_yield`) until the cursor is done, the caller's signal stops it, a strict registered run deadline is about 15 s away (`forward-progress.ts` `registerRunDeadline`, set by `cli.ts` when it arms the sync watchdog), a writer head needs intervention (`recovery_required`, `owner_unavailable`, unexpected bytes), or the no-progress detector sees the awaited request and its worktree head unchanged for 30 s and 3 passes with nothing claimable here. It retries only `worktree_refreshing` (its `retry_after_ms`), `database_contention`, connection errors and statement timeouts (3 attempts). Every page commit notes forward progress, so the progress-aware watchdog never stops a progressing drain. The result carries `drain: { outcome: synced | resumable | blocked, stop_reason, written, waived, remaining, rate_pages_per_min, eta_seconds, stall }`; `drainNext` builds `next` for the CLI from the shared `syncResumeCommand` (`sync-reconcile.ts`). The CLI (`sync/run.ts` single source, `--all`, `--watch`) sets `SyncOpts.drain`; the PGLite owner delegate uses `runDrain` over IPC; jobs, serve, the cycle, `sync-administration.ts` and `worktree-refresh.ts` keep their own loops. `readManagedSyncBacklog` reads unfinished cursors' `progress` window (stamped by `sync-run.ts` on each advance, reset per drain) for `gbrain doctor` (`managed_sync_backlog`) and `sources status`, with `resume_args` built by `sync-reconcile.ts` `managedSyncResumeArgs`. #6278: the no-progress fingerprint keys on state, blocked reason, head id/state and the head claim's phase/step/since (`drainClaimOf`), never on lease columns, so a renewed-forever claim reads as no progress; a live preparation is allowed its budget plus `STALL_GRACE_MS` (budgets read from `persistence.*_preparation_ms` / `preparation_ceiling_ms`), a lapsed claim keeps the plain window (`stall.cause: owner_missing`), a preparation this process's pid owns past its allowance ends `resumable` / `preparation_abandoned`, and `SyncResult.breaker` ends `blocked` / `preparation_systemic`; `stall` carries `phase`, `step`, `waiting_on`, `cause`, and a timer prints `stalled <N>s on <step>` while nothing commits: between passes from the fingerprint's claim, inside a pass (a grouped publish parked in preparation never returns to the loop) from `StallProbe.head`, a 2 s-bounded read of the source's oldest running (else queued) request that prints nothing when no write is unfinished (B6). B7: a pass refused for write capacity (`isWriteCapacityWait`, `admission-retry.ts`: a `queue_capacity` whose `detail` is `outstanding=N limit=M`) is retried with backoff up to 5 s apart while the drain prints `waiting for write capacity (N outstanding of M)`; past the no-progress window it ends `blocked` / `write_capacity` with `drain.capacity` and writer status as `next`, keeping the last pass's result (or an empty one) for the report; a cumulative cap still throws. A pass that finishes one cursor and yields for a scheduled re-screen starts a new run on the next pass, and the report sums the page counts of every run it finished. Tests: `test/sync-drain.test.ts`, `test/sync-drain-claims.test.ts`, `test/managed-sync-drain.test.ts`, `test/sync-drain-write-capacity.test.ts`.
- **`src/core/persistence/sync-window.ts`** — #5984 admit-ahead for draining managed Postgres syncs. While the cursor's `group` publishes, `admitAhead` (`sync-run.ts`) freezes and admits the next group and records it in the cursor's `window` (at most one group), so the consumer claims it as soon as the publishing group commits under the unchanged per-worktree FIFO claim. Window members name the previous group's last request in `intent.after`. `cancelOrphanedWindowGroup` runs before the consumer prepares a claimed group: a window group whose predecessor did not commit is cancelled (`WINDOW_CANCEL_MESSAGE`), never published after a failed page. Publication validation (`sync-prepare.ts`) re-checks the predecessor once per transaction and reads the cursor `FOR KEY SHARE`, accepting `pending`, `group` and `window` members, so the drain's cursor saves never wait for the publishing group. After a failed page the drain cancels the window's queued members (`cancelWindow`) and drops the window; resume re-freezes those entries. Nothing is admitted ahead while foreground writes are recent (one was queued on the worktree in the last minute, `FOREGROUND_RECENT_MS`) or when the next entry is not groupable. Older binaries refuse a window member they did not admit (cursor membership), so a mixed-version drain fails closed instead of publishing twice; finish a drain before downgrading. A claimed head is ordered by `claimedPredecessorState`: a group member follows the member before it in its own group (its `after` names only the previous group), anything else follows `after`. `claimedHeadOrder` (the consumer, before claiming followers) cancels a head whose predecessor ended without committing, and under lanes a member whose predecessor is unfinished releases its claim and waits; `cancelOrphanedLaneRows` uses the same rule, so a member released mid-group (its group fell back to the single path and an earlier member went back to the queue) never publishes after that member fails. Test: `test/sync-group-member-order.test.ts`.
- **`src/core/persistence/sync-lanes.ts`** + **`worktree-lease.ts`** — #5984 lanes. The drain opens a lane policy for its worktree (`openLanes`, keyed by a per-drain run id that lane groups carry as `intent.lane`; `closeLaneRun` at drain end stops new lane claims and waits up to 90 s for the lane tasks still running, counted from the head's claim by `laneTask`; the drain then cancels its run's still-queued rows whose predecessor ended without committing, `cancelOrphanedLaneRows` in sync-window.ts, so a blocked drain never reports while one of its groups is still publishing, aborting or released). While it is open, this process's consumer claims the next admitted lane group head out of FIFO order (`claimNextLaneHead` in journal.ts: every earlier request claimed, any unfinished one a running request of the same run) up to the effective lane count (`laneRoots`), and runs it as a lane (`executeClaimedGroup` with `lane`). Lane publications share the worktree's native lock in this process (`acquireWorktreeShared` / `worktree-lease.ts`; one lane acquires the lock while lanes arriving meanwhile wait and join, and a lease stays registered until its lock is released); every exclusive `acquireWorktree` first yields the lease (marks it draining and wounded, waits up to its budget), and a lease drains for new claims after `LEASE_TURN_MS` of continuous holding. Lane transactions begin in manifest order (`awaitLaneBegin`) and commit in manifest order (`awaitLaneTurn`, inside the transaction before the counters: the predecessor `intent.after` must be committed; a failed one cancels the group, a requeued or unadmitted one releases it, a wounded lease or 60 s rolls it back). Publication validation accepts a lane group whose predecessor is still queued or running (`windowPredecessorAllows`). `laneFallback` in group-publish.ts cancels, releases or falls back to the single path, and a lock or statement timeout steps the lane count down (`stepDownLanes`). Lane settings (`--lanes`/`--no-lanes` > `GBRAIN_SYNC_LANES` > `sync.lanes` > 6, clamped to the pool's long-hold capacity minus 3) resolve in `resolveBulkSettings` (sync-group.ts); with lanes the drain keeps twice the lane count of groups admitted ahead (`admitAhead`).
-- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. A completed discovery that finds nothing to do (`up_to_date`) stamps only `sources.last_sync_at`, inside `withCoordinatedWrite` and guarded by source id and incarnation, so a quiet managed source stays fresh in doctor and a run that outlived a re-added source stamps nothing; dry runs and partial runs do not stamp. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`. A resume adopts the stored options for every option the caller did not set explicitly (`SyncOpts.explicitProcessing`: CLI flags, wire flags, job params; autopilot and the cycle set none); an explicit conflict refuses with `detail: cursor_processing_options_conflict`, the stored options and the exact resume command. Callers that omit `explicitProcessing` stay strict. Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts, also when the run has a recorded failure and its pending write already committed before the cursor advanced; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol. `freezeEntry` checks a rename's source page (id, revision, origin) as well as its target slug, and a committed rename counts in `renamed`. #5522: a new-file entry (`pageId: null`) whose origin another cursor of the source has since imported is re-frozen against that page when it is live, holds exactly that origin at the entry's slug in the cursor's incarnation, and the sync preparer finds its content unchanged; otherwise the origin refusal stands, and the manifest is never rewritten. #5751: the working-tree screen passes the kernel waivers for working-tree entries and counts them into `legacySkips` (printed by `sync-diagnostics.ts` with `gbrain repair contextual-mode`). A terminal `checkpoint_validation_timeout` receipt gets its hint from `checkpoint-validation.ts`. Content holds (#5988, `sync-screen.ts`): `freezeEntry` screens each import (company-profile cursors and `sync.holds=fail` excepted); a refused file becomes a hold written in the same transaction as the cursor step (`saveCursor`'s `inTx`), with no request admitted, and an over-bound pinned blob is held by size before it is read. A cursor whose pending request failed with a content refusal (`isContentRefusal`, old message shapes included) converts in place with its stored options: held, or re-frozen once per distinct bytes (`converted`), so a refusal the screen misses stays blocked without minting receipts. #6188: a failed fence refusal (`fenceReceiptLocation`: the durable `error_detail.fence`, the message, or an older release's message) holds the same bytes even when the screen admits them (`prepareTimeFenceHold`, reason `prepare_time`); a compacted `invalid_params` / `take_row_collision` receipt converts only when the re-screen holds. A page request of the run that fails with a fence refusal is held in the same invocation at the terminal-failure branch (single path and a bulk group's failed member) after the source's other requests settle within the run's wait budget, else the run returns `partial`; it is converted once, gets no failure-ledger row and is logged as a conversion. `sync.holds=fail` and company-profile cursors keep blocking with the typed refusal. #6278: a `preparation_stalled` receipt (the owner gave up preparing a member) is converted the same way by both converters: an import holds by its bytes, a delete as a delete hold (`meta.deleted`, `upstream_version` null), the checkpoint never holds; `preparationStalledHold` (sync-screen.ts) records the receipt's step and the resume arguments. Both converters write their hold through `holdUnderGate`, the narrowed gate: the failed entry's admitted suffix (window, later group members, this run's queued lane rows) is cancelled first, then the hold waits only for active suffix descendants and unfinished requests naming the entry's page (`UNFINISHED_PAGE_REQUEST_SQL`, now matching path and origin too), evaluated inside the transaction that writes the hold under the page-key → cursor lock order; its doc comment states the invariant the old source-wide wait protected. The cursor's `breaker` counts the run's stalled receipts (identities and streak, saved with each CAS): `holdsEscalated`'s rule over the run's screened imports or `BREAKER_STREAK` (5) in a row trips it, the run stops `blocked_by_failures` with `SyncResult.breaker` (drain `preparation_systemic`), and the next run's `convertBlockedCursor` re-freezes the entry and schedules the run's stalled holds for a re-screen instead of holding; a committed page resets the streak. `sameContentAtOrigin` and the waiver screens race the sync preparer against `persistence.sync_preparation_ms` (`raceSyncBudget`, sync-waivers.ts) and fail open. Tests: `test/managed-sync-preparation-stalled-holds.test.ts`, `test/sync-waiver-budget.test.ts`. Results carry this run's holds, the outstanding total, escalation, `converted_from_failed` and `recovered_frontmatter` (`buildHoldReport`); dry runs list `would_hold` / `screen_skipped`. After the checkpoint commits (and unless `noExtract`), the owner derives links for the source's stale pages through `links-maintenance.ts`, so a PGLite-delegated sync and a Postgres sync take the same path; the result carries `links`, and an extraction failure leaves pages stale without failing the committed sync.
+- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. A completed discovery that finds nothing to do (`up_to_date`) stamps only `sources.last_sync_at`, inside `withCoordinatedWrite` and guarded by source id and incarnation, so a quiet managed source stays fresh in doctor and a run that outlived a re-added source stamps nothing; dry runs and partial runs do not stamp. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`. A resume adopts the stored options for every option the caller did not set explicitly (`SyncOpts.explicitProcessing`: CLI flags, wire flags, job params; autopilot and the cycle set none); an explicit conflict refuses with `detail: cursor_processing_options_conflict`, the stored options and the exact resume command. Callers that omit `explicitProcessing` stay strict. Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts, also when the run has a recorded failure and its pending write already committed before the cursor advanced; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol. `freezeEntry` checks a rename's source page (id, revision, origin) as well as its target slug, and a committed rename counts in `renamed`. #5522: a new-file entry (`pageId: null`) whose origin another cursor of the source has since imported is re-frozen against that page when it is live, holds exactly that origin at the entry's slug in the cursor's incarnation, and the sync preparer finds its content unchanged; otherwise the origin refusal stands, and the manifest is never rewritten. #5751: the working-tree screen passes the kernel waivers for working-tree entries and counts them into `legacySkips` (printed by `sync-diagnostics.ts` with `gbrain repair contextual-mode`). A terminal `checkpoint_validation_timeout` receipt gets its hint from `checkpoint-validation.ts`. Content holds (#5988, `sync-screen.ts`): `freezeEntry` screens each import (company-profile cursors and `sync.holds=fail` excepted); a refused file becomes a hold written in the same transaction as the cursor step (`saveCursor`'s `inTx`), with no request admitted, and an over-bound pinned blob is held by size before it is read. A cursor whose pending request failed with a content refusal (`isContentRefusal`, old message shapes included) converts in place with its stored options: held, or re-frozen once per distinct bytes (`converted`), so a refusal the screen misses stays blocked without minting receipts. #6188: a failed fence refusal (`fenceReceiptLocation`: the durable `error_detail.fence`, the message, or an older release's message) holds the same bytes even when the screen admits them (`prepareTimeFenceHold`, reason `prepare_time`); a compacted `invalid_params` / `take_row_collision` receipt converts only when the re-screen holds. A page request of the run that fails with a fence refusal is held in the same invocation at the terminal-failure branch (single path and a bulk group's failed member) after the source's other requests settle within the run's wait budget, else the run returns `partial`; it is converted once, gets no failure-ledger row and is logged as a conversion. `sync.holds=fail` and company-profile cursors keep blocking with the typed refusal. #6278: a `preparation_stalled` receipt (the owner gave up preparing a member) is converted the same way by both converters: an import holds by its bytes, a delete as a delete hold (`meta.deleted`, `upstream_version` null), the checkpoint never holds; `preparationStalledHold` (sync-screen.ts) records the receipt's step and the resume arguments. Both converters write their hold through `holdUnderGate`, the narrowed gate: the failed entry's admitted suffix (window, later group members, this run's queued lane rows) is cancelled first, then the hold waits only for active suffix descendants and unfinished requests naming the entry's page (`UNFINISHED_PAGE_REQUEST_SQL`, now matching path and origin too), evaluated inside the transaction that writes the hold under the page-key → cursor lock order; its doc comment states the invariant the old source-wide wait protected. The cursor's `breaker` counts the run's stalled receipts (identities and streak, saved with each CAS): `holdsEscalated`'s rule over the run's screened imports or `BREAKER_STREAK` (5) in a row trips it, the run stops `blocked_by_failures` with `SyncResult.breaker` (drain `preparation_systemic`), and the next run's `convertBlockedCursor` re-freezes the entry and schedules the run's stalled holds for a re-screen instead of holding; a committed page resets the streak. `sameContentAtOrigin` and the waiver screens race the sync preparer against `persistence.sync_preparation_ms` (`raceSyncBudget`, sync-waivers.ts) and fail open. Tests: `test/managed-sync-preparation-stalled-holds.test.ts`, `test/sync-waiver-budget.test.ts`. Results carry this run's holds, the outstanding total, escalation, `converted_from_failed` and `recovered_frontmatter` (`buildHoldReport`); dry runs list `would_hold` / `screen_skipped`. After the checkpoint commits (and unless `noExtract`), the owner derives links for the source's stale pages through `links-maintenance.ts`, so a PGLite-delegated sync and a Postgres sync take the same path; the result carries `links`, and an extraction failure leaves pages stale without failing the committed sync. #6278 (B7): when the checkpoint commits while `sources retry-held` re-screens are scheduled for the source (scheduled against a backlog, or while this cursor ran), the pass returns `partial` / `writer_yield` instead of `synced`, so the drain's next pass retires the finished cursor and discovers again, taking them; a `queue_capacity` refused for outstanding requests (`isWriteCapacityWait`) is left out of the failure ledger because the drain waits it out.
- **`src/core/persistence/sync-holds.ts`** + **`sync-screen.ts`** + **`sync-blobs.ts`** — Git holds (#5988). One `op_checkpoints` row per held file (`sync-hold`, fingerprint `source:incarnation:path`) plus a per-source `sync-hold-summary` row (`count`, and `stale`: holds whose page exists); `writeGitHold` / `clearGitHold` lock the summary row and are conditional on the writing run's discovery time (`observed_at`), so an older run never replaces or clears a newer hold. Managed and legacy sync write the same rows; `readGitSourceHolds` (current incarnation only) feeds `retry-held` and legacy sync, and `readGitHoldListing` (count from the summary row, rows limited per source in SQL) feeds `sources status`, never `readAllSourceHolds`. `recordSyncConversion` logs each blocked request a managed run converted in place (`sync-conversions`, newest 20 per source, in the transaction that saves the converted cursor); `sources status` shows the newest 5. `gitHoldItem` gives every surface code, reason, key, line, location-only message, `fix` Action and `docs` anchor. #6188 `invalid_fence` holds carry `meta.fence` (reason, fence, section, rows, columns, section line), the file line of the first bad row (`meta.line`, from `fenceFileLine` when the screen holds it), `fence_version` and the last repair attempt (`fence_repair`); the summary row counts them (`fences`), and `holdRepairSteps` is the one router (D6) every surface prints: fence holds preview `gbrain repair fences --source <id>`, other holds preview `gbrain repair frontmatter`, a mixed source names both. One fence hold's fix (`gitHoldFix` → `fence-repair/hold-fix.ts` `fenceHoldFix`) is that file's `--only <path>` preview with the step its state calls for, and `gitHoldItem` carries the D16 `fence` object (classes, tier, `auto_retry`, `next_attempt_after`); callers that can read the maintenance state pass it (`fenceAutoRepairFor`). `holdRescreenDue` is the one re-screen predicate managed discovery and legacy sync share (retry request, database-dependent codes, an older frontmatter reader or fence screen). Policy keys: `sync.holds` (`hold`/`fail`), `sync.hold_cap` (detail shown, default 500), `sync.hold_escalate_count` (50), `sync.hold_escalate_pct` (5, from 40 screened imports), `sync.parser_regression` (`stop`/`hold`). #6278: `preparation_stalled` holds carry `meta.stall` (request, step, `waiting_on`, attempts, the writing gbrain version, the sync's resume arguments) and count under `stalled` in the summary row and `HoldRepairRoute`; `gitHoldFix` routes them to `gbrain sources writer status --source <id> --json`, then `sources retry-held`, then the option-preserving sync (`stalledHoldSteps`), never to frontmatter repair, and `holdRescreenDue` re-screens them on a gbrain version change; `buildHoldReport` routes the escalation text by code. `screenFrozenImport` admits a fence Tier 1 fixes (`fences.normalize`, read once per run only when needed; the dry run lists it in `would_normalize`), turns a refusal into a hold, or throws `sync_parser_regression` only when `sync-import-provenance` proves a validating gbrain imported the same bytes. `sync-blobs.ts` reads blob ids/sizes with chunked `ls-tree -l` and contents with `cat-file --batch`. `held-reads.ts` is the read side: `get_page.file_held`, `stale` on search/query hits and the `held_files` retrieval meta and notice, from one lookup by page id (`op_checkpoints_sync_hold_page_idx`, migration v200) and one summary read per call, cached per request; `stalled` coverage routes a `preparation_stalled` hold to the host operator's writer-status fix instead of a file repair; remote callers get codes and counts, never paths, and a fix addressed to the brain host operator (a held fence page gets `fenceHoldRelay`: the owner-host command and whether it clears by itself). Tests: `test/sync-holds-store.test.ts`, `test/persistence-sync-holds.test.ts`, `test/sync-all-hold-notes.test.ts`, `test/held-read-signals.test.ts`. #5493: with multimodal embedding on, managed discovery admits image imports (deletions reconcile their pages; company plans still refuse) and `freezeEntry` holds each image import as `managed_image_sync_unsupported` (`managedImageHold`, also in the dry-run screen) before any content read or admission, whatever `sync.holds` says: the rest of the source imports and the checkpoint advances, while the image stays recorded as incomplete coverage keyed by its pinned blob (or working bytes), so a later sync re-screens it when it changes, leaves the source (or multimodal is turned off) or `sources retry-held` asks. The summary row also counts `images`; those holds are listed everywhere a hold is but never count toward `holds_escalated` or doctor `git_held_files` escalation.
- **`src/core/persistence/file-repair.ts`** — `managed_file_repair` (#5988), the owner-internal `put_page` kind `gbrain repair frontmatter --apply` submits (accepted only from the trusted local CLI with `managedFileImport`; MCP is refused by the reserved-field gate, remote authority by the preparer). The preparer confines the path (`isWriteTargetContained` plus a component-wise `lstat` walk, no symlinks), requires the file's sha256 to equal the previewed `beforeHash` (`changed_since_preview` otherwise), recomputes `prepareRepairPublication` (the `screenSyncImport` + `importFromContent` preparation a managed sync import gets) and refuses a different result digest or a canonical overlay. It publishes the exact bytes as `file` (`expectedBeforeHash` = previewed hash; no `file_database_drift` check), applies the import (a held new file creates its page, a `renameFrom` moves the page with `updateSlug`), clears the Git hold and records `sync-import-provenance` in the same transaction; the file write queues the Git target effect. A fence repair (`gbrain repair fences`) passes its `FenceRepairReceipt` as `fenceRepair`: submission and the preparer refuse (`invalid_params`, nothing written) a receipt `parseFenceRepairReceipt` rejects or whose `before_sha256`/`after_sha256` are not the previewed and written bytes; the outcome carries it as `fence_repair`, the file target carries the commit note from `fenceRepairCommit` (`effect-model.ts`), and every refusal and fix names `gbrain repair fences --source <id>` instead of `gbrain repair frontmatter` (`FileRepairKind`, also taken by `confinedRepairTarget` and `managedRepairRoot`). Tests: `test/repair-frontmatter.test.ts`, `test/fence-repair-receipts.test.ts`.
- **`src/core/persistence/sync-prepare.ts`** — guarded raw fingerprint/revision, source root and active coordinator checks before preparation and at locked publication. Old imports/checkpoints without durable processing consent refuse under their original IDs; old deletions require their immutable origin manifest and a still-matching page origin. `noEmbed` suppresses the effect itself; `noSchemaPack` bypasses pack loading; optional extraction stays disabled, but mandatory provider-free canonical projections remain. A filename-derived slug mismatch is accepted on every platform only when the page's stored canonical path is this file and the parsed slug is that page's slug; a different declared slug still refuses. CRLF equivalence never weakens raw CAS. No uncoordinated filesystem writes. The checkpoint validates receipts through `checkpoint-validation.ts` and, for a run whose entries another cursor imported (`overtaken`, #5522), also commits when that cursor already checkpointed the same target. Markdown imports pass `screenSyncImport` (the already-published working-tree exemption, then `screenImportContent` with the expected slug and recorded-origin exemption), the same screen the freeze-time hold screen runs, so a file is held exactly when publication would refuse it. Each import, deletion and no-op apply clears the path's Git hold (`holdObservedAt`), the checkpoint clears `releasedHolds` and ignores `supersededRequests` (failed content refusals the run converted in place), and every Markdown import records `sync-import-provenance` (raw sha256, blob, gbrain version, quoting recoveries) and reports `recovered_frontmatter` / `comment_value` in its outcome. Tests: `persistence-sync-origin-native.serial.test.ts`, `persistence-sync-options.serial.test.ts`, `persistence-sync-company.serial.test.ts`. A same-slug `renameFrom` accepts the page's recorded old origin. A different-slug rename prepares against the page where it stands, locks the old slug as an additional page key, and at publication moves the page with `updateSlug` (same id, inbound links and history, `old -> new` in `slug_aliases`, withdrawn claims follow), re-infers an implicit type from the new path, then re-prepares and applies the file content at the new slug, so the move never writes back to the file. Tests: `persistence-managed-lifecycle.test.ts`. #6278: `prepareManagedSyncMutation` calls `enterClaimStep` at each await boundary (`managed_sync_active`, `authority`, `worktree_binding`, `configured_root`, `knowledge_publication`, `manifest_entry`, `git_rev_parse`, `origin_check`, `page_snapshot`, `import_screen`, `import_content`, `canonical_projections` and the rest, each naming `git`, `fs` or `db` where it knows), so a stall reports its step; the consumer's budget and the cancellation reaching those boundaries are in persistence-stalls.md.
diff --git a/docs/eval/managed-sync-stall-repro.md b/docs/eval/managed-sync-stall-repro.md
index 5f942ec1f9..abe0061718 100644
--- a/docs/eval/managed-sync-stall-repro.md
+++ b/docs/eval/managed-sync-stall-repro.md
@@ -526,3 +526,39 @@ lock are the import pipeline's, the snapshot's, the projection's and the
group memo's, none of which runs through `executeRaw` with the bound. The
pass's `queue_capacity` exit and the re-held stalled file are the two new
findings.
+
+### Lane B7: the two 4.1b findings, traced on the local probes
+
+- **The stalled file was never re-screened, not re-held.** Only discovery
+ reads the `sources retry-held` schedule (`sync-discovery.ts`,
+ `readGitHoldRetryPaths`), and `retry-held` against an unfinished cursor
+ prints that cursor's resume command (`sources-retry-held.ts`,
+ `gitFollowUpSync`: the backlog's `resume_args`). The printed sync resumed
+ the pass-1 cursor, finished its 2,755 remaining entries and reported
+ `synced` with the cursor's cumulative `counts.held` (20 fence holds plus the
+ one stalled hold from pass 1: "21 file(s) held this run", `summary.stalled:
+ 1`); the schedule stayed pending for a run nobody was told to start.
+ `convertBlockedCursor` took no part (the entry pass 1 died on was never
+ admitted, so its receipt does not exist), and a re-screened entry starts
+ with `preparation_attempts` 0. Fixed in `sync-run.ts`: a checkpoint that
+ commits while re-screens are scheduled returns `partial` / `writer_yield`,
+ so the drain's next pass retires the cursor and discovers again (taking
+ them); discovery consumes the schedule inside the fresh cursor's save.
+ Probe: `test/managed-sync-preparation-stalled-holds.test.ts` ("retry-held
+ against an unfinished cursor"), sliced pass → hold → `retry-held` → the
+ printed sync drained: one `drainManagedSync` call imports the file, clears
+ the hold, `summary.stalled: 0`, attempts 0.
+- **`queue_capacity` at admission was uncaught on the base branch too.** The
+ admission path (`admitGroup` / `admitWriteInTransaction`,
+ `admissionRoom`) is identical to `origin/capy/sync-feeder-fast-writes`; the
+ refusal escaped `groupStep` → `performManagedSync`'s catch (which recorded a
+ `managed-sync-failure` naming `--retry-failed`) → `runDrain`, whose
+ `transientDelay` does not know the code, so the CLI exited 1 with no drain
+ summary. Whether a pass survives the 99+1 condition depends only on the
+ group size against the room left, which is why the previous head's run
+ did not hit it. Fixed in `sync-drain.ts`: the refusal (now carrying
+ `outstanding=N limit=M` on `detail`) is retried with backoff, prints
+ `waiting for write capacity (N outstanding of M)`, ends `blocked` /
+ `write_capacity` with `next` after the no-progress window, and is left out
+ of the failure ledger. Probe: `test/sync-drain-write-capacity.test.ts`
+ (the sync writer's own outstanding counter set to the cap).
diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.md
index 09512b51e0..2b18ba7c97 100644
--- a/docs/guides/live-sync.md
+++ b/docs/guides/live-sync.md
@@ -88,6 +88,7 @@ The run ends in exactly one outcome:
| `resumable` | 0 | A deadline, `--timeout` or Ctrl-C stopped it; the cursor and accepted writes are intact. | Rerun `next.command`; safe in a loop. |
| `resumable` / `preparation_abandoned` | 0 | A write this process's own writer holds was still preparing past its allowance (its budget plus 30 s) and cannot be cancelled in-process, so the sync exited to end it; `drain.stall.step` says where. | Rerun `next.command`; safe in a loop. The next pass holds the entry if it stalls again. |
| `blocked` | 1 | A page failed or the writer needs intervention. | Follow `next.why`, then run `next.command`. See [drain stops](write-refusals.md#managed-sync-drain-stops). |
+| `blocked` / `write_capacity` | 1 | Other writers' requests held the sync writer's outstanding-request cap (`persistence.limits.principal_outstanding`) for the whole no-progress window, so no sync write could be admitted; the drain waited and printed `waiting for write capacity (N outstanding of M)` first. Nothing failed; the cursor is intact. | `gbrain sources writer status --source <id> --json`, let the outstanding requests finish or raise the cap, then rerun the same sync. See [drain stops](write-refusals.md#drain-write-capacity). |
| `blocked` / `preparation_systemic` | 1 | Too many writes stalled while preparing in one run (the hold-escalation rule, or five in a row with no commit between), so the run stopped with one diagnostic instead of holding every file. | `gbrain sources writer status --source <id> --json`, fix what it names, then rerun the same sync. Runbook: [catch-up stuck](troubleshooting.md#catch-up-stuck). |
**Say to your agent:** *"Catch up my managed brain's sync backlog and tell me
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index 443c14c233..55d6d0fc63 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -25,7 +25,7 @@
| Low health score | preview `gbrain doctor --remediation-plan --json`; then `gbrain doctor --remediate --yes --target-score 90 --max-usd 5` | agent, after the user agrees | `paid`; `destructive` with `--include-repairs` (approve with `--expect <plan_hash>` from the preview) | `gbrain doctor --json` |
| [Sync held a file (`Held <path>: invalid_frontmatter …`, `git_held_files`)](#held-files) | `gbrain sources status <id>`, then preview `gbrain repair frontmatter --source <id>` and apply the printed `--apply --expect <hash> --yes` | agent; the apply after the user agrees | `destructive` (rewrites the previewed lines of the files) | `gbrain doctor --only git_held_files --json` |
| [Sync held a file for its facts or takes fence (`Held <path>: invalid_fence …`)](#held-fence-files) | nothing for most holds: the next maintenance run repairs and commits the fence. To see or do it now, preview `gbrain repair fences --source <id>` and run its printed `--apply --expect <hash>`; to pause automatic repair, `gbrain config set fences.repair.enabled false` (ask the user first). A `manual` reason needs the edit the hold names | agent; the apply needs no extra consent | none (model repair spends within the `fences.repair.*` caps; raising them is `paid`, the user's call) | `gbrain doctor --only fence_integrity --json` |
-| [Managed catch-up stuck, or `Held <path>: preparation_stalled`, or the drain stopped `preparation_abandoned` / `preparation_systemic`](#catch-up-stuck) | `gbrain sources writer status --source <id> --json` (what the stuck write was doing: step, `waiting_on`, owner, version), fix what it names or upgrade the owner, then `gbrain sources retry-held <id>` and the same sync with its options | agent; a restart or upgrade of the owner after the user agrees | none to inspect; `persistent_install` when the fix restarts a service | `gbrain sources status <id> --json`, then `gbrain doctor --only git_held_files,persistence_write_stall --json` |
+| [Managed catch-up stuck, or `Held <path>: preparation_stalled`, or the drain stopped `preparation_abandoned` / `preparation_systemic` / `write_capacity`](#catch-up-stuck) | `gbrain sources writer status --source <id> --json` (what the stuck write was doing: step, `waiting_on`, owner, version), fix what it names or upgrade the owner, then `gbrain sources retry-held <id>` and the same sync with its options | agent; a restart or upgrade of the owner after the user agrees | none to inspect; `persistent_install` when the fix restarts a service | `gbrain sources status <id> --json`, then `gbrain doctor --only git_held_files,persistence_write_stall --json` |
| [A Google or GitHub item is held (`connector_held_items`)](#held-connector-items) | `gbrain sources status <id>`, fix the cause, then `gbrain sources retry-held <id>` and `gbrain sync --source <id>` | agent, after the user agrees | `egress` (fetches from the provider again) | `gbrain doctor --only connector_held_items --json` |
| [`gbrain migrate --to` refused with `writer_coordinator_required`](../ENGINES.md#engine-migration-refused) | follow the refusal's `fix`: relay its `user_message` (stay on PGLite and share with `gbrain mcp expose`, or leave the brain as it is) | agent, after the user agrees | `persistent_install`, `egress` (for `gbrain mcp expose`) | `gbrain doctor --no-migrate --json` |
| [A write was refused with a named reason](#write-refused) | the reason's recovery in [write refusal reasons](write-refusals.md) | as the refusal's `fix` | as the refusal's `fix` | the refusal's `verify` |
@@ -49,14 +49,15 @@
<a id="concurrent-write-hold"></a>**Sync held a file with `concurrent_write`?** A Git edit raced a database-only write; nothing was overwritten. Preview `gbrain sources reconcile <id> <slug> --preview`, let the user choose, then `gbrain sources retry-held <id>`. See [concurrent_write](write-refusals.md#concurrent_write).
-<a id="catch-up-stuck"></a>**Managed catch-up stuck (one write `running` for minutes while the rest waits), held N files as `preparation_stalled`, or the drain stopped with `preparation_abandoned` or `preparation_systemic`?** Every managed write's *preparation* has a deadline (`persistence.sync_preparation_ms`, default 120 s, for sync members; `persistence.maintenance_preparation_ms`, default 120 s, for maintenance writes; a hard ceiling `persistence.preparation_ceiling_ms`, default 600 s; `persistence.max_preparation_attempts`, default 2; all behind the `preparation_deadlines` write switch), so one stuck write costs at most its budget times its attempts and the rest of the source keeps publishing. The runbook branches on what you see; every command below is read-only unless it says otherwise, and the files themselves are never the problem in this branch.
+<a id="catch-up-stuck"></a>**Managed catch-up stuck (one write `running` for minutes while the rest waits), held N files as `preparation_stalled`, or the drain stopped with `preparation_abandoned`, `preparation_systemic` or `write_capacity`?** Every managed write's *preparation* has a deadline (`persistence.sync_preparation_ms`, default 120 s, for sync members; `persistence.maintenance_preparation_ms`, default 120 s, for maintenance writes; a hard ceiling `persistence.preparation_ceiling_ms`, default 600 s; `persistence.max_preparation_attempts`, default 2; all behind the `preparation_deadlines` write switch), so one stuck write costs at most its budget times its attempts and the rest of the source keeps publishing. The runbook branches on what you see; every command below is read-only unless it says otherwise, and the files themselves are never the problem in this branch.
1. **While it is stuck.** The progress line prints `stalled <N>s on <step>` instead of an ETA. Run `gbrain sources writer status --source <id> --json`: the blocked request's `claim.stall` names the step (`origin_check`, `knowledge_publication`, …), `waiting_on` (`git`, `fs`, `db`, `pool`, or an honest `unknown`), `step_age_ms`, the budget, and the owner process (kind, pid, gbrain version). An owner whose version predates this release never gives up: upgrade it and restart it (`gbrain serve`, the jobs worker or autopilot; the drain's own process ends with the drain). Otherwise wait out the budget: the write is released, retried once, then held.
-2. **Held files (`preparation_stalled`).** `gbrain sources status <id> --json` lists them with the step each stalled on; no `gbrain repair` applies. After the cause is fixed (or gbrain upgraded), run `gbrain sources retry-held <id>` and then the same sync with the same options, which the hold's `fix` and `retry-held` print, for example `gbrain sync --source <id> --no-pull --no-embed`. Verify with `gbrain sources status <id> --json` (the held count drops) and `gbrain doctor --only git_held_files --json`. A held deletion keeps its page until that retry. A stalled hold also re-screens by itself when the gbrain version changes.
+2. **Held files (`preparation_stalled`).** `gbrain sources status <id> --json` lists them with the step each stalled on; no `gbrain repair` applies. After the cause is fixed (or gbrain upgraded), run `gbrain sources retry-held <id>` and then the same sync with the same options, which the hold's `fix` and `retry-held` print, for example `gbrain sync --source <id> --no-pull --no-embed`. If that sync still has a backlog, it finishes the backlog and then re-screens the scheduled files in the same run. Verify with `gbrain sources status <id> --json` (the held count drops) and `gbrain doctor --only git_held_files --json`. A held deletion keeps its page until that retry. A stalled hold also re-screens by itself when the gbrain version changes.
3. **The drain stopped `preparation_abandoned` (exit 0).** A preparation in the sync's own process was still running past its allowance (its budget plus 30 s) and cannot be cancelled in-process, so the sync exited to end it; `drain.stall.step` says where. Rerun `next.command` (`safe_to_loop` is true): the next pass holds the entry if it stalls again.
4. **The drain stopped `preparation_systemic` (exit 1).** Too many writes stalled in one run (more than `sync.hold_escalate_count` / `sync.hold_escalate_pct` of the run's screened imports, or five in a row with no page committed between), so the run stopped with one diagnostic instead of holding every file. `breaker` carries the rule, the counts and the last step. Inspect the writer as in step 1, fix the cause, then rerun the same sync: it re-freezes the stopped entry with a fresh request and re-screens the files that run held.
-5. **A `put_page`, `remember` or maintenance write finished `preparation_stalled`.** Nothing is held: the receipt names the step. Read the writer as in step 1, then resubmit a foreground write under a new `request_id`; the next maintenance run submits its write again.
-6. **A manual fence defect among the holds** (`invalid_fence`, reason `manual`, or `repeated_marker`) is a different branch: see [held fence files](#held-fence-files). `gbrain sources status` keeps the kinds apart and routes each to its own command.
+5. **The drain stopped `write_capacity` (exit 1).** Other writers' requests held the sync writer's outstanding-request cap (`persistence.limits.principal_outstanding`, default 100; on one host the CLI sync shares the `local_cli` principal with fact-fence adoption and `dream`) for the whole 30 s window, so the sync could not admit its next write. It waited and printed `waiting for write capacity (N outstanding of M)` first; nothing failed and the cursor is intact. `gbrain sources writer status --source <id> --json` lists the outstanding requests. Let them finish, or raise the cap (`gbrain config set persistence.limits.principal_outstanding 200`), then rerun the same sync. Reference: [drain stops](write-refusals.md#drain-write-capacity).
+6. **A `put_page`, `remember` or maintenance write finished `preparation_stalled`.** Nothing is held: the receipt names the step. Read the writer as in step 1, then resubmit a foreground write under a new `request_id`; the next maintenance run submits its write again.
+7. **A manual fence defect among the holds** (`invalid_fence`, reason `manual`, or `repeated_marker`) is a different branch: see [held fence files](#held-fence-files). `gbrain sources status` keeps the kinds apart and routes each to its own command.
Turning the `preparation_deadlines` switch off (`gbrain config set persistence.preparation_deadlines false`) restores the previous behaviour exactly: no deadlines on sync or maintenance writes, no attempt counter, no `preparation_stalled` holds. See [`preparation_stalled`](write-refusals.md#preparation_stalled), [managed sync drain stops](write-refusals.md#managed-sync-drain-stops) and the [timing knobs](live-sync.md#catching-up-a-large-backlog-on-managed-postgres).
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 600e51eb7b..9c5e7276da 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -45,7 +45,7 @@ of making a duplicate.
| `cursor_processing_options_conflict` | `invalid_params` | An unfinished sync's processing options (`--no-embed`, `--no-extract`, `--no-schema-pack`) conflict with this run, or the cursor predates saved options and has none. When options are saved, a run that omits those flags, including autopilot and `sync` jobs, adopts them. | When the message prints a resume command (`gbrain sync --source <source> --no-pull` plus the saved flags), run it or drop the conflicting flag. When it reports no saved options, resolve pending requests first, then rediscover with `gbrain sync --source <source> --no-pull --retry-failed` and the processing flags you want. |
| `take_row_collision` | `take_row_collision` | A save adds a takes-table row whose row number already belongs to a different take that exists only in the database. The save stops instead of overwriting that take. | Renumber the new takes row, or add the existing take to the page's takes table, then save with the current `expected_revision` and a **new** request ID (the content changed). |
| `invalid_source_uri` | `invalid_source_uri` | The brain has shared skillpacks, and the page's stored `source_uri` is a `file:` URI that cannot be turned into a local path, so gbrain cannot prove the write stays outside a skillpack. Shared-skill protection stays on. | The source owner inspects the page's stored `source_uri` on the brain host and replaces it with an absolute file URI or clears it; there is no dedicated command yet. Retry with a **new** request ID. |
-| `queue_capacity` | `queue_capacity` | Admission would exceed a write-journal limit. Existing requests keep their place; nothing is evicted. For the cumulative limits (lifetime request IDs and receipt bytes), `detail` names the limit, for example `principal_lifetime_ids`. | For a cumulative limit, run the printed `gbrain config set persistence.limits.<limit> <value>` (sized for about one more year at the current rate), then retry with the **same** request ID. For outstanding-request, queued-byte or recovery-byte limits, let outstanding requests finish and check `gbrain sources writer status`. See [bounded admission and retention](concurrent-writes.md#bounded-admission-and-retention). |
+| `queue_capacity` | `queue_capacity` | Admission would exceed a write-journal limit. Existing requests keep their place; nothing is evicted. For the cumulative limits (lifetime request IDs and receipt bytes), `detail` names the limit, for example `principal_lifetime_ids`; for the outstanding-request caps, `detail` carries the counts (`outstanding=<used> limit=<limit>`), and a managed `gbrain sync` drain waits them out ([`write_capacity`](#drain-write-capacity)). | For a cumulative limit, run the printed `gbrain config set persistence.limits.<limit> <value>` (sized for about one more year at the current rate), then retry with the **same** request ID. For outstanding-request, queued-byte or recovery-byte limits, let outstanding requests finish and check `gbrain sources writer status`. See [bounded admission and retention](concurrent-writes.md#bounded-admission-and-retention). |
| <a id="checkpoint-validation-timeout"></a>`index_building`, `index_missing` or `indexes_valid` | `checkpoint_validation_timeout` | A managed sync's checkpoint validation (the check that every page receipt of the run committed) hit the coordinator's 5-second statement timeout on a large `persistence_requests` table. The checkpoint request failed terminally instead of being retried ahead of every other write to the source, so other writes proceed; `last_commit` is unchanged and every page the run already committed stays committed. `detail` says which of three states the request indexes were in when the hint was built. | `index_building`: migration 179 is still building the indexes; wait (doctor `persistence_request_indexes` shows progress), then run the printed retry. `index_missing`: run `gbrain repair request-indexes --apply` (it drops an INVALID index and rebuilds it concurrently on Postgres), then the printed retry. `indexes_valid`: run the printed retry once; if it times out again, report the request id with the `persistence_request_indexes` and `persistence_request_growth` entries of `gbrain doctor --json`. The retry is `gbrain sync --source <source> --no-pull --retry-failed` plus the run's `--repo` base and cursor options (`--full`, `--working-tree`, `--src-subpath`, `--exclude`, `--include-hidden`, `--strategy`) and saved processing flags, so it resumes the same cursor. Do not cancel the request: a cancelled checkpoint still blocks the next one. |
| <a id="connector-account-changed"></a>`account_changed`, `account_unresolved` | `connector_account_changed` | A managed Google or GitHub connector's credential resolves to a different account than the one pinned for the source (Google email, GitHub App installation or login), or to no account at all. Google checks every enabled service before any service runs. Nothing was imported. No reset flag authorizes an account change. | The suggestion gives two branches with real values. (A) Restore the credential for the pinned account (the configured `g_token_env`, `g_token_command`, vault credential, `gh_token_env` or GitHub App key), then `gbrain sync --source <source>`. (B) For a deliberate change, add a new source for the new account (`gbrain google setup --account <email>`, or `gbrain sources add <new-id> --kind github … --app-install <id>`), then `gbrain sources archive <source>`; existing pages stay under the old source. |
| <a id="connector-intent-outdated"></a>`pre_upgrade` | `connector_intent_outdated` | A connector write was admitted in the intent format retired in v0.60.11.0. With detail `pre_upgrade` it was admitted before this brain's upgrade; otherwise a connector host older than v0.60.11.0 admitted it. The consumer recovers any file publication in progress first, then fails the request. | `pre_upgrade`: nothing to do; the item is fetched again on the next `gbrain sync --source <source>` under a new request ID. Otherwise: `gbrain upgrade` on the host that runs connector jobs, then `gbrain sync --source <source>`. |
@@ -71,7 +71,7 @@ of making a duplicate.
| <a id="no_pricing"></a>`no_pricing` | `no_pricing` | A cost cap you set (`--max-cost`, `--max-usd`, `--max-cost-usd`, or an explicit cap in config such as `cycle.extract_atoms.budget_usd`) cannot be enforced, because gbrain has no price for the model the run was about to call. The run stops before that call. Under a default cap an unpriced model warns and runs instead. The message names the model, provider and kind, and JSON output carries the same guidance as fields: `code`, `model`, `provider`, `kind`, `units`, `lookup`, `register_command`, `register_scope` and `docs`. | Look up the provider's current price for the model, for example by searching the web for its pricing page. A chat model needs USD per 1M input tokens and USD per 1M output tokens; an embedding or reranker model needs USD per 1M tokens. On the brain host, run `gbrain pricing set <model> --input <usd> --output <usd> --source <pricing-page-url>` (or `--rate <usd>`), then retry. An agent connected over MCP cannot register prices: give the command to the brain's operator. See [registering a model price](../operations/spend-controls.md#registering-a-model-price). |
| <a id="managed_raw_upload"></a>raw upload on a managed brain | `writer_coordinator_required` | `gbrain files upload-raw` of a small (git-storage) file whose `.raw/` destination is inside a managed canonical worktree. The persistence coordinator does not publish raw files yet, so the worktree refuses writes from outside it; starting a `gbrain serve` owner does not change that. The refusal comes before anything is created: no `.raw/` directory and no `files` row. With no storage backend, `file_upload` for such a page no longer suggests `upload-raw`. | Configure `storage` (supabase, s3 or local) in the gbrain config, then run the printed `gbrain files upload <file> --page <slug>`; check it with `gbrain files list <slug>`. |
| <a id="timeline_rows_would_be_removed"></a>`timeline_rows_would_be_removed` | `timeline_rows_would_be_removed` | A remote `put_page` (or a `put_pages` entry) has no Timeline section at all — no `<!-- timeline -->` sentinel and no `## Timeline` or `## History` heading — and would delete dated entries the page has, including rows `add_timeline_entry` added. `put_page` content replaces the whole page, so the omission must be explicit. Nothing was written. A section that is present but empty is a deliberate delete and is not refused; a local `gbrain put` without `--expected-revision` keeps the rows instead. | Re-read with `get_page include_content:true`, keep the Timeline section and resubmit with a new `request_id`; to remove every dated entry on purpose, resubmit the same content with `drop_timeline: true` (on put_pages, per entry). A successful write that deletes rows reports `timeline_rows_removed {count, earliest, latest, warning, fix}` (dates only); `get_versions` then `revert_version` restores them as new rows. |
-| <a id="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`). 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="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="fence_unrenderable"></a>`fence_unrenderable` | `fence_unrenderable` | A legacy fact row (an active `facts` row with no fence row number) was not adopted into its page's `## Facts` fence because the fence codec reads the rendered row back as something other than the stored fact: a whitespace-only claim comes back empty, `~~x~~` comes back struck, a literal `<br>` comes back as a line break, or another column changes. Surrounding whitespace and CRLF line endings are the one accepted difference: such a row is adopted and `facts.fact` takes the fence's text. A second legacy row whose normalized claim, source and visibility the page already carries is left too (`duplicate_claim`; a private and a world row with one text are two facts and both adopt). The cycle and the v0.32.2 migration print `FACTS_FENCE_FAILED: <slug> (fence_unrenderable: N row(s), <class>)`; doctor `fence_integrity` lists the pages, fact ids and reason classes under `unrenderable_legacy_facts` (never the claim text). The same code refuses a planned adoption whose rendered fence does not read back as its facts; that is a gbrain planning defect, not caller input. | Nothing to fix in the page: the rows stay active and searchable, nothing is lost, and their pages skip destructive fact reconciliation until the rows are adopted. Report the pages and reason classes with the gbrain version. Never `forget_fact` a row to clear the count. |
| <a id="reconcile-private-facts"></a>reconcile private facts | `permission_denied` | `gbrain sources reconcile --apply` (and its preview) found a `## Facts` row that would edit, renumber or change the visibility of a stored private fact, copy a stored private claim into a row under another visibility, or copy a stored private row's context (24 characters or longer) verbatim into a world row. A row is identified by its row number and claim, so a world row that only shares a private row's claim is not a private row and publishes. The refusal names the row number, never its text. It guards against verbatim copies only; reworded text is not detected, so it is not a confidentiality proof. Sources are not compared, because rows share provenance such as "Slack import". Nothing was written. | Read the stored page with the printed `gbrain get --source <id> -- <slug>`, keep the named row as stored in the file (or remove the copied text), then run a fresh `gbrain sources reconcile <id> <slug> --preview` and apply it. Change private facts with `remember` and `forget`. |
| <a id="maintenance_backpressure"></a>`maintenance_backpressure` (exit 12) | `maintenance_backpressure` | A managed maintenance run (`gbrain extract-conversation-facts`, its cycle phase or job) publishes each page as its own request, under the same local CLI writer your own CLI writes use. Before the run it counts the requests the whole run plans; before each page's model work it checks again. It stops admitting once the writer's outstanding requests, reserved receipt bytes (`persistence.limits.principal_terminal_bytes`; each request reserves 16 KiB until its receipt compacts after the retention window) or permanent request ids (`persistence.limits.principal_lifetime_ids`; never freed) would pass 80% of their limit, so the last 20% stays free for your other writes. The message names the resource. Pages already published keep their facts and nothing is half-written. | Outstanding requests: read them with `gbrain sources writer status --source <id> --json`; a resident `gbrain serve`, or the next CLI run, publishes them, then rerun the same command. Receipt bytes or request ids: run the smaller batch the message prints (`gbrain extract-conversation-facts --source-id <id> --limit <n>`), or wait for receipts to compact; raising the named `persistence.limits.*` key is the user's call. |
@@ -432,6 +432,7 @@ retry_after_ms, eta_seconds, rate_pages_per_min, why, docs }`. Run
| <a id="drain-blocked-by-a-failed-page"></a>`blocked_by_failures` | `blocked_by_failures` | `blocked` | A page write failed terminally. `managed_write` and `failures` name the page and cause. Rerunning without a fix returns the same failure. | Fix the cause, then run `next.command` (it adds `--retry-failed`). Ask the user before skipping content. |
| <a id="drain-preparation-abandoned"></a>`preparation_abandoned` | `preparation_abandoned` | `resumable` | A write this process's own writer holds was still preparing past its allowance (its budget plus 30 s, never more than the ceiling `persistence.preparation_ceiling_ms` plus 30 s) and the process cannot cancel it, so the sync exited to end it. The cursor and accepted writes are intact; `drain.stall` names the step (`stall.step`, `stall.waiting_on`). Exit 0. | Rerun `next.command` (`safe_to_loop` is true). The next pass holds the entry as `preparation_stalled` if it stalls again; `gbrain sources writer status --source <source> --json` shows what it was stuck on. |
| <a id="preparation_systemic"></a><a id="drain-preparation-systemic"></a>`preparation_systemic` | `preparation_systemic` | `blocked` | The run's breaker tripped: more `preparation_stalled` receipts than a source should hold (the `sync.hold_escalate_count` / `sync.hold_escalate_pct` rule over this run's screened imports) or five stalled entries in a row with no page committed between them. The run stopped with one diagnostic instead of holding every file: the write owner, not the files, is the likely cause. `breaker` carries the rule, the counts, the last step and the fix; exit 1. | `gbrain sources writer status --source <source> --json`, fix what it names or upgrade gbrain, then rerun the same sync: it re-freezes the stopped entry under a fresh request and schedules the files this run held for a re-screen. |
+| <a id="drain-write-capacity"></a>`write_capacity` | `queue_capacity` | `blocked` | The sync could not admit its next write for the whole no-progress window (30 s) because other writers' requests held the outstanding-request cap of its write principal (`persistence.limits.principal_outstanding`, default 100; the brain cap `persistence.limits.brain_outstanding`, 1000, works the same way): on one host the CLI sync and a maintenance run (fact-fence adoption, `dream`) share the `local_cli` principal, so a long adoption queue leaves no room for a sync write. Nothing failed and the cursor is intact: the drain retried the admission with backoff while they settled, printing `waiting for write capacity (N outstanding of M)`, and stopped only when the window passed. `drain.capacity` carries the counts and the wait; exit 1. A cumulative cap (permanent request IDs, receipt bytes) is a different refusal: it names its config key and stops at once. | `gbrain sources writer status --source <source> --json` lists the outstanding requests (read-only). Let them finish, or raise the cap (`gbrain config set persistence.limits.principal_outstanding 200`), then rerun the same sync; it resumes where it stopped. |
## Unbound sources on Postgres
diff --git a/llms-full.txt b/llms-full.txt
index 003d1eb366..232ec11a14 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -6360,6 +6360,7 @@ The run ends in exactly one outcome:
| `resumable` | 0 | A deadline, `--timeout` or Ctrl-C stopped it; the cursor and accepted writes are intact. | Rerun `next.command`; safe in a loop. |
| `resumable` / `preparation_abandoned` | 0 | A write this process's own writer holds was still preparing past its allowance (its budget plus 30 s) and cannot be cancelled in-process, so the sync exited to end it; `drain.stall.step` says where. | Rerun `next.command`; safe in a loop. The next pass holds the entry if it stalls again. |
| `blocked` | 1 | A page failed or the writer needs intervention. | Follow `next.why`, then run `next.command`. See [drain stops](write-refusals.md#managed-sync-drain-stops). |
+| `blocked` / `write_capacity` | 1 | Other writers' requests held the sync writer's outstanding-request cap (`persistence.limits.principal_outstanding`) for the whole no-progress window, so no sync write could be admitted; the drain waited and printed `waiting for write capacity (N outstanding of M)` first. Nothing failed; the cursor is intact. | `gbrain sources writer status --source <id> --json`, let the outstanding requests finish or raise the cap, then rerun the same sync. See [drain stops](write-refusals.md#drain-write-capacity). |
| `blocked` / `preparation_systemic` | 1 | Too many writes stalled while preparing in one run (the hold-escalation rule, or five in a row with no commit between), so the run stopped with one diagnostic instead of holding every file. | `gbrain sources writer status --source <id> --json`, fix what it names, then rerun the same sync. Runbook: [catch-up stuck](troubleshooting.md#catch-up-stuck). |
**Say to your agent:** *"Catch up my managed brain's sync backlog and tell me
@@ -9378,7 +9379,7 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro
| Low health score | preview `gbrain doctor --remediation-plan --json`; then `gbrain doctor --remediate --yes --target-score 90 --max-usd 5` | agent, after the user agrees | `paid`; `destructive` with `--include-repairs` (approve with `--expect <plan_hash>` from the preview) | `gbrain doctor --json` |
| [Sync held a file (`Held <path>: invalid_frontmatter …`, `git_held_files`)](#held-files) | `gbrain sources status <id>`, then preview `gbrain repair frontmatter --source <id>` and apply the printed `--apply --expect <hash> --yes` | agent; the apply after the user agrees | `destructive` (rewrites the previewed lines of the files) | `gbrain doctor --only git_held_files --json` |
| [Sync held a file for its facts or takes fence (`Held <path>: invalid_fence …`)](#held-fence-files) | nothing for most holds: the next maintenance run repairs and commits the fence. To see or do it now, preview `gbrain repair fences --source <id>` and run its printed `--apply --expect <hash>`; to pause automatic repair, `gbrain config set fences.repair.enabled false` (ask the user first). A `manual` reason needs the edit the hold names | agent; the apply needs no extra consent | none (model repair spends within the `fences.repair.*` caps; raising them is `paid`, the user's call) | `gbrain doctor --only fence_integrity --json` |
-| [Managed catch-up stuck, or `Held <path>: preparation_stalled`, or the drain stopped `preparation_abandoned` / `preparation_systemic`](#catch-up-stuck) | `gbrain sources writer status --source <id> --json` (what the stuck write was doing: step, `waiting_on`, owner, version), fix what it names or upgrade the owner, then `gbrain sources retry-held <id>` and the same sync with its options | agent; a restart or upgrade of the owner after the user agrees | none to inspect; `persistent_install` when the fix restarts a service | `gbrain sources status <id> --json`, then `gbrain doctor --only git_held_files,persistence_write_stall --json` |
+| [Managed catch-up stuck, or `Held <path>: preparation_stalled`, or the drain stopped `preparation_abandoned` / `preparation_systemic` / `write_capacity`](#catch-up-stuck) | `gbrain sources writer status --source <id> --json` (what the stuck write was doing: step, `waiting_on`, owner, version), fix what it names or upgrade the owner, then `gbrain sources retry-held <id>` and the same sync with its options | agent; a restart or upgrade of the owner after the user agrees | none to inspect; `persistent_install` when the fix restarts a service | `gbrain sources status <id> --json`, then `gbrain doctor --only git_held_files,persistence_write_stall --json` |
| [A Google or GitHub item is held (`connector_held_items`)](#held-connector-items) | `gbrain sources status <id>`, fix the cause, then `gbrain sources retry-held <id>` and `gbrain sync --source <id>` | agent, after the user agrees | `egress` (fetches from the provider again) | `gbrain doctor --only connector_held_items --json` |
| [`gbrain migrate --to` refused with `writer_coordinator_required`](../ENGINES.md#engine-migration-refused) | follow the refusal's `fix`: relay its `user_message` (stay on PGLite and share with `gbrain mcp expose`, or leave the brain as it is) | agent, after the user agrees | `persistent_install`, `egress` (for `gbrain mcp expose`) | `gbrain doctor --no-migrate --json` |
| [A write was refused with a named reason](#write-refused) | the reason's recovery in [write refusal reasons](write-refusals.md) | as the refusal's `fix` | as the refusal's `fix` | the refusal's `verify` |
@@ -9402,14 +9403,15 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro
<a id="concurrent-write-hold"></a>**Sync held a file with `concurrent_write`?** A Git edit raced a database-only write; nothing was overwritten. Preview `gbrain sources reconcile <id> <slug> --preview`, let the user choose, then `gbrain sources retry-held <id>`. See [concurrent_write](write-refusals.md#concurrent_write).
-<a id="catch-up-stuck"></a>**Managed catch-up stuck (one write `running` for minutes while the rest waits), held N files as `preparation_stalled`, or the drain stopped with `preparation_abandoned` or `preparation_systemic`?** Every managed write's *preparation* has a deadline (`persistence.sync_preparation_ms`, default 120 s, for sync members; `persistence.maintenance_preparation_ms`, default 120 s, for maintenance writes; a hard ceiling `persistence.preparation_ceiling_ms`, default 600 s; `persistence.max_preparation_attempts`, default 2; all behind the `preparation_deadlines` write switch), so one stuck write costs at most its budget times its attempts and the rest of the source keeps publishing. The runbook branches on what you see; every command below is read-only unless it says otherwise, and the files themselves are never the problem in this branch.
+<a id="catch-up-stuck"></a>**Managed catch-up stuck (one write `running` for minutes while the rest waits), held N files as `preparation_stalled`, or the drain stopped with `preparation_abandoned`, `preparation_systemic` or `write_capacity`?** Every managed write's *preparation* has a deadline (`persistence.sync_preparation_ms`, default 120 s, for sync members; `persistence.maintenance_preparation_ms`, default 120 s, for maintenance writes; a hard ceiling `persistence.preparation_ceiling_ms`, default 600 s; `persistence.max_preparation_attempts`, default 2; all behind the `preparation_deadlines` write switch), so one stuck write costs at most its budget times its attempts and the rest of the source keeps publishing. The runbook branches on what you see; every command below is read-only unless it says otherwise, and the files themselves are never the problem in this branch.
1. **While it is stuck.** The progress line prints `stalled <N>s on <step>` instead of an ETA. Run `gbrain sources writer status --source <id> --json`: the blocked request's `claim.stall` names the step (`origin_check`, `knowledge_publication`, …), `waiting_on` (`git`, `fs`, `db`, `pool`, or an honest `unknown`), `step_age_ms`, the budget, and the owner process (kind, pid, gbrain version). An owner whose version predates this release never gives up: upgrade it and restart it (`gbrain serve`, the jobs worker or autopilot; the drain's own process ends with the drain). Otherwise wait out the budget: the write is released, retried once, then held.
-2. **Held files (`preparation_stalled`).** `gbrain sources status <id> --json` lists them with the step each stalled on; no `gbrain repair` applies. After the cause is fixed (or gbrain upgraded), run `gbrain sources retry-held <id>` and then the same sync with the same options, which the hold's `fix` and `retry-held` print, for example `gbrain sync --source <id> --no-pull --no-embed`. Verify with `gbrain sources status <id> --json` (the held count drops) and `gbrain doctor --only git_held_files --json`. A held deletion keeps its page until that retry. A stalled hold also re-screens by itself when the gbrain version changes.
+2. **Held files (`preparation_stalled`).** `gbrain sources status <id> --json` lists them with the step each stalled on; no `gbrain repair` applies. After the cause is fixed (or gbrain upgraded), run `gbrain sources retry-held <id>` and then the same sync with the same options, which the hold's `fix` and `retry-held` print, for example `gbrain sync --source <id> --no-pull --no-embed`. If that sync still has a backlog, it finishes the backlog and then re-screens the scheduled files in the same run. Verify with `gbrain sources status <id> --json` (the held count drops) and `gbrain doctor --only git_held_files --json`. A held deletion keeps its page until that retry. A stalled hold also re-screens by itself when the gbrain version changes.
3. **The drain stopped `preparation_abandoned` (exit 0).** A preparation in the sync's own process was still running past its allowance (its budget plus 30 s) and cannot be cancelled in-process, so the sync exited to end it; `drain.stall.step` says where. Rerun `next.command` (`safe_to_loop` is true): the next pass holds the entry if it stalls again.
4. **The drain stopped `preparation_systemic` (exit 1).** Too many writes stalled in one run (more than `sync.hold_escalate_count` / `sync.hold_escalate_pct` of the run's screened imports, or five in a row with no page committed between), so the run stopped with one diagnostic instead of holding every file. `breaker` carries the rule, the counts and the last step. Inspect the writer as in step 1, fix the cause, then rerun the same sync: it re-freezes the stopped entry with a fresh request and re-screens the files that run held.
-5. **A `put_page`, `remember` or maintenance write finished `preparation_stalled`.** Nothing is held: the receipt names the step. Read the writer as in step 1, then resubmit a foreground write under a new `request_id`; the next maintenance run submits its write again.
-6. **A manual fence defect among the holds** (`invalid_fence`, reason `manual`, or `repeated_marker`) is a different branch: see [held fence files](#held-fence-files). `gbrain sources status` keeps the kinds apart and routes each to its own command.
+5. **The drain stopped `write_capacity` (exit 1).** Other writers' requests held the sync writer's outstanding-request cap (`persistence.limits.principal_outstanding`, default 100; on one host the CLI sync shares the `local_cli` principal with fact-fence adoption and `dream`) for the whole 30 s window, so the sync could not admit its next write. It waited and printed `waiting for write capacity (N outstanding of M)` first; nothing failed and the cursor is intact. `gbrain sources writer status --source <id> --json` lists the outstanding requests. Let them finish, or raise the cap (`gbrain config set persistence.limits.principal_outstanding 200`), then rerun the same sync. Reference: [drain stops](write-refusals.md#drain-write-capacity).
+6. **A `put_page`, `remember` or maintenance write finished `preparation_stalled`.** Nothing is held: the receipt names the step. Read the writer as in step 1, then resubmit a foreground write under a new `request_id`; the next maintenance run submits its write again.
+7. **A manual fence defect among the holds** (`invalid_fence`, reason `manual`, or `repeated_marker`) is a different branch: see [held fence files](#held-fence-files). `gbrain sources status` keeps the kinds apart and routes each to its own command.
Turning the `preparation_deadlines` switch off (`gbrain config set persistence.preparation_deadlines false`) restores the previous behaviour exactly: no deadlines on sync or maintenance writes, no attempt counter, no `preparation_stalled` holds. See [`preparation_stalled`](write-refusals.md#preparation_stalled), [managed sync drain stops](write-refusals.md#managed-sync-drain-stops) and the [timing knobs](live-sync.md#catching-up-a-large-backlog-on-managed-postgres).
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 45130fcc89..8bad15f5ae 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -318,6 +318,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
// #6278 (the integrator restamps `since` to the release that ships it).
{ since: '0.60.107.0', text: 'A managed sync member\'s preparation now has a deadline (`persistence.sync_preparation_ms`, 120 s): a write that cannot finish preparing is released at its budget and tried once more, and a second cut-off (or a process killed mid-preparation) finishes it `failed` with `preparation_stalled`. The sync holds that file (`preparation_stalled`, listed by `gbrain sources status`; no `gbrain repair` applies) and keeps going, so the file stays out of the index until `gbrain sources retry-held <id>` and the same sync re-import it. A run that stalls more files than `sync.hold_escalate_count` / `sync.hold_escalate_pct` allow, or five in a row with no page committed between them, stops `blocked` with `preparation_systemic` (exit 1) instead of holding every file.' },
{ since: '0.60.107.0', text: 'A `put_page`, `edit_page`, `remember` or maintenance write (fact-fence adoption, maintenance page writes) whose preparation is cut off twice now gets a terminal `preparation_stalled` receipt instead of being claimed again and holding the rest of its root; resubmit a foreground write under a new `request_id`. `gbrain sources writer status` and doctor `persistence_write_stall` name the step it reached, what it waited on and the owner process (`claim.stall`).' },
+ { since: '0.60.107.0', text: 'A managed `gbrain sync` pass that finishes its cursor while `sources retry-held` re-screens are scheduled for the source now returns `partial` / `writer_yield` instead of `synced`, and the drain runs the re-screen in the same invocation; a single-pass caller re-enters as it does at a slice boundary. A sync admission refused for write capacity (`queue_capacity` with `detail` `outstanding=N limit=M`) is waited out by the drain and, past its 30 s no-progress window, ends `blocked` with the new stop reason `write_capacity` and `drain.capacity`, where it used to exit 1 with no drain summary and a failure-ledger row.' },
{ since: '0.60.107.0', text: 'A managed `gbrain sync` drain no longer counts a renewed claim as progress: `drain_stalled` can now stop a catch-up whose head preparation is stuck past its budget plus 30 s, a preparation the sync\'s own process still holds past its budget plus 30 s ends the drain `resumable` / `preparation_abandoned` (exit 0, safe to rerun) and exits, and a progress line prints `stalled <N>s on <step>`. `gbrain sources retry-held` now prints a follow-up sync that keeps `--no-embed` and the run\'s other processing options.' },
{ since: '0.60.107.0', text: 'New keys `persistence.sync_preparation_ms` (120000), `persistence.maintenance_preparation_ms` (120000), `persistence.preparation_ceiling_ms` (600000) and `persistence.max_preparation_attempts` (2) bound write preparation, and `gbrain config set` refuses a value out of range; the `preparation_deadlines` write switch (`gbrain config set persistence.preparation_deadlines false`) restores the old behavior exactly (only `remember`, `put_page` and `edit_page` keep a 30 s budget; nothing is counted or held). `persistence.max_claim_ms` keeps its doctor meaning. Migration v220 adds `persistence_requests.preparation_attempts`; restart every `gbrain serve`, jobs worker and autopilot on the new version, because an older owner never gives up a stuck preparation.' },
{ since: '0.60.107.0', text: 'Fact-fence adoption (the extract_facts cycle phase and the v0.32.2 backfill) now writes the fence\'s parsed text back into `facts.fact`: a legacy claim with surrounding whitespace or CRLF line endings is adopted with that whitespace trimmed and its line endings folded to LF (the row keeps its id, vectors and provenance). A claim the fence codec would change further (whitespace-only, `~~x~~`, a literal `<br>`) or one its page already carries stays a legacy row, active and searchable, and is reported as `FACTS_FENCE_FAILED: <slug> (fence_unrenderable: …)` and under doctor `fence_integrity` `unrenderable_legacy_facts`. Only the pages still holding such rows skip destructive fact reconciliation (the whole source skipped before), and the cycle summary names them while keeping the reconcile counts of the other pages.' },
diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.ts
index eb173e4fda..3a2278fd5f 100644
--- a/src/core/error-catalogue.ts
+++ b/src/core/error-catalogue.ts
@@ -74,6 +74,7 @@ export const ERROR_CATALOGUE = {
sync_drain_blocked_by_failures: { code: 'blocked_by_failures', docs: 'docs/guides/write-refusals.md#drain-blocked-by-a-failed-page' },
sync_drain_preparation_abandoned: { code: 'preparation_abandoned', docs: 'docs/guides/write-refusals.md#drain-preparation-abandoned' },
sync_drain_preparation_systemic: { code: 'preparation_systemic', docs: 'docs/guides/write-refusals.md#preparation_systemic' },
+ sync_drain_write_capacity: { code: 'queue_capacity', docs: 'docs/guides/write-refusals.md#drain-write-capacity' },
} as const satisfies Record<string, CatalogueEntry>;
export type CatalogueName = keyof typeof ERROR_CATALOGUE;
diff --git a/src/core/persistence/admission-retry.ts b/src/core/persistence/admission-retry.ts
index 4686b7d14c..7dfca34006 100644
--- a/src/core/persistence/admission-retry.ts
+++ b/src/core/persistence/admission-retry.ts
@@ -27,3 +27,22 @@ export async function retryWriteAdmission<T>(requestId: string, attempt: (remain
}
}
}
+
+/**
+ * #6278: the outstanding-request cap's `detail`, and its readers. A
+ * `queue_capacity` refused because other requests hold the writer's
+ * outstanding cap clears by itself once they settle, so a caller that can
+ * wait (the managed drain) treats it as a wait; a cumulative cap (permanent
+ * request IDs, receipt bytes) names its config key instead and never is.
+ */
+export const outstandingCapacityDetail = (used: number, limit: number): string => `outstanding=${used} limit=${limit}`;
+const OUTSTANDING_DETAIL = /^outstanding=(\d+) limit=(\d+)$/;
+export function isWriteCapacityWait(error: unknown): error is OperationError {
+ return error instanceof OperationError && error.code === 'queue_capacity' && OUTSTANDING_DETAIL.test(error.detail ?? '');
+}
+/** The counts a write-capacity wait carries: how many requests are outstanding against which cap, and whose cap it is. */
+export function outstandingCapacityOf(error: OperationError): { outstanding: number | null; limit: number | null; scope: 'principal' | 'brain' | null } {
+ const match = OUTSTANDING_DETAIL.exec(error.detail ?? '');
+ const scope = /\bbrain outstanding\b/.test(error.message) ? 'brain' : /\bprincipal outstanding\b/.test(error.message) ? 'principal' : null;
+ return { outstanding: match ? Number(match[1]) : null, limit: match ? Number(match[2]) : null, scope };
+}
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index f609b67f1e..57b6ac2898 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -8,7 +8,7 @@ import type { Action } from '../agent-output.ts';
import { digest, jsonBytes, requireUuid } from './digest.ts';
import { authorizeWrite } from './authority.ts';
import { journalLimitKey, oneYearCapacity, readJournalLimits, readReceiptRetentionDays } from './limits.ts';
-import { retryWriteAdmission } from './admission-retry.ts';
+import { outstandingCapacityDetail, retryWriteAdmission } from './admission-retry.ts';
import { PreadmitBrainChanged } from './preadmit-cache.ts';
import { pipelined } from '../page-state/transactions.ts';
import { writeHealth, type WriteHealthFacts } from './health.ts';
@@ -61,9 +61,16 @@ function ownerStatusFix(sourceId: string): Action {
}
const lifecycleIdConflict = (requestId: string) => opError('idempotency_conflict', 'This request_id belongs to a source lifecycle operation.',
`Request ID ${requestId} is already recorded for a source lifecycle change of this CLI writer, so this page write was not admitted and nothing changed. Submit the page write with a new request_id.`);
-export function capacityError(resource: string): OperationError {
- return new OperationError('queue_capacity', `Write capacity exhausted: ${resource}.`,
+/**
+ * `outstanding` (#6278): the outstanding-request cap carries its counts on `detail`
+ * (`outstandingCapacityDetail`), so a caller that can wait for the other
+ * requests to settle (the managed drain) knows how many stand in its way.
+ */
+export function capacityError(resource: string, outstanding?: { used: number; limit: number }): OperationError {
+ const error = new OperationError('queue_capacity', `Write capacity exhausted: ${resource}.`,
'Inspect writer status and configured persistence limits. Existing requests retain their reserved completion space.');
+ if (outstanding) error.detail = outstandingCapacityDetail(outstanding.used, outstanding.limit);
+ return error;
}
/** Cumulative caps name their config key and a value that covers one more year at the current admission rate. */
async function cumulativeCapacityError(tx: SqlEngine, resource: string, scope: string, setting: keyof JournalLimits, used: number, limit: number): Promise<OperationError> {
@@ -196,7 +203,8 @@ async function prepareAdmission(engine: BrainEngine, input: WriteAdmission, over
if (input.targetKind === 'skill_bundle') await assertSharedSkillPersistence(tx, input.sourceId);
for (const row of counters) {
const brain = row.key === 'brain';
- if (Number(row.outstanding_count) + 1 > (brain ? limits.brainOutstanding : limits.principalOutstanding)) throw capacityError(`${brain ? 'brain' : 'principal'} outstanding requests`);
+ const outstandingLimit = brain ? limits.brainOutstanding : limits.principalOutstanding;
+ if (Number(row.outstanding_count) + 1 > outstandingLimit) throw capacityError(`${brain ? 'brain' : 'principal'} outstanding requests`, { used: Number(row.outstanding_count), limit: outstandingLimit });
if (Number(row.intent_bytes) + bytes > (brain ? limits.brainIntentBytes : limits.principalIntentBytes)) throw capacityError(`${brain ? 'brain' : 'principal'} intent bytes`);
const scope = brain ? 'brain' : 'principal';
if (Number(row.lifetime_ids) + 1 > limits[`${scope}LifetimeIds`]) throw await cumulativeCapacityError(tx, `${scope} permanent request IDs`,
@@ -275,7 +283,8 @@ export async function admitWriteGroupInTransaction(tx: BrainEngine, inputs: Writ
const bytes = fresh.reduce((sum, item) => sum + item.bytes, 0), terminalBytes = fresh.reduce((sum, item) => sum + item.terminalBytes, 0);
for (const row of counters) {
const brain = row.key === 'brain', scope = brain ? 'brain' : 'principal';
- if (Number(row.outstanding_count) + fresh.length > (brain ? limits.brainOutstanding : limits.principalOutstanding)) throw capacityError(`${scope} outstanding requests`);
+ const outstandingLimit = brain ? limits.brainOutstanding : limits.principalOutstanding;
+ if (Number(row.outstanding_count) + fresh.length > outstandingLimit) throw capacityError(`${scope} outstanding requests`, { used: Number(row.outstanding_count), limit: outstandingLimit });
if (Number(row.intent_bytes) + bytes > (brain ? limits.brainIntentBytes : limits.principalIntentBytes)) throw capacityError(`${scope} intent bytes`);
if (Number(row.lifetime_ids) + fresh.length > limits[`${scope}LifetimeIds`]) throw await cumulativeCapacityError(tx, `${scope} permanent request IDs`,
row.key, `${scope}LifetimeIds`, Number(row.lifetime_ids), limits[`${scope}LifetimeIds`]);
diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.ts
index f1d2ebbde4..13ec5b41ce 100644
--- a/src/core/persistence/sync-discovery.ts
+++ b/src/core/persistence/sync-discovery.ts
@@ -43,7 +43,7 @@ export interface SyncDiscovery { binding: WorktreeBinding; root: string; gitRoot
discoveredAt?: string;
/** #5988: held paths that left the source (now excluded); their holds clear when the run checkpoints. */
releasedHolds?: string[];
- /** #5988: `sources retry-held` paths this discovery took into its manifest. */
+ /** #5988: `sources retry-held` paths this discovery consumed (screened as an entry or a candidate, or no longer eligible); cleared with the cursor save. */
retryTaken?: string[]; }
export interface ManagedSyncContext { binding: WorktreeBinding; root: string; gitRoot: string; sourceId: string; incarnation: string;
source: { last_commit: string | null; config: Record<string, unknown> }; }
@@ -269,7 +269,9 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
for (const path of dirty.deleted) put(path, 'delete', true);
for (const rename of dirty.renamed) putRename(rename, true);
}
- const released: string[] = [], retryTaken: string[] = [];
+ // #6278 (B7): every scheduled path is consumed by this discovery: it is screened as an entry (the file changed in Git),
+ // re-screened as a candidate below, or can never be screened (no longer eligible), so none may outlive the run.
+ const released: string[] = [], retryTaken = [...retry];
if (holds.length || retry.size) {
const candidates = [...new Set([...holds.map(hold => hold.path), ...retry])].filter(path => !entries.has(toGitPath(path)));
for (const path of candidates.filter(path => holdByPath.has(path) && !eligible(toGitPath(path)))) released.push(path);
@@ -295,7 +297,6 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
changed = hold!.meta.deleted ? !!blob : !blob || (hold!.meta.blob_oid ? blob.oid !== hold!.meta.blob_oid : sha256(contents.get(blob.oid) ?? '') !== hold!.upstream_version);
}
if (!changed) continue;
- if (retry.has(path)) retryTaken.push(path);
put(gitPath, present ? 'import' : 'delete', workingHold);
}
}
diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.ts
index f8b2fee1df..29345b8260 100644
--- a/src/core/persistence/sync-drain.ts
+++ b/src/core/persistence/sync-drain.ts
@@ -21,6 +21,7 @@ import { currentRunDeadline, noteForwardProgress } from '../forward-progress.ts'
import { serr } from '../console-prefix.ts';
import { ERROR_CATALOGUE, type CatalogueName } from '../error-catalogue.ts';
import { managedSyncResumeArgs, syncResumeCommand } from '../sync-reconcile.ts';
+import { isWriteCapacityWait, outstandingCapacityOf } from './admission-retry.ts';
export type DrainOutcome = 'synced' | 'resumable' | 'blocked';
/** Why a drain ended short of `synced`. Each value has an error-catalogue entry (DX-A4). */
@@ -29,7 +30,11 @@ export type DrainStopReason = 'deadline' | 'drain_stalled' | 'database_contentio
/** #6278: a preparation this process owned outran its budget and allowance; exiting ended it, the same command resumes and the next pass holds the entry if it stalls again. */
| 'preparation_abandoned'
/** #6278: the run's breaker tripped on `preparation_stalled` receipts (one systemic diagnostic instead of a pile of holds). */
- | 'preparation_systemic';
+ | 'preparation_systemic'
+ /** #6278 (B7): the sync's next admission was refused for the whole no-progress window because other requests held the writer's outstanding-request cap. */
+ | 'write_capacity';
+/** #6278 (B7): what the drain waited on when `write_capacity` stopped it: the counts the last refusal carried and how long it waited. */
+export interface DrainCapacityWait { outstanding: number | null; limit: number | null; scope: 'principal' | 'brain' | null; waited_seconds: number }
/** #6278: what a stalled head's live claim says it is doing (`claim_phase`, stamped by its owner on every renewal). */
export interface DrainClaim {
phase: 'preparing' | 'publishing' | null;
@@ -75,6 +80,7 @@ export interface DrainReport {
eta_seconds: number | null;
retry_after_ms?: number;
stall?: DrainStall;
+ capacity?: DrainCapacityWait;
/** DX-A5: whether pages were published in bulk groups, and why not when they were not. */
bulk?: { enabled: boolean; reason: string | null; groups: number; grouped_pages: number; largest_group: number;
/** #5984 admit-ahead: groups admitted while the previous group was still publishing. */
@@ -100,6 +106,12 @@ const STALL_PASSES = 3;
export const STALL_GRACE_MS = 30_000;
const SYNC_PREPARATION_DEFAULT_MS = 120_000, MAINTENANCE_PREPARATION_DEFAULT_MS = 120_000, PREPARATION_CEILING_DEFAULT_MS = 600_000;
const TRANSIENT_ATTEMPTS = 3;
+/** #6278 (B7): the longest pause between admission retries while other requests hold the writer's outstanding cap. */
+const CAPACITY_RETRY_MAX_MS = 5_000;
+/** #6278 (B7): the page counts of a run a drain finished before yielding for the next one. */
+type RunCounts = Pick<SyncResult, 'added' | 'modified' | 'deleted' | 'renamed' | 'chunksCreated'>;
+/** The result a drain reports when every pass was refused before it could read its cursor. */
+const NO_PASS_RESULT: SyncResult = { status: 'partial', reason: 'writer_pending', fromCommit: null, toCommit: '', added: 0, modified: 0, deleted: 0, renamed: 0, chunksCreated: 0, embedded: 0, pagesAffected: [] };
const REFRESH_WAIT_MS = 5 * 60_000;
const DEADLINE_MARGIN_MS = 15_000;
const PROGRESS_EVERY_MS = 10_000;
@@ -219,6 +231,10 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
let lanes: { effective: number; stepDown: string | null; overlapped: number; fallbacks: number } | null = null;
let stall: { key: string; since: number; passes: number; claim: DrainClaim | null; stallInfo: Omit<DrainStall, 'stalled_seconds'> } | null = null;
let lastCommitAt = startedAt, inPass = false, readingHead = false;
+ // #6278 (B7): a pass refused for write capacity keeps the last pass's result for the report; `capacity` spans the refusals since the last pass that ran.
+ let last: SyncResult | undefined, capacity: { since: number; attempts: number } | null = null;
+ // #6278 (B7): a pass may finish one run and yield for the next (re-screens scheduled while it ran); the counts of finished runs carry into the report.
+ let carried: RunCounts | null = null;
const remaining = () => total === null ? null : Math.max(0, total - index);
const every = input.progressMs ?? PROGRESS_EVERY_MS;
// #6278: the progress line prints on commits; while nothing commits, a timer names the stall instead of an ETA that assumes none.
@@ -269,6 +285,8 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
if (result.managedCursor) { index = result.managedCursor.index; total = result.managedCursor.total; }
const left = outcome === 'synced' ? 0 : remaining();
if (stopReason === 'deadline' && continues(result)) result = { ...result, reason: 'timeout' };
+ if (carried) result = { ...result, added: result.added + carried.added, modified: result.modified + carried.modified, deleted: result.deleted + carried.deleted,
+ renamed: result.renamed + carried.renamed, chunksCreated: result.chunksCreated + carried.chunksCreated };
return { ...result, drain: { outcome, ...(stopReason ? { stop_reason: stopReason } : {}), passes, processed: written + waived, written, waived,
remaining: left, ...drainEstimate(left, written + waived, Date.now() - startedAt),
...(input.bulk ? { bulk: { enabled: input.bulk.enabled, reason: input.bulk.reason, groups, grouped_pages: groupedPages, largest_group: largestGroup, admitted_ahead: admittedAhead,
@@ -282,8 +300,27 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
try {
inPass = true;
try { result = await input.pass(signal, onProgress); } finally { inPass = false; }
- attempt = 0;
+ attempt = 0; capacity = null;
+ if (last?.runId && result.runId && result.runId !== last.runId) {
+ const sum: RunCounts = carried ?? { added: 0, modified: 0, deleted: 0, renamed: 0, chunksCreated: 0 };
+ carried = { added: sum.added + last.added, modified: sum.modified + last.modified, deleted: sum.deleted + last.deleted, renamed: sum.renamed + last.renamed, chunksCreated: sum.chunksCreated + last.chunksCreated };
+ }
+ last = result;
} catch (error) {
+ // #6278 (B7): other requests (another writer on the same principal, or the brain) hold the outstanding-request cap, so the pass
+ // could not admit its next write. They settle on their own: wait with backoff, say so, and past the no-progress window stop
+ // `blocked` with the counts and the writer to inspect, never an uncaught exit without a drain summary.
+ if (isWriteCapacityWait(error) && !signal?.aborted) {
+ capacity ??= { since: Date.now(), attempts: 0 };
+ const counts = outstandingCapacityOf(error), waitedMs = Date.now() - capacity.since;
+ if (waitedMs >= (input.stallMs ?? STALL_MS)) return finish(last ?? NO_PASS_RESULT, 'blocked', 'write_capacity', { capacity: { ...counts, waited_seconds: Math.round(waitedMs / 1000) } });
+ if (input.announce && Date.now() - lastLine >= every) {
+ lastLine = Date.now();
+ serr(`[sync] ${index}/${total ?? '?'} processed · waiting for write capacity (${counts.outstanding ?? '?'} outstanding${counts.limit === null ? '' : ` of ${counts.limit}`})`);
+ }
+ await sleep(Math.min(CAPACITY_RETRY_MAX_MS, (input.backoffMs ?? 250) * 2 ** capacity.attempts++), signal);
+ continue;
+ }
const delay = transientDelay(error, ++attempt, refreshWaitedMs, input.backoffMs ?? 250);
if (delay === null || signal?.aborted) throw error;
if (error instanceof OperationError && (error.code === 'worktree_refreshing' || error.detail === 'database_contention')) refreshWaitedMs += delay;
@@ -499,7 +536,7 @@ const STOP_DOCS: Record<DrainStopReason, CatalogueName> = {
deadline: 'sync_drain_deadline', drain_stalled: 'sync_drain_stalled', database_contention: 'sync_drain_database_contention',
recovery_required: 'sync_drain_writer_blocked', owner_unavailable: 'sync_drain_writer_blocked', unexpected_file_bytes: 'sync_drain_writer_blocked',
unexpected_staging_bytes: 'sync_drain_writer_blocked', blocked_by_failures: 'sync_drain_blocked_by_failures',
- preparation_abandoned: 'sync_drain_preparation_abandoned', preparation_systemic: 'sync_drain_preparation_systemic',
+ preparation_abandoned: 'sync_drain_preparation_abandoned', preparation_systemic: 'sync_drain_preparation_systemic', write_capacity: 'sync_drain_write_capacity',
};
/** What the agent runs next, or null when the sync is done (DX-A2). */
@@ -525,6 +562,15 @@ export function drainNext(result: SyncResult, resumeCommand: string, sourceId: s
+ `is the likely cause. Inspect it (read-only), fix what it names or upgrade gbrain, then rerun: ${resumeCommand} (it re-freezes the stopped entry and re-screens the files this run held).`,
...(docs ? { docs } : {}) };
}
+ if (d?.stop_reason === 'write_capacity') {
+ const c = d.capacity, scope = c?.scope ?? 'principal';
+ const key = scope === 'brain' ? 'persistence.limits.brain_outstanding' : 'persistence.limits.principal_outstanding';
+ return { command: `gbrain sources writer status --source ${sourceId} --json`, safe_to_loop: false, retry_after_ms: 0, ...estimate,
+ why: `The sync could not admit its next write for ${c?.waited_seconds ?? 30}s: ${c?.outstanding ?? 'other'} of the ${scope === 'brain' ? "brain's" : "write principal's"} ${c?.limit ?? ''} outstanding-request slots `
+ + 'were in use, most of them by another writer on this host (a maintenance run shares the CLI principal), so there was no room for a sync write. Nothing failed and the cursor is intact. '
+ + `Inspect them (read-only) and let them finish, or raise ${key}, then rerun: ${resumeCommand}`,
+ ...(docs ? { docs } : {}) };
+ }
if (d?.stop_reason === 'database_contention') {
const wait = result.writeWait?.status === 'read_failed' ? result.writeWait : null;
return { command: resumeCommand, safe_to_loop: false, retry_after_ms: 0, ...estimate,
@@ -561,6 +607,7 @@ export function formatDrainSummary(result: SyncResult, resumeCommand: string, so
const lines = [`Managed sync ${d.outcome}: ${d.processed} entries this run (${d.written} written, ${d.waived} waived)`
+ (d.remaining ? `, ${d.remaining} remaining` : '') + (d.rate_pages_per_min !== null ? `, ${d.rate_pages_per_min} pages/min` : '')
+ (d.remaining && d.eta_seconds !== null ? `, indexing ETA ${formatDuration(d.eta_seconds)}` : '') + '.'];
+ if (d.capacity) lines.push(` Waited ${d.capacity.waited_seconds}s for write capacity: ${d.capacity.outstanding ?? '?'} of ${d.capacity.limit ?? '?'} ${d.capacity.scope ?? 'principal'} outstanding-request slots in use.`);
if (d.stall) lines.push(` Oldest unfinished request ${d.stall.head_request_id ?? d.stall.request_id} (${d.stall.head_state ?? d.stall.state})`
+ `${d.stall.blocked_reason ? `, blocked_reason=${d.stall.blocked_reason}` : ''}${d.stall.step ? `, step=${d.stall.step}` : ''}${d.stall.waiting_on ? `, waiting_on=${d.stall.waiting_on}` : ''}`
+ `${d.stall.cause ? `, cause=${d.stall.cause}` : ''}; claimable here: ${d.stall.claimable_here ? 'yes' : 'no'}.`);
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 446762c9c1..b780c15c7c 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -10,7 +10,7 @@ import { throwIfAborted } from '../abort-check.ts';
import { digest, sha256 } from './digest.ts';
import { getWriteRequest, admitWriteInTransaction, foregroundPriority, intentDigest, receiptFor } from './journal.ts';
import { preparationConfigView } from './config-snapshot.ts';
-import { retryWriteAdmission } from './admission-retry.ts';
+import { isWriteCapacityWait, retryWriteAdmission } from './admission-retry.ts';
import { assertPersistenceAccepting, awaitWrite, foregroundWriteCompletions, startPersistenceConsumer, type WriteWait } from './service.ts';
import { assertSyncEntryOrigin, discoverManagedSync, resolveManagedSyncContext, readSyncContent, readSyncFile, syncGit, type SyncDiscovery } from './sync-discovery.ts';
import { isImageFilePath } from '../sync.ts';
@@ -48,7 +48,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, readGitSourceHolds, readSyncHoldPolicy, recordSyncConversion, recoveredReport, requestGitHoldRetry, writeGitHold, type FencesTally, type SyncHoldPolicy } from './sync-holds.ts';
+import { addFencesNormalized, addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, heldGitPaths, fencesNormalizedReport, holdsEscalated, readGitHoldRetryPaths, readGitSourceHolds, readSyncHoldPolicy, recordSyncConversion, recoveredReport, requestGitHoldRetry, writeGitHold, type FencesTally, type SyncHoldPolicy } from './sync-holds.ts';
export interface ManagedSyncWriteDiagnostic {
source_id: string;
@@ -206,7 +206,9 @@ async function writeCursor(tx: BrainEngine, key: string, before: Cursor | null,
if (before === null) {
if (synchronous) await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");
await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb) ON CONFLICT DO NOTHING`, [`${OP}-manifest`, next.runId, JSON.stringify(next.entries)]);
- await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb) ON CONFLICT DO NOTHING`, [OP, key, JSON.stringify([header(next)])]);
+ const inserted = await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb) ON CONFLICT DO NOTHING RETURNING fingerprint`, [OP, key, JSON.stringify([header(next)])]);
+ // #6278 (B7): what rides a fresh cursor's save (the retry schedule it consumed) commits only with the insert that won.
+ if (inserted.length) await inTx?.(tx);
} else {
// #5984: the settings, the compare-and-swap and the manifest touch go out together; a won swap is the saved cursor.
const [, saved] = await pipelined(tx, [
@@ -265,8 +267,10 @@ async function replaceCursor(engine: BrainEngine, key: string, before: CursorHea
return current;
}
await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb)`, [`${OP}-manifest`, next.runId, JSON.stringify(next.entries)]);
- await tx.executeRaw('UPDATE op_checkpoints SET completed_keys=$4::text::jsonb,updated_at=now() WHERE op=$1 AND fingerprint=$2 AND completed_keys=$3::text::jsonb',
+ const swapped = await tx.executeRaw('UPDATE op_checkpoints SET completed_keys=$4::text::jsonb,updated_at=now() WHERE op=$1 AND fingerprint=$2 AND completed_keys=$3::text::jsonb RETURNING fingerprint',
[OP, key, JSON.stringify([before]), JSON.stringify([header(next)])]);
+ // #6278 (B7): the re-screens the replacing manifest took are consumed with the swap that records them.
+ if (swapped.length && next.retryTaken?.length) await clearGitHoldRetryPaths(tx, next.sourceId, next.incarnation, next.retryTaken);
const current = (await readCursor(tx, key, next))!;
assertActive();
return current;
@@ -1038,6 +1042,20 @@ async function cursorMovedAdmission(engine: BrainEngine, key: string, admitting:
throw error;
}
+/**
+ * The result of a committed checkpoint. #6278 (B7): `sources retry-held` schedules re-screens that only discovery honours,
+ * and a cursor discovered before them (a backlog the retry was scheduled against, or a run the retry overlapped) never sees
+ * them, so the pass yields (`writer_yield`, as at a slice boundary) and the drain's next pass retires the finished cursor and
+ * discovers again, taking them; a single-pass caller re-enters the same way.
+ */
+async function finishCheckpoint(engine: BrainEngine, key: string, cursor: Cursor, company: boolean, assertActive: () => void): Promise<SyncResult> {
+ await clearManagedSyncFailureAfterSuccess(engine, key);
+ if (cursor.counts.added + cursor.counts.modified + cursor.counts.deleted > 0) await refreshProjectionStatistics(engine);
+ assertActive();
+ const scheduled = company ? [] : await readGitHoldRetryPaths(engine, cursor.sourceId, cursor.incarnation);
+ assertActive();
+ return scheduled.length ? result(cursor, 'partial', 'writer_yield') : result(cursor, cursor.from === null ? 'first_sync' : 'synced');
+}
/** A finished cursor is deleted (compare-and-swap) before the next run discovers; returns whichever cursor replaced it. */
async function retireCompletedCursor(engine: BrainEngine, key: string, completed: Cursor, assertActive: () => void): Promise<Cursor | null> {
await engine.transaction(async tx => {
@@ -1206,8 +1224,9 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
}
if (company) await company.protect([{ op: OP, fingerprint: key, kind: 'managed_cursor' }, { op: `${OP}-manifest`, fingerprint: fresh.runId, kind: 'manifest' }]);
assertActive();
- cursor = await saveCursor(engine, key, null, fresh, false, assertActive);
- if (fresh.retryTaken?.length) await clearGitHoldRetryPaths(engine, fresh.sourceId, fresh.incarnation, fresh.retryTaken);
+ // #6278 (B7): the re-screens this manifest took are consumed by the save that records them (a kill between the two loses nothing).
+ cursor = await saveCursor(engine, key, null, fresh, false, assertActive,
+ fresh.retryTaken?.length ? tx => clearGitHoldRetryPaths(tx, fresh.sourceId, fresh.incarnation, fresh.retryTaken!) : undefined);
}
assertActive();
if (cursor.incarnation !== context.incarnation || cursor.binding.worktree_id !== context.binding.worktree_id ||
@@ -1340,10 +1359,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
if (!cursor?.done) throw syncRunRefusal('storage_error', 'Committed sync checkpoint lost its cursor.',
{ sourceId: context.sourceId, processingOptions: pending.intent.processingOptions, syncOptions: pending.intent.syncOptions ?? syncOptions, repoPath: pending.intent.repoPath ?? frozenRun.repoPath },
`The final checkpoint request ${pending.requestId} of this sync committed, but its cursor could not be read back to finish the run.`);
- await clearManagedSyncFailureAfterSuccess(engine, key);
- if (cursor.counts.added + cursor.counts.modified + cursor.counts.deleted > 0) await refreshProjectionStatistics(engine);
- assertActive();
- return withLinks(cursor, result(cursor, cursor.from === null ? 'first_sync' : 'synced'));
+ return withLinks(cursor, await finishCheckpoint(engine, key, cursor, !!company, assertActive));
}
// The frozen manifest is shared; only the cursor header changes per page.
const next: Cursor = { ...cursor, ...committedBreaker(cursor), index: cursor.index + 1, counts: { ...cursor.counts }, progress: stampProgress(cursor.progress, cursor.index, cursor.index + 1, drainStartedAt) }; delete next.pending; delete next.group;
@@ -1374,8 +1390,9 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
}
if (!opts.dryRun) {
const code = error instanceof OperationError ? error.code : 'storage_error';
- // A refresh fence is transient admission back-pressure, not a sync failure to record.
- if (!['permission_denied', 'worktree_refreshing', 'refresh_recovery_required'].includes(code)) {
+ // A refresh fence, or an admission refused while other requests hold the writer's outstanding cap (#6278: the drain
+ // waits for them), is transient admission back-pressure, not a sync failure to record.
+ if (!['permission_denied', 'worktree_refreshing', 'refresh_recovery_required'].includes(code) && !isWriteCapacityWait(error)) {
const [stored] = cursor ? [] : await engine.executeRaw<{ completed_keys: [CursorHeader] }>('SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [OP, key]);
const failedCursor = cursor ?? stored?.completed_keys?.[0];
const { failure } = await recordManagedSyncFailure(engine, { source_id: context.sourceId, source_incarnation: context.incarnation, path: cursor?.entries[cursor.index]?.path ?? failedCursor?.pending?.intent.path ?? `<${phase}>`, code,
diff --git a/test/managed-sync-preparation-stalled-holds.test.ts b/test/managed-sync-preparation-stalled-holds.test.ts
index 5d9465d698..a78c0b4545 100644
--- a/test/managed-sync-preparation-stalled-holds.test.ts
+++ b/test/managed-sync-preparation-stalled-holds.test.ts
@@ -25,7 +25,8 @@ import { claimWorktree } from '../src/core/persistence/ownership.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { performManagedSync } from '../src/core/persistence/sync-run.ts';
import { installFaultHook, type FaultPoint } from '../src/core/persistence/fault-points.ts';
-import { readGitSourceHolds, holdRescreenDue, GIT_HOLD_SUMMARY_OP } from '../src/core/persistence/sync-holds.ts';
+import { readGitSourceHolds, holdRescreenDue, readGitHoldRetryPaths, GIT_HOLD_SUMMARY_OP } from '../src/core/persistence/sync-holds.ts';
+import { drainManagedSync, readManagedSyncBacklog } from '../src/core/persistence/sync-drain.ts';
import { preparationStallMeta } from '../src/core/persistence/sync-screen.ts';
import { readHeldCoverage, coverageRoute } from '../src/core/persistence/held-reads.ts';
import { retryHeld } from '../src/commands/sources-retry-held.ts';
@@ -306,6 +307,100 @@ test('bulk groups: a stalled first, middle or last member is held, the committed
}
}), 300_000);
+// ── #6278 (B7): retry-held against a backlog ──
+
+/** The committed import request for `path`, with the attempt counter the owner left on it. */
+const committedAttempts = async (engine: BrainEngine, sourceId: string, path: string) => (await engine.executeRaw<{ n: number }>(
+ "SELECT preparation_attempts::int AS n FROM persistence_requests WHERE source_id=$1 AND intent->>'path'=$2 AND state='committed' ORDER BY sequence DESC LIMIT 1", [sourceId, path]))[0]?.n;
+
+test('retry-held against an unfinished cursor: the printed sync finishes the backlog and re-screens the scheduled file in the same drain (Phase 4.1b)', () => each(async engine => {
+ const s = await source(engine, { 'notes/a.md': note('A'), 'notes/stuck.md': note('Stuck'), 'notes/z1.md': note('Z1'), 'notes/z2.md': note('Z2'), 'notes/z3.md': note('Z3') });
+ stallPaths(engine, s.id, new Set(['notes/stuck.md']));
+ // A sliced pass holds the stalled entry and yields with entries left: the cursor is a backlog, as after the lock run's queue_capacity exit.
+ const sliced = await performManagedSync(engine, { sourceId: s.id, noPull: true, noEmbed: true, noExtract: true }, { maxPages: 2, maxMs: 60_000 });
+ expect(sliced).toMatchObject({ status: 'partial', reason: 'writer_yield', held_count: 1 });
+ expect(sliced.managedCursor!.index).toBeLessThan(5);
+ const [failed] = await s.failedRequests();
+ expect(failed).toMatchObject({ error_code: 'preparation_stalled', path: 'notes/stuck.md' });
+ const [backlog] = await readManagedSyncBacklog(engine, [s.id]);
+ expect(backlog!.remaining).toBeGreaterThan(0);
+ // The cause is gone; the operator follows the route: retry-held prints the backlog's own resume command.
+ installFaultHook(undefined);
+ const retry = await retryHeld(engine, s.id);
+ expect(retry).toMatchObject({ scheduled: 1, items: [{ key: 'notes/stuck.md', code: 'preparation_stalled', action: 'retry_scheduled' }] });
+ expect(retry.fix!.argv).toEqual(['gbrain', 'sync', ...backlog!.resume_args]);
+ expect(await readGitHoldRetryPaths(engine, s.id, await s.incarnation())).toEqual(['notes/stuck.md']);
+ // The printed sync, drained as the CLI drains it: the backlog finishes, then the scheduled re-screen runs before the drain reports synced.
+ const drained = await drainManagedSync(engine, { sourceId: s.id, noPull: true, noEmbed: true, noExtract: true }, false);
+ expect(drained.drain).toMatchObject({ outcome: 'synced', remaining: 0 });
+ expect(drained.drain!.passes).toBeGreaterThanOrEqual(2);
+ // The report covers both runs: the backlog cursor's four pages (two from the sliced pass) plus the re-screened one; the drain itself wrote three.
+ expect(drained).toMatchObject({ status: 'synced', added: 5, modified: 0 });
+ expect(drained.drain!.written).toBe(5 - sliced.added);
+ expect(drained.holds_outstanding ?? 0).toBe(0);
+ expect(await engine.getPage('notes/stuck', { sourceId: s.id })).not.toBeNull();
+ for (const slug of ['notes/a', 'notes/z1', 'notes/z2', 'notes/z3']) expect(await engine.getPage(slug, { sourceId: s.id })).not.toBeNull();
+ expect(await s.holds()).toEqual([]);
+ expect(await s.summary()).toMatchObject({ count: 0, stalled: 0 });
+ expect(await committedAttempts(engine, s.id, 'notes/stuck.md')).toBe(0);
+ expect(await readGitHoldRetryPaths(engine, s.id, await s.incarnation())).toEqual([]);
+ expect(await s.failedRequests()).toHaveLength(1);
+ expect(await s.ledger()).toEqual([]);
+ expect(await s.sync()).toMatchObject({ status: 'up_to_date' });
+}), 240_000);
+
+test('retry-held while the stall persists: the file is re-held once under the new receipt, counted once, with one hold row', () => each(async engine => {
+ const s = await source(engine, { 'notes/a.md': note('A'), 'notes/stuck.md': note('Stuck') });
+ stallPaths(engine, s.id, new Set(['notes/stuck.md']));
+ expect(await s.sync()).toMatchObject({ status: 'first_sync', added: 1, held_count: 1 });
+ const [first] = await s.failedRequests();
+ await retryHeld(engine, s.id);
+ const rescreened = await s.sync();
+ expect(rescreened).toMatchObject({ status: 'synced', added: 0, held_count: 1, holds_outstanding: 1 });
+ const failed = await s.failedRequests();
+ expect(failed).toHaveLength(2);
+ expect(failed.map(row => row.error_code)).toEqual(['preparation_stalled', 'preparation_stalled']);
+ const holds = await s.holds();
+ expect(holds).toHaveLength(1);
+ expect(holds[0]).toMatchObject({ path: 'notes/stuck.md', code: 'preparation_stalled', meta: { stall: { request_id: failed[1]!.request_id } } });
+ expect(holds[0]!.meta.stall!.request_id).not.toBe(first!.request_id);
+ expect(await s.summary()).toMatchObject({ count: 1, stalled: 1 });
+ expect(await readGitHoldRetryPaths(engine, s.id, await s.incarnation())).toEqual([]);
+ expect(await engine.getPage('notes/stuck', { sourceId: s.id })).toBeNull();
+ // It waits again: no third receipt without another retry.
+ expect(await s.sync()).toMatchObject({ status: 'up_to_date', holds_outstanding: 1 });
+ expect(await s.failedRequests()).toHaveLength(2);
+}), 180_000);
+
+test('a scheduled re-screen survives a run killed before it reached the file; a run killed after freezing it carries it in its manifest and leaves no stale schedule', () => each(async engine => {
+ const s = await source(engine, { 'notes/a.md': note('A'), 'notes/stuck.md': note('Stuck') });
+ stallPaths(engine, s.id, new Set(['notes/stuck.md']));
+ expect(await s.sync()).toMatchObject({ status: 'first_sync', held_count: 1 });
+ installFaultHook(undefined);
+ await retryHeld(engine, s.id);
+ const incarnation = await s.incarnation();
+ // Killed before discovery: the schedule is untouched.
+ const aborted = new AbortController(); aborted.abort();
+ expect((await s.sync({ signal: aborted.signal })).status).toBe('partial');
+ expect(await readGitHoldRetryPaths(engine, s.id, incarnation)).toEqual(['notes/stuck.md']);
+ // Killed right after the fresh cursor is saved: the manifest carries the entry and the schedule was consumed with the same save.
+ let killed = 0;
+ installFaultHook(async (point, detail) => { if (point === 'sync:mid_checkpoint' && detail.sourceId === s.id && killed++ === 0) throw new Error('injected kill after the cursor save'); });
+ await expect(s.sync()).rejects.toThrow('injected kill');
+ installFaultHook(undefined);
+ expect(killed).toBe(1);
+ const [cursor] = await engine.executeRaw<{ c: { entries?: Array<{ path: string }>; total: number; index: number } }>(
+ "SELECT completed_keys->0 AS c FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [s.id]);
+ expect(cursor!.c).toMatchObject({ total: 1, index: 0 });
+ expect(await readGitHoldRetryPaths(engine, s.id, incarnation)).toEqual([]);
+ // The next run resumes that cursor and imports the file; nothing is left scheduled, so the run after it has nothing to do.
+ expect(await s.sync()).toMatchObject({ status: 'synced', added: 1 });
+ expect(await engine.getPage('notes/stuck', { sourceId: s.id })).not.toBeNull();
+ expect(await s.holds()).toEqual([]);
+ expect(await readGitHoldRetryPaths(engine, s.id, incarnation)).toEqual([]);
+ expect(await s.sync()).toMatchObject({ status: 'up_to_date' });
+}), 180_000);
+
// ── #6278 (B2): the systemic breaker ──
test('breaker: five consecutive stalled entries with no commit between stop the run with one systemic diagnostic; the next run re-freezes and re-screens instead of holding', () => each(async engine => {
@@ -325,10 +420,11 @@ test('breaker: five consecutive stalled entries with no commit between stop the
"SELECT completed_keys->0 AS c FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [s.id]);
expect(cursor!.c).toMatchObject({ index: 4, pending: { intent: { path: 'notes/s4.md' } }, breaker: { streak: 5, tripped: { rule: 'consecutive' } } });
expect(cursor!.c.breaker.stalled).toHaveLength(5);
- // Cause fixed: the next run re-freezes the stopped entry under a fresh request (nothing held), finishes, and scheduled the run's four stalled holds for a re-screen.
+ // Cause fixed: the next run re-freezes the stopped entry under a fresh request (nothing held), finishes, and scheduled the run's four stalled holds
+ // for a re-screen. B7: that schedule is the same catch-up's work, so the pass yields (`writer_yield`) for the drain's next pass to discover and take it.
installFaultHook(undefined);
const resumed = await s.sync();
- expect(resumed).toMatchObject({ status: 'first_sync', added: 3 });
+ expect(resumed).toMatchObject({ status: 'partial', reason: 'writer_yield', added: 3, managedCursor: { index: 7, total: 7 } });
expect(resumed.converted_from_failed).toEqual([...cursor!.c.breaker.stalled]);
expect(await s.failedRequests()).toHaveLength(5);
expect(await engine.getPage('notes/s4', { sourceId: s.id })).not.toBeNull();
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 900f2e949c..045fa01810 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -103,6 +103,7 @@ test/shared-skills-writer-boundary.test.ts
test/source-retire-missing-checkout.test.ts
test/stats-health-source-scope.test.ts
test/sync-drain-claims.test.ts
+test/sync-drain-write-capacity.test.ts
test/sync-frontmatter-recovery.test.ts
test/sync-frontmatter-slug-conflict.test.ts
test/sync-group-member-order.test.ts
diff --git a/test/sync-drain-write-capacity.test.ts b/test/sync-drain-write-capacity.test.ts
new file mode 100644
index 0000000000..684335d4ab
--- /dev/null
+++ b/test/sync-drain-write-capacity.test.ts
@@ -0,0 +1,166 @@
+/**
+ * #6278 (B7, defect 2): a managed drain whose next admission is refused for
+ * write capacity (`queue_capacity`, the writer's outstanding-request cap held
+ * by another writer's queued requests on the same principal) waits instead of
+ * dying. Before this change the refusal escaped `performManagedSync`, the run
+ * recorded a managed-sync failure that named `--retry-failed`, and the CLI
+ * exited 1 with no drain summary and no `next` (the Phase 4.1b lock run). Now
+ * the drain retries with backoff while the other writer's requests settle,
+ * prints `waiting for write capacity (N outstanding)`, and after its
+ * no-progress window ends `blocked` / `write_capacity` with `next` naming
+ * writer status; a cumulative cap (permanent request IDs, receipt bytes) is
+ * still a refusal that needs a config change, never a wait. The forced probe
+ * fills the sync writer's own outstanding counter to the cap, so the pass is
+ * refused exactly where the bench died. Synthetic content only.
+ */
+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, 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 { OperationError } from '../src/core/ops/contract.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { capacityError } from '../src/core/persistence/journal.ts';
+import { isWriteCapacityWait } from '../src/core/persistence/admission-retry.ts';
+import { drainManagedSync, drainJsonFields, drainNext, formatDrainSummary, runDrain } from '../src/core/persistence/sync-drain.ts';
+import { ERROR_CATALOGUE } from '../src/core/error-catalogue.ts';
+import type { SyncResult } from '../src/commands/sync.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const base: SyncResult = { status: 'synced', fromCommit: 'a', toCommit: 'b', added: 0, modified: 0, deleted: 0, renamed: 0, chunksCreated: 0, embedded: 0, pagesAffected: [] };
+const RESUME = 'gbrain sync --source s --no-pull';
+const refused = () => capacityError('principal outstanding requests', { used: 99, limit: 100 });
+
+function captureStderr(): { lines: string[]; waiting: () => string[]; restore(): void } {
+ const lines: string[] = [];
+ const spy = spyOn(console, 'error').mockImplementation((...args: unknown[]) => { lines.push(args.map(String).join(' ')); });
+ return { lines, waiting: () => lines.filter(line => line.includes('waiting for write capacity')), restore: () => spy.mockRestore() };
+}
+const until = async (check: () => boolean, ms: number) => { const end = Date.now() + ms; while (!check() && Date.now() < end) await new Promise(r => setTimeout(r, 10)); return check(); };
+
+describe('write-capacity refusals at admission', () => {
+ test('the outstanding-request refusal carries its counts and is a wait; cumulative caps and other codes are not', () => {
+ const error = refused();
+ expect(error).toMatchObject({ code: 'queue_capacity', message: 'Write capacity exhausted: principal outstanding requests.', detail: 'outstanding=99 limit=100' });
+ expect(isWriteCapacityWait(error)).toBe(true);
+ expect(isWriteCapacityWait(capacityError('brain outstanding requests', { used: 1000, limit: 1000 }))).toBe(true);
+ expect(isWriteCapacityWait(capacityError('principal intent bytes'))).toBe(false);
+ const cumulative = new OperationError('queue_capacity', 'Write capacity exhausted: principal permanent request IDs (5 used of 5).', 'raise it');
+ cumulative.detail = 'principalLifetimeIds';
+ expect(isWriteCapacityWait(cumulative)).toBe(false);
+ expect(isWriteCapacityWait(new OperationError('storage_error', 'x', 'y'))).toBe(false);
+ expect(isWriteCapacityWait(new Error('queue_capacity'))).toBe(false);
+ });
+
+ test('a refused pass is retried with backoff until capacity returns, printing the wait; the drain then finishes synced', async () => {
+ let passes = 0;
+ const err = captureStderr();
+ try {
+ const result = await runDrain({ announce: true, progressMs: 20, backoffMs: 5, stallMs: 5000, pass: async () => { if (++passes <= 4) throw refused(); return { ...base, managedCursor: { index: 3, total: 3 } }; } });
+ expect(result.drain).toMatchObject({ outcome: 'synced', passes: 5 });
+ expect(result.drain!.stop_reason).toBeUndefined();
+ expect(err.waiting().length).toBeGreaterThanOrEqual(1);
+ expect(err.waiting()[0]).toMatch(/^\[sync\] \d+\/\? processed · waiting for write capacity \(99 outstanding of 100\)$/);
+ } finally { err.restore(); }
+ });
+
+ test('capacity still full after the no-progress window: blocked / write_capacity with the wait on the report, writer status as next, and docs', async () => {
+ let passes = 0;
+ const result = await runDrain({ backoffMs: 5, stallMs: 150, pass: async () => { passes++; throw refused(); } });
+ expect(passes).toBeGreaterThan(1);
+ expect(result.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'write_capacity', capacity: { outstanding: 99, limit: 100, scope: 'principal' } });
+ expect(result.drain!.capacity!.waited_seconds).toBeGreaterThanOrEqual(0);
+ const next = drainNext(result, RESUME, 's')!;
+ expect(next).toMatchObject({ command: 'gbrain sources writer status --source s --json', safe_to_loop: false, docs: ERROR_CATALOGUE.sync_drain_write_capacity.docs });
+ expect(next.why).toContain('99 of the write principal\'s 100 outstanding-request slots');
+ expect(next.why).toContain(RESUME);
+ expect(next.why).toContain('persistence.limits.principal_outstanding');
+ expect(ERROR_CATALOGUE.sync_drain_write_capacity).toEqual({ code: 'queue_capacity', docs: 'docs/guides/write-refusals.md#drain-write-capacity' });
+ expect(drainJsonFields(result, RESUME, 's')).toMatchObject({ outcome: 'blocked', next: { command: 'gbrain sources writer status --source s --json' } });
+ const summary = formatDrainSummary(result, RESUME, 's');
+ expect(summary[0]).toMatch(/^Managed sync blocked: 0 entries this run/);
+ expect(summary.join('\n')).toContain('Waited');
+ expect(summary.join('\n')).toContain('Next: gbrain sources writer status --source s --json');
+ });
+
+ test('a pass that succeeded before the refusal keeps its result on the blocked report; a cumulative cap still ends the drain with the error', async () => {
+ let passes = 0;
+ const pendingResult: SyncResult = { ...base, status: 'partial', reason: 'writer_yield', added: 7, managedCursor: { index: 7, total: 20 } };
+ const result = await runDrain({ backoffMs: 5, stallMs: 100, pass: async () => { if (++passes === 1) return pendingResult; throw refused(); } });
+ expect(result).toMatchObject({ added: 7, drain: { outcome: 'blocked', stop_reason: 'write_capacity', remaining: 13 } });
+ const cumulative = new OperationError('queue_capacity', 'Write capacity exhausted: principal permanent request IDs (5 used of 5).', 'raise it');
+ cumulative.detail = 'principalLifetimeIds';
+ await expect(runDrain({ backoffMs: 5, stallMs: 100, pass: async () => { throw cumulative; } })).rejects.toBe(cumulative);
+ });
+});
+
+describe('forced probe: a real managed sync refused for write capacity', () => {
+ const engines: BrainEngine[] = [];
+ let closePostgres: (() => Promise<void>) | undefined;
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-drain-capacity-'));
+ beforeAll(async () => {
+ if (testBackends().includes('pglite')) { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite); }
+ if (testBackends().includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }
+ }, 120_000);
+ afterAll(async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });
+ });
+
+ test('the cap held by other requests: the drain waits and prints, proceeds when they settle; held past the window it ends blocked with next, nothing in the failure ledger', () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
+ for (const engine of engines) {
+ const id = `cap-${randomUUID().replace(/-/g, '').slice(0, 20)}`, root = join(home, id);
+ const git = (...args: string[]) => execFileSync('git', ['-C', root, ...args], { stdio: ['ignore', 'pipe', 'pipe'] });
+ const write = (name: string) => writeFileSync(join(root, 'notes', `${name}.md`), `---\ntitle: ${name}\n---\nA synthetic observation about ${name}.\n`);
+ const commit = (message: string) => { git('add', '-A'); git('-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ git('init', '-q'); write('a'); commit('fixture');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);
+ await claimWorktree(engine, id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const opts = { sourceId: id, noPull: true, noEmbed: true, noExtract: true };
+ const ledger = () => engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND completed_keys::text LIKE $1", [`%${id}%`]);
+ const outstanding = (n: number) => engine.executeRaw("UPDATE persistence_counters SET outstanding_count=$1 WHERE key LIKE 'principal:local_cli:%'", [n]);
+ const err = captureStderr();
+ try {
+ // A first sync registers the writer's counter row.
+ expect((await drainManagedSync(engine, opts, false)).drain).toMatchObject({ outcome: 'synced', written: 1 });
+ const [principal] = await engine.executeRaw<{ key: string }>("SELECT key FROM persistence_counters WHERE key LIKE 'principal:local_cli:%'");
+ expect(principal).toBeDefined();
+ // Another writer on the same principal holds the whole cap (the bench: 89 queued adoption writes and one running against 100).
+ await engine.setConfig('persistence.limits.principal_outstanding', '4');
+ await outstanding(4);
+ write('b'); write('c'); commit('two more');
+ const drain = drainManagedSync(engine, { ...opts, drainStartedAt: Date.now() }, true);
+ expect(await until(() => err.waiting().length > 0, 20_000)).toBe(true);
+ expect(err.waiting()[0]).toMatch(/waiting for write capacity \(4 outstanding of 4\)$/);
+ // The other writer's requests settle: the same drain proceeds.
+ await outstanding(0);
+ const result = await drain;
+ expect(result.drain).toMatchObject({ outcome: 'synced', written: 2, remaining: 0 });
+ expect(result.drain!.passes).toBeGreaterThan(1);
+ expect(await engine.getPage('notes/c', { sourceId: id })).not.toBeNull();
+ expect(await ledger()).toEqual([]);
+ // Held past the window: one blocked stop with next, no uncaught error, no failure-ledger row, and the cursor intact for the rerun.
+ await outstanding(4);
+ write('d'); commit('one more');
+ const blocked = await runDrain({ announce: false, stallMs: 300, backoffMs: 10, pass: (signal, onProgress) => import('../src/core/persistence/sync-run.ts')
+ .then(m => m.performManagedSync(engine, { ...opts, signal, onProgress, drainStartedAt: Date.now() })) });
+ expect(blocked.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'write_capacity', capacity: { outstanding: 4, limit: 4, scope: 'principal' } });
+ expect(drainNext(blocked, `gbrain sync --source ${id} --no-pull`, id)!.command).toBe(`gbrain sources writer status --source ${id} --json`);
+ expect(await ledger()).toEqual([]);
+ expect(await engine.getPage('notes/d', { sourceId: id })).toBeNull();
+ await outstanding(0);
+ expect((await drainManagedSync(engine, opts, false)).drain).toMatchObject({ outcome: 'synced', written: 1 });
+ expect(await engine.getPage('notes/d', { sourceId: id })).not.toBeNull();
+ } finally { err.restore(); await engine.unsetConfig('persistence.limits.principal_outstanding'); await disposePersistenceConsumer(engine); }
+ }
+ }), 180_000);
+});