Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): re-run a write admission whose session dropped, give up a dead lane, and repair two driver reconnect defects
garrytan517e0179fbab
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fd3988158e..8e82804caf 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,42 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.60.123.0] - 2026-10-09++**A write whose database session drops during admission no longer hands the caller a false refusal: the admission is re-run against the retained request id, and a session that keeps dropping returns the typed `write_outcome_unknown`. Two reconnect defects in the vendored Postgres driver that the same fault reached are fixed with it.**++The crash robot (`pooler_disconnect`, seed 5105, master run 37872222822) caught an `edit_page` caller receiving the raw `write CONNECTION_CLOSED` from a dropped session while its admitted request went on to commit: the receipt the caller held said refused, the page held the write (`untrue_receipt`, `lost_write`). `retryWriteAdmission` was right not to retry an admission on a lost socket, since a second INSERT could double-apply, but the safe step was missing: every admission attempt begins by reading the retained `request_id` and replays an admitted row, so re-running the attempt is a read, never a second admission. Pre-existing (the same shape replays on the commit before #6347); found by the robot's seed, fixed here.++### How to use it++Nothing to configure. A single drop resolves by itself (re-runs after 100, 300 and 900 ms). When the session keeps dropping the caller sees:++```bash+gbrain errors write_outcome_unknown # the new code, offline+gbrain write-request -- <request_id> # the fix it names: a committed or pending row means accepted (replay the same id); no row means not (submit again with the same id)+```++### What you see++| Where | What changed |+|---|---|+| A write whose session drops under admission | Re-run after 100, 300 and 900 ms; the re-run replays the admitted row when the lost acknowledgment had committed, admits when it had not. |+| A session that keeps dropping | `write_outcome_unknown` (`reason: connection_lost`, `detail` the socket error without URLs, `fix` the read of the request by id, `write_error` on the receipt) instead of the raw `CONNECTION_CLOSED` / `57P01`. |+| A write admitted on this process's warm lane (the consumer's reserved backend) whose session dropped | The re-run takes a transaction from the engine's pool instead of the dead reservation, and the consumer gives the lane up at once (retaken after a minute) whatever the admission makes of the loss. Before, every re-run and the next write hit "Connection is no longer owned" on the same reservation. |+| A backend terminated while the driver is still starting its connection (during the driver's own array-types fetch) | The fresh connection serves the caller's first statement. Before, the driver reconnected but kept the dead startup's internal query and its FATAL `57P01`: the caller's first statement on the live connection failed with that stale `57P01` (the robot's `put_page refused/57P01`), and the orphaned internal query rejected with nobody awaiting it, which Bun treats as fatal (the robot worker's exit 1). |+| A connection closed while a statement's bytes still wait for its write immediate | The next connection on that pool slot starts normally. Before, the cleared immediate left its handle and bytes behind, the reconnect's StartupMessage was appended and never scheduled, and the slot sat open until `CONNECT_TIMEOUT` (10 s) on every statement bound to it, for as long as it kept being chosen (the robot's effects worker, for minutes, leaving a running effect unreclaimed). |+| A managed sync's stall line in the unit lane (`test/sync-drain-claims.test.ts`) | Attributed to the head read that produced it instead of counted by position, so a read in flight across a park no longer reads as the park's first line (the master flake on #6271). |+| Confirmed aborts (`40001`, `40P01`, `55P03`, `57014`) | Unchanged. |++### Itemized changes++- `src/core/retry-matcher.ts`: `isConnectionLoss` (connection-class SQLSTATEs, postgres.js connection codes, `57P01`/`57P02`/`57P03`, socket errnos; not auth or timeouts). `src/core/persistence/admission-retry.ts`: `CONNECTION_LOSS_RETRY_MS`, `writeOutcomeUnknown`, the re-run branch. `types.ts`: `write_outcome_unknown` in `WRITE_ERROR_CODES`. Registry, `write-refusals.md`, `error-codes.md`, KEY_FILES, one `BEHAVIOR_CHANGES` row.+- `vendor/postgres` (`src`, `cjs/src`, `cf/src` `connection.js`; `patches/[email protected]` regenerated, `bash vendor/update-postgres.sh --check` clean): `closed()` settles a startup's internal query and clears its saved error before reconnecting for `initial`, clears the pending write buffer and its immediate handle, and drops the errored `query`; `fetchArrayTypes` swallows its own failure (`errored()` has already told the caller's query; `connected()` re-arms the fetch). `scripts/persistence/ops.ts`: the harness read retry also covers `CONNECTION_DESTROYED` and `CONNECT_TIMEOUT` (a backend killed mid-handshake surfaces as a connect timeout), still only after a drop the robot injected.+- `src/core/persistence/journal.ts` `admitWrite`: after a connection loss the re-run runs on `engine.transaction` (the pool), never again on a lent transaction, once `engine.reconnect` rebuilt the pool. `src/core/persistence/consumer.ts` `onLane`: a lent transaction that reports a connection loss (`isConnectionLoss`) releases the lane and sets the one-minute retake delay in `finally`, independent of how `run` ends.+- Tests: `test/persistence-admission-connection-loss.test.ts` (classifier; re-run / typed outcome / budget / other errors untouched; forced probes: `admitWrite` with a lost COMMIT acknowledgment returns the admitted row and exactly one request exists, and a dead lent transaction is used once with the pool finishing the write; on the previous code the raw `write CONNECTION_CLOSED` escapes). `test/persistence-consumer-lane-loss.test.ts` (forced probe: the lane is given up after a lost lent transaction whether the run ends typed or succeeds; kept on success; fails on the previous `onLane`). `test/sync-drain-claims.test.ts`: stall lines are attributed to their head read's start (`parkedStallLines`), with a forced probe replaying the by-position misattribution. `test/postgres-driver-startup-death.test.ts` (scripted wire-protocol server, no database: a connection killed with FATAL 57P01 at its first statement, and a close delivered while a statement's bytes wait for the write immediate; both fail on the previous driver with 57P01 / CONNECT_TIMEOUT). The seed-5105 crash-robot manifest replays clean (20 of 20 sequential after the driver fixes; before them 1 run in about 7 wedged or crashed).++Fixes #6355. Follows #6347.+## [0.60.122.0] - 2026-10-09**An eval-only evidence brief for the LongMemEval harness: a cheap model's claims, each with a verbatim quote, a pointer and a date, checked against the sessions before a reader sees them.**diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex 32431538fe..381d08b024 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. #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/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. #6355: a session that drops under the attempt (`isConnectionLoss` in `retry-matcher.ts`: connection-class SQLSTATEs, postgres.js's connection codes, `57P01`/`57P02`/`57P03`, the socket errnos) re-runs the attempt after `CONNECTION_LOSS_RETRY_MS` (100/300/900 ms), which is safe because every attempt reads the retained request id first and replays an admitted row; when the session keeps dropping the caller gets `writeOutcomeUnknown` (`write_outcome_unknown`, `reason: connection_lost`, fix: read the request by id), never the raw socket error the crash robot's receipt oracle took for a refusal while the write committed (`test/persistence-admission-connection-loss.test.ts`, forced probes: a lost COMMIT acknowledgment; a dead lent transaction used once with the pool finishing the write). The optional `recover(error)` hook runs before each re-run; `admitWrite` uses it to rebuild the pool (`engine.reconnect`) and to move the re-run from a lent transaction (the consumer's lane, `onPersistenceLane`) to `engine.transaction`, since a dropped reservation fails every later use the same way ("Connection is no longer owned"). 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/engines-2.md b/docs/architecture/key-files/engines-2.mdindex f5bcd8aee9..722c4131bd 100644--- a/docs/architecture/key-files/engines-2.md+++ b/docs/architecture/key-files/engines-2.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `patches/[email protected]` — auditable delta for the driver ownership and cancellation repair already applied to the shipped `vendor/postgres` ESM/CommonJS/workerd source (not an install hook; `bash vendor/update-postgres.sh --check` verifies it), consumed by `PostgresEngine.runUnsafe` through `#postgres`. Abortable reservations settle atomically; shared transaction queues isolate cancellable SQL from tagged/savepoint siblings while preserving unfenced pipelining. A pooled connection (pool `max` above 1) or a released reservation whose last ReadyForQuery status is not idle is terminated instead of reused, and the `onpoisoned(status)` option reports it (pinned by `test/e2e/postgres-poisoned-connection.test.ts`). See [PostgreSQL cancellation ownership](../postgres-cancellation.md) for settlement, deadline, transport and clean-install invariants. Pinned by `test/e2e/persistence-chaos.test.ts`. The patch also shares each pool's described parameter types across its connections (`shared_types`; `db.resolveSharedTypes()` reads the `GBRAIN_PG_TYPE_CACHE=0` kill switch at the four pool construction sites, `db.clearSharedTypes()` runs after `initSchema` applies migrations), so a first run on another connection, and every run under `prepare: false`, skips the describe round trip; pinned by `test/e2e/postgres-shared-types.test.ts`.+- `patches/[email protected]` — auditable delta for the driver ownership and cancellation repair already applied to the shipped `vendor/postgres` ESM/CommonJS/workerd source (not an install hook; `bash vendor/update-postgres.sh --check` verifies it), consumed by `PostgresEngine.runUnsafe` through `#postgres`. Abortable reservations settle atomically; shared transaction queues isolate cancellable SQL from tagged/savepoint siblings while preserving unfenced pipelining. A pooled connection (pool `max` above 1) or a released reservation whose last ReadyForQuery status is not idle is terminated instead of reused, and the `onpoisoned(status)` option reports it (pinned by `test/e2e/postgres-poisoned-connection.test.ts`). See [PostgreSQL cancellation ownership](../postgres-cancellation.md) for settlement, deadline, transport and clean-install invariants. Pinned by `test/e2e/persistence-chaos.test.ts`. The patch also shares each pool's described parameter types across its connections (`shared_types`; `db.resolveSharedTypes()` reads the `GBRAIN_PG_TYPE_CACHE=0` kill switch at the four pool construction sites, `db.clearSharedTypes()` runs after `initSchema` applies migrations), so a first run on another connection, and every run under `prepare: false`, skips the describe round trip; pinned by `test/e2e/postgres-shared-types.test.ts`. #6355: `closed()` settles a startup's internal query (the array-types fetch) and clears its saved error before reconnecting for `initial`, so a backend terminated during startup neither hands the caller's first statement a stale `57P01` on the fresh connection nor leaves an unhandled rejection (`fetchArrayTypes` also swallows its own failure); it clears the pending write buffer and its immediate handle, so a close that catches a buffered statement does not leave the next StartupMessage appended and unscheduled (a pool slot stuck at `CONNECT_TIMEOUT`); pinned by `test/postgres-driver-startup-death.test.ts` against a scripted wire-protocol server.- `src/core/pg-type-cache.ts` — the store `shared_types` uses: one `SharedParameterTypes` Map per database target in this process (`sharedParameterTypes(url)`), keyed by SHA-256 digests of the driver's (types, SQL) key, and saved under `<gbrain home>/cache/pg-types/` (0600) for the next process. `db.checkPoolAndLoadSharedTypes` reads its scope (`server_version_num`, `config.version`, and the database as the server names it, so a proxy and a direct URL share a file) in each new pool's connection check and loads it; a different scope is ignored and replaced, a migration's `clearSharedTypes` deletes the file. `GBRAIN_PG_TYPE_CACHE_PERSIST=0` keeps it in-process. Pinned by `test/pg-type-cache.test.ts` and the new-process case in `test/e2e/postgres-shared-types.test.ts`.- `src/core/engine-sql/` — one SQL implementation per migrated storage domain (the domains are the `migrated` rows of `scripts/engine-sql-baseline.tsv`), run by both engines through one executor contract:diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.mdindex 2f4ea08333..6615d6b9c1 100644--- a/docs/architecture/key-files/persistence-stalls.md+++ b/docs/architecture/key-files/persistence-stalls.md@@ -24,7 +24,7 @@ owner (`owner_wedged_here`), movement surfaces (`data_moving`, doctor- `src/core/persistence/bounded-reads.ts` — #6278 (plan item 1.4): a preparation read that can wait on a relation lock ends at the budget on the server. Phase 0 (`docs/eval/managed-sync-stall-repro.md`) showed that through a transaction-mode pooler gbrain's `statement_timeout` startup parameter is dropped, so a preparation read outside the publication transaction had no server-side bound; an `ACCESS EXCLUSIVE` lock on `pages` held elsewhere pinned the member's origin check and its connection until the lock lifted, and with the budget alone the released member's statement kept running as a zombie that blocked its root until the ceiling. `boundedReads(engine, clock)` is the engine view every preparer reads through (`prepareManagedSyncMutation` and its helpers, `preparePageMutation`, `prepareFactFenceAdoption`, the sync's out-of-consumer preparations): each unmemoized raw statement runs with `executeRaw`'s `timeoutMs` set to the clock's remaining budget (`ClaimPhaseClock.deadlineAt`, set by `startClaimPhase(now, signal, budgetMs)`) and the clock's signal, which ends only the wait for a free connection. On Postgres `timeoutMs` runs the statement on a reserved connection as `BEGIN; SET LOCAL statement_timeout; <statement>; COMMIT` in one pipelined round trip, so the bound holds through the pooler and `SET LOCAL` ends with it; inside a transaction and on PGLite the option is ignored. A statement the server ends (57014, or a 55P03 raised by a shorter session `lock_timeout`) surfaces as the member's own `preparation_deadline` (`PreparationDeadlineError`, or the signal's reason once it aborted), which `preparationAbortReason` classifies as the deadline: the consumer and the group route handle it as the deadline even inside the budget (charged release, `preparation_stalled` at the limit, the group cut like the timer), never as a `storage_error` receipt or an uncharged release. The memo rule holds: `preparationReads` answers a bounded read once with the member's bound and signal dropped. Engine helpers that bypass `executeRaw` (`readPageSnapshot`, the import pipeline) stay under the consumer's race and the ceiling. Tests: `test/persistence-bounded-reads.test.ts`, `test/e2e/persistence-preparation-lock-wait-postgres.test.ts` (a real lock held in another session), the server-ended cases in `test/persistence-consumer-scheduling.test.ts` and `test/e2e/persistence-group-deadline-postgres.test.ts`.- `src/core/persistence/owner-refusal.ts` — #6278: the `owner_unavailable` reasons matrix. `checkOwner(binding, incarnation, hostId)` names the first failing condition in a fixed order (`binding_missing`, `incarnation_changed`, `host_mismatch`, `transfer_in_progress` for a `draining` worktree, `clone_in_progress` for `recovering`, `local_path_missing`, `coordination_path_missing`) or returns the usable `ActiveOwnerBinding`; `ownerRefusal` gives each reason its message, `why`, actor, fix (always the read-only `gbrain sources writer status --source <id> --json`, with the same verify; `actor: provider` so the two in-progress reasons render `next: wait` with a 30 s delay, `host_admin` for the rest) and `retryable` (`host_mismatch` false at the site, carried by `OperationError.retryable`); `ownerUnavailableError` is the thrown form. `host_mismatch` prints both host ids' first 8 characters and, when `remote` is false, the `host.json` path this process read; nothing here claims or transfers ownership. Used by `maintenancePreflight`, `loadFenceSource` and `managedRepairRoot`; the registry's `owner_unavailable.reasons` and the `FENCE_REASONS` owner entries carry the same vocabulary. Tests: `test/owner-refusal.test.ts` (matrix, every preflight condition on a claimed worktree, the HTTP envelope without a local path), `test/fence-repair-reasons.test.ts`.- `src/core/persistence/repair-busy.ts` — #6278: the busy set a repair must not write while a managed sync runs. `loadRepairBusySet(engine, sourceId, incarnation)` returns the paths and slugs named by queued, running and recovering requests and terminal rows with an open recovery (both rename endpoints included) plus, for every unfinished `managed-sync` cursor of the incarnation, the entries of its frozen `managed-sync-manifest` from the cursor's index on (a path with a `sync-hold` record is left out: the sync retries a held file only when its bytes change); it never throws and fails closed (`unknown` set, so `repairBusy` answers true for everything) when a query fails or a cursor's manifest is missing. `repairBusyMessage` is the hold text, `repairBusyError` the `sync_in_progress` refusal (`reason` `candidate_in_flight` or `busy_set_unreadable`) `submitManagedFileRepair` raises at admission. Tests: `test/repair-busy.test.ts`, `test/repair-fences.test.ts`, `test/repair-fences-during-catchup.test.ts` (Postgres: `test/e2e/repair-fences-during-catchup-postgres.test.ts`).-- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Every claimed write has a preparation budget (`preparation-budget.ts`): `execute` races the preparation against it (`startPreparation`), so the claim is released with `blocked_reason` `preparation_deadline` and one counted attempt at the budget even when the preparer ignores its signal, and a late result never publishes (the execution-token fence). A request already at `persistence.max_preparation_attempts` is finished `failed` with `preparation_stalled` at claim without preparing again, and the release that reaches the limit finishes it there (`coordinator.ts` `finishPreparationStalled`; a waiting `awaitWrite` caller gets the terminal receipt, foreground writes included); a preparer's rejection on the consumer's own abort (its reason, an `AbortError` or a cancelled statement, `preparationAbortReason`) is a release, never a receipt. The expired-claim sweep (Postgres, and PGLite's `releaseAbandonedClaims`) charges one attempt for a claim stamped `preparing` (a process killed mid-preparation); `claim_lost`, `consumer_stopping` and `group_member_waiting` never charge, and a commit resets the counter. The #5373 root barrier for an abandoned preparation ends at `persistence.preparation_ceiling_ms` measured from the claim: the root is freed, the counter is pinned at the limit (an overrun proves cancellation is ignored, so the next claim fails the request `preparation_stalled`) and the zombie stays in `status().outlived_ceiling`; at the per-process cap (`zombieCap`, default 1) the consumer claims nothing more and `status().restart_required` is true. `stop()` gives abandoned preparations `ABANDONED_STOP_GRACE_MS` (5 s) after aborting them instead of waiting forever. The fault point `consumer:preparing` sits inside the budget, `status()` reports `preparation_policy` and `abandoned_preparations`, and the stderr line carries `phase=preparation reason=deadline_exceeded | preparation_stalled | ceiling_exceeded`. With the `preparation_deadlines` switch off only `remember` and intent-less `put_page`/`edit_page` keep the 30 s budget, the old unbounded wait applies and no attempt is counted. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `claimableWriteSql` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms per page). On PGLite the first full tick releases claims last written before this process started (`releaseAbandonedClaims` in `effect-journal.ts`: running effects and unpublished requests without a recovery record), since the datastore admits one process and those owners have exited; Postgres keeps lease expiry (requests 30 s, effects 2 minutes). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`. With `requestsOnly` (engine graduation's drain) the effect, projection, topology and maintenance workers never start; claim, recovery, expired-claim and publication run as usual and `stop()` remains the barrier. Both the single route and the grouped/lane route (`executeClaimedGroup` in `group-publish.ts`) prepare under a claim lease (`claim-lease.ts`: a renewal every `renewalIntervalMs`, default 10 s, each bounded by `phaseMs`); the claim is lost the first time a renewal says it is gone, throws or overruns, and `whileHeld` stops waiting on the preparation at that moment (the single route also aborts it). The claims still ours are released unpublished with `claim_lost` (token-fenced, so a consumer that took one over keeps it); the abandoned preparation is never published and keeps its root or lane slot until it settles or the ceiling passes, while the consumer slot frees at once. Renewals are never awaited on the way out: `stop()` drains in-flight renewals and gives abandoned preparations their grace before engine close. Tests: `test/persistence-claim-lease.test.ts`, `test/persistence-consumer-scheduling.test.ts`, `test/e2e/persistence-consumer-claim-loss.test.ts`, `test/persistence-preparation-kill-accounting.test.ts`, `test/e2e/persistence-preparation-deadline.e2e.test.ts`.+- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Every claimed write has a preparation budget (`preparation-budget.ts`): `execute` races the preparation against it (`startPreparation`), so the claim is released with `blocked_reason` `preparation_deadline` and one counted attempt at the budget even when the preparer ignores its signal, and a late result never publishes (the execution-token fence). A request already at `persistence.max_preparation_attempts` is finished `failed` with `preparation_stalled` at claim without preparing again, and the release that reaches the limit finishes it there (`coordinator.ts` `finishPreparationStalled`; a waiting `awaitWrite` caller gets the terminal receipt, foreground writes included); a preparer's rejection on the consumer's own abort (its reason, an `AbortError` or a cancelled statement, `preparationAbortReason`) is a release, never a receipt. The expired-claim sweep (Postgres, and PGLite's `releaseAbandonedClaims`) charges one attempt for a claim stamped `preparing` (a process killed mid-preparation); `claim_lost`, `consumer_stopping` and `group_member_waiting` never charge, and a commit resets the counter. The #5373 root barrier for an abandoned preparation ends at `persistence.preparation_ceiling_ms` measured from the claim: the root is freed, the counter is pinned at the limit (an overrun proves cancellation is ignored, so the next claim fails the request `preparation_stalled`) and the zombie stays in `status().outlived_ceiling`; at the per-process cap (`zombieCap`, default 1) the consumer claims nothing more and `status().restart_required` is true. `stop()` gives abandoned preparations `ABANDONED_STOP_GRACE_MS` (5 s) after aborting them instead of waiting forever. The fault point `consumer:preparing` sits inside the budget, `status()` reports `preparation_policy` and `abandoned_preparations`, and the stderr line carries `phase=preparation reason=deadline_exceeded | preparation_stalled | ceiling_exceeded`. With the `preparation_deadlines` switch off only `remember` and intent-less `put_page`/`edit_page` keep the 30 s budget, the old unbounded wait applies and no attempt is counted. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `claimableWriteSql` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms per page). On PGLite the first full tick releases claims last written before this process started (`releaseAbandonedClaims` in `effect-journal.ts`: running effects and unpublished requests without a recovery record), since the datastore admits one process and those owners have exited; Postgres keeps lease expiry (requests 30 s, effects 2 minutes). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`. With `requestsOnly` (engine graduation's drain) the effect, projection, topology and maintenance workers never start; claim, recovery, expired-claim and publication run as usual and `stop()` remains the barrier. Both the single route and the grouped/lane route (`executeClaimedGroup` in `group-publish.ts`) prepare under a claim lease (`claim-lease.ts`: a renewal every `renewalIntervalMs`, default 10 s, each bounded by `phaseMs`); the claim is lost the first time a renewal says it is gone, throws or overruns, and `whileHeld` stops waiting on the preparation at that moment (the single route also aborts it). The claims still ours are released unpublished with `claim_lost` (token-fenced, so a consumer that took one over keeps it); the abandoned preparation is never published and keeps its root or lane slot until it settles or the ceiling passes, while the consumer slot frees at once. Renewals are never awaited on the way out: `stop()` drains in-flight renewals and gives abandoned preparations their grace before engine close. Tests: `test/persistence-claim-lease.test.ts`, `test/persistence-consumer-scheduling.test.ts`, `test/e2e/persistence-consumer-claim-loss.test.ts`, `test/persistence-preparation-kill-accounting.test.ts`, `test/e2e/persistence-preparation-deadline.e2e.test.ts`. #6355: `onLane` lends its warm lane's transaction through a wrapper that notes a connection loss (`isConnectionLoss`); in `finally` a lost lane is released and `idleLaneRetryAt` set a minute out, whatever `run` returned or threw (admission turns the loss into `write_outcome_unknown` or succeeds on the pool, so the catch alone never saw it), because the dead reservation answers every later statement with "Connection is no longer owned" (`test/persistence-consumer-lane-loss.test.ts`).- **`src/core/persistence/sync-group.ts`** + **`group-publish.ts`** — #5984 bulk publication for draining managed Postgres syncs. `sync-group.ts` resolves bulk settings (`--no-bulk` > `GBRAIN_SYNC_BULK` > `sync.bulk` > on; `sync.bulk_size` 16, `sync.bulk_max_txn_ms` 15 s; PGLite off), sizes the next group from the last group's admission-to-commit time per member, freezes followers (four at a time, stopping at a rename, company plan, overtaken entry or one the waiver would take) and admits a group in one transaction (`admitWriteGroupInTransaction`, which keeps one request row, ID and digest per page and replays priors). `sync-run.ts` keeps the head in `pending` and all members in the cursor's `group` (members carry `intent.group` = the head's request ID), waits for the last member and advances over the committed prefix; a terminal failure becomes the single pending entry, a still-pending member returns `writer_pending`. Any caller finishes an existing group; only a drain forms one. #6075: when another owner loop already admitted the group's head on the single path with the head's pre-group intent (the intent minus the `group`/`lane` keys `formGroup` adds, `groupedIntent`/`ungroupedIntent`), `groupStep` drops the group and the single path takes that request, and the never-admitted followers are frozen again; a different intent under the head's request ID still refuses `idempotency_conflict`. The single path's ENG-A7 admission guard compares the stored pending intent as well as its request ID, so a pass that read the head before a drain grouped it re-reads the cursor instead of admitting the stale intent, and an `idempotency_conflict` against a head the group admitted first re-reads the cursor too (`test/managed-sync-stale-group-head.test.ts`). The consumer claims a head's directly following queued members (`claimGroupFollowers`, never past an unfinished non-member) and `executeClaimedGroup` prepares four at a time, then `publishGroup` publishes them in one transaction: one worktree lock, ownership guard and coordinated write (each member set as the attributed actor with `setMemberAttribution`), per-member authorization, preimage read, sync validation (its source-wide part shared per transaction), apply (which reads the postimage the receipt and effects use), effects and receipt; `completeGroup` then reads every member's effect bytes, and pipelines the counter lock with one `UPDATE ... FROM unnest(...) RETURNING` that checks each member's claim and terminal reservation and releases the counters (a short `RETURNING` throws, so the single path reports each member's own code). Any failure rolls the group back; members then publish singly, later members are cancelled after a terminal failure or released after a requeue. Sync validation accepts a group member through the cursor's `group`. #6007: the pages of one `put_pages` batch (`intent.page_batch.id`; the group key is `journal.ts` `publicationGroupKey`) also publish as groups of at most `PAGE_BATCH_GROUP_MAX` (8) pages, prepared all at once, files included: one transaction records every member's recovery record (`prepareRecoveries`) before any file is touched, the publication transaction marks the members `publication_started`, publishes each member's file before its apply and re-arms the batch's mention links once after every member completes (`reconcileFinishedBatch`), and one transaction clears the records after commit (`clearResolvedRecoveries`). A single foreground page write publishes here too, as a group of one (core-persistence-continued.md, `switches.ts` entry). Within that transaction the source's local path, the owner's host binding and config values are read once per group (source membership and the writer registration are already memoized per transaction by `transactionMemo`). On failure every file the group published is restored by `recoverPublication`, which requeues those claims; the fallback claims them back in order (`reclaimReleasedWrite`) and publishes the members singly, and a batch member's failure never cancels its siblings. Each member has its own preparation budget (#6278): `executeClaimedGroup` marks a wave durably (`markDispatched`) and starts each member's clock when the wave dispatches it, so a follower waiting behind four others is never charged; the lease renews the mutable set of members still held (`renewGroupClaims` stamps each member's own phase), so releasing one member never reads as a lost group lease. When member k's budget passes, nothing later is dispatched, the in-flight suffix is aborted, k is released `preparation_deadline` (charged; finished `preparation_stalled` when that reaches the limit) and the later members `group_member_waiting` (not charged), and the contiguous prepared prefix 0..k-1 publishes (singly when shorter than two; under lanes in the original group's key order). An independent `put_pages` batch group releases only k, `laneFallback` keeps the expired member's reason, and an abandoned member's preparation goes to the consumer with its clock, so the root waits for it until it settles or the ceiling. A member's signal reaches its preparer through its clock (`enterClaimStep`), never as a blanket statement signal: `preparationReads` and `groupReads` answer one read for every member and skip their memo for a signalled statement, so a member that must give up on a shared read races its own signal against the shared promise (pinned by `test/persistence-preparation-memo-rule.test.ts`). A commit resets `preparation_attempts` (`completeGroup`). Tests: `test/managed-sync-bulk.test.ts`, `test/e2e/put-pages-group-postgres.test.ts`, `test/e2e/persistence-group-deadline-postgres.test.ts`.- `src/core/persistence/consumer-heartbeat.ts` — #6317 (B1a, B3): the probe and heartbeat behind one full consumer per host. `consumerIdentity()` is this process's `{pid, nonce, pid_ns}` (a random per-process nonce and the pid-namespace inode from `/proc/self/ns/pid` where readable), so a reused pid after a container restart is a new row; every `owner_pid === process.pid` check compares the nonce too. `startConsumerHeartbeat(engine, row, opts)` renews this process's `persistence_consumers` row every 10 s on its own single-flight timer through `executeRawDirect` (independent of claim renewal: an idle `serve` holds no claim), carrying kind (`claimOwner().kind`), mode (`probing|full|waiter_only|promoted`), `restart_required`, the age of the oldest abandoned root barrier, the pool gauge `{checked_out, max, waiters}`, `host_json_path`, `persistence_home`, `minted_under` and the build; each renewal deletes rows lapsed over 60 s in the same CTE, and a failed write is logged once and never stops the consumer. `probeLiveFullConsumer(engine, hostId, self)` is the database-only probe (never a socket: the persistence IPC socket exists only on PGLite): a row of a resident kind (`serve`, `sync`, `jobs`, `autopilot`, `mcp`), mode `full`, not this process, renewed within 30 s, not `restart_required` and not wedged (no root barrier older than `persistence.preparation_ceiling_ms`), on an `active` binding. `listHostConsumers(engine, hostId)` feeds `writer status --json` `host.consumers` and doctor. Live is 30 s, lapsed 60 s. The consumer mode machine in `consumer.ts` (`probing` → `full` or `waiter_only` → `promoted` → back to `waiter_only` after three healthy owner ticks) consumes the probe on every tick; `startPersistenceConsumer` in `service.ts` stays synchronous and returns the waiter-only seam (`WaiterOnlyConsumer` behind `PersistenceConsumerLike`: `wake()` no-op, settlement listeners kept, `holds()` false, `status()` `waiter_only` with the owner pid) when the probe finds an owner and `persistence.single_consumer` is on. A `serve` always starts full; short-lived kinds (`put`, `import`, `dream`, `cycle`, `sources`, `cli`) keep their own consumer; PGLite is inert.- `src/core/schema-migrations/v222-persistence-consumers.ts` — #6317 (T-01): the `persistence_consumers` table, primary key `(host_id, pid, nonce)`, columns `pid_ns`, `kind`, `mode`, `started_at`, `renewed_at`, `restart_required`, `root_barrier_age_ms`, `pool` jsonb, `host_json_path`, `persistence_home`, `minted_under` jsonb, `version`; plus the partial index `persistence_requests (worktree_id, completed_at DESC) WHERE state = 'committed'` that the movement watermark reads (the baseline indexes cover pending, recovery and principal reads only). Both objects are also in `src/schema.sql` for fresh installs (PGLite and Postgres parity, goldens). The number is taken at the merge slot by `bun run release:restamp`.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 22f384cb84..4081f81232 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -2780,6 +2780,16 @@ More: [docs/guides/write-refusals.md#worktree_dirty](../../docs/guides/write-ref|---|---|---|---|---|---|---|| Execution claim changed before publication. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait briefly, then retry the same request (writes: reuse the same request_id). | agent | `repeat the read that failed` | 1 | yes |+### write_outcome_unknown++<a id="write_outcome_unknown"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The database connection dropped while a write was being admitted, and it kept dropping through the re-reads, so whether the write was accepted is unknown. | A session that closes under an admission (a pooler reap, a failover, pg_terminate_backend) leaves the transaction either committed or rolled back with no way to tell from the lost socket. gbrain re-runs the attempt, which starts by reading the retained request_id, so a single drop resolves by itself; this code means the database stayed unreachable through those re-reads. Before #6355 the raw socket error reached the caller, and a receipt oracle took it for a refusal while the write committed. | Read the request first (the fix names it): a committed or pending row means the write was accepted, replay the same request_id to wait for it; no row means it was not, submit it again with the same request_id. Never resubmit under a new request_id without that read. | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/write-refusals.md#write_outcome_unknown](../../docs/guides/write-refusals.md#write_outcome_unknown)+### write_pending<a id="write_pending"></a>diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex b35f8bc675..64b89a67b1 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -72,6 +72,7 @@ of making a duplicate.| <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`). When that sync still has a backlog to finish, it finishes it first and re-screens the scheduled files in the same invocation (the drain yields at the checkpoint and discovers again), so one run of the printed command clears the hold. A foreground write needs a new `request_id`; the next maintenance run submits its write again. Runbook: [catch-up stuck / held N files](troubleshooting.md#catch-up-stuck). |+| <a id="write_outcome_unknown"></a>`write_outcome_unknown` | `write_outcome_unknown` | The database session dropped while the write was being admitted (a pooler reap, a failover, `pg_terminate_backend`), and it kept dropping through the re-reads, so whether the write was accepted is unknown (#6355). A single drop never reaches you: the admission attempt is re-run after 100, 300 and 900 ms, and every attempt begins by reading the retained `request_id`, so a re-run replays an admitted row instead of admitting again. Before this code existed the raw socket error (`write CONNECTION_CLOSED …`, `57P01`) reached the caller while the write went on to commit, and a receipt oracle took it for a refusal. | Read the request first: `gbrain write-request -- <request_id>` or `get_write_request { request_id }` (the error's `fix` names it). A committed or pending row means the write was accepted: replay the same `request_id` to wait for it. No row means it was not: submit it again with the same `request_id`. Never resubmit under a new `request_id` without that read. || <a id="fence_unrenderable"></a>`fence_unrenderable` | `fence_unrenderable` | A legacy fact row (an active `facts` row with no fence row number) was not adopted into its page's `## Facts` fence because the fence codec reads the rendered row back as something other than the stored fact: a whitespace-only claim comes back empty, `~~x~~` comes back struck, a literal `<br>` comes back as a line break, or another column changes. Surrounding whitespace and CRLF line endings are the one accepted difference: such a row is adopted and `facts.fact` takes the fence's text. A second legacy row whose normalized claim, source and visibility the page already carries is left too (`duplicate_claim`; a private and a world row with one text are two facts and both adopt). The cycle and the v0.32.2 migration print `FACTS_FENCE_FAILED: <slug> (fence_unrenderable: N row(s), <class>)`; doctor `fence_integrity` lists the pages, fact ids and reason classes under `unrenderable_legacy_facts` (never the claim text). The same code refuses a planned adoption whose rendered fence does not read back as its facts; that is a gbrain planning defect, not caller input. | Nothing to fix in the page: the rows stay active and searchable, nothing is lost, and their pages skip destructive fact reconciliation until the rows are adopted. Report the pages and reason classes with the gbrain version. Never `forget_fact` a row to clear the count. || <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. |diff --git a/patches/[email protected] b/patches/[email protected]index e5d7039813..a19fcc0d79 100644--- a/patches/[email protected]+++ b/patches/[email protected]@@ -1,5 +1,5 @@diff --git a/cjs/src/connection.js b/cjs/src/connection.js-index 07f6716..f6d76e5 100644+index 07f6716..ec88b7c 100644--- a/cjs/src/connection.js+++ b/cjs/src/connection.js@@ -78,6 +78,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose@@ -87,19 +87,43 @@ index 07f6716..f6d76e5 100644stream && (stream.destroy(err), stream = null)query && queryError(query, err)initial && (queryError(initial, err), initial = null)-@@ -447,6 +462,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -438,6 +453,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+ remaining = 0+ incomings = null+ clearImmediate(nextWriteTimer)++ // GBrain (#6355): bytes still waiting for the cleared immediate belonged to this socket. Left in place, the next++ // connection's StartupMessage is appended to them and never scheduled for writing (the timer handle is not++ // null), so the connection sits open until CONNECT_TIMEOUT and every statement bound to it fails.++ chunk = nextWriteTimer = null+ socket.removeListener('data', data)+ socket.removeListener('connect', connected)+ idleTimer.cancel()+@@ -447,10 +466,23 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosesocket.removeAllListeners()socket = null+- if (initial)+ if (cancelMessage)+ return cancelError || hadError+ ? cancelReject(cancelError || Errors.connection('CONNECTION_CLOSED', options))+ : cancelResolve()+- if (initial)++ if (initial) {++ // GBrain (#6355): a connection that died during startup (its backend terminated under the array-types fetch)++ // leaves that internal query and the error it saw behind. The fresh connection must not deliver the stale++ // error to the caller's query at its first ReadyForQuery, and the internal query settles here instead of++ // rejecting with nobody to hear it.++ query && query !== initial && queryError(query, Errors.connection('CONNECTION_CLOSED', options, socket))++ query = results = errorResponse = nullreturn reconnect()++ }-@@ -533,8 +553,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+ !hadError && (query || sent.length) && error(Errors.connection('CONNECTION_CLOSED', options, socket))++ query = null+ closedTime = performance.now()+ hadError && options.shared.retries+++ delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000+@@ -533,8 +565,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}function ReadyForQuery(x) {@@ -111,7 +135,7 @@ index 07f6716..f6d76e5 100644query.retried? errored(query.retried): query.prepared && retryRoutines.has(errorResponse.routine)-@@ -564,10 +587,12 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -564,10 +599,12 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosereturn fetchArrayTypes()}@@ -126,7 +150,7 @@ index 07f6716..f6d76e5 100644}while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))-@@ -580,7 +605,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -580,7 +617,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose? !connection.reserved.release && x[5] === 73 // I? ending? terminate()@@ -135,7 +159,7 @@ index 07f6716..f6d76e5 100644: connection.reserved(): ending? terminate()-@@ -630,6 +655,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -630,6 +667,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose!query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4))query.prepare && (statements[query.signature] = query.statement)@@ -145,6 +169,36 @@ index 07f6716..f6d76e5 100644query.describeFirst && !query.onlyDescribe && (write(prepared(query)), query.describeFirst = false)}+@@ -767,14 +807,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose++ async function fetchArrayTypes() {+ needsTypes = false+- const types = await new Query([`+- select b.oid, b.typarray+- from pg_catalog.pg_type a+- left join pg_catalog.pg_type b on b.oid = a.typelem+- where a.typcategory = 'A'+- group by b.oid, b.typarray+- order by b.oid+- `], [], execute)++ let types++ try {++ types = await new Query([`++ select b.oid, b.typarray++ from pg_catalog.pg_type a++ left join pg_catalog.pg_type b on b.oid = a.typelem++ where a.typcategory = 'A'++ group by b.oid, b.typarray++ order by b.oid++ `], [], execute)++ } catch (error) {++ // GBrain (#6355): the fetch failed or its connection closed; errored() has already told the caller's query, and++ // connected() re-arms the fetch for the next connection. Nothing awaits this promise, so it must not reject.++ return++ }+ types.forEach(({ oid, typarray }) => addArrayType(oid, typarray))+ }+diff --git a/cjs/src/index.js b/cjs/src/index.jsindex f09c61c..694550b 100644--- a/cjs/src/index.js@@ -521,7 +575,7 @@ index 8438f5d..c444310 100644const out = xs[index++]diff --git a/src/connection.js b/src/connection.js-index 1b1cccd..792c83d 100644+index 1b1cccd..c4d90e6 100644--- a/src/connection.js+++ b/src/connection.js@@ -78,6 +78,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose@@ -609,19 +663,43 @@ index 1b1cccd..792c83d 100644stream && (stream.destroy(err), stream = null)query && queryError(query, err)initial && (queryError(initial, err), initial = null)-@@ -447,6 +462,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -438,6 +453,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+ remaining = 0+ incomings = null+ clearImmediate(nextWriteTimer)++ // GBrain (#6355): bytes still waiting for the cleared immediate belonged to this socket. Left in place, the next++ // connection's StartupMessage is appended to them and never scheduled for writing (the timer handle is not++ // null), so the connection sits open until CONNECT_TIMEOUT and every statement bound to it fails.++ chunk = nextWriteTimer = null+ socket.removeListener('data', data)+ socket.removeListener('connect', connected)+ idleTimer.cancel()+@@ -447,10 +466,23 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosesocket.removeAllListeners()socket = null+- if (initial)+ if (cancelMessage)+ return cancelError || hadError+ ? cancelReject(cancelError || Errors.connection('CONNECTION_CLOSED', options))+ : cancelResolve()+- if (initial)++ if (initial) {++ // GBrain (#6355): a connection that died during startup (its backend terminated under the array-types fetch)++ // leaves that internal query and the error it saw behind. The fresh connection must not deliver the stale++ // error to the caller's query at its first ReadyForQuery, and the internal query settles here instead of++ // rejecting with nobody to hear it.++ query && query !== initial && queryError(query, Errors.connection('CONNECTION_CLOSED', options, socket))++ query = results = errorResponse = nullreturn reconnect()++ }-@@ -533,8 +553,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+ !hadError && (query || sent.length) && error(Errors.connection('CONNECTION_CLOSED', options, socket))++ query = null+ closedTime = performance.now()+ hadError && options.shared.retries+++ delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000+@@ -533,8 +565,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}function ReadyForQuery(x) {@@ -633,7 +711,7 @@ index 1b1cccd..792c83d 100644query.retried? errored(query.retried): query.prepared && retryRoutines.has(errorResponse.routine)-@@ -564,10 +587,12 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -564,10 +599,12 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosereturn fetchArrayTypes()}@@ -648,7 +726,7 @@ index 1b1cccd..792c83d 100644}while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))-@@ -580,7 +605,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -580,7 +617,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose? !connection.reserved.release && x[5] === 73 // I? ending? terminate()@@ -657,7 +735,7 @@ index 1b1cccd..792c83d 100644: connection.reserved(): ending? terminate()-@@ -630,6 +655,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -630,6 +667,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose!query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4))query.prepare && (statements[query.signature] = query.statement)@@ -667,6 +745,36 @@ index 1b1cccd..792c83d 100644query.describeFirst && !query.onlyDescribe && (write(prepared(query)), query.describeFirst = false)}+@@ -767,14 +807,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose++ async function fetchArrayTypes() {+ needsTypes = false+- const types = await new Query([`+- select b.oid, b.typarray+- from pg_catalog.pg_type a+- left join pg_catalog.pg_type b on b.oid = a.typelem+- where a.typcategory = 'A'+- group by b.oid, b.typarray+- order by b.oid+- `], [], execute)++ let types++ try {++ types = await new Query([`++ select b.oid, b.typarray++ from pg_catalog.pg_type a++ left join pg_catalog.pg_type b on b.oid = a.typelem++ where a.typcategory = 'A'++ group by b.oid, b.typarray++ order by b.oid++ `], [], execute)++ } catch (error) {++ // GBrain (#6355): the fetch failed or its connection closed; errored() has already told the caller's query, and++ // connected() re-arms the fetch for the next connection. Nothing awaits this promise, so it must not reject.++ return++ }+ types.forEach(({ oid, typarray }) => addArrayType(oid, typarray))+ }+diff --git a/src/index.js b/src/index.jsindex c7fba3d..fc9f766 100644--- a/src/index.jsdiff --git a/scripts/persistence/ops.ts b/scripts/persistence/ops.tsindex dc28f8e9cd..559d19f161 100644--- a/scripts/persistence/ops.ts+++ b/scripts/persistence/ops.ts@@ -127,7 +127,8 @@ export class SessionDrops {}}-const DROPPED_CONNECTION = /CONNECTION_CLOSED|CONNECTION_ENDED|ECONNRESET|57P01|08P01|08006|server conn crashed|terminating connection|Connection terminated/i;+// CONNECT_TIMEOUT: a backend the fault killed mid-handshake surfaces to the client as a connect timeout, not a close.+const DROPPED_CONNECTION = /CONNECTION_CLOSED|CONNECTION_ENDED|CONNECTION_DESTROYED|CONNECT_TIMEOUT|ECONNRESET|57P01|08P01|08006|server conn crashed|terminating connection|Connection terminated/i;const DROP_RETRIES = 8;/**diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 095b956196..ecdf3fc8e2 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -345,6 +345,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.121.0', text: 'A managed catch-up no longer stops on a page that moved under it: a database page that changed after the manifest was frozen is held as `concurrent_write` (re-bound and passed when it already holds what the file would import), uncommitted working-tree bytes that match neither the pinned commit nor the page are held with the new code `worktree_dirty`, and working-tree bytes committed at HEAD past the pinned target are imported as HEAD has them; the run finishes `synced` with the holds listed instead of `blocked_by_failures` (`sync.holds=fail` and company-brain sources keep blocking).' },{ since: '0.60.121.0', text: 'A managed sync drain that loses its database connection (`write ECONNABORTED`, `ECONNRESET`, `ETIMEDOUT`, `EPIPE`) now reconnects and retries at 5, 15 and 45 seconds instead of exiting, and a connection fault is no longer recorded in the sync failure ledger, so a relaunch (with or without `--retry-failed`) resumes at the stored cursor against the frozen manifest instead of re-freezing it; three drops in a row with no page committed between them stop the drain `connection_lost`.' },{ since: '0.60.121.0', text: 'New commands `gbrain sync status --source <id> --json` (cursor position, pages committed in the last 10 minutes, each hold and the last error with `class`, `safe_actions` and `needs_human`, and `next`) and `gbrain sync unblock --source <id> [--apply] --json` (performs the safe action for every hold and the last error, refuses the rest by name) let an operator agent drive a catch-up without a human; the decision table is `docs/guides/sync-unblock-runbook.md`.' },+ // #6355 (GBRA-64); `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.+ { since: '0.60.123.0', text: 'A write whose database session drops during admission (a pooler reap, a failover, pg_terminate_backend) is re-run after 100, 300 and 900 ms, which replays the admitted row when the lost acknowledgment had committed; a session that keeps dropping returns the new typed `write_outcome_unknown` (reason `connection_lost`, fix: read the request by id) instead of the raw `CONNECTION_CLOSED` / `57P01` the caller used to take for a refusal while the write committed. A write admitted on the consumer\'s warm lane re-runs on the pool and the dead lane is given up at once. The vendored Postgres driver no longer hands a caller the stale `57P01` of a connection killed during startup, nor leaves a pool slot stuck until `CONNECT_TIMEOUT` after a close caught a pending write.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 7e13a2850d..23f91fd3bc 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -395,6 +395,11 @@ export const CODES = {withdrawal_capacity: { class: 'caller', summary: "Withdrawal capacity." },withdrawal_provenance: { class: 'server', summary: "The withdrawal target manifest is invalid." },write_claim_lost: { class: 'retryable', summary: "Execution claim changed before publication." },+ write_outcome_unknown: { class: 'retryable', retryable: false, actor: 'agent',+ summary: "The database connection dropped while a write was being admitted, and it kept dropping through the re-reads, so whether the write was accepted is unknown.",+ why: "A session that closes under an admission (a pooler reap, a failover, pg_terminate_backend) leaves the transaction either committed or rolled back with no way to tell from the lost socket. gbrain re-runs the attempt, which starts by reading the retained request_id, so a single drop resolves by itself; this code means the database stayed unreachable through those re-reads. Before #6355 the raw socket error reached the caller, and a receipt oracle took it for a refusal while the write committed.",+ docs: 'docs/guides/write-refusals.md#write_outcome_unknown',+ suggestion: 'Read the request first (the fix names it): a committed or pending row means the write was accepted, replay the same request_id to wait for it; no row means it was not, submit it again with the same request_id. Never resubmit under a new request_id without that read.' },write_pending: { class: 'retryable', summary: "The write was accepted and is still pending; it may commit later.", exit: 10 },worktree_dirty: { class: 'caller', retryable: false, actor: 'agent',summary: "A managed sync held a file whose uncommitted working-tree bytes match neither the pinned commit nor the current page; the rest of the source synced and the local edit was not overwritten.",diff --git a/src/core/persistence/admission-retry.ts b/src/core/persistence/admission-retry.tsindex 7dfca34006..1e3e94e0a0 100644--- a/src/core/persistence/admission-retry.ts+++ b/src/core/persistence/admission-retry.ts@@ -1,17 +1,54 @@import { setTimeout as delay } from 'node:timers/promises';-import { OperationError } from '../ops/contract.ts';-import { getCode } from '../retry-matcher.ts';+import { OperationError, opError } from '../ops/contract.ts';+import { getCode, isConnectionLoss } from '../retry-matcher.ts';-/** Retry only database-confirmed transaction aborts, retaining the accepted intent and UUID. */-export async function retryWriteAdmission<T>(requestId: string, attempt: (remainingMs: number) => Promise<T>, budgetMs = 5000): Promise<T> {+/** #6355: how many times an admission attempt is re-run after the session dropped under it, and the pauses before each re-run. */+export const CONNECTION_LOSS_RETRY_MS = [100, 300, 900] as const;+const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++/**+ * #6355: the typed outcome when the session kept dropping under the admission. Nothing here says whether the write was+ * accepted: the caller re-reads the retained request id (replaying the same request_id is a read, never a second admission).+ */+export function writeOutcomeUnknown(requestId: string, error: unknown): OperationError {+ const cause = error instanceof Error ? error.message.replace(/\b\w+:\/\/\S+/g, '<url>').slice(0, 160) : String(error).slice(0, 160);+ const uuid = UUID.test(requestId);+ const unknown = opError('write_outcome_unknown', 'The database connection dropped while this write was being admitted, so whether it was accepted is unknown.',+ uuid ? `Read request ${requestId} before doing anything else: a committed or pending row means the write was accepted (replay the same request_id to wait for it); no row means it was not (submit it again with the same request_id). Never submit it under a new request_id without that read.`+ : 'Read the writer status before doing anything else; replay the same request ids rather than allocating new ones.',+ { reason: 'connection_lost', detail: cause, fix: uuid+ ? { argv: ['gbrain', 'write-request', '--', requestId], mcp: { tool: 'get_write_request', arguments: { request_id: requestId } }, consent: [], actor: 'agent', requires_exclusive: false,+ why: `Reads request ${requestId}'s durable row, read-only: its presence and state are the truth the dropped connection could not deliver.` }+ : { argv: ['gbrain', 'sources', 'writer', 'status', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows every pending, running or recovering request of this writer, read-only.' } });+ unknown.writeError = 'write_outcome_unknown';+ return unknown;+}++/**+ * Retry only database-confirmed transaction aborts, retaining the accepted intent and UUID. #6355: a session that drops+ * under the attempt (a pooler or failover closing the socket with the admission in flight) is re-run too, because every+ * attempt begins by reading the retained request id and replays an admitted row instead of admitting again; so re-running+ * is a read, never an inference of rollback. When the session keeps dropping, the caller gets `write_outcome_unknown`+ * with the id to read, never the raw socket error that a receipt oracle would take for a refusal.+ */+export async function retryWriteAdmission<T>(requestId: string, attempt: (remainingMs: number) => Promise<T>, budgetMs = 5000,+ recover?: (error: unknown) => Promise<void>): Promise<T> {const deadline = performance.now() + budgetMs;+ let lost = 0;for (;;) {try {return await attempt(Math.max(1, Math.floor(deadline - performance.now())));} catch (error) {- // Connection/commit uncertainty is deliberately excluded: the caller must- // inspect/replay its retained ID, never infer rollback from a lost socket.const code = getCode(error);+ if (isConnectionLoss(error)) {+ const remaining = deadline - performance.now();+ if (lost >= CONNECTION_LOSS_RETRY_MS.length || remaining <= 25) throw writeOutcomeUnknown(requestId, error);+ await delay(Math.min(remaining - 1, CONNECTION_LOSS_RETRY_MS[lost++]!));+ // A pool whose sessions a pooler or failover killed hands out dead connections one statement at a time; the+ // engine's reconnect swaps in a fresh pool (best-effort: a failed rebuild is the next attempt's error).+ await recover?.(error).catch(() => undefined);+ continue;+ }if (!['40001', '40P01', '55P03', '57014'].includes(code ?? '')) throw error;const remaining = deadline - performance.now();if (remaining <= 25) {diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex 081a745d55..c1662e4435 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -29,6 +29,7 @@ import { faultPoint } from './fault-points.ts';import { releaseAbandonedClaims } from './effect-journal.ts';import { readWriteSwitchSnapshot, writeSwitchOn } from './switches.ts';import { consumerConnectionRoute, consumerStatementEngine, poolerExposureLine } from './consumer-lane.ts';+import { isConnectionLoss } from '../retry-matcher.ts';type PhaseObservation = { name: string; started_at: string; deadline_exceeded: boolean; attempt: number; first_conn_ms?: number };/** #5373: set by a task that abandons a still-running preparation after losing its claim; its root is freed only once `until` settles. */@@ -370,15 +371,23 @@ export class PersistenceConsumer implements PersistenceConsumerLike {const conn = await this.acquireIdleLane(undefined, true) as (ReservedConnection & Partial<ReservedTransactions>) | undefined;if (!conn?.transaction || this.laneInUse || this.probeOnLane || this.idleLane?.conn !== conn) return LANE_BUSY;this.laneInUse = true;+ // #6355: a lent transaction that lost its session says the lane's backend is gone (a pooler or failover closed it);+ // the lane is given up whatever `run` makes of the error (admission re-runs on the pool and may still succeed).+ let lost = false;+ const lend = async <R>(fn: (tx: BrainEngine) => Promise<R>): Promise<R> => {+ try { return await conn.transaction!(fn); }+ catch (error) { if (isConnectionLoss(error)) lost = true; throw error; }+ };try {- return await run(fn => conn.transaction!(fn));+ return await run(lend);} catch (error) {const code = (error as { code?: unknown } | null)?.code;- if (!(error instanceof OperationError) && !(typeof code === 'string' && /^[0-9A-Z]{5}$/.test(code)) && this.idleLane?.conn === conn) {- this.laneInUse = false; await this.releaseIdleLane(); this.idleLaneRetryAt = Date.now() + 60_000;- }+ if (!lost && !(error instanceof OperationError) && !(typeof code === 'string' && /^[0-9A-Z]{5}$/.test(code))) lost = true;throw error;- } finally { this.laneInUse = false; }+ } finally {+ this.laneInUse = false;+ if (lost && this.idleLane?.conn === conn) { await this.releaseIdleLane(); this.idleLaneRetryAt = Date.now() + 60_000; }+ }}private async probeQuery<T>(lane: ReservedConnection | undefined, sql: string, params: unknown[], signal?: AbortSignal): Promise<T[]> {if (!lane) return this.statements.executeRaw<T>(sql, params, { signal });diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex d49289f983..e458474de6 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -151,11 +151,14 @@ export function assertReplayIntent(row: WriteRequest, expectedDigest: string): Wexport async function admitWrite(engine: BrainEngine, input: WriteAdmission, overrides?: Partial<JournalLimits>,transaction: <T>(fn: (tx: BrainEngine) => Promise<T>) => Promise<T> = fn => engine.transaction(fn)): Promise<WriteRequest> {const { requestId, apply } = await prepareAdmission(engine, input, overrides);- return retryWriteAdmission(requestId, remaining => transaction(async tx => {+ // #6355: a lent connection (the consumer's warm lane) whose session dropped is dead for every later attempt, so the+ // re-run takes a transaction from the engine's pool after the pool itself is rebuilt.+ let run = transaction;+ return retryWriteAdmission(requestId, remaining => run(async tx => {const brain = await declareDurablePersistence(tx, `${Math.min(100, remaining)}ms`, `${remaining}ms`);if (input.brainId !== undefined && brain !== input.brainId) throw new PreadmitBrainChanged();return apply(tx);- }));+ }), undefined, async error => { run = fn => engine.transaction(fn); await engine.reconnect({ error }); });}/** Caller owns the transaction and retries its entire unit of work after rollback. */export async function admitWriteInTransaction(tx: BrainEngine, input: WriteAdmission, overrides?: Partial<JournalLimits>): Promise<WriteRequest> {diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.tsindex f44f1f9fd7..7dac52dcec 100644--- a/src/core/persistence/memory-mutations.ts+++ b/src/core/persistence/memory-mutations.ts@@ -235,7 +235,7 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'fo: { id, expired: true, path: 'legacy_db', reason: reason ?? 'forgotten' };return completeWrite(tx, row, 'committed', { ...outcome, persistence: { mode: 'database' } });}, requestAttribution(row));- }));+ }), undefined, error => ctx.engine.reconnect({ error }));// The commit removed the withdrawn pages' chunks. Rebuild them before// acknowledging: a CLI process exits without a resident projection worker.// A failed rebuild stays queued as durable projection work.diff --git a/src/core/persistence/page-batch.ts b/src/core/persistence/page-batch.tsindex 2c81d6a580..6520a97916 100644--- a/src/core/persistence/page-batch.ts+++ b/src/core/persistence/page-batch.ts@@ -167,7 +167,7 @@ async function admitBatch(ctx: OperationContext, batchId: string, admissions: Wrindexes.forEach((index, position) => { rows[index] = admitted[position]!; });}return rows;- }), BATCH_ADMISSION_BUDGET_MS);+ }), BATCH_ADMISSION_BUDGET_MS, error => ctx.engine.reconnect({ error }));}async function prepareAll(caller: OperationContext, batchId: string, sourceId: string, pages: BatchPage[]) {diff --git a/src/core/persistence/sync-group.ts b/src/core/persistence/sync-group.tsindex 1cb3f16f22..a4a372f90b 100644--- a/src/core/persistence/sync-group.ts+++ b/src/core/persistence/sync-group.ts@@ -144,6 +144,6 @@ export async function admitGroup(engine: BrainEngine, members: WaiverEntry[], cu]) as [unknown, WriteRequest[]];if (!await cursorHolds(tx)) throw new GroupMoved();return rows;- })).catch(error => { if (error instanceof GroupMoved) return null; throw error; });+ }), undefined, error => engine.reconnect({ error })).catch(error => { if (error instanceof GroupMoved) return null; throw error; });}class GroupMoved extends Error {}diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 73904cc137..a3ab20da36 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -1407,7 +1407,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPif (held?.request_id !== pending.requestId || held.same !== true) throw new CursorMoved();assertActive();return accepted;- })).catch(error => cursorMovedAdmission(engine, key, admitting, pending, error));+ }), undefined, error => engine.reconnect({ error })).catch(error => cursorMovedAdmission(engine, key, admitting, pending, error));if (!row) { cursor = await currentCursor(engine, key, cursor); continue; }await validateSyncAuthority(engine, cursor.authority, pending.slug);assertSyncDispatchActive();diff --git a/src/core/persistence/types.ts b/src/core/persistence/types.tsindex 8a196de996..a3d459278f 100644--- a/src/core/persistence/types.ts+++ b/src/core/persistence/types.ts@@ -21,6 +21,7 @@ export const WRITE_ERROR_CODES = ['timeline_rows_would_be_removed', 'preparation_stalled','timeline_rows_would_be_removed','fence_unrenderable',+ 'write_outcome_unknown',] as const;export type WriteErrorCode = typeof WRITE_ERROR_CODES[number];diff --git a/src/core/pg-access-classify.ts b/src/core/pg-access-classify.tsindex 02ab33a4de..703690241e 100644--- a/src/core/pg-access-classify.ts+++ b/src/core/pg-access-classify.ts@@ -285,11 +285,16 @@ const REASON_ROWS: ReadonlyArray<ReasonRow> = [{reason: 'conn_dropped',transient: true,- codes: ['CONNECTION_ENDED', 'CONNECTION_CLOSED'],+ // #6355: the server's own session ends (pg_terminate_backend, a crash or a failover: 57P01/57P02/57P03) and the+ // socket errnos a pooler drop surfaces are the same class; before this row they fell through to `unknown`.+ codes: ['CONNECTION_ENDED', 'CONNECTION_CLOSED', 'CONNECTION_DESTROYED', '57P01', '57P02', '57P03'],codePrefixes: ['08'],patterns: [/Connection terminated unexpectedly/i,+ /terminating connection due to administrator command/i,/ECONNRESET/i,+ /ECONNABORTED/i,+ /EPIPE/i,/connection.*closed/i,/server closed the connection/i,/could not connect to server/i,diff --git a/src/core/retry-matcher.ts b/src/core/retry-matcher.tsindex 56489be257..d4703dedf9 100644--- a/src/core/retry-matcher.ts+++ b/src/core/retry-matcher.ts@@ -150,6 +150,19 @@ export function isRetryableConnError(err: unknown): boolean {return CONN_PATTERNS.some(p => p.test(msg));}+/**+ * #6355: did the database session go away under a statement that was already sent? Narrower than+ * `isRetryableConnError` (no auth or startup races): the connection-class SQLSTATEs, postgres.js's own+ * connection codes, the server's admin/crash shutdown codes (`pg_terminate_backend`, a failover) and the+ * socket errnos. Such an error says nothing about whether the statement's transaction committed, so a+ * caller that sent a write must re-read its retained request id instead of inferring rollback.+ */+export function isConnectionLoss(err: unknown): boolean {+ const code = getCode(err);+ if (code && (/^08/.test(code) || ['CONNECTION_CLOSED', 'CONNECTION_ENDED', 'CONNECTION_DESTROYED', '57P01', '57P02', '57P03'].includes(code))) return true;+ return /\b(ECONNRESET|ECONNABORTED|ETIMEDOUT|EPIPE)\b|Connection terminated unexpectedly|server closed the connection|connection.*closed|terminating connection due to administrator command/i.test(getMessage(err));+}+/*** issue #1685 (CODEX #8): is this error specifically a POOLER REAP — postgres.js's* library-level `CONNECTION_ENDED` code (the transaction-mode pooler dropping andiff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex c240d79230..dde98d5a26 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -5865,7 +5865,7 @@"kind": "type","name": "ErrorCode","signature": [- "\"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"rate_limited\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | (string & {})"+ "\"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"rate_limited\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | (string & {})"]},{@@ -5952,7 +5952,7 @@{"kind": "class","members": [- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"rate_limited\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"budget_below_recent_runtime\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"pending_writes\" | \"persistence_write_stall\" | \"pglite_busy\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"serve_port_in_use\" | \"serve_status_only\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"source_binding_required\" | \"source_id_taken\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | undefined",+ "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"rate_limited\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"budget_below_recent_runtime\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"pending_writes\" | \"persistence_write_stall\" | \"pglite_busy\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"serve_port_in_use\" | \"serve_status_only\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"source_binding_required\" | \"source_id_taken\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | undefined","canonicalCode: string","cause?: unknown","code: ErrorCode",@@ -5971,9 +5971,9 @@"retryable?: boolean | undefined","stack?: string | undefined","suggestion?: string | undefined",- "toJSON: () => { contract_version?: 1 | undefined; fence_issues?: Record<string, unknown>[] | undefined; fence?: Record<string, unknown> | undefined; notices?: unknown[] | undefined; fix?: unknown; why?: string | undefined; reason?: string | undefined; write_error?: \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"preparation_stalled\" | \"fence_unrenderable\" | undefined; write_request?: WriteReceipt | undefined; error: ErrorCode; code: string; message: string; suggestion: string | undefined; docs: string | undefined; detail: string | undefined; protocol_version: number | undefined; }",+ "toJSON: () => { contract_version?: 1 | undefined; fence_issues?: Record<string, unknown>[] | undefined; fence?: Record<string, unknown> | undefined; notices?: unknown[] | undefined; fix?: unknown; why?: string | undefined; reason?: string | undefined; write_error?: \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | undefined; write_request?: WriteReceipt | undefined; error: ErrorCode; code: string; message: string; suggestion: string | undefined; docs: string | undefined; detail: string | undefined; protocol_version: number | undefined; }","why?: string | undefined",- "writeError?: \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"preparation_stalled\" | \"fence_unrenderable\" | undefined",+ "writeError?: \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | undefined","writeRequest?: WriteReceipt | undefined"],"name": "OperationError",diff --git a/test/persistence-admission-connection-loss.test.ts b/test/persistence-admission-connection-loss.test.tsnew file mode 100644index 0000000000..fad51dd5c5--- /dev/null+++ b/test/persistence-admission-connection-loss.test.ts@@ -0,0 +1,141 @@+/**+ * #6355: a session that drops under a write's admission is an ambiguous outcome,+ * never a refusal. The crash robot (`pooler_disconnect`, seed 5105) saw an+ * `edit_page` caller get the raw `write CONNECTION_CLOSED` back while its+ * admitted request went on to commit, so the receipt the caller held was untrue.+ * `retryWriteAdmission` now re-runs the attempt after a connection loss (every+ * attempt begins by reading the retained request id, so a re-run replays an+ * admitted row instead of admitting again) and, when the session keeps dropping,+ * returns the typed `write_outcome_unknown` with the id to read.+ *+ * Forced probe: `admitWrite` whose transaction commits but whose COMMIT+ * acknowledgment is lost (the wrapper throws `CONNECTION_CLOSED` after the body+ * ran). Before the fix the raw error escaped while the row existed; now the+ * admitted row comes back and exactly one request exists.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { admitWrite, getWriteRequest } from '../src/core/persistence/journal.ts';+import { CONNECTION_LOSS_RETRY_MS, retryWriteAdmission, writeOutcomeUnknown } from '../src/core/persistence/admission-retry.ts';+import { isConnectionLoss } from '../src/core/retry-matcher.ts';+import { CODES } from '../src/core/error-registry.ts';+import { admission, fixtures, initializeFixtures, selectFixtureHost, type HarnessConfig } from '../scripts/persistence/harness.ts';+import { withEnv } from './helpers/with-env.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-admission-connection-loss-'));+const config: HarnessConfig = {+ kind: 'pglite', root: home, dataDir: join(home, 'data'), hostId: randomUUID(),+ seed: 5105, schedules: 0, operations: 0,+ sourceIds: ['admission-loss', 'admission-loss-other'], principalIds: [randomUUID()],+};+const env = { GBRAIN_HOME: home, GBRAIN_PERSISTENCE_FIXTURE_HOME: home };+let engine: PGLiteEngine;+const dropped = (code = 'CONNECTION_CLOSED', message = `write ${code} 127.0.0.1:5432`) => Object.assign(new Error(message), { code });++beforeAll(async () => withEnv(env, async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ selectFixtureHost(config.hostId);+ await initializeFixtures(engine, config);+}), 120_000);+afterAll(async () => { await engine.disconnect(); rmSync(home, { recursive: true, force: true }); });++test('isConnectionLoss: the drop shapes a pooler, a failover and pg_terminate_backend produce; not auth, not a lock or statement timeout', () => {+ for (const error of [dropped(), dropped('CONNECTION_ENDED'), dropped('CONNECTION_DESTROYED'), Object.assign(new Error('terminating connection due to administrator command'), { code: '57P01' }),+ Object.assign(new Error('connection_failure'), { code: '08006' }), new Error('write ECONNABORTED db.example.invalid:5432'), new Error('write EPIPE'), new Error('Connection terminated unexpectedly')]) {+ expect(isConnectionLoss(error)).toBe(true);+ }+ for (const error of [Object.assign(new Error('canceled'), { code: '57014' }), Object.assign(new Error('lock'), { code: '55P03' }), Object.assign(new Error('serialize'), { code: '40001' }),+ new Error('password authentication failed for user "x"'), new OperationError('revision_conflict', 'x', 'y')]) {+ expect(isConnectionLoss(error)).toBe(false);+ }+});++test('retryWriteAdmission re-runs the attempt after a connection loss, ends write_outcome_unknown when it keeps dropping, and leaves every other error alone', async () => {+ const id = randomUUID();+ let calls = 0;+ const row = { request_id: id };+ // One drop, then the re-run reads the admitted row (what every attempt does first): the caller gets the row.+ expect(await retryWriteAdmission(id, async () => { calls++; if (calls === 1) throw dropped(); return row; })).toBe(row);+ expect(calls).toBe(2);+ // Keeps dropping: three re-runs on the 100/300/900 ms schedule, then the typed outcome with the id to read.+ calls = 0;+ const started = performance.now();+ const outcome = await retryWriteAdmission(id, async () => { calls++; throw dropped('57P01', 'terminating connection due to administrator command'); }).catch(error => error as OperationError);+ expect(calls).toBe(CONNECTION_LOSS_RETRY_MS.length + 1);+ expect(performance.now() - started).toBeGreaterThanOrEqual(CONNECTION_LOSS_RETRY_MS.reduce((a, b) => a + b, 0) - 20);+ expect(outcome).toBeInstanceOf(OperationError);+ expect(outcome).toMatchObject({ code: 'write_outcome_unknown', writeError: 'write_outcome_unknown', reason: 'connection_lost', detail: 'terminating connection due to administrator command' });+ expect(outcome.message).toContain('whether it was accepted is unknown');+ expect(outcome.suggestion).toContain(id);+ expect(outcome.fix).toMatchObject({ argv: ['gbrain', 'write-request', '--', id], mcp: { tool: 'get_write_request', arguments: { request_id: id } }, actor: 'agent' });+ expect(CODES.write_outcome_unknown).toMatchObject({ class: 'retryable', actor: 'agent' });+ // A batch id is not a request id: the fix is writer status.+ expect(writeOutcomeUnknown('batch 7', dropped()).fix?.argv).toEqual(['gbrain', 'sources', 'writer', 'status', '--json']);+ // The budget bounds the re-runs too.+ calls = 0;+ const short = await retryWriteAdmission(id, async () => { calls++; throw dropped(); }, 60).catch(error => error as OperationError);+ expect(short.code).toBe('write_outcome_unknown'); expect(calls).toBeLessThanOrEqual(2);+ // Any other error still escapes at once; a confirmed abort still retries as before.+ calls = 0;+ await expect(retryWriteAdmission(id, async () => { calls++; throw new OperationError('revision_conflict', 'x', 'y'); })).rejects.toMatchObject({ code: 'revision_conflict' });+ expect(calls).toBe(1);+ calls = 0;+ expect(await retryWriteAdmission(id, async () => { calls++; if (calls === 1) throw Object.assign(new Error('deadlock'), { code: '40P01' }); return row; })).toBe(row);+ expect(calls).toBe(2);+});++test('forced probe: admitWrite whose COMMIT acknowledgment is lost returns the admitted row instead of the raw socket error, and exactly one request exists', async () => withEnv(env, async () => {+ const sources = await fixtures(engine, config);+ const input = admission(config, sources[0], 'notes/ambiguous', 'A write whose commit acknowledgment the pooler dropped.');+ let drops = 0;+ // The transaction body runs and commits; the socket closes before the client hears about it.+ const lossy = <T>(fn: (tx: BrainEngine) => Promise<T>): Promise<T> => engine.transaction(fn).then(value => { if (drops++ === 0) throw dropped(); return value; });+ const row = await admitWrite(engine, input, undefined, lossy);+ // The lent transaction is tried once; the re-run that found the admitted row ran on the engine's pool.+ expect(drops).toBe(1);+ expect(row.request_id).toBe(input.requestId!);+ expect(['queued', 'running', 'committed']).toContain(row.state);+ const stored = await getWriteRequest(engine, input.principal, input.requestId!);+ expect(stored?.id).toBe(row.id);+ expect(await engine.executeRaw('SELECT count(*)::int AS n FROM persistence_requests WHERE request_id=$1::uuid', [input.requestId])).toEqual([{ n: 1 }]);+ // A pool whose sessions never come back: the typed outcome, still exactly one request (admitted by the first, acknowledged-lost attempt).+ const second = admission(config, sources[0], 'notes/ambiguous-twice', 'A second write under a connection that keeps dropping.');+ const always = <T>(fn: (tx: BrainEngine) => Promise<T>): Promise<T> => engine.transaction(fn).then(() => { throw dropped('CONNECTION_ENDED'); });+ const dying = Object.create(engine) as BrainEngine;+ Object.defineProperty(dying, 'transaction', { value: always });+ Object.defineProperty(dying, 'reconnect', { value: async () => undefined });+ const unknown = await admitWrite(dying, second).then(() => null, error => error as OperationError);+ expect(unknown).toMatchObject({ code: 'write_outcome_unknown' });+ expect(unknown!.suggestion).toContain(second.requestId!);+ expect(await engine.executeRaw('SELECT count(*)::int AS n FROM persistence_requests WHERE request_id=$1::uuid', [second.requestId])).toEqual([{ n: 1 }]);+ // Reading the id, as the fix says, finds the accepted write; replaying it is a read.+ expect((await getWriteRequest(engine, second.principal, second.requestId!))?.request_id).toBe(second.requestId!);+ expect((await admitWrite(engine, second)).request_id).toBe(second.requestId!);+ expect(await engine.executeRaw('SELECT count(*)::int AS n FROM persistence_requests WHERE request_id=$1::uuid', [second.requestId])).toEqual([{ n: 1 }]);+}), 60_000);++test('forced probe: a lent connection (the consumer\'s lane) that dropped is not retried; the re-run admits on the engine\'s pool', async () => withEnv(env, async () => {+ // The robot\'s probe write after `pooler_disconnect` (seed 5105, s1 of 10): the admission ran on the consumer\'s warm lane whose+ // backend the fault had killed, every re-run hit the same dead reservation ("Connection is no longer owned") and the caller got+ // write_outcome_unknown for a connection the pool could have served. The lent transaction is used once; the pool finishes the write.+ const sources = await fixtures(engine, config);+ const input = admission(config, sources[0], 'notes/lane-dropped', 'A write admitted on a lane the pooler killed.');+ let lent = 0;+ const deadLane = <T>(_fn: (tx: BrainEngine) => Promise<T>): Promise<T> => { lent++; return Promise.reject(dropped('CONNECTION_CLOSED', 'CONNECTION_CLOSED: Connection is no longer owned')); };+ let reconnects = 0;+ const pooled = Object.create(engine) as BrainEngine;+ Object.defineProperty(pooled, 'reconnect', { value: async () => { reconnects++; } });+ const row = await admitWrite(pooled, input, undefined, deadLane);+ expect(lent).toBe(1);+ expect(reconnects).toBe(1);+ expect(row.request_id).toBe(input.requestId!);+ expect(await engine.executeRaw('SELECT count(*)::int AS n FROM persistence_requests WHERE request_id=$1::uuid', [input.requestId])).toEqual([{ n: 1 }]);+}), 60_000);diff --git a/test/persistence-consumer-lane-loss.test.ts b/test/persistence-consumer-lane-loss.test.tsnew file mode 100644index 0000000000..1bdfb09ab5--- /dev/null+++ b/test/persistence-consumer-lane-loss.test.ts@@ -0,0 +1,61 @@+/**+ * #6355: the consumer's warm lane is one reserved backend. When the session under a lent transaction drops (a pooler or+ * failover killed it), every later use of the reservation fails the same way ("Connection is no longer owned"), so the lane+ * is given up as soon as a lent transaction reports a connection loss, whatever the lender makes of the error. Before the+ * fix, the lane was kept whenever `run` ended in an OperationError (admission turning the loss into a typed outcome) or+ * succeeded by other means, and the next write hit the dead reservation again.+ */+import { expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { LANE_BUSY, PersistenceConsumer } from '../src/core/persistence/consumer.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { resetWriteSwitches } from '../src/core/persistence/switches.ts';+import type { GBrainConfig } from '../src/core/config.ts';++const dropped = () => Object.assign(new Error('CONNECTION_CLOSED: Connection is no longer owned'), { code: 'CONNECTION_CLOSED' });++/** A postgres-shaped engine whose idle pool lends one reserved connection; `released` counts the reservations handed back. */+function laneEngine() {+ const state = { reserved: 0, released: 0, transactions: 0 };+ const engine = {+ kind: 'postgres',+ async executeRaw(sql: string) { return sql.startsWith('SELECT key,value FROM config') ? [] : []; },+ getPoolDiagnostics: () => ({ poolMax: 8, tracked: {}, poisonedDiscards: 0, pool: null, prepare: null }),+ async withReservedConnection(fn: (conn: unknown) => Promise<unknown>) {+ state.reserved++;+ try {+ return await fn({ executeRaw: async () => [], transaction: async <T>(run: (tx: BrainEngine) => Promise<T>) => { state.transactions++; return run(engine as unknown as BrainEngine); } });+ } finally { state.released++; }+ },+ };+ return { engine: engine as unknown as BrainEngine, state };+}+const consumerOf = (engine: BrainEngine) => new PersistenceConsumer(engine, {} as GBrainConfig, (async () => { throw new Error('unused'); }) as never, { hostId: 'lane-test' });++test('onLane lends its lane transaction and keeps the lane when the run succeeds on it', async () => {+ resetWriteSwitches();+ const { engine, state } = laneEngine();+ const consumer = consumerOf(engine);+ expect(await consumer.onLane(async transaction => transaction(async () => 'ran'))).toBe('ran');+ expect(state).toEqual({ reserved: 1, released: 0, transactions: 1 });+ expect(await consumer.onLane(async transaction => transaction(async () => 'again'))).toBe('again');+ expect(state).toEqual({ reserved: 1, released: 0, transactions: 2 });+});++test('forced probe: a lent transaction that lost its session gives the lane up even when the run turns the loss into a typed outcome or succeeds elsewhere', async () => {+ for (const ending of ['typed', 'succeeded'] as const) {+ resetWriteSwitches();+ const { engine, state } = laneEngine();+ const consumer = consumerOf(engine);+ const outcome = await consumer.onLane(async transaction => {+ await transaction(async () => { throw dropped(); }).catch(() => undefined);+ if (ending === 'typed') throw new OperationError('write_outcome_unknown', 'unknown', 'read the id');+ return 'admitted on the pool';+ }).then(value => ({ value }), error => ({ error: (error as OperationError).code }));+ expect(outcome).toEqual(ending === 'typed' ? { error: 'write_outcome_unknown' } : { value: 'admitted on the pool' });+ // The dead reservation went back to the pool, and the lane is not retaken for a minute.+ expect(state).toEqual({ reserved: 1, released: 1, transactions: 1 });+ expect(await consumer.onLane(async transaction => transaction(async () => 'late'))).toBe(LANE_BUSY);+ expect(state.reserved).toBe(1);+ }+});diff --git a/test/postgres-driver-startup-death.test.ts b/test/postgres-driver-startup-death.test.tsnew file mode 100644index 0000000000..c7e11b3b3f--- /dev/null+++ b/test/postgres-driver-startup-death.test.ts@@ -0,0 +1,157 @@+/**+ * #6355: two reconnect defects of the vendored driver that the crash robot's `pooler_disconnect` fault reached.+ *+ * A backend terminated while the driver is still starting the connection (the array-types fetch that+ * `fetch_types` runs before the caller's first statement) used to leave that internal query and its FATAL+ * `57P01` behind in the connection's state. The fresh connection then delivered the stale error to the caller's+ * query at its first ReadyForQuery (the crash robot's `put_page refused/57P01` on a live database), and the+ * internal query's promise rejected with nobody awaiting it, which Bun treats as fatal for the process (the+ * robot worker's exit 1). The vendored driver now settles the internal query and clears the saved error before+ * reconnecting, and the fetch swallows its own failure.+ *+ * A close that arrives while a statement's bytes wait for the connection's write immediate used to leave those+ * bytes and the cleared timer handle behind, so the next connection's StartupMessage was appended to them and never+ * scheduled: the socket stayed open until CONNECT_TIMEOUT and every statement the pool bound to that slot failed,+ * for as long as the slot kept being chosen (the robot's effects worker, 10 s per pass, for minutes).+ *+ * Forced probes against a scripted server: the first kills the first connection with FATAL 57P01 at its first+ * statement (before the fix the caller's `select 1` rejected with 57P01 or the process saw an unhandled rejection);+ * the second delivers a close to the driver while a statement's bytes wait for the write immediate (before the fix+ * the statement after it failed with CONNECT_TIMEOUT against a server that answers in a millisecond). Both serve+ * the second connection normally.+ */+import { afterEach, expect, test } from 'bun:test';+import { createServer, Socket, type Server } from 'node:net';+import postgres from '#postgres';++/** A client socket whose close the test can deliver to the driver synchronously, the way a FIN read in the same poll as a reply lands. */+class ScriptedSocket extends Socket {+ closeNow(): void {+ const listeners = this.listeners('close') as ((hadError: boolean) => void)[];+ this.removeAllListeners('close');+ this.destroy();+ for (const listener of listeners) listener(false);+ }+}++/** A one-byte type plus int32 length frame of the wire protocol. */+const frame = (type: string, body: Buffer = Buffer.alloc(0)): Buffer => {+ const header = Buffer.alloc(5);+ header.write(type, 0, 'ascii'); header.writeInt32BE(body.length + 4, 1);+ return Buffer.concat([header, body]);+};+const cstr = (s: string): Buffer => Buffer.from(`${s}\0`, 'utf8');+const readyForQuery = frame('Z', Buffer.from('I'));+const startupReply = Buffer.concat([+ frame('R', Buffer.from([0, 0, 0, 0])),+ frame('S', Buffer.concat([cstr('server_version'), cstr('16.0')])),+ frame('S', Buffer.concat([cstr('client_encoding'), cstr('UTF8')])),+ frame('K', Buffer.from([0, 0, 0, 7, 0, 0, 0, 9])),+ readyForQuery,+]);+const fatalTerminated = frame('E', Buffer.concat([+ Buffer.from('S'), cstr('FATAL'), Buffer.from('V'), cstr('FATAL'), Buffer.from('C'), cstr('57P01'),+ Buffer.from('M'), cstr('terminating connection due to administrator command'), Buffer.from([0]),+]));++/**+ * Answers the extended protocol with empty results (ParseComplete, BindComplete, NoData, CommandComplete, ReadyForQuery)+ * and a simple Query with CommandComplete. `kill` ends the connection with FATAL 57P01 at its first statement.+ */+function serve(socket: Socket, buffered: Buffer, mode: { kill?: boolean }, onStatement: () => void): Buffer {+ let rest: Buffer = buffered;+ for (;;) {+ if (rest.length < 5) return rest;+ const type = String.fromCharCode(rest[0]!), length = rest.readInt32BE(1);+ if (rest.length < length + 1) return rest;+ rest = rest.subarray(length + 1);+ if (type === 'P' || type === 'Q') onStatement();+ if (mode.kill) { socket.write(fatalTerminated); socket.end(); return Buffer.alloc(0); }+ if (type === 'P') socket.write(frame('1'));+ else if (type === 'B') socket.write(frame('2'));+ else if (type === 'D') socket.write(frame('n'));+ else if (type === 'E') socket.write(frame('C', cstr('SELECT 0')));+ else if (type === 'S') socket.write(readyForQuery);+ else if (type === 'Q') socket.write(Buffer.concat([frame('C', cstr('SELECT 0')), readyForQuery]));+ else if (type === 'X') { socket.end(); return Buffer.alloc(0); }+ }+}++let server: Server | undefined;+afterEach(() => new Promise<void>(resolve => { server ? server.close(() => resolve()) : resolve(); server = undefined; }));++/** A scripted server; `script(n)` chooses how the n-th connection (1-based) behaves. */+async function listen(script: (connection: number) => { kill?: boolean }): Promise<{ port: number; connections: { statements: number }[] }> {+ const connections: { statements: number }[] = [];+ server = createServer(socket => {+ const connection = { statements: 0 };+ connections.push(connection);+ const mode = script(connections.length);+ let buffered: Buffer = Buffer.alloc(0), started = false;+ socket.on('data', (chunk: Buffer) => {+ buffered = Buffer.concat([buffered, chunk]);+ if (!started) {+ if (buffered.length < 8) return;+ const length = buffered.readInt32BE(0);+ if (buffered.length < length) return;+ buffered = buffered.subarray(length); started = true;+ socket.write(startupReply);+ }+ buffered = serve(socket, buffered, mode, () => { connection.statements++; });+ });+ socket.on('error', () => undefined);+ });+ await new Promise<void>(resolve => server!.listen(0, '127.0.0.1', () => resolve()));+ return { port: (server.address() as { port: number }).port, connections };+}+function client(port: number): { sql: ReturnType<typeof postgres>; socket: () => ScriptedSocket } {+ let current: ScriptedSocket | undefined;+ // A socket option hands the driver a connecting socket (the driver then skips its own connect step); the option is not in the public types.+ const options = { host: '127.0.0.1', port, user: 'u', password: 'p', database: 'd', ssl: false, max: 1, prepare: false, fetch_types: true, connect_timeout: 2, onnotice() {},+ socket: () => (current = new ScriptedSocket()).connect(port, '127.0.0.1') };+ const sql = postgres(options as unknown as Parameters<typeof postgres>[0]);+ return { sql, socket: () => current! };+}++test('forced probe: a backend terminated during startup neither fails the caller\'s first statement with the stale 57P01 nor leaves an unhandled rejection', async () => {+ const { port, connections } = await listen(connection => ({ kill: connection === 1 }));+ const unhandled: unknown[] = [];+ const onUnhandled = (reason: unknown) => { unhandled.push(reason); };+ process.on('unhandledRejection', onUnhandled);+ const { sql } = client(port);+ try {+ // The caller's first statement: the driver's own types fetch runs ahead of it on the first connection, which the server kills.+ const rows = await sql.unsafe('select 1');+ expect([...rows]).toEqual([]);+ expect(connections.length).toBe(2);+ expect(connections[0]).toEqual({ statements: 1 });+ expect(connections[1]!.statements).toBeGreaterThanOrEqual(2);+ await Bun.sleep(20);+ expect(unhandled).toEqual([]);+ } finally {+ process.off('unhandledRejection', onUnhandled);+ await sql.end({ timeout: 1 });+ }+}, 15_000);++test('forced probe: a close delivered while a statement\'s bytes wait for the write immediate does not leave the next connection\'s startup unsent', async () => {+ // The crash robot's stuck pool slot: a backend answered and was terminated at once; the caller's next statement was+ // buffered for that socket (its write immediate pending) when the close arrived. The cleared immediate left its+ // handle and bytes behind, so the reconnect's StartupMessage was appended and never flushed: the socket sat open+ // until CONNECT_TIMEOUT, and every statement the pool bound to that slot failed the same way, for minutes.+ const { port, connections } = await listen(() => ({}));+ const { sql, socket } = client(port);+ try {+ expect([...await sql.unsafe('select 1')]).toEqual([]);+ const second = sql.unsafe('select 2').then(() => null, (error: { code?: string }) => error.code);+ // Let the statement reach the connection (Query.handle awaits one tick before dispatching) without letting the+ // write immediate run, then deliver the close: the bytes are still buffered for the socket that just closed.+ for (let i = 0; i < 4; i++) await Promise.resolve();+ socket().closeNow();+ expect(await second).toBe('CONNECTION_CLOSED');+ // The next statement takes the slot the pool reconnects: before the fix, CONNECT_TIMEOUT against a server that answers at once.+ expect([...await sql.unsafe('select 3')]).toEqual([]);+ expect(connections.length).toBe(2);+ expect(connections[1]!.statements).toBeGreaterThanOrEqual(2);+ } finally { await sql.end({ timeout: 1 }); }+}, 15_000);diff --git a/test/sync-drain-claims.test.ts b/test/sync-drain-claims.test.tsindex df8ffe58b1..179021d4da 100644--- a/test/sync-drain-claims.test.ts+++ b/test/sync-drain-claims.test.ts@@ -259,10 +259,35 @@ describe('engineStallProbe fingerprint', () => {});/** Captures the drain's stderr lines (`serr` writes through console.error without a source prefix). */-function captureStderr(): { lines: string[]; stalled: () => string[]; restore(): void } {- const lines: string[] = [];- const spy = spyOn(console, 'error').mockImplementation((...args: unknown[]) => { lines.push(args.map(String).join(' ')); });- return { lines, stalled: () => lines.filter(line => line.includes('· stalled ')), restore: () => spy.mockRestore() };+function captureStderr(): { lines: string[]; stalled: () => string[]; stalledAt: () => Array<{ line: string; at: number }>; restore(): void } {+ const lines: string[] = [], at: number[] = [];+ const spy = spyOn(console, 'error').mockImplementation((...args: unknown[]) => { lines.push(args.map(String).join(' ')); at.push(Date.now()); });+ const stalledAt = () => lines.flatMap((line, i) => line.includes('· stalled ') ? [{ line, at: at[i]! }] : []);+ return { lines, stalled: () => stalledAt().map(entry => entry.line), stalledAt, restore: () => spy.mockRestore() };+}+/** One head read of the stall probe: when it started and when it settled (the line it feeds prints right after it settles). */+interface HeadRead { startedAt: number; settledAt: number }+/** Wraps a probe's `head` so every read's start and settle times are kept, in settle order. */+function headReadsOf(probe: StallProbe): { probe: StallProbe; list: HeadRead[] } {+ const list: HeadRead[] = [];+ const head = probe.head;+ if (!head) return { probe, list };+ return { list, probe: { ...probe, head: async () => {+ const startedAt = Date.now();+ try { return await head(); } finally { list.push({ startedAt, settledAt: Date.now() }); }+ } } };+}+/**+ * The stall lines that belong to the park: each line is attributed to the latest head read settled at or before it was+ * printed, and counts only when that read started after `parkedAt`. A read in flight across the stamp shows the state+ * before it (a true "preparing" line), so counting lines by position misattributes it to the park.+ */+function parkedStallLines(lines: ReadonlyArray<{ line: string; at: number }>, reads: ReadonlyArray<HeadRead>, parkedAt: number): string[] {+ if (!parkedAt) return [];+ return lines.flatMap(({ line, at }) => {+ const read = [...reads].reverse().find(entry => entry.settledAt <= at);+ return read && read.startedAt >= parkedAt ? [line] : [];+ });}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(); };const committed = { phase: 'managed_sync.page_committed' } as Parameters<NonNullable<Parameters<typeof runDrain>[0]['onProgress']>>[0];@@ -331,6 +356,21 @@ describe('live stall line during a pass (B6)', () => {await closePostgres?.(); rmSync(home, { recursive: true, force: true });});+ test('forced probe: a head read in flight across the park stamp prints a true "preparing" line that is not the park\'s first line', () => {+ // The master flake (#6271's unit-lane arm): read 1 starts before the stamp, settles after it, and its line prints after+ // the park snapshot. Counting lines by position took that line as the parked member's; attributing by read start does not.+ const parkedAt = 1_000;+ const reads: HeadRead[] = [{ startedAt: 990, settledAt: 1_005 }, { startedAt: 1_010, settledAt: 1_020 }];+ const lines = [{ line: '[sync] 1/3 processed · stalled 0s on preparing', at: 1_006 }, { line: '[sync] 1/3 processed · stalled 1s on origin_check (waiting on db) · allowed 2m', at: 1_021 }];+ const byPosition = lines.map(entry => entry.line);+ expect(byPosition[0]).toMatch(/on preparing$/);+ expect(parkedStallLines(lines, reads, parkedAt)).toEqual([lines[1]!.line]);+ // A line before the park, or with no settled read behind it, is never the park's.+ expect(parkedStallLines([{ line: lines[0]!.line, at: 900 }], reads, parkedAt)).toEqual([]);+ expect(parkedStallLines(lines, [], parkedAt)).toEqual([]);+ expect(parkedStallLines(lines, reads, 0)).toEqual([]);+ });+test('the line names the parked member\'s step within about two intervals, then the sync finishes once it is released', () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {for (const engine of engines) {const id = `live-${randomUUID().replace(/-/g, '').slice(0, 20)}`, root = join(home, id);@@ -345,22 +385,25 @@ describe('live stall line during a pass (B6)', () => {await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');let release!: () => void;const released = new Promise<void>(resolve => { release = resolve; });- let parkedAt = 0, linesBeforePark = 0;+ let parkedAt = 0;const err = captureStderr();- // Lines printed before the park (a request still queued at startup) are not the parked member's.- const parkedLines = () => err.stalled().slice(linesBeforePark);+ // A stall line comes from a head read; only a read that started after the park can show the parked member's stamp.+ // A read started before the stamp committed and settled after it prints a true-at-read-time "preparing" line, so the+ // lines are attributed to their read's start, never counted by position (#6355 fold-in: the master flake on #6271).+ const probe = engineStallProbe(engine, id);+ const reads = headReadsOf(probe);+ const parkedLines = () => parkedStallLines(err.stalledAt(), reads.list, parkedAt);// The first member parks in preparation, honouring its signal; the stamp gains the step a preparer would enter (the keys a renewal writes).installFaultHook(async (at, detail) => {if (at !== 'consumer:preparing' || detail.sourceId !== id || parkedAt) return;await engine.executeRaw(`UPDATE persistence_requests SET claim_phase = claim_phase || '{"step":"origin_check","waiting_on":"db"}'::jsonb WHERE request_id=$1::uuid`, [detail.requestId]);parkedAt = Date.now();- linesBeforePark = err.stalled().length;await new Promise<void>(resolve => { void released.then(resolve); detail.signal?.addEventListener('abort', () => resolve(), { once: true }); });});try {const bulk = await resolveBulkSettings(await preparationConfigView(engine), false);expect(bulk.enabled).toBe(engine.kind === 'postgres');- const drain = runDrain({ announce: true, progressMs: PROGRESS, probe: engineStallProbe(engine, id), bulk: { enabled: bulk.enabled, reason: bulk.reason },+ const drain = runDrain({ announce: true, progressMs: PROGRESS, probe: reads.probe, bulk: { enabled: bulk.enabled, reason: bulk.reason },pass: (signal, onProgress) => performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true, signal, onProgress, ...(bulk.enabled ? { bulk } : {}) }) });expect(await until(() => parkedAt > 0, 30_000)).toBe(true);const seen = await until(() => parkedLines().length > 0, 10 * PROGRESS);diff --git a/vendor/postgres/cf/src/connection.js b/vendor/postgres/cf/src/connection.jsindex 28a432b7ea..4f654a37ab 100644--- a/vendor/postgres/cf/src/connection.js+++ b/vendor/postgres/cf/src/connection.js@@ -455,6 +455,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseremaining = 0incomings = nullclearImmediate(nextWriteTimer)+ // GBrain (#6355): bytes still waiting for the cleared immediate belonged to this socket. Left in place, the next+ // connection's StartupMessage is appended to them and never scheduled for writing (the timer handle is not+ // null), so the connection sits open until CONNECT_TIMEOUT and every statement bound to it fails.+ chunk = nextWriteTimer = nullsocket.removeListener('data', data)socket.removeListener('connect', connected)idleTimer.cancel()@@ -469,10 +473,18 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose? cancelReject(cancelError || Errors.connection('CONNECTION_CLOSED', options)): cancelResolve()- if (initial)+ if (initial) {+ // GBrain (#6355): a connection that died during startup (its backend terminated under the array-types fetch)+ // leaves that internal query and the error it saw behind. The fresh connection must not deliver the stale+ // error to the caller's query at its first ReadyForQuery, and the internal query settles here instead of+ // rejecting with nobody to hear it.+ query && query !== initial && queryError(query, Errors.connection('CONNECTION_CLOSED', options, socket))+ query = results = errorResponse = nullreturn reconnect()+ }!hadError && (query || sent.length) && error(Errors.connection('CONNECTION_CLOSED', options, socket))+ query = nullclosedTime = performance.now()hadError && options.shared.retries++delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000@@ -797,14 +809,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseasync function fetchArrayTypes() {needsTypes = false- const types = await new Query([`- select b.oid, b.typarray- from pg_catalog.pg_type a- left join pg_catalog.pg_type b on b.oid = a.typelem- where a.typcategory = 'A'- group by b.oid, b.typarray- order by b.oid- `], [], execute)+ let types+ try {+ types = await new Query([`+ select b.oid, b.typarray+ from pg_catalog.pg_type a+ left join pg_catalog.pg_type b on b.oid = a.typelem+ where a.typcategory = 'A'+ group by b.oid, b.typarray+ order by b.oid+ `], [], execute)+ } catch (error) {+ // GBrain (#6355): the fetch failed or its connection closed; errored() has already told the caller's query, and+ // connected() re-arms the fetch for the next connection. Nothing awaits this promise, so it must not reject.+ return+ }types.forEach(({ oid, typarray }) => addArrayType(oid, typarray))}diff --git a/vendor/postgres/cjs/src/connection.js b/vendor/postgres/cjs/src/connection.jsindex f6d76e59ab..ec88b7ca40 100644--- a/vendor/postgres/cjs/src/connection.js+++ b/vendor/postgres/cjs/src/connection.js@@ -453,6 +453,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseremaining = 0incomings = nullclearImmediate(nextWriteTimer)+ // GBrain (#6355): bytes still waiting for the cleared immediate belonged to this socket. Left in place, the next+ // connection's StartupMessage is appended to them and never scheduled for writing (the timer handle is not+ // null), so the connection sits open until CONNECT_TIMEOUT and every statement bound to it fails.+ chunk = nextWriteTimer = nullsocket.removeListener('data', data)socket.removeListener('connect', connected)idleTimer.cancel()@@ -467,10 +471,18 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose? cancelReject(cancelError || Errors.connection('CONNECTION_CLOSED', options)): cancelResolve()- if (initial)+ if (initial) {+ // GBrain (#6355): a connection that died during startup (its backend terminated under the array-types fetch)+ // leaves that internal query and the error it saw behind. The fresh connection must not deliver the stale+ // error to the caller's query at its first ReadyForQuery, and the internal query settles here instead of+ // rejecting with nobody to hear it.+ query && query !== initial && queryError(query, Errors.connection('CONNECTION_CLOSED', options, socket))+ query = results = errorResponse = nullreturn reconnect()+ }!hadError && (query || sent.length) && error(Errors.connection('CONNECTION_CLOSED', options, socket))+ query = nullclosedTime = performance.now()hadError && options.shared.retries++delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000@@ -795,14 +807,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseasync function fetchArrayTypes() {needsTypes = false- const types = await new Query([`- select b.oid, b.typarray- from pg_catalog.pg_type a- left join pg_catalog.pg_type b on b.oid = a.typelem- where a.typcategory = 'A'- group by b.oid, b.typarray- order by b.oid- `], [], execute)+ let types+ try {+ types = await new Query([`+ select b.oid, b.typarray+ from pg_catalog.pg_type a+ left join pg_catalog.pg_type b on b.oid = a.typelem+ where a.typcategory = 'A'+ group by b.oid, b.typarray+ order by b.oid+ `], [], execute)+ } catch (error) {+ // GBrain (#6355): the fetch failed or its connection closed; errored() has already told the caller's query, and+ // connected() re-arms the fetch for the next connection. Nothing awaits this promise, so it must not reject.+ return+ }types.forEach(({ oid, typarray }) => addArrayType(oid, typarray))}diff --git a/vendor/postgres/src/connection.js b/vendor/postgres/src/connection.jsindex 792c83d36a..c4d90e6282 100644--- a/vendor/postgres/src/connection.js+++ b/vendor/postgres/src/connection.js@@ -453,6 +453,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseremaining = 0incomings = nullclearImmediate(nextWriteTimer)+ // GBrain (#6355): bytes still waiting for the cleared immediate belonged to this socket. Left in place, the next+ // connection's StartupMessage is appended to them and never scheduled for writing (the timer handle is not+ // null), so the connection sits open until CONNECT_TIMEOUT and every statement bound to it fails.+ chunk = nextWriteTimer = nullsocket.removeListener('data', data)socket.removeListener('connect', connected)idleTimer.cancel()@@ -467,10 +471,18 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose? cancelReject(cancelError || Errors.connection('CONNECTION_CLOSED', options)): cancelResolve()- if (initial)+ if (initial) {+ // GBrain (#6355): a connection that died during startup (its backend terminated under the array-types fetch)+ // leaves that internal query and the error it saw behind. The fresh connection must not deliver the stale+ // error to the caller's query at its first ReadyForQuery, and the internal query settles here instead of+ // rejecting with nobody to hear it.+ query && query !== initial && queryError(query, Errors.connection('CONNECTION_CLOSED', options, socket))+ query = results = errorResponse = nullreturn reconnect()+ }!hadError && (query || sent.length) && error(Errors.connection('CONNECTION_CLOSED', options, socket))+ query = nullclosedTime = performance.now()hadError && options.shared.retries++delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000@@ -795,14 +807,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseasync function fetchArrayTypes() {needsTypes = false- const types = await new Query([`- select b.oid, b.typarray- from pg_catalog.pg_type a- left join pg_catalog.pg_type b on b.oid = a.typelem- where a.typcategory = 'A'- group by b.oid, b.typarray- order by b.oid- `], [], execute)+ let types+ try {+ types = await new Query([`+ select b.oid, b.typarray+ from pg_catalog.pg_type a+ left join pg_catalog.pg_type b on b.oid = a.typelem+ where a.typcategory = 'A'+ group by b.oid, b.typarray+ order by b.oid+ `], [], execute)+ } catch (error) {+ // GBrain (#6355): the fetch failed or its connection closed; errored() has already told the caller's query, and+ // connected() re-arms the fetch for the next connection. Nothing awaits this promise, so it must not reject.+ return+ }types.forEach(({ oid, typarray }) => addArrayType(oid, typarray))}