Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.57.0.0 fix: bound accepted-write waits and report safe receipt health (#5411)

Garry Tan467ff6737f74
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index a3a6e07b8c..1e1b71a0ba 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.56.2.0",
+ "version": "0.57.0.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index bb77fc6835..81873941a8 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.56.2.0",
+ "version": "0.57.0.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index 267d06a8e6..adb20e111b 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.56.2.0 -->
+<!-- gbrain-runbook-stamp: 0.57.0.0 -->
<!-- This stamp must equal the VERSION file at every release; CI enforces it
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
the installed binary and warns on skew. -->
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f6233b5bd2..3585d34c9a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,52 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [0.57.0.0] - 2026-09-24
+
+**Know when an accepted write needs attention.**
+
+An accepted write is not always a finished write. When a page or remembered fact is waiting, its receipt can now distinguish ordinary pending work from a known blocker or an unusually old request. Your agent gets a sensible polling interval and a clear instruction to inspect the existing owner when waiting alone is no longer enough. It keeps the original request reference instead of creating a duplicate.
+
+Locked expired work no longer holds up the entire scheduler while unrelated work could proceed. Slow preparation and supported database waits have deadlines, and repeated receipt waits no longer accumulate unfinished reads. A deadline does not turn a pending write into a successful save or authorize another publisher. Work that cannot actually be cancelled stays tracked until it settles, and shutdown keeps the existing safety protections in place. Once contention clears, the original accepted request can finish without losing its identity or applying its content twice.
+
+### How to check a pending write
+
+Keep the original `request_id` and arguments. Read its receipt, then inspect the selected brain's existing owner when advised:
+
+```bash
+gbrain write-request <request-id> --json
+gbrain sources writer status --brain <brain> --probe --json
+```
+
+| What the receipt knows | What to do |
+| --- | --- |
+| Recent request, no known blocker | Poll after 1 second, then 5 seconds as it ages. |
+| Ordinary contention or an earlier write | Retain the original request and poll after 5 seconds. |
+| At least two minutes old, or an operator-required blocker | Inspect the existing owner; poll no faster than every 30 seconds. |
+
+Age is advisory, not proof of a dead owner. Older clients may omit the optional diagnosis. Never remove locks, transfer ownership, or discard recovery records just because a request is old.
+
+## To take advantage of v0.57.0.0
+
+Use `gbrain upgrade` during your approved owner rollout. If automatic migrations did not complete, run:
+
+```bash
+gbrain apply-migrations --yes --no-autopilot-install
+gbrain sources writer status --brain <brain> --probe --json
+gbrain stats
+```
+
+Schema migration 165 adds an index for database-only pending writes. It does not rewrite accepted requests or change the writer protocol. Quiesce the existing owner before replacing or rolling it back, preserve original receipts and recovery state, and verify canonical page or fact readback before calling a deployed incident recovered. If migration or verification fails, report sanitized doctor output and the failing step at https://github.com/garrytan/gbrain/issues; do not include credentials or private content.
+
+### Itemized changes
+
+- Pending receipts include validated, privacy-filtered age, assessment, reason and next action. Initial responses, replay, receipt helpers and frozen memory verbs preserve their existing required fields and error codes.
+- Receipt health enrichment is authorization-first, batched for at most 100 receipts, bounded to a 500ms caller wait, and limited to one unsettled query per engine. The new pending index keeps retained terminal history out of this lookup.
+- Expired-claim sweeps skip locked rows without bypassing same-root order. Supported scheduler and renewal waits use cancellation budgets; ordinary `put_page` and `remember` preparation gets a cooperative deadline with late-result fencing.
+- PostgreSQL timeout cancellation isolates the affected query from neighboring work, including transaction siblings and connections reassigned after a disconnect. Cancellation failures do not authorize blind statement retries.
+- PostgreSQL pool shutdown rejects work still waiting for a connection instead of silently reconnecting after shutdown. Recognized shutdown cancellations no longer appear as resident storage failures.
+- Trusted writer status exposes process-local phases, deadlines and attempts, with inspection advice consistent with receipt health. Operator guidance distinguishes observation from recovery authority and local tests from live recovery.
+
## [0.56.2.0] - 2026-09-24
**Keep valid search data, publish the right file, and restore backups safely.**
diff --git a/VERSION b/VERSION
index cbf49b916d..7f8cf5a566 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.56.2.0
+0.57.0.0
diff --git a/bun.lock b/bun.lock
index 881154e808..b3357aa4d6 100644
--- a/bun.lock
+++ b/bun.lock
@@ -31,7 +31,7 @@
"marked": "^18.0.2",
"openai": "^4.0.0",
"pgvector": "^0.2.0",
- "postgres": "^3.4.0",
+ "postgres": "3.4.9",
"tree-sitter-wasms": "0.1.13",
"web-tree-sitter": "0.22.6",
"zod": "^4.3.6",
@@ -52,6 +52,9 @@
"trustedDependencies": [
"@electric-sql/pglite",
],
+ "patchedDependencies": {
+ },
"overrides": {
"@ai-sdk/provider-utils": "4.0.33",
"@hono/node-server": "^2.0.5",
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 89a892c153..6225b89c26 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -326,6 +326,28 @@ active preparation without starting another request.
do not replace their durable files while unbound, moved and original bound paths
all remain fenced.
+`test/e2e/persistence-http-liveness.test.ts` drives real authenticated HTTP MCP
+with legacy and source-bound OAuth credentials against an isolated PostgreSQL
+database. It covers pending page/fact writes, lost acknowledgments, owner
+interruption, exact canonical readback, 44 pages over three clients, and current
+receipt authorization. Set `GBRAIN_TEST_OLD_BINARY` to a retained compatible
+executable to additionally exercise old/new owner handoffs in both directions
+for queued, actually claimed and recovery-bearing rows. Interrupted owners are
+reaped and native exclusion is verified before their successors start; only the
+abandoned running lease is advanced by the fixture. An omitted executable skips
+these compatibility cases, not proves them.
+`test/e2e/persistence-phase-liveness.test.ts` holds real table/row locks and
+ordinary/direct pool slots to verify phase cancellation (including capacity
+marking), tracked queued `BEGIN`, renewal, expired-head FIFO and shutdown fences.
+A loopback TCP gate separately delays or rejects cold direct initialization,
+checking retained work through shutdown and same-ID completion after retry.
+The memory-mutation tests use a
+deterministic loopback embedding transport for slow and aborted preparation;
+they do not contact a paid provider. Receipt contract, MCP parser, IPC and CLI
+tests pin the same nested allowlist and advisory age policy. Diagnostic tests
+exercise both fresh/index-upgrade parity and a genuinely interrupted PostgreSQL
+concurrent index build when a PostgreSQL fixture is supplied.
+
`test/persistence-chaos.slow.test.ts` and `test/e2e/persistence-chaos.test.ts`
execute real journal/coordinator schedules and eight SIGKILL publication
boundaries, followed by a small multi-process soak. The Postgres test creates
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index 56425a5534..24be7e559b 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -53,11 +53,13 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/persistence/{atom-maintenance,atom-retry,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry, authorized multi-entity fact-fence/backstop append and local synthesize/patterns/consolidation. Accepted output replays provider-free after restart; page/take preparers recheck original/current grants, source incarnation and revisions. Unresolved facts remain DB-only without phantom pages. Retired takes skip; semantic fact snapshots exclude derived vector/cache fields and journal quotas reject overlarge retained intent. Managed consolidation retains the explicit chronological `valid_until` writeback from the legacy consolidation phase, scoped to the accepted source/fact IDs and revalidated semantic snapshots; contradiction probes never gain supersession authority. Remote maintenance and unapproved bulk lanes remain refused. Tests: `test/managed-extract-atoms.test.ts`, `test/managed-facts-backstop.test.ts`, `test/managed-maintenance.test.ts`.
-- `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. Backoff occurs after rollback releases the connection; ambiguous connection/commit errors are never classified as confirmed rollback. Real counter-lock and after-insert rollback tests live in `test/persistence-journal.test.ts`. Withdrawal retries wrap its whole source-exclusive transaction; `admitWriteInTransaction` never backs off inside an existing unit of work. `test/persistence-withdrawal-retry.test.ts` verifies guard release, complete rollback and bounded contention.
+- `src/core/persistence/admission-retry.ts` — bounded retries for database-confirmed admission transaction aborts. Each retry reuses the UUID and normalized intent, rechecks guarded authority and reserves quota only on commitment. Standalone journal admission uses 10ms lock waits within the five-second retry budget; 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, read-capacity and after-insert rollback tests live in `test/persistence-journal.test.ts`. Withdrawal retries wrap its whole source-exclusive transaction with its existing lock policy; `admitWriteInTransaction` never backs off inside an existing unit of work. `test/persistence-withdrawal-retry.test.ts` verifies guard release, complete rollback and bounded contention.
- `src/core/persistence/connector-sync.ts` — managed Google/GitHub API ingestion uses source-scoped journaled import/deletion and `managed-connector` checkpoint CAS, not Git cursors. Unbound connectors use reviewed `connector_database` SQL-only authority; bound connectors retain canonical file publication with guarded root/hash/revision/epoch. Standalone entry, page reads and submissions authenticate the current source, local grant and canonical owner, then start the existing consumer and wait up to five seconds for retained worktree publications to settle before checking file bytes or deriving new request identity. Blocked recovery returns its retained receipt and `blocked_reason`; startup recovery precedes connector fetching, and operator edits still fail the strict file-drift check. Explicit `--retry-failed` atomically admits a new linked attempt and stores a per-base-request `managed-connector-retry` pointer, without changing the API cursor or reopening terminal receipts. Approval revalidates current and accepted authority, source/configuration/owner and idle state; concurrent approvals and pending/restarted calls reuse the already approved attempt. Receipt compaction retains the digest and authority needed for exact replay and retry. Checkpoint page-receipt lists are server-derived validation dependencies, excluded from caller identity but frozen in the first admitted intent; changed dependency lists on an unchanged sweep cannot bypass a terminal checkpoint. Durable connector cursors and retry pointers survive generic seven-day checkpoint GC, including completed sweeps needed for incremental resume. Source incarnation/configuration changes select separate cursors; obsolete state remains retained rather than automatically retiring by age. Failed pagination/identity reads cannot advance freshness or delete unconfirmed pages. Tests: `test/persistence-connectors.test.ts`, `test/persistence-connector-retry.test.ts` and `test/helpers/connector-restart.ts` cover synthetic public sync entry in fresh processes, actual SIGKILL between file publication and DB commit, blocked recovery, zero-fetch authorization refusal, aged cursor purge/resume, real storage failures, compacted retries, checkpoint dependencies, atomic approval/lost acknowledgement and concurrent paused-owner replay on PGLite and disposable Postgres.
-- `src/core/persistence/consumer.ts` — bounded resident canonical-write consumer. Terminal completion preempts a pending idle poll; wake-ups requested during an active tick are retained until it finishes. Blocked/retryable attempts retain normal polling, and stop drains active work without scheduling its successor. `test/persistence-consumer-scheduling.test.ts` pins these scheduling boundaries. Managed-root refresh selects one stable record per path, preferring a bound worktree over a fallback source path, so repeated refreshes do not replace the same durable record twice; distinct unbound and moved paths remain fenced (`test/persistence-root-refresh.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. 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. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`.
+
+- `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`.
- `src/core/persistence/effect-facts.ts` + `page-advisories.ts` — bounded writer-lint/facts-backstop outbox. Eligibility, anti-loop, selected configuration, original/current grants and source/page revision guards precede scheduling. Page publication records the effect; job insertion and completion use its stable idempotency key. Managed backstop retains the committed original page request as the facts-absorb job authority, including OAuth/stdio origin; no fabricated CLI authority or blanket managed skip. Legacy unsupported raw queue/fence paths remain refused. Tests: `test/persistence-facts-backstop.test.ts`, `test/managed-facts-backstop.test.ts`.
diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.md
index 6fb5a2d026..257a112226 100644
--- a/docs/architecture/key-files/engines-2.md
+++ b/docs/architecture/key-files/engines-2.md
@@ -3,6 +3,8 @@
[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]` — pinned ESM/CommonJS driver ownership and cancellation repair consumed by `PostgresEngine.runUnsafe`. Abortable reservations settle atomically; shared transaction queues isolate cancellable SQL from tagged/savepoint siblings while preserving unfenced pipelining. See [PostgreSQL cancellation ownership](../postgres-cancellation.md) for settlement, deadline, transport and clean-install invariants. Pinned by `test/e2e/persistence-chaos.test.ts`.
+
- `src/core/pglite-resetwal.ts` — pg_resetwal for PGLite NodeFS data dirs, in TypeScript (a port of the electric-sql/pglite pg_resetwal contribution, PR #994, Apache-2.0). Validates the PG17 pg_control layout fail-closed (`WalResetUnsupportedError` on any unsupported shape — PG_VERSION ≠ 17, control ≠ 8192 bytes, control version ≠ 1700, bad seg/block size), removes stale postmaster.pid + old WAL segments + archive_status/summaries entries, writes a replacement shutdown-checkpoint WAL segment + CRC32C'd pg_control. Both file writes are atomic + durable (tmp cleared then opened `'wx'` so a pre-planted symlink at the predictable tmp name can never redirect the write, + fsync(tmp) + rename + fsync(parent dir)); write order is segment-first/control-last so a mid-write kill leaves a state that still fails startup and the next attempt re-runs (idempotent — a torn pair can never claim success). WAL segment size is capped at 64MB (pglite ships 16MB; the Postgres-general 1GB bound would let a corrupt-but-plausible control field drive a 1GB allocation on the repair path). Exports the shared PG17 layout literals (`PG_CONTROL_FILE_SIZE`, `isWalSegmentName`) consumed by pglite-repair.ts. LAYOUT COUPLING: any pglite bump past PG17 must revisit this file together with the `./vector` export blocker (TODOS.md "pglite upgrade blocker" entry). Pinned by `test/pglite-resetwal.test.ts`.
- `src/core/pool-budget.ts` + `src/core/persistence/pool-capacity.ts` — physical-pool shared long-hold ceilings retain one ordinary/control connection across engine clones; pool size one pauses canonical consumption with `writer_pool_capacity`. Publication concurrency is capped at two per actual Postgres pool and one per PGLite owner. `persistence/takes-prepare.ts` journals semantic takes with frozen dates/resolver identity and original/current holder ceilings; canonical row updates and receipt commit together. Publication retains the actual affected holders privately in authority JSON, so narrowed holder grants also hide committed/replayed receipts after input compaction.
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index ba53935dce..899d408968 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -4,12 +4,12 @@
- `src/core/persistence/sync-failures.ts` — durable managed cursor/receipt diagnostics are the authority; JSONL is a compatibility mirror keyed by cursor and source/path. Failure observations deduplicate terminal receipts, retaining structured codes and attempts; success clears only its matching cursor. Local CLI shows request/run/pinned target details, while remote doctor returns source-scoped aggregates without paths, raw messages or receipt IDs. Missing durable state warns rather than certifying health. Failed receipts cannot be acknowledged, auto-skipped or rewritten; explicit idle ordinary-source retry creates fresh admission, while approved company manifests remain pinned. Tests: `test/persistence-sync-failures.serial.test.ts`, `test/e2e/managed-sync-failures.test.ts`.
-- `src/commands/mcp-expose-probe.ts` — the health / occupancy probes `mcp-expose.ts` runs, peeled out behind a narrow `ProbeDeps` (`fetch`, `tcpProbe`, `lookup`, `now`, `sleep`, `healthIntervalMs`) rather than the whole resolved-deps bag: `tryFetch(d, url, timeoutMs)` (one bounded fetch, `redirect: 'manual'`, never throws → `FetchOutcome { res, unresolved }`), `probeHealth` (`res.ok` — the `verify.*` / `--status` bar), `probeOccupied` (an accepted TCP connect OR any HTTP answer — the foreign-listener bar), `pollHealth` (wall-clock budget from `d.now()`, per-probe timeout `min(1500, remaining)`, attempt cap `ceil(budget / healthIntervalMs)` as the frozen-clock backstop, `unresolved` = the LAST probe's verdict), `unresolvedDetail(dnsName)`, `defaultTcpProbe` (one `node:net` connect, socket destroyed on every outcome) and `defaultLookup` (`dns.promises.lookup`). The name-resolution verdict is the reason the module exists: Bun's `fetch` rejects an unresolvable host with the SAME error as a refused connection ("Unable to connect. Is the computer able to access the url?", code `ConnectionRefused`), so a message match alone never fires in production. After a rejection `nameUnresolved` takes `new URL(url).hostname`, skips IP literals (`isIP`) and `localhost`, and otherwise awaits `d.lookup(host)` raced against the probe's `timeoutMs` (a lookup that does not answer in time proves nothing; the race keeps a late rejection handled); `isUnresolvedLookupError` classifies the lookup rejection by `code` — `ENOTFOUND`, `EAI_AGAIN`, `EAI_NONAME`, `EAI_NODATA`, `DNS_ENOTFOUND` (a resolver outage counts: the verdict is about THIS host) — or by those tokens in its message, and the fetch-message regex (`ENOTFOUND|getaddrinfo|EAI_AGAIN|failed to resolve|Unable to connect.*resolve`) is OR-ed in afterwards as the secondary hint. Tests inject a fake fetch, TCP probe and resolver (`test/mcp-expose.test.ts`; the fixture's default `lookup` resolves every name, and one test uses the real `defaultLookup` against a `.invalid` name).
+- `src/commands/mcp-expose-probe.ts` — the health / occupancy probes `mcp-expose.ts` runs, peeled out behind a narrow `ProbeDeps` (`fetch`, `tcpProbe`, `lookup`, `now`, `sleep`, `healthIntervalMs`) rather than the whole resolved-deps bag: `tryFetch(d, url, timeoutMs)` (one bounded fetch, `redirect: 'manual'`, never throws → `FetchOutcome { res, unresolved }`), `probeHealth` (`res.ok` — the `verify.*` / `--status` bar), `probeOccupied` (an accepted TCP connect OR any HTTP answer — the foreign-listener bar), `pollHealth` (wall-clock budget from `d.now()`, per-probe timeout `min(1500, remaining)`, attempt cap `ceil(budget / healthIntervalMs)` as the frozen-clock backstop, `unresolved` = the LAST probe's verdict), `unresolvedDetail(dnsName)`, `defaultTcpProbe` (one `node:net` connect, socket destroyed on every outcome) and `defaultLookup` (local RFC 6761 `.invalid` rejection, otherwise `dns.promises.lookup`). The name-resolution verdict is the reason the module exists: Bun's `fetch` rejects an unresolvable host with the SAME error as a refused connection ("Unable to connect. Is the computer able to access the url?", code `ConnectionRefused`), so a message match alone never fires in production. After a rejection `nameUnresolved` takes `new URL(url).hostname`, skips IP literals (`isIP`) and `localhost`, and otherwise awaits `d.lookup(host)` raced against the probe's `timeoutMs` (a lookup that does not answer in time proves nothing; the race keeps a late rejection handled); `isUnresolvedLookupError` classifies the lookup rejection by `code` — `ENOTFOUND`, `EAI_AGAIN`, `EAI_NONAME`, `EAI_NODATA`, `DNS_ENOTFOUND` (a resolver outage counts: the verdict is about THIS host) — or by those tokens in its message, and the fetch-message regex (`ENOTFOUND|getaddrinfo|EAI_AGAIN|failed to resolve|Unable to connect.*resolve`) is OR-ed in afterwards as the secondary hint. Tests inject a fake fetch, TCP probe and resolver (`test/mcp-expose.test.ts`; the fixture's default `lookup` resolves every name, reserved-name and label-boundary cases do not query external DNS, and the real `defaultLookup` resolves localhost).
- `src/core/tailscale.ts` — Tailscale helpers with an injected exec seam (`CommandRunner = (argv, { inherit?, timeoutMs?, stdoutToStderr? }) => Promise<CommandResult>` where `CommandResult = { status, stdout, stderr }` and `status: null` means killed at the timeout or never spawned; `defaultCommandRunner` on `Bun.spawn` — at `timeoutMs` it sends SIGTERM and, when the child has still not exited `SIGKILL_GRACE_MS` (3s) later, SIGKILL, so a child that ignores SIGTERM never hangs the caller; both timers are cleared in a `finally` — also the runner `serve-service.ts` types against; `stdoutToStderr` sends an inherited child's stdout to fd 2 so `--json` stdout stays pure): `parseTailscaleStatus` (`BackendState` — `Running`, `NeedsLogin`, `NeedsMachineAuth`, `NoState`, `Stopped`; `Self.DNSName`, `CertDomains`, and `funnelCapable`: true/false from `Self.CapMap` keys or `Self.Capabilities` entries containing `https://tailscale.com/cap/funnel`, null when both are absent), `publicUrlFromDnsName` (strip trailing dot, lowercase, `https://`), `TAILSCALE_BINARY_CANDIDATES` + `findTailscaleBinary` (`Bun.which`, then the macOS app bundle, Homebrew and `/usr/bin` paths; the candidate list doubles as `mcp-expose.ts`'s allowlist for a binary path recorded in a receipt) + `isSystemTailscaleBinary(binary, realpath = realpathSync)` (true when the path is a candidate literally or resolves to one through symlinks; an unresolvable path is false — `mcp-expose.ts` puts `sudo` in front of the binary only when this holds), `tailscaleInstallPlan(platform, hasBrew)`, `tailscaleLoginArgv(platform, user, binary)` → `{ setOperator?, up }` (Linux: `sudo <bin> set --operator=<user>` then a flagless `sudo <bin> up` — a flagged `up` trips the CLI's settings-revert check on a node with non-default prefs; macOS: `<bin> up`), `tailscaleManualLoginCommand(binary = 'tailscale')` (the Linux login the operator runs themselves when gbrain refuses to `sudo` a non-system binary — `sudo <bin> set --operator=$USER && sudo <bin> up` with the DISCOVERED path shell-quoted through `shellQuote`, because a binary outside sudo's `secure_path` is exactly that case) and `TAILSCALE_ACCEPT_DNS_COMMAND` (`tailscale set --accept-dns=true`, the MagicDNS-off remedy) — both keep their tailscale flag literals in this module so the flag-registry scan of `mcp-expose.ts` never sees them, `tailscaleServeArgv(port, { funnel })` (`serve --bg` / `funnel --bg`) + `tailscaleServeOffArgv({ funnel })` (`serve|funnel --https=443 --set-path=/ off` — `--set-path=/` scopes `off` to OUR `/` mount; without it the CLI removes every mount under `:443` and, when more than one exists, prompts interactively — with stdin ignored the prompt reads EOF and the command exits 0 having removed nothing; never `serve reset`), `parseServeStatusStrict` (the only serve-status parser, fail-closed: background `Web` handlers, `Foreground[<session>].Web` handlers marked `foreground: true`, and `TCP['443'].TCPForward` as a non-proxy root handler; an empty document / `{}` / `null` is the legitimately empty view, but non-JSON, an array or a scalar returns `null` so `mcp-expose.ts`'s `readServeView` can tell "could not read" from "nothing configured") + `findProxiedHandler(view, port)`, `classifyTailscaleError(stderr)` (Funnel rule before the HTTPS rule; the HTTPS rule matches certificate vocabulary, never a bare `https://` URL: `funnel_not_enabled` | `https_not_enabled` | `needs_operator` | `needs_login` | `daemon_not_running` | `unknown`), and the admin/KB URL constants (`TAILSCALE_ADMIN_DNS_URL`, `TAILSCALE_ADMIN_ACL_URL`, `TAILSCALE_FUNNEL_KB_URL` = `https://tailscale.com/kb/1223/funnel`, `TAILSCALE_DOWNLOAD_URL`). The parsers and argv builders are pure; the injectable `which` / `fileExists` / runner defaults touch `existsSync`, `process.env.PATH` and `process.platform`, and tests replace them. Note `tailscale status --json` exits 0 in every `BackendState` (only the human-readable form exits 1 when logged out), and `serve`/`funnel` wait interactively rather than failing when HTTPS certificates or the Funnel attribute are off — which is why `mcp-expose.ts` pre-checks before starting them.
- `src/core/serve-service.ts` — the persistent-service half of `mcp expose`, everything under `gbrainPath('serve')` (`serveDir`, `adminTokenPath`, `wrapperPath`, `receiptPath`, `serveLogPath`, `serveErrPath`) so `GBRAIN_HOME` is honored. `SERVE_LAUNCHD_LABEL = 'com.gbrain.serve'`, `SERVE_SYSTEMD_UNIT = 'gbrain-serve.service'`, `detectServiceTarget(signals)` → `'macos' | 'linux-systemd' | 'none'` (a working user bus is required for systemd; cloud sandboxes and ephemeral containers fall to `none`). `renderServeWrapper` produces the 0755 launcher that sources the shell profiles and `~/.gbrain/env`, prepends the Bun dir to `PATH`, reads the admin token from its file at run time into `GBRAIN_ADMIN_BOOTSTRAP_TOKEN` (the token is never written into the wrapper, plist or unit), resolves `gbrain` the way autopilot's wrapper does (baked installer path, `type -P gbrain` fallback) and `exec`s `serve --http --port N --public-url URL [--surface] [--enable-dcr]`. `resolveServeGbrainCommand({ which, execPath, argv1, metaUrl, fileExists })` picks the baked program: a `gbrain` on PATH wins; a COMPILED binary — `import.meta.url` (or the injected `metaUrl`) under `/$bunfs/`, or an `execPath` that is not the bun runtime while `argv[1]` is absent/virtual — is `[execPath]` whatever its basename (release assets are renamed); otherwise the `[bun, <cli.ts>]` dev form only when that `cli.ts` exists on disk, else `[execPath]` rather than a path that cannot run; `renderServeLaunchdPlist` (RunAtLoad, KeepAlive, ThrottleInterval 30, logs to `serve.log` / `serve.err`, local `escapeXml`) and `renderServeSystemdUnit` (After=network-online.target, Restart=always, RestartSec=10, start-limit window; systemd specifiers escaped — `%` → `%%` in `ExecStart` and both `append:` log paths, `$` → `$$` in `ExecStart`). `ensureAdminToken` (0700 dir, 0600 file created with `wx` semantics, 64 hex chars; reuse a file matching the exported `ADMIN_TOKEN_SHAPE` = `^[A-Za-z0-9_-]{32,}$` — the same regex `serve-http.ts`'s `resolveBootstrapToken` accepts, so the file and the env var can never disagree on what a valid token is — unlink and regenerate otherwise), `installServeService` (launchd: domain-explicit `launchctl bootout gui/<uid> <plist>` — failure ignored — then `launchctl bootstrap gui/<uid> <plist>`, both through the one `launchctl(run, uid, plist, { modern, legacy })` helper whose legacy `launchctl unload` / `load` fallback is used ONLY when the modern verb exits non-zero with stderr matching `/Unknown command|unrecognized|not found/i`, never on a genuine failure or a killed call, and which reports the `verb` whose result it returns; a bootstrap that fails with stderr matching `LAUNCHCTL_SETTLE_RE` (`Input/output error`, `already in progress`, `\b5\b`, `\b37\b` — launchd still unloading the previous job) is retried up to `LAUNCHCTL_SETTLE_RETRIES` (5) times, `LAUNCHCTL_SETTLE_MS` (1s) apart through the injectable `sleep` param (default `setTimeout`; `mcp-expose.ts` passes `d.sleep`), a success after retries is a note and an exhausted retry appends "(after N settle retries)" to `error`; systemd: `daemon-reload` → `enable` → `restart` so a regenerated wrapper takes effect; `loginctl enable-linger` best effort) / `uninstallServeService` (launchd: the same `bootout gui/<uid>` with the same fallback; a bootout that exits non-zero — or is killed — with stderr NOT matching `LAUNCHCTL_NOT_LOADED_RE` (`No such process|not loaded|Could not find|not find service`) pushes `launchctl <verb> failed: <describeFailure>` into `notes`, and the exported `launchdBootoutFailed(result)` recognizes that note so `mcp-expose.ts` can say the job may still be loaded) / `serveServiceState` (`launchctl print gui/<uid>/<label>` / `systemctl --user is-active`); all three take `uid?: number` defaulting to `process.getuid?.() ?? 501`, threaded from `mcp-expose.ts`. Every supervisor subprocess carries a timeout — 60s for `launchctl bootstrap/bootout` (and the legacy `load/unload`) and `systemctl --user enable/restart/disable`, 15s for `launchctl print`, `daemon-reload`, `is-active` and `loginctl enable-linger` — and a `status: null` (killed) result counts as a failure (`error` / note) or `unknown` state; a failed call is described by `describeFailure` (its stderr, else stdout, else `exit <status>`). `readExposeReceipt` / `writeExposeReceipt` (`expose.json`, 0600, version 1, no secrets): the reader is a structural shape guard, not just `version`/`port`/`public_url` — it also requires `mode` in `tailnet|funnel`, a `service` object with a string `wrapper_path`, a `target` in `macos|linux-systemd|none`, a string `state` and string-or-null `plist_path` / `unit_path`, a `tailscale` object whose `binary` / `dns_name` are string-or-null, and string `mcp_url` / `admin_url` / `admin_token_file`; anything less is null (absent), so `--status` / `--remove` never dereference a half-written receipt. The token, receipt, wrapper, plist and unit writers refuse (clear error) when the target path is a symlink (`lstatSync`) before any supervisor call runs. Uses `shellQuote` from `src/core/mcp-registration.ts`; every filesystem/exec effect is behind injectable deps.
- `src/core/harness/verify.ts` — Randomized server-side memory verification with revision-conditional cleanup and retained mutation UUIDs, with separate transport, identity, authority, read, write/readback, delegation and cleanup verdicts. Lost mutation responses are reconciled before retry; server success never certifies native-harness activation or cross-conversation behavior.
-- `src/core/persistence/memory-mutations.ts` + `memory-prepare.ts` — managed `remember`, `forget`, and `forget_fact`: durable same-ID replay precedes entity/TTL/provider work; semantic append preparation preserves hidden canonical fences and revalidates dedup under page guards. Withdrawal admits and completes in one source-exclusive database transaction, independent of filesystem ownership, with durable mirror/projection work. `src/core/facts/single-prepare.ts` isolates provider preparation from the SQL-only semantic decision. Tests: `test/persistence-memory-mutations.test.ts` runs identical races on PGLite and PostgreSQL.
+- `src/core/persistence/memory-mutations.ts` + `memory-prepare.ts` — managed `remember`, `forget`, and `forget_fact`: durable same-ID replay precedes entity/TTL/provider work; semantic append preparation preserves hidden canonical fences and revalidates dedup under page guards. Withdrawal admits and completes in one source-exclusive database transaction, independent of filesystem ownership, with durable mirror/projection work. `src/core/facts/single-prepare.ts` isolates provider preparation from the SQL-only semantic decision and propagates cooperative provider abort without degrading it into success. Preparation checkpoints prevent a late aborted result from reaching publication. Tests: `test/persistence-memory-mutations.test.ts` runs identical races on PGLite and PostgreSQL.
- `src/core/page-state/import-guard.ts` — imported canonical bytes publish only after source/page identity and knowledge-revision CAS, including unchanged-file and legacy hash-repair paths. Prepared same-hash imports compare full canonical metadata and additive tags, since captured timestamps are excluded from content hashes. Tests: `import-revision-concurrency.test.ts`.
- `src/core/persistence/{maintenance,root-registry,filesystem-guard,writer-guard-schema}.ts` — fail-closed legacy writer coverage: durable private refusal records and shared refusal-only root markers work before PGLite connect, resolve symlink ancestors, and retain stale roots conservatively. The selected PGLite path is registered at connect/init and source claim refresh, so managed reinit refuses even offline; unmanaged backup acquires the stable sibling native lock through rename. SQL guards include free-text aliases and canonical source sync checkpoints. `docs/architecture/canonical-writers.tsv` is the finite writer census; `canonical-writer-inventory.test.ts` rejects unreviewed additions, and `persistence-writer-fences.test.ts`/`pglite-maintenance-fence.test.ts` exercise real engines, competing processes and separate homes.
diff --git a/docs/architecture/postgres-cancellation.md b/docs/architecture/postgres-cancellation.md
new file mode 100644
index 0000000000..d59585ddcd
--- /dev/null
+++ b/docs/architecture/postgres-cancellation.md
@@ -0,0 +1,31 @@
+# PostgreSQL cancellation ownership
+
+GBrain pins `postgres` to 3.4.9 and applies `patches/[email protected]` through Bun's `patchedDependencies`. The patch covers the ESM and CommonJS entrypoints and their shared types. Keep both implementations equivalent, and verify a clean frozen-lockfile install after changing the patch. An edited `node_modules` directory is not a distributable fix.
+
+## Dispatch and settlement
+
+`PostgresEngine.runUnsafe` uses an abortable exclusive reservation for signaled SQL outside a transaction. Inside an existing transaction or reserved callback, it uses that owner. The driver's `cancelFence` option drains predecessors before dispatch and prevents successor dispatch until both the marked query and its cancellation transport settle. This includes tagged queries and savepoints sharing the transaction, not just calls to `executeRaw`. Unmarked work can still pipeline.
+
+The fence prevents two different failures: a late CancelRequest hitting a successor, and an inactive canceled query being skipped while its protocol responses are incorrectly delivered to another query. Cancellation is not a statement retry. A failed cancellation transport discards only the connection still owned by that lease; a stale release or discard cannot affect its replacement.
+
+A transaction installs its owner while sending `BEGIN`, but does not expose the scoped SQL handle until `BEGIN` settles. Its synchronous ReadyForQuery handler runs before the awaiting continuation. Preserve that ordering: the fence's idle state must mean no active or sent predecessor remains.
+
+Reservation grant parks and assigns the connection before resolving the waiter. Grant, rejection and abort share idempotent queue/listener cleanup. An abort observed after grant releases that exact lease. Saved query and savepoint handles reject after ownership changes rather than borrowing the replacement owner.
+
+The engine's abort listener stays attached across reservation acquisition and query execution. Removing the last listener from `AbortSignal.timeout()` during that handoff disables its timer on Bun 1.3.13 and 1.3.14, even if another listener is attached afterward; the same control works on 1.3.11. This protects a single engine call, not reuse of that timeout signal across completed calls. Production phase and renewal budgets use explicit `AbortController` timers. Pool shutdown rejects queued work and cannot reconnect or grant a released slot to a new owner.
+
+## Deadline and transport limits
+
+A phase deadline requests cancellation; it is not a promise that PostgreSQL has stopped at that instant. The owner remains accounted for until actual settlement. Cancellation-channel completion is bounded by the driver's connection timeout, which defaults to ten seconds, and can outlast a five-second phase budget. A blocked or failed transport must not be reported as a successful cancellation.
+
+The phase's `deadline_exceeded` observation records an elapsed budget even when shutdown requested cancellation first and settlement is still pending. It does not replace that first abort reason: recognized stop-owned cancellation is not reported as a storage error, while deadline-first cancellation and unrelated errors remain visible.
+
+An abort before dispatch can produce `AbortError`; a PostgreSQL cancellation can produce SQLSTATE `57014`. Callers must honor their aborted signal rather than interpreting every `57014` as permission to retry. The raw engine methods do not retry statements.
+
+Direct PostgreSQL closes the cancellation connection after handling the request. Through a transaction pooler, safe reuse also depends on the pooler's cancellation routing and backend quarantine. Tests against one pooler version do not establish safety for every proxy or deployment. Direct TLS negotiation and PostgreSQL STARTTLS are separate transport cases; coverage of one is not evidence for the other.
+
+## Regression evidence
+
+`test/e2e/persistence-chaos.test.ts` exercises active, queued, delayed and failed cancellation; transaction siblings; stale ownership; atomic reservation settlement; reconnects; completed cursors; and real socket backpressure in both module formats. Its optional PgBouncer case requires `GBRAIN_PGBOUNCER_URL` and `GBRAIN_PGBOUNCER_DIRECT_URL`, uses a dedicated test database, and verifies another client can reuse the same server backend without receiving a late cancellation.
+
+Keep the response-mapping, actual-settlement and unchanged persistence latency checks alongside these protocol tests. Global `max_pipeline: 1`, serializer fallbacks and blind retries are not substitutes for ownership isolation.
diff --git a/docs/guides/concurrent-writes.md b/docs/guides/concurrent-writes.md
index 4eceb21465..ff71910ced 100644
--- a/docs/guides/concurrent-writes.md
+++ b/docs/guides/concurrent-writes.md
@@ -206,6 +206,36 @@ revision, outcome, persistence status, and timestamps. Terminal receipts have
`retry_after_ms: null`. Private queued content, credential hashes, and recovery
bytes are never part of the receipt.
+Nonterminal receipts may include a validated `diagnostic` with `age_ms`,
+`assessment` (`pending`, `blocked`, or `stalled`), a closed `reason`, and
+`next_action` (`poll` or `inspect_owner`). An optional `observed_at` is the
+observation time, not the last useful progress time. Older servers may omit
+diagnostics. A fallback without fresh dependency evidence omits the observation
+timestamp; it does not claim that a cached row is current.
+
+| Observation | Recommended polling |
+| --- | ---: |
+| No known blocker, younger than 30 seconds | 1 second |
+| No known blocker, 30 seconds to under 2 minutes | 5 seconds |
+| Ordinary contention or an earlier write | 5 seconds |
+| At least 2 minutes old, or an operator-required blocker | 30 seconds; inspect the existing owner |
+
+These are advisory thresholds, not a completion SLA. `stalled` means the request
+is taking longer than expected, not that a deadlock or dead owner is proven.
+Request age starts at durable acceptance; lease renewals do not reset it.
+`cause_unknown` is an honest lack of evidence. `waiting_on_earlier_write` never
+identifies another caller's request. Recovery, owner binding, native capability
+and pool-capacity reasons can require inspection without granting repair authority.
+
+**Say to your agent:** *“Keep the original request ID. Tell me whether this write
+is committed or needs the existing owner's inspection; don't submit a duplicate.”*
+
+Acceptance is not completion. Retain the UUID and original arguments, poll the
+receipt when permitted, and verify the canonical page or fact before saying it
+was saved. If receipt helpers aren't available, repeat the same verb and original
+arguments with that UUID. When `next_action` is `inspect_owner`, ask the operator
+to inspect first instead of repeatedly submitting mutations.
+
`write_pending` means accepted work remains outstanding. `owner_unavailable`
and `writer_lock_unavailable` do not authorize a competing owner or a fresh
request ID. `queue_capacity` refuses additional admission without evicting
@@ -232,8 +262,15 @@ serializes startup and remains held until the listener has actually closed.
Admission retries confirmed database lock/serialization aborts for up to five
-seconds using the same UUID. Persistent contention returns a storage error with
-that UUID and no fabricated queued receipt. Keep the ID for the next attempt.
+seconds using the same UUID. Standalone journal admission limits each database
+lock wait to 10ms and backs off after rollback releases the connection. Confirmed
+lock-contention aborts use 5–25ms retry jitter; other retryable aborts retain
+25–100ms jitter. Waiting page writers release pool capacity between attempts
+instead of holding connections through long counter-lock waits.
+Persistent contention returns a storage error with that UUID and no fabricated
+queued receipt. Keep the ID for the next attempt. Admission inside a caller-owned
+transaction retains that transaction's lock policy; its caller is responsible for
+retrying the whole transaction after a confirmed abort.
## Frozen memory verbs
@@ -422,6 +459,49 @@ adjust; usage at or above 80% includes expansion guidance. Blocked requests carr
a concrete next action. Diagnostics contain no request content, credentials or
private checkout paths.
+The read-only incident recipe is to select the correct brain, retain the original
+receipts privately, and run:
+
+```bash
+gbrain sources writer status --brain <brain> --probe --json
+```
+
+Correlate request IDs with queued/running heads, retained recovery, pool capacity
+and sanitized owner logs. Resident phase, phase-start, deadline and attempt
+observations are process-local and reset on restart; a separate CLI process
+cannot infer another process's progress from its own ingress status. Worktree
+heartbeats and renewed request timestamps do not prove useful progress or owner
+death. Do not include content, SQL text, credentials or checkout paths in an
+incident report. Diagnosis does not authorize claiming, activating, transferring,
+restarting an owner, removing locks, or discarding recovery.
+
+The synchronous write wait stays bounded at five seconds. Receipt reads and
+optional health queries are accounted until their underlying work settles;
+health enrichment has a 500ms caller budget and at most one query per engine.
+Supported scheduler SQL waits use a five-second cancellation budget. Expired
+claim sweeps skip locked rows without bypassing same-root FIFO. Ordinary
+`put_page` and `remember` preparation receive a cooperative 30-second deadline;
+settled unpublished attempts can retry the same UUID. Work that ignores abort
+remains tracked and fenced. PGLite's in-process work cannot be forcibly cancelled,
+and shutdown must wait for actual settlement before releasing its datastore.
+Queued transaction `BEGIN` and direct-route initialization can also remain in
+flight after the phase deadline; the status reports that wait without claiming
+cancellation. A stopped consumer cannot begin preparation when a delayed claim
+eventually returns.
+
+PostgreSQL cancellation keeps the affected connection isolated until both the
+query and its cancellation transport settle, so a late cancellation cannot be
+sent into a successor's work by reusing that connection early. The cancellation
+transport can outlast the phase budget; this is not a hard database execution
+deadline. See [PostgreSQL cancellation ownership](../architecture/postgres-cancellation.md)
+for driver and pooler boundaries.
+
+An authorized replacement or rollback must quiesce the designated owner and
+retain accepted IDs, recovery reservations and additive indexes. Never downgrade
+below the existing writer protocol floor. If publication cannot safely drain,
+retain the fence and escalate. Local fixture success is not evidence that a
+particular deployed incident has recovered.
+
## Source lifecycle
After activation, source add, archive, restore, remove, purge, path rebind and
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index 80c5e905c3..06d6c0b63a 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -284,12 +284,21 @@ Response: `{ id, expired, reason, protocol_version }`.
Write receipts distinguish accepted work from committed memory. Their public
shape is `{request_id, state, retry_after_ms, revision?, outcome?, persistence?,
-compacted?, created_at?, updated_at?}`. States are `queued`, `running`,
+compacted?, created_at?, updated_at?, diagnostic?}`. States are `queued`, `running`,
`recovering`, `committed`, `conflict`, `failed`, and `cancelled`. Terminal
receipts have `retry_after_ms: null`. `persistence.mode` distinguishes a
filesystem-backed write from an intentional database-only write; Git progress
does not change the meaning of committed memory.
+Nonterminal receipts may include `diagnostic: {age_ms, assessment, reason,
+next_action, observed_at?}`. `assessment` is `pending`, `blocked`, or `stalled`;
+`reason` uses a closed allowlist, and `next_action` is `poll` or `inspect_owner`.
+Age measures time since acceptance, not time since the last lease renewal.
+`observed_at` is omitted when fresh dependency evidence is unavailable. These
+fields are advisory, not proof of owner death or permission to repair. Honor
+`retry_after_ms`, retain the original request ID, and inspect the existing owner
+before replay when advised. Older servers may omit `diagnostic` entirely.
+
A pending write is a protocol `unavailable` error with a populated suggestion,
`protocol_version: 1`, and optional `write_request` and `write_error` fields.
It never returns a success `status` or `expired` value. `write_error` carries
diff --git a/llms-full.txt b/llms-full.txt
index 648e3fa377..2d97f0f4fb 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -7076,12 +7076,21 @@ Response: `{ id, expired, reason, protocol_version }`.
Write receipts distinguish accepted work from committed memory. Their public
shape is `{request_id, state, retry_after_ms, revision?, outcome?, persistence?,
-compacted?, created_at?, updated_at?}`. States are `queued`, `running`,
+compacted?, created_at?, updated_at?, diagnostic?}`. States are `queued`, `running`,
`recovering`, `committed`, `conflict`, `failed`, and `cancelled`. Terminal
receipts have `retry_after_ms: null`. `persistence.mode` distinguishes a
filesystem-backed write from an intentional database-only write; Git progress
does not change the meaning of committed memory.
+Nonterminal receipts may include `diagnostic: {age_ms, assessment, reason,
+next_action, observed_at?}`. `assessment` is `pending`, `blocked`, or `stalled`;
+`reason` uses a closed allowlist, and `next_action` is `poll` or `inspect_owner`.
+Age measures time since acceptance, not time since the last lease renewal.
+`observed_at` is omitted when fresh dependency evidence is unavailable. These
+fields are advisory, not proof of owner death or permission to repair. Honor
+`retry_after_ms`, retain the original request ID, and inspect the existing owner
+before replay when advised. Older servers may omit `diagnostic` entirely.
+
A pending write is a protocol `unavailable` error with a populated suggestion,
`protocol_version: 1`, and optional `write_request` and `write_error` fields.
It never returns a success `status` or `expired` value. `write_error` carries
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index aa52384d8c..121abc239b 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.56.2.0",
+ "version": "0.57.0.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"kind": "context-engine",
diff --git a/package.json b/package.json
index 9e93fe9c69..d2e8c782d8 100644
--- a/package.json
+++ b/package.json
@@ -156,7 +156,7 @@
"marked": "^18.0.2",
"openai": "^4.0.0",
"pgvector": "^0.2.0",
- "postgres": "^3.4.0",
+ "postgres": "3.4.9",
"tree-sitter-wasms": "0.1.13",
"web-tree-sitter": "0.22.6",
"zod": "^4.3.6"
@@ -179,7 +179,7 @@
"bun": ">=1.3.11"
},
"license": "MIT",
- "version": "0.56.2.0",
+ "version": "0.57.0.0",
"overrides": {
"@ai-sdk/provider-utils": "4.0.33",
"@hono/node-server": "^2.0.5",
@@ -192,5 +192,8 @@
"ip-address": "^10.3.1",
"qs": "6.16.0",
"js-yaml": "^3.15.2"
+ },
+ "patchedDependencies": {
}
}
diff --git a/patches/[email protected] b/patches/[email protected]
new file mode 100644
index 0000000000..99495d6b52
--- /dev/null
+++ b/patches/[email protected]
@@ -0,0 +1,844 @@
+diff --git a/cjs/src/connection.js b/cjs/src/connection.js
+index 07f6716702ac888215c86ad6e0071aaf55ae519c..be36dfd08e084c7f1c181e42cd1c57d5213e3293 100644
+--- a/cjs/src/connection.js
++++ b/cjs/src/connection.js
+@@ -78,6 +78,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+
+ let socket = null
+ , cancelMessage
++ , cancelResolve
++ , cancelReject
++ , cancelError
+ , errorResponse = null
+ , result = new Result()
+ , incoming = Buffer.alloc(0)
+@@ -143,11 +146,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ }
+
+ async function cancel({ pid, secret }, resolve, reject) {
++ cancelResolve = resolve
++ cancelReject = reject
+ try {
+ cancelMessage = b().i32(16).i32(80877102).i32(pid).i32(secret).end(16)
+ await connect()
+- socket.once('error', reject)
+- socket.once('close', resolve)
++ if (!socket)
++ reject(cancelError || Errors.connection('CONNECTION_CLOSED', options))
+ } catch (error) {
+ reject(error)
+ }
+@@ -170,11 +175,12 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ : (query = q, query.active = true)
+
+ build(q)
++ const mayPipeline = !q.options.onexecute || q.options.onexecute(connection)
+ return write(toBuffer(q))
+ && !q.describeFirst
+ && !q.cursorFn
+ && sent.length < max_pipeline
+- && (!q.options.onexecute || q.options.onexecute(connection))
++ && mayPipeline
+ } catch (error) {
+ sent.length === 0 && write(Sync)
+ errored(error)
+@@ -295,7 +301,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+
+ /* c8 ignore next 3 */
+ function drain() {
+- !query && onopen(connection)
++ !query && !connection.reserved && onopen(connection)
+ }
+
+ function data(x) {
+@@ -379,6 +385,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ }
+
+ function error(err) {
++ if (cancelMessage)
++ cancelError = err
+ if (connection.queue === queues.connecting && options.host[retries + 1])
+ return
+
+@@ -388,6 +396,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ }
+
+ function errored(err) {
++ if (cancelMessage)
++ cancelError = err
+ stream && (stream.destroy(err), stream = null)
+ query && queryError(query, err)
+ initial && (queryError(initial, err), initial = null)
+@@ -447,6 +457,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ socket.removeAllListeners()
+ socket = null
+
++ if (cancelMessage)
++ return cancelError || hadError
++ ? cancelReject(cancelError || Errors.connection('CONNECTION_CLOSED', options))
++ : cancelResolve()
++
+ if (initial)
+ return reconnect()
+
+@@ -564,10 +579,12 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ return fetchArrayTypes()
+ }
+
+- initial && !initial.reserve && execute(initial)
++ const reserving = initial && initial.reserve
++ initial && !reserving && execute(initial)
+ options.shared.retries = retries = 0
+ initial = null
+- return
++ if (!reserving)
++ return
+ }
+
+ while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))
+@@ -580,7 +597,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ ? !connection.reserved.release && x[5] === 73 // I
+ ? ending
+ ? terminate()
+- : (connection.reserved = null, onopen(connection))
++ : connection.reserved(true)
+ : connection.reserved()
+ : ending
+ ? terminate()
+diff --git a/cjs/src/index.js b/cjs/src/index.js
+index f09c61c7e998f411560b95c9a8e1ed6a97972c11..9dc0c7a2303941079f2c3c4e668105444a8ef1af 100644
+--- a/cjs/src/index.js
++++ b/cjs/src/index.js
+@@ -200,40 +200,134 @@ function Postgres(a, b) {
+ return await sql`select pg_notify(${ channel }, ${ '' + payload })`
+ }
+
+- async function reserve() {
++ function own(c) {
+ const queue = Queue()
+- const c = open.length
+- ? open.shift()
++ let busy = false, fence = null, holding = null, releasing = false
++ const reservation = c.reserved = (ended = false) => {
++ if (c.reserved !== reservation)
++ return
++ busy = false
++ if (ended) {
++ releasing = true
++ reservation.reject(Errors.generic('CONNECTION_CLOSED', 'Transaction has ended'))
++ }
++ const completed = fence
++ fence = null
++ if (completed && completed.cancelPromise) {
++ holding = completed
++ completed.cancelPromise.then(() => {
++ if (c.reserved !== reservation || holding !== completed)
++ return
++ holding = null
++ pump()
++ }, reservation.discard)
++ } else {
++ pump()
++ }
++ }
++ reservation.enqueue = q => {
++ if (c.reserved !== reservation || releasing)
++ return q.reject(Errors.generic('CONNECTION_CLOSED', 'Connection is no longer owned'))
++ queue.push(q)
++ pump()
++ }
++ reservation.reject = error => {
++ while (queue.length)
++ queue.shift().reject(error)
++ }
++ reservation.discard = () => {
++ if (c.reserved !== reservation)
++ return
++ c.reserved = null
++ reservation.reject(Errors.generic('CONNECTION_CLOSED', 'Connection was discarded'))
++ c.terminate()
++ }
++ reservation.releaseConnection = () => {
++ if (c.reserved !== reservation)
++ return
++ releasing = true
++ pump()
++ }
++ return reservation
++
++ function pump() {
++ if (c.reserved !== reservation || holding || fence)
++ return
++ while (queue.length) {
++ const q = queue.peek()
++ if (q.cancelled) {
++ queue.shift()
++ continue
++ }
++ if (busy && (q.options.cancelFence || c.queue === full))
++ return
++ queue.shift()
++ busy = true
++ if (q.options.cancelFence)
++ fence = q
++ const ready = c.execute(q)
++ move(c, ready ? reserved : full)
++ if (fence || !ready)
++ return
++ }
++ if (!busy) {
++ if (releasing) {
++ c.reserved = null
++ onopen(c)
++ } else {
++ move(c, reserved)
++ }
++ }
++ }
++ }
++
++ async function reserve({ signal } = {}) {
++ signal && signal.throwIfAborted()
++ if (ending)
++ throw Errors.connection('CONNECTION_ENDED', options, options)
++ const sql = open.length
++ ? claim(open.shift())
+ : await new Promise((resolve, reject) => {
+- const query = { reserve: resolve, reject }
++ let settled = false
++ const query = {
++ reserve: c => { if (settle()) resolve(claim(c)) },
++ reject: error => { if (settle()) reject(error) }
++ }
++ const abort = () => query.reject(signal.reason)
++ function settle() {
++ if (settled)
++ return false
++ settled = true
++ queries.remove(query)
++ signal && signal.removeEventListener('abort', abort)
++ return true
++ }
++ if (signal)
++ signal.addEventListener('abort', abort, { once: true })
+ queries.push(query)
+ closed.length && connect(closed.shift(), query)
+ })
+
+- move(c, reserved)
+- c.reserved = () => queue.length
+- ? c.execute(queue.shift())
+- : move(c, reserved)
+- c.reserved.release = true
+-
+- const sql = Sql(handler)
+- sql.release = () => {
+- c.reserved = null
+- onopen(c)
++ if (signal && signal.aborted) {
++ sql.release()
++ signal.throwIfAborted()
+ }
+
+ return sql
+
+- function handler(q) {
+- c.queue === full
+- ? queue.push(q)
+- : c.execute(q) || move(c, full)
++ function claim(c) {
++ move(c, reserved)
++ const reservation = own(c)
++ reservation.release = true
++ const sql = Sql(reservation.enqueue)
++ sql.release = reservation.releaseConnection
++ sql.discard = reservation.discard
++ return sql
+ }
+ }
+
+ async function begin(options, fn) {
+ !fn && (fn = options, options = '')
+- const queries = Queue()
+ let savepoints = 0
+ , connection
+ , prepare = null
+@@ -249,9 +343,13 @@ function Postgres(a, b) {
+ }
+
+ async function scope(c, fn, name) {
++ const reservation = c.reserved
++ if (!reservation)
++ throw Errors.generic('CONNECTION_CLOSED', 'Transaction connection is no longer owned')
+ const sql = Sql(handler)
+ sql.savepoint = savepoint
+ sql.prepare = x => prepare = x.replace(/[^a-z0-9$-_. ]/gi)
++ sql.discard = reservation.discard
+ let uncaughtError
+ , result
+
+@@ -281,6 +379,8 @@ function Postgres(a, b) {
+ return result
+
+ function savepoint(name, fn) {
++ if (c.reserved !== reservation)
++ return Promise.reject(Errors.generic('CONNECTION_CLOSED', 'Transaction connection is no longer owned'))
+ if (name && Array.isArray(name.raw))
+ return savepoint(sql => sql.apply(sql, arguments))
+
+@@ -290,18 +390,16 @@ function Postgres(a, b) {
+
+ function handler(q) {
+ q.catch(e => uncaughtError || (uncaughtError = e))
+- c.queue === full
+- ? queries.push(q)
+- : c.execute(q) || move(c, full)
++ if (!reservation || c.reserved !== reservation)
++ return q.reject(Errors.generic('CONNECTION_CLOSED', 'Transaction connection is no longer owned'))
++ reservation.enqueue(q)
+ }
+ }
+
+ function onexecute(c) {
+ connection = c
+ move(c, reserved)
+- c.reserved = () => queries.length
+- ? c.execute(queries.shift())
+- : move(c, reserved)
++ own(c)
+ }
+ }
+
+@@ -399,6 +497,11 @@ function Postgres(a, b) {
+ }
+
+ function onopen(c) {
++ if (ending) {
++ while (queries.length)
++ queries.shift().reject(Errors.connection('CONNECTION_ENDED', options))
++ return c.terminate()
++ }
+ if (queries.length === 0)
+ return move(c, open)
+
+@@ -420,10 +523,20 @@ function Postgres(a, b) {
+
+ function onclose(c, e) {
+ move(c, closed)
++ const reservation = c.reserved
+ c.reserved = null
++ reservation && reservation.reject(e)
+ c.onclose && (c.onclose(e), c.onclose = null)
+ options.onclose && options.onclose(c.id)
+- queries.length && connect(c, queries.shift())
++ if (ending) {
++ while (queries.length)
++ queries.shift().reject(Errors.connection('CONNECTION_ENDED', options))
++ return
++ }
++ if (queries.length) {
++ const query = queries.peek()
++ connect(c, query.reserve ? query : queries.shift())
++ }
+ }
+ }
+
+diff --git a/cjs/src/query.js b/cjs/src/query.js
+index 45327f2fabcdbf8f8ec5020675012c310c04fee6..1d092504ac1ce1fdac78cb0c4ef3a8aa957676e4 100644
+--- a/cjs/src/query.js
++++ b/cjs/src/query.js
+@@ -23,11 +23,12 @@ const Query = module.exports.Query = class Query extends Promise {
+ this.state = null
+ this.statement = null
+
+- this.resolve = x => (this.active = false, resolve(x))
+- this.reject = x => (this.active = false, reject(x))
++ this.resolve = x => (this.active = false, this.canceller = null, resolve(x))
++ this.reject = x => (this.active = false, this.canceller = null, reject(x))
+
+ this.active = false
+ this.cancelled = null
++ this.cancelPromise = null
+ this.executed = false
+ this.signature = ''
+
+@@ -50,7 +51,12 @@ const Query = module.exports.Query = class Query extends Promise {
+ }
+
+ cancel() {
+- return this.canceller && (this.canceller(this), this.canceller = null)
++ if (this.cancelPromise)
++ return this.cancelPromise
++
++ const canceller = this.canceller
++ this.canceller = null
++ return this.cancelPromise = canceller ? canceller(this) : Promise.resolve()
+ }
+
+ simple() {
+@@ -96,8 +102,8 @@ const Query = module.exports.Query = class Query extends Promise {
+ resolve({ value, done: false })
+ return new Promise(r => prev = r)
+ }
+- this.resolve = () => (this.active = false, resolve({ done: true }))
+- this.reject = x => (this.active = false, reject(x))
++ this.resolve = () => (this.active = false, this.canceller = null, resolve({ done: true }))
++ this.reject = x => (this.active = false, this.canceller = null, reject(x))
+ })
+ this.execute()
+ return promise
+diff --git a/cjs/src/queue.js b/cjs/src/queue.js
+index 8438f5da92cf7637d98a33491d75c75b1c817c25..c444310ff87b0ac81fd19cd3170a0ba607a66781 100644
+--- a/cjs/src/queue.js
++++ b/cjs/src/queue.js
+@@ -15,6 +15,7 @@ function Queue(initial = []) {
+ : (xs.splice(index, 1), x)
+ },
+ push: (x) => (xs.push(x), x),
++ peek: () => xs[index],
+ shift: () => {
+ const out = xs[index++]
+
+diff --git a/src/connection.js b/src/connection.js
+index 1b1cccde43b4570d5d071d6ffaab2669b3c2065a..617335d1b039866e86cd63872eeaf9ef7039a13c 100644
+--- a/src/connection.js
++++ b/src/connection.js
+@@ -78,6 +78,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+
+ let socket = null
+ , cancelMessage
++ , cancelResolve
++ , cancelReject
++ , cancelError
+ , errorResponse = null
+ , result = new Result()
+ , incoming = Buffer.alloc(0)
+@@ -143,11 +146,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ }
+
+ async function cancel({ pid, secret }, resolve, reject) {
++ cancelResolve = resolve
++ cancelReject = reject
+ try {
+ cancelMessage = b().i32(16).i32(80877102).i32(pid).i32(secret).end(16)
+ await connect()
+- socket.once('error', reject)
+- socket.once('close', resolve)
++ if (!socket)
++ reject(cancelError || Errors.connection('CONNECTION_CLOSED', options))
+ } catch (error) {
+ reject(error)
+ }
+@@ -170,11 +175,12 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ : (query = q, query.active = true)
+
+ build(q)
++ const mayPipeline = !q.options.onexecute || q.options.onexecute(connection)
+ return write(toBuffer(q))
+ && !q.describeFirst
+ && !q.cursorFn
+ && sent.length < max_pipeline
+- && (!q.options.onexecute || q.options.onexecute(connection))
++ && mayPipeline
+ } catch (error) {
+ sent.length === 0 && write(Sync)
+ errored(error)
+@@ -295,7 +301,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+
+ /* c8 ignore next 3 */
+ function drain() {
+- !query && onopen(connection)
++ !query && !connection.reserved && onopen(connection)
+ }
+
+ function data(x) {
+@@ -379,6 +385,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ }
+
+ function error(err) {
++ if (cancelMessage)
++ cancelError = err
+ if (connection.queue === queues.connecting && options.host[retries + 1])
+ return
+
+@@ -388,6 +396,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ }
+
+ function errored(err) {
++ if (cancelMessage)
++ cancelError = err
+ stream && (stream.destroy(err), stream = null)
+ query && queryError(query, err)
+ initial && (queryError(initial, err), initial = null)
+@@ -447,6 +457,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ socket.removeAllListeners()
+ socket = null
+
++ if (cancelMessage)
++ return cancelError || hadError
++ ? cancelReject(cancelError || Errors.connection('CONNECTION_CLOSED', options))
++ : cancelResolve()
++
+ if (initial)
+ return reconnect()
+
+@@ -564,10 +579,12 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ return fetchArrayTypes()
+ }
+
+- initial && !initial.reserve && execute(initial)
++ const reserving = initial && initial.reserve
++ initial && !reserving && execute(initial)
+ options.shared.retries = retries = 0
+ initial = null
+- return
++ if (!reserving)
++ return
+ }
+
+ while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))
+@@ -580,7 +597,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ ? !connection.reserved.release && x[5] === 73 // I
+ ? ending
+ ? terminate()
+- : (connection.reserved = null, onopen(connection))
++ : connection.reserved(true)
+ : connection.reserved()
+ : ending
+ ? terminate()
+diff --git a/src/index.js b/src/index.js
+index c7fba3dace20173f4cb13f3f138bb6d213b43683..4c9192680a0da45fe13e1f06f1d8d05dcbe5a8a1 100644
+--- a/src/index.js
++++ b/src/index.js
+@@ -200,40 +200,134 @@ function Postgres(a, b) {
+ return await sql`select pg_notify(${ channel }, ${ '' + payload })`
+ }
+
+- async function reserve() {
++ function own(c) {
+ const queue = Queue()
+- const c = open.length
+- ? open.shift()
++ let busy = false, fence = null, holding = null, releasing = false
++ const reservation = c.reserved = (ended = false) => {
++ if (c.reserved !== reservation)
++ return
++ busy = false
++ if (ended) {
++ releasing = true
++ reservation.reject(Errors.generic('CONNECTION_CLOSED', 'Transaction has ended'))
++ }
++ const completed = fence
++ fence = null
++ if (completed && completed.cancelPromise) {
++ holding = completed
++ completed.cancelPromise.then(() => {
++ if (c.reserved !== reservation || holding !== completed)
++ return
++ holding = null
++ pump()
++ }, reservation.discard)
++ } else {
++ pump()
++ }
++ }
++ reservation.enqueue = q => {
++ if (c.reserved !== reservation || releasing)
++ return q.reject(Errors.generic('CONNECTION_CLOSED', 'Connection is no longer owned'))
++ queue.push(q)
++ pump()
++ }
++ reservation.reject = error => {
++ while (queue.length)
++ queue.shift().reject(error)
++ }
++ reservation.discard = () => {
++ if (c.reserved !== reservation)
++ return
++ c.reserved = null
++ reservation.reject(Errors.generic('CONNECTION_CLOSED', 'Connection was discarded'))
++ c.terminate()
++ }
++ reservation.releaseConnection = () => {
++ if (c.reserved !== reservation)
++ return
++ releasing = true
++ pump()
++ }
++ return reservation
++
++ function pump() {
++ if (c.reserved !== reservation || holding || fence)
++ return
++ while (queue.length) {
++ const q = queue.peek()
++ if (q.cancelled) {
++ queue.shift()
++ continue
++ }
++ if (busy && (q.options.cancelFence || c.queue === full))
++ return
++ queue.shift()
++ busy = true
++ if (q.options.cancelFence)
++ fence = q
++ const ready = c.execute(q)
++ move(c, ready ? reserved : full)
++ if (fence || !ready)
++ return
++ }
++ if (!busy) {
++ if (releasing) {
++ c.reserved = null
++ onopen(c)
++ } else {
++ move(c, reserved)
++ }
++ }
++ }
++ }
++
++ async function reserve({ signal } = {}) {
++ signal && signal.throwIfAborted()
++ if (ending)
++ throw Errors.connection('CONNECTION_ENDED', options, options)
++ const sql = open.length
++ ? claim(open.shift())
+ : await new Promise((resolve, reject) => {
+- const query = { reserve: resolve, reject }
++ let settled = false
++ const query = {
++ reserve: c => { if (settle()) resolve(claim(c)) },
++ reject: error => { if (settle()) reject(error) }
++ }
++ const abort = () => query.reject(signal.reason)
++ function settle() {
++ if (settled)
++ return false
++ settled = true
++ queries.remove(query)
++ signal && signal.removeEventListener('abort', abort)
++ return true
++ }
++ if (signal)
++ signal.addEventListener('abort', abort, { once: true })
+ queries.push(query)
+ closed.length && connect(closed.shift(), query)
+ })
+
+- move(c, reserved)
+- c.reserved = () => queue.length
+- ? c.execute(queue.shift())
+- : move(c, reserved)
+- c.reserved.release = true
+-
+- const sql = Sql(handler)
+- sql.release = () => {
+- c.reserved = null
+- onopen(c)
++ if (signal && signal.aborted) {
++ sql.release()
++ signal.throwIfAborted()
+ }
+
+ return sql
+
+- function handler(q) {
+- c.queue === full
+- ? queue.push(q)
+- : c.execute(q) || move(c, full)
++ function claim(c) {
++ move(c, reserved)
++ const reservation = own(c)
++ reservation.release = true
++ const sql = Sql(reservation.enqueue)
++ sql.release = reservation.releaseConnection
++ sql.discard = reservation.discard
++ return sql
+ }
+ }
+
+ async function begin(options, fn) {
+ !fn && (fn = options, options = '')
+- const queries = Queue()
+ let savepoints = 0
+ , connection
+ , prepare = null
+@@ -249,9 +343,13 @@ function Postgres(a, b) {
+ }
+
+ async function scope(c, fn, name) {
++ const reservation = c.reserved
++ if (!reservation)
++ throw Errors.generic('CONNECTION_CLOSED', 'Transaction connection is no longer owned')
+ const sql = Sql(handler)
+ sql.savepoint = savepoint
+ sql.prepare = x => prepare = x.replace(/[^a-z0-9$-_. ]/gi)
++ sql.discard = reservation.discard
+ let uncaughtError
+ , result
+
+@@ -281,6 +379,8 @@ function Postgres(a, b) {
+ return result
+
+ function savepoint(name, fn) {
++ if (c.reserved !== reservation)
++ return Promise.reject(Errors.generic('CONNECTION_CLOSED', 'Transaction connection is no longer owned'))
+ if (name && Array.isArray(name.raw))
+ return savepoint(sql => sql.apply(sql, arguments))
+
+@@ -290,18 +390,16 @@ function Postgres(a, b) {
+
+ function handler(q) {
+ q.catch(e => uncaughtError || (uncaughtError = e))
+- c.queue === full
+- ? queries.push(q)
+- : c.execute(q) || move(c, full)
++ if (!reservation || c.reserved !== reservation)
++ return q.reject(Errors.generic('CONNECTION_CLOSED', 'Transaction connection is no longer owned'))
++ reservation.enqueue(q)
+ }
+ }
+
+ function onexecute(c) {
+ connection = c
+ move(c, reserved)
+- c.reserved = () => queries.length
+- ? c.execute(queries.shift())
+- : move(c, reserved)
++ own(c)
+ }
+ }
+
+@@ -399,6 +497,11 @@ function Postgres(a, b) {
+ }
+
+ function onopen(c) {
++ if (ending) {
++ while (queries.length)
++ queries.shift().reject(Errors.connection('CONNECTION_ENDED', options))
++ return c.terminate()
++ }
+ if (queries.length === 0)
+ return move(c, open)
+
+@@ -420,10 +523,20 @@ function Postgres(a, b) {
+
+ function onclose(c, e) {
+ move(c, closed)
++ const reservation = c.reserved
+ c.reserved = null
++ reservation && reservation.reject(e)
+ c.onclose && (c.onclose(e), c.onclose = null)
+ options.onclose && options.onclose(c.id)
+- queries.length && connect(c, queries.shift())
++ if (ending) {
++ while (queries.length)
++ queries.shift().reject(Errors.connection('CONNECTION_ENDED', options))
++ return
++ }
++ if (queries.length) {
++ const query = queries.peek()
++ connect(c, query.reserve ? query : queries.shift())
++ }
+ }
+ }
+
+diff --git a/src/query.js b/src/query.js
+index 0d44a15cd9e42beaf11d4be6ccde60223e09508a..96967780bdb55671bdcdda0fd0bb6e718e0a0e78 100644
+--- a/src/query.js
++++ b/src/query.js
+@@ -23,11 +23,12 @@ export class Query extends Promise {
+ this.state = null
+ this.statement = null
+
+- this.resolve = x => (this.active = false, resolve(x))
+- this.reject = x => (this.active = false, reject(x))
++ this.resolve = x => (this.active = false, this.canceller = null, resolve(x))
++ this.reject = x => (this.active = false, this.canceller = null, reject(x))
+
+ this.active = false
+ this.cancelled = null
++ this.cancelPromise = null
+ this.executed = false
+ this.signature = ''
+
+@@ -50,7 +51,12 @@ export class Query extends Promise {
+ }
+
+ cancel() {
+- return this.canceller && (this.canceller(this), this.canceller = null)
++ if (this.cancelPromise)
++ return this.cancelPromise
++
++ const canceller = this.canceller
++ this.canceller = null
++ return this.cancelPromise = canceller ? canceller(this) : Promise.resolve()
+ }
+
+ simple() {
+@@ -96,8 +102,8 @@ export class Query extends Promise {
+ resolve({ value, done: false })
+ return new Promise(r => prev = r)
+ }
+- this.resolve = () => (this.active = false, resolve({ done: true }))
+- this.reject = x => (this.active = false, reject(x))
++ this.resolve = () => (this.active = false, this.canceller = null, resolve({ done: true }))
++ this.reject = x => (this.active = false, this.canceller = null, reject(x))
+ })
+ this.execute()
+ return promise
+diff --git a/src/queue.js b/src/queue.js
+index c4ef97164f057db99dce1b9af3401dbb1af37e31..8fba891b879e8f5c7fdb03ea0590753663c824c3 100644
+--- a/src/queue.js
++++ b/src/queue.js
+@@ -15,6 +15,7 @@ function Queue(initial = []) {
+ : (xs.splice(index, 1), x)
+ },
+ push: (x) => (xs.push(x), x),
++ peek: () => xs[index],
+ shift: () => {
+ const out = xs[index++]
+
+diff --git a/types/index.d.ts b/types/index.d.ts
+index 13c3432f761e2c2ee5b7dc1bdafe93e49f993dc7..5d8903e3246e1f596e717019db76e87008b25bfc 100644
+--- a/types/index.d.ts
++++ b/types/index.d.ts
+@@ -605,7 +605,7 @@ declare namespace postgres {
+ writable(): Promise<Writable>;
+
+ execute(): this;
+- cancel(): void;
++ cancel(): Promise<void>;
+
+ /**
+ * @deprecated `.stream` has been renamed to `.forEach`
+@@ -659,6 +659,7 @@ declare namespace postgres {
+ | Fragment[]
+
+ interface UnsafeQueryOptions {
++ cancelFence?: boolean;
+ /**
+ * When executes query as prepared statement.
+ * @default false
+@@ -717,10 +718,11 @@ declare namespace postgres {
+ begin<T>(cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;
+ begin<T>(options: string, cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;
+
+- reserve(): Promise<ReservedSql<TTypes>>
++ reserve(options?: { signal?: AbortSignal }): Promise<ReservedSql<TTypes>>
+ }
+
+ interface TransactionSql<TTypes extends Record<string, unknown> = {}> extends ISql<TTypes> {
++ discard(): void;
+ savepoint<T>(cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;
+ savepoint<T>(name: string, cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;
+
+@@ -728,6 +730,7 @@ declare namespace postgres {
+ }
+
+ interface ReservedSql<TTypes extends Record<string, unknown> = {}> extends Sql<TTypes> {
++ discard(): void;
+ release(): void;
+ }
+ }
diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
index 2a38a80268..eb02a40c48 100644
--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-coding",
- "version": "0.56.2.0",
+ "version": "0.57.0.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
index ddb64c5694..1306fd0301 100644
--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-coding",
- "version": "0.56.2.0",
+ "version": "0.57.0.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.md
index 90dbb44561..813513cd84 100644
--- a/plugin-variants/gbrain-coding/README.md
+++ b/plugin-variants/gbrain-coding/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.56.2.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.57.0.0 -->
# gbrain-coding (generated persona variant — do not hand-edit)
Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.
diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
index 5ad173f6ca..f8c12582de 100644
--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-daily",
- "version": "0.56.2.0",
+ "version": "0.57.0.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
index 12b2a1a977..37f7e68452 100644
--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-daily",
- "version": "0.56.2.0",
+ "version": "0.57.0.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.md
index 3b0bdf030c..96e1e9dc12 100644
--- a/plugin-variants/gbrain-daily/README.md
+++ b/plugin-variants/gbrain-daily/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.56.2.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.57.0.0 -->
# gbrain-daily (generated persona variant — do not hand-edit)
Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.
diff --git a/plugin/README.md b/plugin/README.md
index 601f981962..4989dce927 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.56.2.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.57.0.0 -->
# gbrain plugin skill tree (generated — do not hand-edit)
This tree is the curated skill set for the gbrain Codex and Claude Code
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.ts
index c7783b18e0..3a2fa69152 100644
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@ -164,6 +164,8 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"src/core/db-lock.ts": ["test/e2e/db-lock-acquisition-token.test.ts", "test/e2e/sync-lock-overlap-postgres.test.ts", "test/e2e/managed-connector-fencing.test.ts", "test/e2e/managed-connector-recovery.test.ts"],
"src/core/lease-schema.ts": ["test/e2e/db-lock-acquisition-token.test.ts"],
"src/core/persistence/**": [
+ "test/e2e/persistence-http-liveness.test.ts",
+ "test/e2e/persistence-phase-liveness.test.ts",
"test/e2e/persistence-publication-parity.test.ts",
"test/e2e/persistence-sync-origin-parity.test.ts",
"test/e2e/persistence-sync-options-parity.test.ts",
diff --git a/scripts/persistence/README.md b/scripts/persistence/README.md
index dff9f3d3eb..f582ab79e3 100644
--- a/scripts/persistence/README.md
+++ b/scripts/persistence/README.md
@@ -153,6 +153,13 @@ without a provider or remote embedding latency.
The manifest records all three runs, exact source hashes, storage/runtime
and runner characteristics, admission/completion distributions, queue age,
recovery bytes, RSS, throughput and Postgres activity samples. The harness
+records Bun's known `Failed to get memory usage` exception as a `null` RSS
+sample and counts it in `rss_unavailable_samples`; `peak_rss_bytes` is the maximum
+available sample, or `null` when none are available. These counters and peaks
+include every settled sample, including those completing during final validation.
+This known sampling limitation does not invalidate actual read/write measurements
+or relax the latency and overlap gates. Unexpected sampler errors still invalidate
+the run and retain only safe diagnostic fields. The harness
measures durable admission when the public handler's top-level queued journal
transaction resolves, and completion when its terminal committed receipt is
observed. Nested savepoints never count as admission. The same harness proxy
diff --git a/scripts/persistence/read-workload.ts b/scripts/persistence/read-workload.ts
index b1a470458f..7282b18192 100644
--- a/scripts/persistence/read-workload.ts
+++ b/scripts/persistence/read-workload.ts
@@ -50,10 +50,10 @@ export async function runReadLatencyWorkload(options: ReadWorkloadOptions = {})
const engine = observeAdmissionTransactions(kind === 'postgres' ? new PostgresEngine() : new PGLiteEngine(), (requestId, now) => {
timings.admitted(requestId, now);
});
- const sampleRecords = new BoundedRecords<{ at_ms: number; queue_count: number; queue_age_ms: number; recovery_bytes: number; rss_bytes: number; pool: unknown }>(4096);
+ const sampleRecords = new BoundedRecords<{ at_ms: number; queue_count: number; queue_age_ms: number; recovery_bytes: number; rss_bytes: number | null; pool: unknown }>(4096);
const samples = sampleRecords.records;
result.metrics = samples;
- let peakQueueAge = 0; let peakRecovery = 0; let peakRss = 0;
+ let peakQueueAge = 0; let peakRecovery = 0; let peakRss: number | null = null; let rssUnavailable = 0;
// Production search can degrade when one lexical arm fails. A benchmark
// must not count that cheaper, partial read as a successful measurement.
const keyword = engine.searchKeyword; const titles = engine.searchTitles;
@@ -130,8 +130,14 @@ export async function runReadLatencyWorkload(options: ReadWorkloadOptions = {})
'idle', count(*) FILTER(WHERE state='idle'), 'idle_in_transaction', count(*) FILTER(WHERE state='idle in transaction'))
FROM pg_stat_activity WHERE datname=current_database()) AS database_sessions` : ''} FROM persistence_requests`);
sampleStage = 'metrics_rss';
- const rss = process.memoryUsage().rss;
- peakQueueAge = Math.max(peakQueueAge, Number(row.age)); peakRecovery = Math.max(peakRecovery, Number(row.recovery)); peakRss = Math.max(peakRss, rss);
+ let rss: number | null;
+ try { rss = process.memoryUsage().rss; }
+ catch (error) {
+ if (!(error instanceof Error) || error.message !== 'Failed to get memory usage') throw error;
+ rss = null; rssUnavailable++;
+ }
+ peakQueueAge = Math.max(peakQueueAge, Number(row.age)); peakRecovery = Math.max(peakRecovery, Number(row.recovery));
+ if (rss !== null) peakRss = Math.max(peakRss ?? 0, rss);
sampleRecords.add({ at_ms: performance.now() - at, queue_count: row.pending, queue_age_ms: Number(row.age), recovery_bytes: Number(row.recovery),
rss_bytes: rss, pool: engine instanceof PostgresEngine ? {
tracked_subset: engine.getPoolDiagnostics(), database_sessions: row.database_sessions,
@@ -162,9 +168,6 @@ export async function runReadLatencyWorkload(options: ReadWorkloadOptions = {})
stage = 'validate';
assert.equal(admissionMs.length, completed, 'every completed write needs an observed durable admission');
result.metrics = samples; result.throughput_writes_per_second = completed * 1000 / (performance.now() - queryStart);
- result.peak_queue_age_ms = peakQueueAge;
- result.peak_recovery_bytes = peakRecovery;
- result.peak_rss_bytes = peakRss;
for (const p of ['p50', 'p95', 'p99']) result[`delta_${p}_pct`] = 100 * (result.phase_b[`${p}_ms`] / result.phase_a[`${p}_ms`] - 1);
result.brain_page_count = Number((await engine.executeRaw<{ n: number }>('SELECT count(*)::integer AS n FROM pages'))[0].n);
assert(result.phase_b.writes_committed_during_reads > 0, 'actual writes must commit while reads are still running');
@@ -178,6 +181,10 @@ export async function runReadLatencyWorkload(options: ReadWorkloadOptions = {})
catch (error) { diagnostics.failure('shutdown', error); result.ok = false; result.error = 'benchmark workload failed'; }
if (backgroundFailure || diagnostics.failures.total > 0) { result.ok = false; result.error = 'benchmark workload failed'; }
restoreBegin?.(); diagnostics.stop();
+ result.peak_queue_age_ms = peakQueueAge;
+ result.peak_recovery_bytes = peakRecovery;
+ result.peak_rss_bytes = peakRss;
+ result.rss_unavailable_samples = rssUnavailable;
result.metrics_retention = { limit: sampleRecords.limit, total: sampleRecords.total, dropped: sampleRecords.dropped };
result.elapsed_ms = performance.now() - at;
}
diff --git a/src/commands/mcp-expose-probe.ts b/src/commands/mcp-expose-probe.ts
index b2e441eeb6..40ab111fa9 100644
--- a/src/commands/mcp-expose-probe.ts
+++ b/src/commands/mcp-expose-probe.ts
@@ -55,8 +55,13 @@ export function defaultTcpProbe(host: string, port: number, timeoutMs: number):
});
}
-/** Default `lookup`: the system resolver (`getaddrinfo`), the same one `fetch` consults. */
-export const defaultLookup: HostLookup = async (hostname) => { await lookup(hostname); };
+/** Default `lookup`: RFC 6761 `.invalid` negatives, otherwise the system resolver (`getaddrinfo`). */
+export const defaultLookup: HostLookup = async (hostname) => {
+ if (/(^|\.)invalid\.?$/i.test(hostname)) {
+ throw Object.assign(new Error('getaddrinfo ENOTFOUND'), { code: 'ENOTFOUND' });
+ }
+ await lookup(hostname);
+};
export interface FetchOutcome {
/** The response (whatever its status), or null when the fetch rejected (connection refused / timeout / unresolved name). */
diff --git a/src/core/facts/single-prepare.ts b/src/core/facts/single-prepare.ts
index b416cde376..0fd55b18bf 100644
--- a/src/core/facts/single-prepare.ts
+++ b/src/core/facts/single-prepare.ts
@@ -10,9 +10,10 @@ export interface SingleFactIntent {
fact: string; kind: FactRow['kind']; visibility: FactRow['visibility']; entity_slug: string | null;
}
/** Provider work belongs to preparation, never to a page/source transaction. */
-export async function prepareFactEmbedding(fact: string): Promise<{ embedding: Float32Array | null; degraded: boolean }> {
+export async function prepareFactEmbedding(fact: string, signal?: AbortSignal): Promise<{ embedding: Float32Array | null; degraded: boolean }> {
+ signal?.throwIfAborted();
if (isAvailable('embedding')) {
- try { return { embedding: await embedOne(fact), degraded: false }; } catch { /* keyless-compatible fail soft */ }
+ try { return { embedding: await embedOne(fact, { abortSignal: signal }), degraded: false }; } catch { signal?.throwIfAborted(); }
}
return { embedding: null, degraded: true };
}
diff --git a/src/core/migrate.ts b/src/core/migrate.ts
index 3fe3c20bed..0b8c3fe2c8 100644
--- a/src/core/migrate.ts
+++ b/src/core/migrate.ts
@@ -1,7 +1,7 @@
import { SOURCE_INGESTION_RECEIPTS_SCHEMA_SQL } from './company-brain/receipt-schema.ts';
import { MANAGED_WRITER_GUARD_SQL } from './persistence/writer-guard-schema.ts';
import { PERSISTENCE_TOPOLOGY_SCHEMA_SQL } from './persistence/topology-schema.ts';
-import { PERSISTENCE_SCHEMA_STATEMENTS, PERSISTENCE_REQUEST_RECOVERY_INDEX_SQL } from './persistence/schema.ts';
+import { PERSISTENCE_SCHEMA_STATEMENTS, PERSISTENCE_REQUEST_RECOVERY_INDEX_SQL, PERSISTENCE_DATABASE_PENDING_INDEX_SQL } from './persistence/schema.ts';
import { PERSISTENCE_EFFECT_SCHEMA_SQL } from './persistence/effect-schema.ts';
import { PAGE_PROJECTION_SCHEMA_SQL, PAGE_PROJECTION_ACTIVATION_SQL } from './page-state/projection-schema.ts';
import { LEASE_TOKEN_SCHEMA_SQL } from './lease-schema.ts';
@@ -6651,6 +6651,15 @@ CREATE TRIGGER minion_queue_protocol BEFORE INSERT OR UPDATE ON minion_jobs
return Boolean(row?.heads && row?.members && row?.protocol);
},
},
+ {
+ version: 165, name: 'index_database_only_pending_writes', idempotent: true, transaction: false, sql: '',
+ handler: async engine => {
+ if (engine.kind === 'postgres') await dropInvalidConcurrentIndex(engine, 165, 'persistence_requests_database_pending');
+ await engine.runMigration(165, engine.kind === 'postgres'
+ ? PERSISTENCE_DATABASE_PENDING_INDEX_SQL.replace('CREATE INDEX', 'CREATE INDEX CONCURRENTLY')
+ : PERSISTENCE_DATABASE_PENDING_INDEX_SQL);
+ },
+ },
];
export const LATEST_VERSION = MIGRATIONS.length > 0
diff --git a/src/core/ops/persistence.ts b/src/core/ops/persistence.ts
index 8ef7eb04e2..8966854691 100644
--- a/src/core/ops/persistence.ts
+++ b/src/core/ops/persistence.ts
@@ -7,6 +7,7 @@ import { parseWriteRequestId } from '../persistence/preconditions.ts';
import { publicWriteReceipt, isWriteErrorCode } from '../persistence/types.ts';
import type { Principal, WriteRequest } from '../persistence/model.ts';
import type { LocalGrant } from '../persistence/identity.ts';
+import type { WriteHealthFacts } from '../persistence/health.ts';
const RECEIPT_NAMES = ['get_write_request', 'list_write_requests', 'cancel_write_request'] as const;
type ReceiptOperation = typeof RECEIPT_NAMES[number];
@@ -88,11 +89,11 @@ async function visible(ctx: OperationContext, row: WriteRequest): Promise<boolea
}
}
-async function publicReceipt(ctx: OperationContext, row: WriteRequest): Promise<Record<string, unknown>> {
+async function publicReceipt(ctx: OperationContext, row: WriteRequest, facts?: WriteHealthFacts): Promise<Record<string, unknown>> {
const { receiptFor } = await import('../persistence/journal.ts');
const { publicEffectsForRequest } = await import('../persistence/effect-journal.ts');
return {
- ...publicWriteReceipt(receiptFor(row)),
+ ...publicWriteReceipt(receiptFor(row, facts)),
operation: row.operation, source_id: row.source_id, slug: row.slug,
...(isWriteErrorCode(row.error_code) ? { write_error: row.error_code } : {}),
effects: await publicEffectsForRequest(ctx.engine, row.id),
@@ -117,10 +118,10 @@ export const persistenceOperations: Operation[] = [
handler: async (ctx, params) => {
const id = requiredRequestId(params.request_id);
const { principal } = await receiptAccess(ctx, 'get_write_request');
- const { getWriteRequest } = await import('../persistence/journal.ts');
+ const { getWriteRequest, writeHealthFacts } = await import('../persistence/journal.ts');
const row = await getWriteRequest(ctx.engine, principal, id);
if (!row || !await visible(ctx, row)) throw missing();
- return publicReceipt(ctx, row);
+ return publicReceipt(ctx, row, (await writeHealthFacts(ctx.engine, [row])).get(row.id));
},
},
{
@@ -149,7 +150,9 @@ export const persistenceOperations: Operation[] = [
slugPrefixes: access.slugPrefixes, operations: access.operations, slugAllowList,
authorize: row => visible(ctx, row),
});
- return { requests: await Promise.all(result.requests.map(row => publicReceipt(ctx, row))), next: result.next };
+ const { writeHealthFacts } = await import('../persistence/journal.ts');
+ const facts = await writeHealthFacts(ctx.engine, result.requests);
+ return { requests: await Promise.all(result.requests.map(row => publicReceipt(ctx, row, facts.get(row.id)))), next: result.next };
},
},
{
@@ -161,7 +164,7 @@ export const persistenceOperations: Operation[] = [
handler: async (ctx, params) => {
const id = requiredRequestId(params.request_id);
const { principal } = await receiptAccess(ctx, 'cancel_write_request');
- const { getWriteRequest } = await import('../persistence/journal.ts');
+ const { getWriteRequest, writeHealthFacts } = await import('../persistence/journal.ts');
const row = await getWriteRequest(ctx.engine, principal, id);
if (!row || !await visible(ctx, row)) throw missing();
if (ctx.dryRun) return { dry_run: true, action: 'cancel_write_request', request_id: id, state: row.state };
@@ -174,7 +177,7 @@ export const persistenceOperations: Operation[] = [
},
});
if (!cancelled) throw missing();
- return publicReceipt(ctx, cancelled);
+ return publicReceipt(ctx, cancelled, (await writeHealthFacts(ctx.engine, [cancelled])).get(cancelled.id));
},
},
];
diff --git a/src/core/persistence/admission-retry.ts b/src/core/persistence/admission-retry.ts
index ba993d5725..7bf526f4d0 100644
--- a/src/core/persistence/admission-retry.ts
+++ b/src/core/persistence/admission-retry.ts
@@ -11,7 +11,8 @@ export async function retryWriteAdmission<T>(requestId: string, attempt: (remain
} catch (error) {
// Connection/commit uncertainty is deliberately excluded: the caller must
// inspect/replay its retained ID, never infer rollback from a lost socket.
- if (!['40001', '40P01', '55P03', '57014'].includes(getCode(error) ?? '')) throw error;
+ const code = getCode(error);
+ if (!['40001', '40P01', '55P03', '57014'].includes(code ?? '')) throw error;
const remaining = deadline - performance.now();
if (remaining <= 25) {
const unavailable = new OperationError('storage_error', 'Write admission is temporarily blocked by database contention.',
@@ -21,7 +22,7 @@ export async function retryWriteAdmission<T>(requestId: string, attempt: (remain
}
// The transaction has rolled back and released its connection before any
// backoff. Jitter keeps independent ingress processes from retrying in step.
- await delay(Math.min(remaining - 1, 25 + Math.random() * 75));
+ await delay(Math.min(remaining - 1, code === '55P03' ? 5 + Math.random() * 20 : 25 + Math.random() * 75));
}
}
}
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index b12acbc403..8d23cb7963 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -9,8 +9,9 @@ import { rebuildPendingPageProjections } from '../page-state/projections.ts';
import { publicationConcurrency } from './pool-capacity.ts';
import { runPersistenceEffects } from './effects.ts';
import { PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
+import { isWriteErrorCode } from './types.ts';
-export type PrepareMutation = (engine: BrainEngine, row: WriteRequest, config: GBrainConfig) => Promise<PreparedMutation>;
+export type PrepareMutation = (engine: BrainEngine, row: WriteRequest, config: GBrainConfig, signal?: AbortSignal) => Promise<PreparedMutation>;
export class PersistenceConsumer {
private stopping = false;
private timer: ReturnType<typeof setTimeout> | undefined;
@@ -25,11 +26,17 @@ export class PersistenceConsumer {
private topologyWorker: Promise<unknown> | undefined;
private maintenanceWorker: Promise<unknown> | undefined;
private nextMaintenance = 0;
- private lastError: { code: string; at: string } | undefined;
+ private lastError: { code: string; at: string; phase?: string } | undefined;
private abort = new AbortController();
+ private phaseObservation: { name: string; started_at: string; deadline_exceeded: boolean; attempt: number } | undefined;
+ private phaseAttempts = 0;
+ private lastLog: { key: string; at: number } | undefined;
+ private lastPhaseError: string | undefined;
+ private preparationAttempts = 0;
+ private preparing = new Map<string, { request_id: string; started_at: string; deadline_exceeded: boolean; attempt: number }>();
readonly hostId: string;
constructor(readonly engine: BrainEngine, readonly config: GBrainConfig, readonly prepare: PrepareMutation,
- private opts: { hostId?: string; concurrency?: number; pollMs?: number; onError?: (error: unknown) => void } = {}) {
+ private opts: { hostId?: string; concurrency?: number; pollMs?: number; phaseMs?: number; preparationMs?: number; onError?: (error: unknown) => void } = {}) {
this.hostId = opts.hostId ?? localHostId();
}
start(): void { this.stopping = false; this.abort = new AbortController(); this.schedule(0); }
@@ -51,7 +58,9 @@ export class PersistenceConsumer {
}
private async doTick(): Promise<void> {
if (this.stopping) return;
- await refreshManagedFilesystemRoots(this.engine, this.engine.kind === 'pglite' ? this.config.database_path : undefined);
+ await this.phase('refresh_roots', signal => refreshManagedFilesystemRoots(this.engine,
+ this.engine.kind === 'pglite' ? this.config.database_path : undefined, signal));
+ if (this.stopping) return;
if (!this.topologyWorker) this.topologyWorker = import('./topology-recovery.ts')
.then(({ recoverSourceTopologies }) => recoverSourceTopologies(this.engine, { hostId: this.hostId, limit: 2 }))
.catch(error => this.report(error)).finally(() => { this.topologyWorker = undefined; });
@@ -70,12 +79,12 @@ export class PersistenceConsumer {
const now = Date.now();
for (const [root, retryAt] of this.rootRetryAfter) if (retryAt <= now) this.rootRetryAfter.delete(root);
const excluded = [...this.activeRoots, ...this.rootRetryAfter.keys()];
- const recovery = await this.engine.executeRaw<WriteRequest>(`SELECT r.* FROM persistence_requests r
+ const recovery = await this.phase('recovery_scan', signal => this.engine.executeRaw<WriteRequest>(`SELECT r.* FROM persistence_requests r
JOIN persistence_worktrees w ON w.id=r.worktree_id
WHERE w.owner_host_id=$1::uuid AND r.recovery IS NOT NULL AND NOT(r.worktree_id::text=ANY($2::text[]))
AND NOT EXISTS (SELECT 1 FROM persistence_requests earlier WHERE earlier.worktree_id=r.worktree_id
AND earlier.recovery IS NOT NULL AND earlier.sequence<r.sequence)
- ORDER BY r.updated_at,r.sequence LIMIT 16`, [this.hostId, excluded]);
+ ORDER BY r.updated_at,r.sequence LIMIT 16`, [this.hostId, excluded], { signal }));
for (const row of recovery) {
const root = row.worktree_id!;
// Always skip at least the next scheduled poll for an unresolved root.
@@ -83,7 +92,7 @@ export class PersistenceConsumer {
const delay = Math.max(1000, (this.opts.pollMs ?? 250) * 2);
this.rootRetryAfter.set(root, Date.now() + delay);
try {
- const recovered = await recoverPublication(this.engine, row.id, this.hostId);
+ const recovered = await this.phase('recovery', () => recoverPublication(this.engine, row.id, this.hostId));
if (!recovered.recovery) this.rootRetryAfter.delete(root);
else if (recovered.blocked_reason === 'unexpected_file_bytes') this.rootRetryAfter.set(root, Date.now() + Math.max(delay, 30_000));
} catch (error) {
@@ -91,20 +100,24 @@ export class PersistenceConsumer {
this.report(error);
}
}
- await this.engine.executeRaw(`UPDATE persistence_requests r SET state='queued',execution_token=NULL,claim_expires_at=NULL
- WHERE r.state='running' AND r.recovery IS NULL AND r.claim_expires_at<now()
- AND ${PERSISTENCE_PROTOCOL_PREDICATE}
- AND (r.worktree_id IS NULL OR EXISTS (SELECT 1 FROM persistence_worktrees w WHERE w.id=r.worktree_id AND w.owner_host_id=$1::uuid))`, [this.hostId]);
+ await this.phase('expired_claims', signal => this.engine.executeRaw(`WITH expired AS (
+ SELECT r.id FROM persistence_requests r WHERE r.state='running' AND r.recovery IS NULL
+ AND r.publication_started=false AND r.claim_expires_at<now() AND ${PERSISTENCE_PROTOCOL_PREDICATE}
+ AND (r.worktree_id IS NULL OR EXISTS (SELECT 1 FROM persistence_worktrees w WHERE w.id=r.worktree_id AND w.owner_host_id=$1::uuid))
+ ORDER BY r.sequence LIMIT 100 FOR UPDATE OF r SKIP LOCKED)
+ UPDATE persistence_requests r SET state='queued',execution_token=NULL,claim_expires_at=NULL
+ FROM expired WHERE r.id=expired.id`, [this.hostId], { signal }));
if (publicationConcurrency(this.engine) === 0) {
- await this.engine.executeRaw(`UPDATE persistence_requests SET blocked_reason='writer_pool_capacity'
- WHERE state='queued' AND blocked_reason IS DISTINCT FROM 'writer_pool_capacity' AND ${PERSISTENCE_PROTOCOL_PREDICATE}`);
+ await this.phase('capacity', signal => this.engine.executeRaw(`UPDATE persistence_requests SET blocked_reason='writer_pool_capacity'
+ WHERE state='queued' AND blocked_reason IS DISTINCT FROM 'writer_pool_capacity' AND ${PERSISTENCE_PROTOCOL_PREDICATE}`, undefined, { signal }));
return;
}
const concurrency = this.opts.concurrency ?? 2;
const attemptedRoots = new Set([...this.activeRoots, ...this.rootRetryAfter.keys()]);
while (!this.stopping && this.active.size < concurrency) {
- const row = await claimNextWrite(this.engine, this.hostId, 30_000, [...attemptedRoots]);
+ const row = await this.phase('claim', () => claimNextWrite(this.engine, this.hostId, 30_000, [...attemptedRoots]));
if (!row) break;
+ if (this.stopping) { await releaseUnpublishedClaim(this.engine, row, 'consumer_stopping'); break; }
const key = row.worktree_id ?? `db:${row.source_incarnation}`;
attemptedRoots.add(key);
if (this.activeRoots.has(key)) { await releaseUnpublishedClaim(this.engine, row, 'writer_busy'); break; }
@@ -118,41 +131,110 @@ export class PersistenceConsumer {
}
}
foregroundCompletions(worktreeId: string): number { return this.foregroundCounts.get(worktreeId) ?? 0; }
- status(): { accepting: boolean; active_preparations: number; active_worktrees: number; last_error?: { code: string; at: string } } {
+ status() {
return { accepting: !this.stopping, active_preparations: this.active.size, active_worktrees: this.activeRoots.size,
+ sampled_at: new Date().toISOString(), observation_scope: 'current_process_reset_on_restart',
+ preparation_attempts: this.preparationAttempts,
+ phase: this.phaseObservation ? { ...this.phaseObservation } : null,
+ preparations: [...this.preparing.values()].map(value => ({ ...value })),
...(this.lastError ? { last_error: { ...this.lastError } } : {}) };
}
+ private async phase<T>(name: string, run: (signal?: AbortSignal) => Promise<T>): Promise<T> {
+ const observation = { name, started_at: new Date().toISOString(), deadline_exceeded: false, attempt: ++this.phaseAttempts };
+ this.phaseObservation = observation;
+ const abort = new AbortController();
+ const stop = () => abort.abort(this.abort.signal.reason);
+ this.abort.signal.addEventListener('abort', stop, { once: true });
+ if (this.stopping) stop();
+ const timer = setTimeout(() => { observation.deadline_exceeded = true; abort.abort(); this.log(name, 'deadline_exceeded'); }, this.opts.phaseMs ?? 5000);
+ try { return await run(this.engine.kind === 'postgres' ? abort.signal : undefined); }
+ catch (error) {
+ const cancelled = error as { name?: unknown; code?: unknown; message?: unknown } | null;
+ if (this.stopping && abort.signal.aborted && abort.signal.reason === this.abort.signal.reason
+ && (error === abort.signal.reason || cancelled?.name === 'AbortError'
+ || cancelled?.code === '57014' && typeof cancelled.message === 'string'
+ && /^(?:57014: )?canceling statement due to user request$/.test(cancelled.message))) {
+ throw this.abort.signal.reason;
+ }
+ this.lastPhaseError = name; throw error;
+ }
+ finally { clearTimeout(timer); this.abort.signal.removeEventListener('abort', stop); this.phaseObservation = undefined; }
+ }
private report(error: unknown): void {
+ if (this.stopping && error === this.abort.signal.reason) return;
const code = (error as { code?: unknown })?.code;
- this.lastError = { code: typeof code === 'string' && /^[a-zA-Z0-9_]{1,64}$/.test(code) ? code : 'storage_error', at: new Date().toISOString() };
+ this.lastError = { code: typeof code === 'string' && (/^[A-Z0-9]{5}$/.test(code) || isWriteErrorCode(code)) ? code : 'storage_error', at: new Date().toISOString(),
+ ...(this.lastPhaseError ? { phase: this.lastPhaseError } : {}) };
if (this.opts.onError) this.opts.onError(error);
- else process.stderr.write('[persistence] Consumer paused after a storage error; inspect writer status.\n');
+ else this.log(this.lastPhaseError ?? 'execution', this.lastError.code);
+ this.lastPhaseError = undefined;
+ }
+ private log(phase: string, code: string): void {
+ const key = `${phase}:${code}`, at = Date.now();
+ if (this.lastLog && (at - this.lastLog.at < 1000 || this.lastLog.key === key && at - this.lastLog.at < 30_000)) return;
+ this.lastLog = { key, at };
+ if (!this.opts.onError) process.stderr.write(`[persistence] phase=${phase} reason=${code}; unfinished work remains tracked; inspect writer status.\n`);
}
private async execute(row: WriteRequest): Promise<boolean> {
let renewing: Promise<unknown> | undefined;
let claimLive = true;
let closed = false;
+ let preparationActive = true;
+ const abort = new AbortController();
+ const observation = { request_id: row.request_id, started_at: new Date().toISOString(), deadline_exceeded: false, attempt: ++this.preparationAttempts };
+ this.preparing.set(row.id, observation);
+ const stop = () => abort.abort({ code: 'consumer_stopping' });
+ this.abort.signal.addEventListener('abort', stop, { once: true });
+ const bounded = row.operation === 'remember' || row.operation === 'put_page' && !row.intent?.kind;
+ const budget = this.opts.preparationMs ?? 30_000;
+ const deadline = performance.now() + budget;
+ const timeout = bounded ? setTimeout(() => {
+ observation.deadline_exceeded = true;
+ abort.abort({ code: 'preparation_deadline' });
+ this.log('preparation', 'deadline_exceeded');
+ }, budget) : undefined;
const interval = setInterval(() => {
if (closed || renewing) return;
- renewing = renewWriteClaim({ executeRaw: this.engine.executeRawDirect.bind(this.engine) }, row.id, row.execution_token!).then(live => { claimLive &&= live; })
- .catch(() => { claimLive = false; }).finally(() => { renewing = undefined; });
+ const renewalAbort = new AbortController();
+ const deadline = setTimeout(() => { claimLive = false; renewalAbort.abort(); }, this.opts.phaseMs ?? 5000);
+ renewing = renewWriteClaim({ executeRaw: this.engine.executeRawDirect.bind(this.engine) }, row.id, row.execution_token!, 30_000,
+ this.engine.kind === 'postgres' ? renewalAbort.signal : undefined).then(live => { claimLive &&= live; })
+ .catch(() => { claimLive = false; }).finally(() => { clearTimeout(deadline); renewing = undefined; });
}, 10_000);
interval.unref?.();
try {
- const prepared = await this.prepare(this.engine, row, this.config);
- if (!claimLive || this.stopping) { await releaseUnpublishedClaim(this.engine, row, 'consumer_stopping'); return false; }
+ const prepared = await this.prepare(this.engine, row, this.config, bounded ? abort.signal : undefined);
+ if (timeout) clearTimeout(timeout);
+ if (bounded && performance.now() >= deadline && !abort.signal.aborted) {
+ observation.deadline_exceeded = true;
+ abort.abort({ code: 'preparation_deadline' });
+ this.log('preparation', 'deadline_exceeded');
+ }
+ if (!claimLive || this.stopping || abort.signal.aborted) {
+ await releaseUnpublishedClaim(this.engine, row, observation.deadline_exceeded ? 'preparation_deadline' : 'consumer_stopping'); return false;
+ }
+ this.preparing.delete(row.id);
+ preparationActive = false;
const done = await publishMutation(this.engine, row, prepared, this.hostId);
if (done.state === 'committed' && row.worktree_id && !String(row.intent?.kind).startsWith('managed_sync_')) {
this.foregroundCounts.set(row.worktree_id, this.foregroundCompletions(row.worktree_id) + 1);
}
return isTerminal(done);
} catch (error) {
+ if (preparationActive && bounded && performance.now() >= deadline) observation.deadline_exceeded = true;
+ if (preparationActive && (abort.signal.aborted || observation.deadline_exceeded)) {
+ await releaseUnpublishedClaim(this.engine, row, observation.deadline_exceeded ? 'preparation_deadline' : 'consumer_stopping');
+ return false;
+ }
const current = await getWriteRequestById(this.engine, row.id);
if (current && !isTerminal(current) && current.execution_token === row.execution_token && !current.recovery) {
return isTerminal(await finishUnpublishedFailure(this.engine, current, error));
}
throw error;
- } finally { closed = true; clearInterval(interval); await renewing; }
+ } finally {
+ closed = true; clearInterval(interval); if (timeout) clearTimeout(timeout);
+ this.abort.signal.removeEventListener('abort', stop); this.preparing.delete(row.id); await renewing;
+ }
}
/** Mandatory barrier: engine.close must be sequenced AFTER this promise. */
async stop(): Promise<void> {
diff --git a/src/core/persistence/diagnostics.ts b/src/core/persistence/diagnostics.ts
index c0d696e294..6bb1e6189b 100644
--- a/src/core/persistence/diagnostics.ts
+++ b/src/core/persistence/diagnostics.ts
@@ -3,6 +3,8 @@ import { journalLimitKey, readJournalLimits } from './limits.ts';
import type { JournalLimits } from './model.ts';
import { publicationConcurrency } from './pool-capacity.ts';
import { WRITER_INSPECTION_HINT } from './admin-intent.ts';
+import { writeHealth } from './health.ts';
+import type { WriteRequestState } from './types.ts';
export const WRITER_NEXT_ACTIONS: Record<string, string> = {
unexpected_staging_bytes: 'Keep the worktree blocked and retain its staging files and recovery capacity. Compare the recorded staging size and hash, then reconcile unexpected bytes explicitly before retrying; never discard unverified staging files.',
@@ -58,9 +60,9 @@ export async function readWriterDiagnostics(engine: BrainEngine) {
FROM persistence_worktrees w LEFT JOIN persistence_requests r ON r.worktree_id=w.id
GROUP BY w.id ORDER BY w.id`);
const counters = await engine.executeRaw<Counter>(`SELECT key,outstanding_count::text,intent_bytes::text,lifetime_ids::text,terminal_bytes::text,recovery_bytes::text FROM persistence_counters ORDER BY key`);
- const blockers = await engine.executeRaw<{ request_id: string; worktree_id: string | null; state: string; blocked_reason: string | null; error_code: string | null }>(
+ const blockers = await engine.executeRaw<{ request_id: string; worktree_id: string | null; state: WriteRequestState; created_at: Date | string; blocked_reason: string | null; error_code: string | null }>(
`SELECT request_id,worktree_id,state,blocked_reason,error_code,created_at
- FROM persistence_requests WHERE state='recovering' OR blocked_reason IS NOT NULL ORDER BY sequence LIMIT 100`);
+ FROM persistence_requests WHERE state IN ('queued','running','recovering') OR blocked_reason IS NOT NULL ORDER BY sequence LIMIT 100`);
const queue = await engine.executeRaw(`SELECT state,COUNT(*)::integer AS count,COALESCE(SUM(intent_bytes),0)::text AS intent_bytes,
MIN(created_at) AS oldest_request_at,
MAX(EXTRACT(EPOCH FROM (now()-created_at))*1000)::bigint::text AS oldest_age_ms
@@ -73,5 +75,10 @@ export async function readWriterDiagnostics(engine: BrainEngine) {
const ingress = persistenceConsumerStatus(engine);
return { ...brain, sampled_at: new Date().toISOString(), publication_concurrency: publicationConcurrency(engine),
ingress, worktrees, counters, queue, effects, limits, capacity: capacityDiagnostics(counters, limits),
- blockers: blockers.map(row => ({ ...row, next_action: writerNextAction(row.blocked_reason ?? row.error_code) })) };
+ blockers: blockers.map(row => {
+ const health = writeHealth(row);
+ const advice = writerNextAction(row.blocked_reason ?? row.error_code);
+ return { ...row, ...health, next_action: health.diagnostic?.next_action === 'inspect_owner' && advice !== WRITER_INSPECTION_HINT
+ ? `${WRITER_INSPECTION_HINT} ${advice}` : advice };
+ }) };
}
diff --git a/src/core/persistence/filesystem-guard.ts b/src/core/persistence/filesystem-guard.ts
index 0ded6a9aaa..6f91334c25 100644
--- a/src/core/persistence/filesystem-guard.ts
+++ b/src/core/persistence/filesystem-guard.ts
@@ -21,14 +21,15 @@ function encloses(root: string, path: string): boolean {
const rel = relative(canonicalFilesystemPath(root), canonicalFilesystemPath(path));
return !isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`);
}
-export async function refreshManagedFilesystemRoots(engine: SqlEngine, databasePath = datastorePaths.get(engine)): Promise<void> {
- const [brain] = await engine.executeRaw<{ brain_id: string; enabled: boolean }>('SELECT brain_id,enabled FROM persistence_brain WHERE singleton=1');
+export async function refreshManagedFilesystemRoots(engine: SqlEngine, databasePath = datastorePaths.get(engine), signal?: AbortSignal): Promise<void> {
+ const [brain] = await engine.executeRaw<{ brain_id: string; enabled: boolean }>('SELECT brain_id,enabled FROM persistence_brain WHERE singleton=1', undefined, { signal });
if (!brain) return;
const roots = brain.enabled ? await engine.executeRaw<ManagedRootRecord>(`SELECT DISTINCT ON (local_path) * FROM (
SELECT h.local_path,s.source_id,s.source_incarnation,s.worktree_id,s.topology_generation
FROM persistence_host_bindings h JOIN persistence_source_bindings s ON s.worktree_id=h.worktree_id WHERE h.host_id=$1::uuid
UNION SELECT local_path,id,incarnation,NULL,NULL FROM sources WHERE local_path IS NOT NULL
- ) roots ORDER BY local_path,worktree_id NULLS LAST,source_id,source_incarnation,topology_generation`, [localHostId()]) : [];
+ ) roots ORDER BY local_path,worktree_id NULLS LAST,source_id,source_incarnation,topology_generation`, [localHostId()], { signal }) : [];
+ signal?.throwIfAborted();
if (brain.enabled && databasePath) roots.push({ local_path: databasePath });
if (brain.enabled) recordManagedRoots(brain.brain_id, roots);
managedRoots.set(brain.brain_id, new Set(roots.map(row => resolve(row.local_path))));
diff --git a/src/core/persistence/health.ts b/src/core/persistence/health.ts
new file mode 100644
index 0000000000..18df43c0db
--- /dev/null
+++ b/src/core/persistence/health.ts
@@ -0,0 +1,33 @@
+import { isTerminalWriteState, WRITE_HEALTH_REASONS, type WriteDiagnostic, type WriteReceipt, type WriteRequestState } from './types.ts';
+
+export interface WriteHealthFacts {
+ observed_at?: string;
+ earlier_write?: boolean;
+ recovery_required?: boolean;
+ owner_unavailable?: boolean;
+ inspect_owner?: boolean;
+}
+export function writeHealth(row: { state: WriteRequestState; created_at: Date | string; blocked_reason?: string | null },
+ facts: WriteHealthFacts = {}, now = Date.now()): { retry_after_ms: number | null; diagnostic?: WriteDiagnostic } {
+ if (isTerminalWriteState(row.state)) return { retry_after_ms: null };
+ const created = new Date(row.created_at).getTime();
+ const age = Number.isFinite(created) && Number.isFinite(now) ? Math.min(Number.MAX_SAFE_INTEGER, Math.max(0, Math.floor(now - created))) : 0;
+ const raw = row.blocked_reason;
+ const unexpected = raw === 'unexpected_file_bytes' || raw === 'unexpected_staging_bytes';
+ let reason: WriteDiagnostic['reason'] = unexpected || facts.inspect_owner || facts.recovery_required || row.state === 'recovering'
+ ? 'recovery_required' : facts.owner_unavailable ? 'owner_unavailable' : facts.earlier_write ? 'waiting_on_earlier_write'
+ : raw ? (WRITE_HEALTH_REASONS as readonly string[]).includes(raw) ? raw as WriteDiagnostic['reason'] : 'cause_unknown' : 'pending';
+ const aged = age >= 120_000;
+ const unknown = reason === 'pending' || reason === 'cause_unknown';
+ if (aged && unknown) reason = 'cause_unknown';
+ const inspect = aged || unexpected || facts.inspect_owner || ['writer_pool_capacity', 'owner_unavailable', 'writer_lock_unavailable'].includes(reason);
+ return { retry_after_ms: inspect ? 30_000 : !unknown || age >= 30_000 ? 5000 : 1000,
+ diagnostic: { age_ms: age, assessment: unknown ? aged ? 'stalled' : 'pending' : 'blocked', reason,
+ next_action: inspect ? 'inspect_owner' : 'poll', ...(facts.observed_at ? { observed_at: facts.observed_at } : {}) } };
+}
+
+export function pendingWriteHint(receipt: WriteReceipt): string {
+ const identity = `Use the same operation with the same arguments and request_id ${receipt.request_id}. Do not submit a new request_id for this write.`;
+ if (receipt.diagnostic?.next_action === 'inspect_owner') return `${identity} Ask the operator to inspect gbrain sources writer status --probe --json on the selected brain's existing owner. Do not claim, transfer, activate, or remove locks. Poll no faster than ${receipt.retry_after_ms ?? 30_000} ms; if receipt helpers are unavailable, replay the same verb only after inspection.`;
+ return `${identity} Poll get_write_request after ${receipt.retry_after_ms ?? 1000} ms, or retry the same verb with identical arguments if receipt helpers are unavailable.`;
+}
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index 93f9d344ca..61c3736a04 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -6,6 +6,7 @@ import { digest, jsonBytes, requireUuid } from './digest.ts';
import { authorizeWrite } from './authority.ts';
import { readJournalLimits } from './limits.ts';
import { retryWriteAdmission } from './admission-retry.ts';
+import { writeHealth, type WriteHealthFacts } from './health.ts';
import { assertMutationProtocol, assertSharedSkillPersistence, declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
import {
isTerminal, principalKey, requestPrincipal, recoveryFiles,
@@ -62,8 +63,8 @@ export async function assertPageRequestIdentity(engine: SqlEngine, principal: Pr
[principal.id, requireUuid(requestId)]);
if (topology) throw new OperationError('idempotency_conflict', 'This request_id belongs to a source lifecycle operation.');
}
-export async function getWriteRequestById(engine: SqlEngine, id: string): Promise<WriteRequest | null> {
- const [row] = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid', [id]);
+export async function getWriteRequestById(engine: SqlEngine, id: string, signal?: AbortSignal): Promise<WriteRequest | null> {
+ const [row] = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid', [id], { signal });
return row ?? null;
}
export function intentDigest(a: Pick<WriteAdmission, 'operation' | 'sourceId' | 'slug' | 'callerIntent'>): string {
@@ -78,7 +79,7 @@ export async function admitWrite(engine: BrainEngine, input: WriteAdmission, ove
const { requestId, apply } = await prepareAdmission(engine, input, overrides);
return retryWriteAdmission(requestId, remaining => engine.transaction(async tx => {
await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout',$1,true),set_config('statement_timeout',$2,true)",
- [`${Math.min(1000, remaining)}ms`, `${remaining}ms`]);
+ [`${Math.min(10, remaining)}ms`, `${remaining}ms`]);
return apply(tx);
}));
}
@@ -166,10 +167,10 @@ export async function claimNextWrite(engine: BrainEngine, hostId: string, leaseM
return claimed;
});
}
-export async function renewWriteClaim(engine: SqlEngine, id: string, token: string, leaseMs = 30_000): Promise<boolean> {
+export async function renewWriteClaim(engine: SqlEngine, id: string, token: string, leaseMs = 30_000, signal?: AbortSignal): Promise<boolean> {
const rows = await engine.executeRaw(`UPDATE persistence_requests SET
claim_expires_at=now()+($3::double precision*interval '1 millisecond'),updated_at=now()
- WHERE id=$1::uuid AND execution_token=$2::uuid AND state='running' AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING id`, [id, token, leaseMs]);
+ WHERE id=$1::uuid AND execution_token=$2::uuid AND state='running' AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING id`, [id, token, leaseMs], { signal });
return rows.length === 1;
}
export async function releaseUnpublishedClaim(engine: SqlEngine, row: WriteRequest, reason: string): Promise<void> {
@@ -271,15 +272,60 @@ export async function compactWriteReceipts(engine: BrainEngine, retentionDays =
});
return count;
}
-export function receiptFor(row: WriteRequest) {
+export function receiptFor(row: WriteRequest, facts?: WriteHealthFacts, now = Date.now()) {
return {
...(row.outcome ?? {}),
...(row.outcome ? { outcome: row.outcome } : {}),
request_id: row.request_id, state: row.state,
- retry_after_ms: isTerminal(row) ? null : 1000,
+ ...writeHealth(row, facts, now),
...(row.error_code ? { write_error: row.error_code } : {}),
...(row.blocked_reason ? { blocked_reason: row.blocked_reason } : {}),
...(row.compacted ? { compacted: true } : {}),
created_at: new Date(row.created_at).toISOString(), updated_at: new Date(row.updated_at).toISOString(),
};
}
+
+const healthQueries = new WeakMap<BrainEngine, Promise<unknown>>();
+export async function writeHealthFacts(engine: BrainEngine, rows: WriteRequest[]): Promise<Map<string, WriteHealthFacts>> {
+ if (rows.length > 100) throw new RangeError('Receipt health pages are limited to 100 rows.');
+ const pending = rows.filter(row => !isTerminal(row));
+ const result = new Map<string, WriteHealthFacts>();
+ if (!pending.length || healthQueries.has(engine)) return result;
+ const roots = [...new Set(pending.map(row => row.worktree_id ?? `db:${row.source_incarnation}`))];
+ const abort = new AbortController();
+ const observed_at = new Date().toISOString();
+ const query = engine.executeRaw<{ root: string; sequence: string | null; recovery_required: boolean; owner_unavailable: boolean; inspect_owner: boolean }>(`
+ WITH roots AS (SELECT unnest($1::text[]) AS root)
+ SELECT roots.root,head.sequence::text,COALESCE(head.inspect_owner,false) AS inspect_owner,
+ COALESCE(head.recovering,false) OR EXISTS (SELECT 1 FROM persistence_effects e
+ WHERE e.worktree_id=w.id AND e.recovery IS NOT NULL) AS recovery_required,
+ w.id IS NOT NULL AND (w.state<>'active' OR w.owner_host_id IS NULL) AS owner_unavailable
+ FROM roots LEFT JOIN persistence_worktrees w ON w.id::text=roots.root
+ LEFT JOIN LATERAL (
+ (SELECT r.sequence,r.recovery IS NOT NULL AS recovering,
+ r.blocked_reason IN ('unexpected_file_bytes','unexpected_staging_bytes') AS inspect_owner FROM persistence_requests r
+ WHERE r.worktree_id=w.id AND (r.state IN ('queued','running','recovering') OR r.recovery IS NOT NULL)
+ ORDER BY r.sequence LIMIT 1)
+ UNION ALL
+ (SELECT r.sequence,r.recovery IS NOT NULL AS recovering,
+ r.blocked_reason IN ('unexpected_file_bytes','unexpected_staging_bytes') AS inspect_owner FROM persistence_requests r
+ WHERE r.worktree_id IS NULL AND r.source_incarnation=CASE WHEN roots.root LIKE 'db:%' THEN substring(roots.root FROM 4)::uuid END
+ AND r.state IN ('queued','running','recovering') ORDER BY r.sequence LIMIT 1)
+ ) head ON true`, [roots], { signal: engine.kind === 'postgres' ? abort.signal : undefined })
+ .catch(() => null).finally(() => { if (healthQueries.get(engine) === query) healthQueries.delete(engine); });
+ healthQueries.set(engine, query);
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const facts = await Promise.race([query, new Promise<null>(resolve => {
+ timer = setTimeout(() => { abort.abort(); resolve(null); }, 500);
+ })]).finally(() => { if (timer) clearTimeout(timer); });
+ if (!facts) return result;
+ const byRoot = new Map(facts.map(fact => [fact.root, fact]));
+ for (const row of pending) {
+ const fact = byRoot.get(row.worktree_id ?? `db:${row.source_incarnation}`);
+ if (fact) result.set(row.id, { observed_at, recovery_required: fact.recovery_required,
+ owner_unavailable: fact.owner_unavailable,
+ inspect_owner: fact.inspect_owner,
+ earlier_write: fact.sequence != null && BigInt(fact.sequence) < BigInt(row.sequence) });
+ }
+ return result;
+}
diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.ts
index ab51997809..90ae93e578 100644
--- a/src/core/persistence/memory-prepare.ts
+++ b/src/core/persistence/memory-prepare.ts
@@ -25,7 +25,8 @@ function outcome(id: number, status: 'inserted' | 'duplicate' | 'superseded', en
}
/** Every retry renders the semantic append from the latest coherent snapshot. */
-export async function prepareMemoryMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {
+export async function prepareMemoryMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig, signal?: AbortSignal): Promise<PreparedMutation> {
+ signal?.throwIfAborted();
if (row.operation !== 'remember' || !row.intent) throw new OperationError('storage_error', 'Unknown memory mutation intent.');
const p = row.intent;
const input: SingleFactIntent = { fact: String(p.fact).trim(), kind: (p.kind ?? 'fact') as SingleFactIntent['kind'],
@@ -35,7 +36,9 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque
if (p.expected_revision !== undefined) assertPageRevision(snapshot, engineMutationPrecondition(parseMutationPrecondition(p)));
const observedRevision = snapshot?.revision ?? null;
await assertFactNotWithdrawn(engine, row.source_id, input);
- const { embedding, degraded } = await prepareFactEmbedding(input.fact);
+ signal?.throwIfAborted();
+ const { embedding, degraded } = await prepareFactEmbedding(input.fact, signal);
+ signal?.throwIfAborted();
const decision = await decideSingleFact(engine, row.source_id, input, embedding);
const validate = async (tx: BrainEngine) => {
await assertFactNotWithdrawn(tx, row.source_id, input);
@@ -69,7 +72,7 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque
const content = serializePageToMarkdown({ ...snapshot.page, compiled_truth: body }, snapshot.tags);
// Reuse the canonical parser/chunker and durable filesystem publication.
// The original caller revision was checked above; this CAS binds this render.
- page = await preparePageMutation(engine, { ...row, intent: { ...p, content, expected_revision: observedRevision, force: false } }, config);
+ page = await preparePageMutation(engine, { ...row, intent: { ...p, content, expected_revision: observedRevision, force: false } }, config, undefined, signal);
if (page.observedRevision !== observedRevision) conflict();
}
return { observedRevision, file: page?.file, validate: async tx => { await validate(tx); await page?.validate?.(tx); }, apply: async tx => {
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 64fd9e68ec..83937b6a45 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -96,12 +96,14 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ
/** Providers and parsing run before the OS lock and before any publication transaction. */
export async function preparePageMutation(engine: BrainEngine, row: WriteRequest, _config: GBrainConfig,
- preparedIntent?: { content: string; expectedRevision: string; tags?: string[] }): Promise<PreparedMutation> {
+ preparedIntent?: { content: string; expectedRevision: string; tags?: string[] }, signal?: AbortSignal): Promise<PreparedMutation> {
+ signal?.throwIfAborted();
if (!row.intent) throw new OperationError('storage_error', 'A pending write lost its normalized intent.');
await assertKnowledgePublicationAllowed(engine, row);
const p = row.intent;
const source = { sourceId: row.source_id };
const snapshot = await engine.readPageSnapshot(row.slug, { ...source, includeDeleted: true });
+ signal?.throwIfAborted();
assertPageRevision(snapshot, preparedIntent ? { expectedRevision: preparedIntent.expectedRevision } : engineMutationPrecondition(parseMutationPrecondition(p)));
if ((snapshot?.page.id ?? null) !== row.page_id) throw new OperationError('page_identity_changed', 'The accepted page identity changed.');
const observedRevision = snapshot?.revision ?? null;
@@ -184,6 +186,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest
prepareFrontmatter: page => { provenance = putProvenance(row, snapshot, page); },
prepare: async value => { prepared = value; return value.result; },
});
+ signal?.throwIfAborted();
if (!prepared) {
const oversized = result.error?.startsWith('Content too large') === true;
throw new OperationError(oversized ? 'request_too_large' : 'invalid_params', oversized ? result.error!
diff --git a/src/core/persistence/params.ts b/src/core/persistence/params.ts
index 7cfb5f9b2d..de0a36a084 100644
--- a/src/core/persistence/params.ts
+++ b/src/core/persistence/params.ts
@@ -8,7 +8,7 @@ export const CAPTURE_EVENT_PARAMS: Record<string, ParamDef> = {
kind: { type: 'string', description: 'For event captures, the event kind.' },
depth: { type: 'string', description: 'For event captures, the depth page to link.' },
};
-import { WRITE_REQUEST_STATES } from './types.ts';
+import { WRITE_REQUEST_STATES, WRITE_HEALTH_REASONS, WRITE_HEALTH_ASSESSMENTS, WRITE_HEALTH_ACTIONS } from './types.ts';
/** Leaf definitions: safe to import while the frozen verb registry is evaluating.
* Runtime validators belong in separate modules; importing OperationError here
@@ -57,5 +57,15 @@ export const WRITE_RECEIPT_SCHEMA = {
},
created_at: { type: 'string' },
updated_at: { type: 'string' },
+ diagnostic: {
+ type: 'object', required: ['age_ms', 'assessment', 'reason', 'next_action'],
+ properties: {
+ age_ms: { type: 'integer', minimum: 0, maximum: Number.MAX_SAFE_INTEGER },
+ observed_at: { type: 'string', format: 'date-time' },
+ assessment: { type: 'string', enum: [...WRITE_HEALTH_ASSESSMENTS] },
+ reason: { type: 'string', enum: [...WRITE_HEALTH_REASONS] },
+ next_action: { type: 'string', enum: [...WRITE_HEALTH_ACTIONS] },
+ },
+ },
},
};
diff --git a/src/core/persistence/schema.ts b/src/core/persistence/schema.ts
index 40457c3a49..e716f287fb 100644
--- a/src/core/persistence/schema.ts
+++ b/src/core/persistence/schema.ts
@@ -2,6 +2,8 @@ import { MANAGED_WRITER_GUARD_SQL } from './writer-guard-schema.ts';
/** Permanent terminal receipts stay outside owner recovery scans after cleanup. */
export const PERSISTENCE_REQUEST_RECOVERY_INDEX_SQL = `CREATE INDEX IF NOT EXISTS persistence_requests_recovery
ON persistence_requests(worktree_id,sequence) WHERE recovery IS NOT NULL`;
+export const PERSISTENCE_DATABASE_PENDING_INDEX_SQL = `CREATE INDEX IF NOT EXISTS persistence_requests_database_pending
+ ON persistence_requests(source_incarnation,sequence) WHERE worktree_id IS NULL AND state IN ('queued','running','recovering')`;
/** Durable infrastructure: never reconstruct or discard these rows during page reindexing. */
export const PERSISTENCE_SCHEMA_STATEMENTS = [
`CREATE TABLE IF NOT EXISTS persistence_brain (
@@ -88,6 +90,7 @@ export const PERSISTENCE_SCHEMA_STATEMENTS = [
`CREATE INDEX IF NOT EXISTS persistence_requests_pending ON persistence_requests(worktree_id,sequence)
WHERE state IN ('queued','running','recovering')`,
PERSISTENCE_REQUEST_RECOVERY_INDEX_SQL,
+ PERSISTENCE_DATABASE_PENDING_INDEX_SQL,
`CREATE INDEX IF NOT EXISTS persistence_requests_principal ON persistence_requests(principal_kind,principal_id,sequence DESC)`,
`CREATE TABLE IF NOT EXISTS persistence_effects (
id bigserial PRIMARY KEY,
diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.ts
index 2b571bc184..efd5338d39 100644
--- a/src/core/persistence/service.ts
+++ b/src/core/persistence/service.ts
@@ -9,19 +9,21 @@ import { isTerminal, type WriteRequest } from './model.ts';
import { isWriteErrorCode, type WriteReceipt } from './types.ts';
import { registerPgliteReopen } from '../pglite-lifecycle.ts';
import { assertMutationProtocol } from './protocol.ts';
+import { pendingWriteHint } from './health.ts';
interface Service { consumer: PersistenceConsumer; stopping: boolean; unregisterStop?: () => void; unregisterReopen?: () => void; }
const services = new WeakMap<BrainEngine, Service>();
+const receiptReads = new WeakMap<BrainEngine, Map<string, { read: Promise<WriteRequest | null>; abort: AbortController }>>();
const preparers = new Map<string, { prepare: PrepareMutation; target: 'page' | 'skill_bundle' }>();
export function registerMutationPreparer(operation: string, prepare: PrepareMutation, target: 'page' | 'skill_bundle' = 'page'): void {
preparers.set(operation, { prepare, target });
}
-export async function preparePersistedMutation(e: BrainEngine, row: WriteRequest, cfg: GBrainConfig) {
+export async function preparePersistedMutation(e: BrainEngine, row: WriteRequest, cfg: GBrainConfig, signal?: AbortSignal) {
assertMutationProtocol(row);
const registered = preparers.get(row.operation);
if (registered) {
if (registered.target !== (row.target_kind ?? 'page')) throw new OperationError('unsupported_mutation_protocol', 'The registered preparer does not support this mutation target.');
- return registered.prepare(e, row, cfg);
+ return registered.prepare(e, row, cfg, signal);
}
if (row.target_kind === 'skill_bundle') {
if (['put_skill', 'delete_skill'].includes(row.operation)) return (await import('../shared-skills/publication.ts')).prepareSharedSkillMutation(e, row, cfg);
@@ -36,10 +38,10 @@ export async function preparePersistedMutation(e: BrainEngine, row: WriteRequest
if (row.operation === 'submit_job' && String(row.intent?.kind).startsWith('managed_sync_')) return (await import('./sync-prepare.ts')).prepareManagedSyncMutation(e, row, cfg);
if (row.operation === 'submit_job' && String(row.intent?.kind).startsWith('managed_maintenance_')) return (await import('./prepared-maintenance.ts')).prepareMaintenanceMutation(e, row, cfg);
if (row.operation === 'put_page' && row.intent?.kind === 'managed_file_import') return (await import('./import-prepare.ts')).prepareManagedImportMutation(e, row, cfg);
- if (row.operation === 'remember') return (await import('./memory-mutations.ts')).prepareMemoryMutation(e, row, cfg);
+ if (row.operation === 'remember') return (await import('./memory-mutations.ts')).prepareMemoryMutation(e, row, cfg, signal);
if (['takes_add','takes_update','takes_supersede','takes_resolve'].includes(row.operation)) return (await import('./takes-prepare.ts')).prepareTakesMutation(e,row,cfg);
if (['add_tag','remove_tag','add_timeline_entry'].includes(row.operation)) return prepareSemanticPageMutation(e, row, cfg);
- if (['put_page','capture','delete_page','restore_page','revert_version'].includes(row.operation)) return preparePageMutation(e, row, cfg);
+ if (['put_page','capture','delete_page','restore_page','revert_version'].includes(row.operation)) return preparePageMutation(e, row, cfg, undefined, signal);
throw new OperationError('unsupported_mutation_protocol', 'No compatible mutation preparer is registered for this operation.');
}
export function startPersistenceConsumer(engine: BrainEngine, config: GBrainConfig): PersistenceConsumer {
@@ -67,7 +69,10 @@ export async function stopPersistenceConsumer(engine: BrainEngine): Promise<void
const service = services.get(engine);
if (!service) return;
service.stopping = true;
+ const pending = [...(receiptReads.get(engine)?.values() ?? [])];
+ for (const entry of pending) entry.abort.abort();
await service.consumer.stop();
+ await Promise.all(pending.map(entry => entry.read));
}
/** Reset fixtures and drained lifecycle owners may discard a stopped service. */
export async function disposePersistenceConsumer(engine: BrainEngine): Promise<void> {
@@ -93,16 +98,29 @@ export function assertPersistenceAccepting(engine: BrainEngine): void {
export async function waitForWrite(engine: BrainEngine, row: WriteRequest, config: GBrainConfig, waitMs = 5000): Promise<WriteRequest> {
if (isTerminal(row)) return row;
startPersistenceConsumer(engine, config);
+ const service = services.get(engine)!;
+ let reads = receiptReads.get(engine);
+ if (!reads) { reads = new Map(); receiptReads.set(engine, reads); }
const deadline = performance.now() + waitMs;
- while (performance.now() < deadline) {
+ while (!service.stopping && performance.now() < deadline) {
await new Promise(resolve => setTimeout(resolve, Math.min(50, Math.max(1, deadline - performance.now()))));
const remaining = deadline - performance.now();
- if (remaining <= 0) break;
- // A DB outage must not stretch a bounded synchronous wait indefinitely.
+ if (service.stopping || remaining <= 0) break;
+ let pending = reads.get(row.id);
+ const ownsRead = !pending;
+ if (!pending) {
+ if (reads.size >= 4) continue;
+ const abort = new AbortController();
+ const id = row.id;
+ const read = getWriteRequestById(engine, row.id, engine.kind === 'postgres' ? abort.signal : undefined)
+ .catch(() => null).finally(() => { if (reads.get(id)?.read === read) reads.delete(id); });
+ pending = { read, abort };
+ reads.set(id, pending);
+ }
let timer: ReturnType<typeof setTimeout> | undefined;
const found = await Promise.race([
- getWriteRequestById(engine, row.id).catch(() => null),
- new Promise<null>(resolve => { timer = setTimeout(() => resolve(null), remaining); }),
+ pending.read,
+ new Promise<null>(resolve => { timer = setTimeout(() => { if (ownsRead) pending.abort.abort(); resolve(null); }, remaining); }),
]).finally(() => { if (timer) clearTimeout(timer); });
if (found) row = found;
if (isTerminal(row)) return row;
@@ -115,7 +133,7 @@ export function writeResponse(row: WriteRequest): Record<string, unknown> {
const reason = !isTerminal(row) ? 'write_pending' : row.error_code ?? (row.state === 'cancelled' ? 'cancelled' : 'storage_error');
const error = new OperationError(reason, !isTerminal(row) ? 'The write is accepted and is still pending.'
: row.error_message ?? 'The write did not commit.', !isTerminal(row)
- ? 'Repeat the same operation, arguments, and request_id, or inspect get_write_request.'
+ ? pendingWriteHint(receipt)
: 'Inspect this receipt before submitting a new request_id.');
error.writeRequest = receipt as WriteReceipt;
error.writeError = isWriteErrorCode(reason) ? reason : reason === 'page_identity_changed' ? 'source_changed' : 'storage_error';
diff --git a/src/core/persistence/types.ts b/src/core/persistence/types.ts
index 10720e9cd9..e68f6208aa 100644
--- a/src/core/persistence/types.ts
+++ b/src/core/persistence/types.ts
@@ -19,6 +19,19 @@ export const WRITE_ERROR_CODES = [
export type WriteErrorCode = typeof WRITE_ERROR_CODES[number];
+export const WRITE_HEALTH_REASONS = ['pending', 'waiting_on_earlier_write', 'database_contention', 'writer_busy',
+ 'revision_changed_repreparing', 'recovery_required', 'writer_pool_capacity', 'owner_unavailable',
+ 'writer_lock_unavailable', 'consumer_stopping', 'cause_unknown'] as const;
+export const WRITE_HEALTH_ASSESSMENTS = ['pending', 'blocked', 'stalled'] as const;
+export const WRITE_HEALTH_ACTIONS = ['poll', 'inspect_owner'] as const;
+export interface WriteDiagnostic {
+ age_ms: number;
+ observed_at?: string;
+ assessment: typeof WRITE_HEALTH_ASSESSMENTS[number];
+ reason: typeof WRITE_HEALTH_REASONS[number];
+ next_action: typeof WRITE_HEALTH_ACTIONS[number];
+}
+
export interface WriteReceipt {
request_id: string;
state: WriteRequestState;
@@ -34,6 +47,7 @@ export interface WriteReceipt {
};
created_at?: string;
updated_at?: string;
+ diagnostic?: WriteDiagnostic;
}
/** Wire names stay separate from the engine's camelCase precondition. */
@@ -61,6 +75,20 @@ function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
+export function isWriteDiagnostic(value: unknown): value is WriteDiagnostic {
+ if (!isRecord(value) || !Number.isSafeInteger(value.age_ms) || Number(value.age_ms) < 0
+ || !(WRITE_HEALTH_ASSESSMENTS as readonly unknown[]).includes(value.assessment)
+ || !(WRITE_HEALTH_REASONS as readonly unknown[]).includes(value.reason)
+ || !(WRITE_HEALTH_ACTIONS as readonly unknown[]).includes(value.next_action)) return false;
+ if (value.observed_at !== undefined) {
+ if (typeof value.observed_at !== 'string') return false;
+ const utc = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,3}))?Z$/.exec(value.observed_at);
+ if (!utc || !Number.isFinite(Date.parse(value.observed_at))
+ || new Date(value.observed_at).toISOString() !== `${utc[1]}.${(utc[2] ?? '').padEnd(3, '0')}Z`) return false;
+ }
+ return true;
+}
+
/** Validate a receipt received over a transport before exposing structured retry information. */
export function isWriteReceipt(value: unknown): value is WriteReceipt {
if (!isRecord(value) || !isWriteRequestId(value.request_id)
@@ -73,6 +101,8 @@ export function isWriteReceipt(value: unknown): value is WriteReceipt {
if (value.outcome !== undefined && !isRecord(value.outcome)) return false;
if (value.created_at !== undefined && typeof value.created_at !== 'string') return false;
if (value.updated_at !== undefined && typeof value.updated_at !== 'string') return false;
+ if (value.diagnostic !== undefined && (!isWriteDiagnostic(value.diagnostic)
+ || isTerminalWriteState(value.state as WriteRequestState))) return false;
if (value.persistence !== undefined) {
if (!isRecord(value.persistence) || !['filesystem', 'database'].includes(String(value.persistence.mode))) return false;
if (value.persistence.file_written !== undefined && typeof value.persistence.file_written !== 'boolean') return false;
@@ -97,5 +127,10 @@ export function publicWriteReceipt(receipt: WriteReceipt): WriteReceipt {
} } : {}),
...(receipt.created_at !== undefined ? { created_at: receipt.created_at } : {}),
...(receipt.updated_at !== undefined ? { updated_at: receipt.updated_at } : {}),
+ ...(!isTerminalWriteState(receipt.state) && isWriteDiagnostic(receipt.diagnostic) ? { diagnostic: {
+ age_ms: receipt.diagnostic.age_ms, assessment: receipt.diagnostic.assessment,
+ reason: receipt.diagnostic.reason, next_action: receipt.diagnostic.next_action,
+ ...(receipt.diagnostic.observed_at !== undefined ? { observed_at: receipt.diagnostic.observed_at } : {}),
+ } } : {}),
};
}
diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.ts
index 4f5bb0f2f7..15619d4d87 100644
--- a/src/core/persistence/verb-errors.ts
+++ b/src/core/persistence/verb-errors.ts
@@ -1,5 +1,6 @@
import { verbError, OperationError } from '../ops/contract.ts';
import { isTerminalWriteState, isWriteErrorCode, type WriteErrorCode, type WriteReceipt } from './types.ts';
+import { pendingWriteHint } from './health.ts';
export function writeFailureDiagnostic(code: string, message?: string | null): { reason: string; message: string; suggestion: string } {
if (code === 'source_changed') {
@@ -75,7 +76,7 @@ export function frozenVerbWriteError(receipt: WriteReceipt, reason?: WriteErrorC
? 'invalid_params' : 'unavailable';
const diagnostic = writeFailureDiagnostic(writeError, message);
const suggestion = pending
- ? `Retry the same verb with the same arguments and request_id ${receipt.request_id}${receipt.retry_after_ms === null ? ' after checking writer availability' : ` after ${receipt.retry_after_ms} ms`}. Do not submit a new request_id for this write.`
+ ? pendingWriteHint(receipt)
: receipt.state === 'cancelled'
? 'This request was cancelled. Submit a new request_id only if you want to make a new write.'
: `${diagnostic.suggestion} Submit any corrected write with a new request_id. Reusing this request_id returns the same ${receipt.state === 'conflict' ? 'conflict' : 'outcome'}.`;
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 74aa78ee2e..6390f9219a 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -5284,14 +5284,8 @@ export class PostgresEngine implements BrainEngine {
/**
* Shared body for executeRaw / executeRawDirect: run a raw statement on the
* given connection and wire AbortSignal cancellation onto the pending query.
- * The ONLY difference between the two public methods is which connection they
- * pick (read pool vs direct session pool), so the cancellation plumbing lives
- * here in one place rather than being copy-pasted.
- *
- * v0.41.18.0 (A20, codex #7): real cancellation via postgres.js's .cancel()
- * on the pending query. Init nudge (3s wallclock cap) is the first consumer;
- * the AbortSignal fires when the timer trips. An already-aborted signal
- * short-circuits before the network round-trip.
+ * Cancellable statements retain an exclusive connection through query and
+ * cancellation settlement so a late CancelRequest cannot hit its successor.
*/
private runUnsafe<T>(
conn: ReturnType<typeof postgres>,
@@ -5299,30 +5293,38 @@ export class PostgresEngine implements BrainEngine {
params?: unknown[],
opts?: { signal?: AbortSignal },
): Promise<T[]> {
- // #4145 R2-2 preflight: an ALREADY-aborted signal must short-circuit
- // BEFORE the query is dispatched — the previous order created the
- // pending query first and cancelled it after, which still burned a
- // round-trip (and on a saturated pool, a slot). Cancellation remains
- // BEST-EFFORT overall (PG protocol cancel is async); callers that need
- // correctness must rely on their own fencing, not this signal.
if (opts?.signal?.aborted) {
throw new DOMException('aborted', 'AbortError');
}
- const pending = conn.unsafe(sql, params as Parameters<typeof conn.unsafe>[1]);
- if (opts?.signal) {
- const onAbort = () => {
+ return (async () => {
+ const signal = opts?.signal;
+ let reserved: postgres.ReservedSql | undefined;
+ let pending: ReturnType<typeof conn.unsafe> | undefined;
+ let cancellation: Promise<void> | undefined;
+ let retired = false;
+ let owner: postgres.TransactionSql | postgres.ReservedSql = conn as unknown as postgres.TransactionSql;
+ signal?.addEventListener('abort', onAbort, { once: true });
+ try {
+ reserved = signal && typeof conn.reserve === 'function' ? await conn.reserve({ signal }) : undefined;
+ if (reserved) conn = reserved;
+ owner = reserved ?? conn as unknown as postgres.TransactionSql;
+ if (signal?.aborted) throw new DOMException('aborted', 'AbortError');
+ if (signal && typeof owner.discard !== 'function') throw new Error('Postgres cancellation requires the pinned driver patch');
+ pending = conn.unsafe(sql, params as Parameters<typeof conn.unsafe>[1], { cancelFence: !!signal });
+ return await pending as unknown as T[];
+ } finally {
+ signal?.removeEventListener('abort', onAbort);
try {
- (pending as unknown as { cancel?: () => void }).cancel?.();
- } catch {
- // best-effort; the .finally below settles regardless
- }
- };
- opts.signal.addEventListener('abort', onAbort, { once: true });
- return (pending as unknown as Promise<T[]>).finally(() => {
- opts.signal?.removeEventListener('abort', onAbort);
- });
- }
- return pending as unknown as Promise<T[]>;
+ if (cancellation) await cancellation;
+ if (retired) owner.discard();
+ } finally { reserved?.release(); }
+ }
+ function onAbort() {
+ if (!pending || cancellation) return;
+ try { cancellation = pending.cancel().catch(() => { retired = true; }); }
+ catch { retired = true; }
+ }
+ })();
}
async executeRaw<T = Record<string, unknown>>(
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index f12e3954dc..0e0bdbad70 100644
--- a/templates/bootstrap/template-repo/README.md
+++ b/templates/bootstrap/template-repo/README.md
@@ -1,6 +1,6 @@
# gbrain agent workspace — template
-<!-- gbrain-template-stamp: 0.56.2.0 -->
+<!-- gbrain-template-stamp: 0.57.0.0 -->
This repository is the **"Use this template"** distribution artifact for a
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same
diff --git a/test/e2e/persistence-chaos.test.ts b/test/e2e/persistence-chaos.test.ts
index cc54f5b212..d2302d5072 100644
--- a/test/e2e/persistence-chaos.test.ts
+++ b/test/e2e/persistence-chaos.test.ts
@@ -1,5 +1,15 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, spyOn, test } from 'bun:test';
import { CRASH_BOUNDARIES, runValidation } from '../../scripts/persistence/validate.ts';
+import { createConnection, createServer, Socket } from 'node:net';
+import { createRequire } from 'node:module';
+import { randomUUID } from 'node:crypto';
+import { createServer as createTlsServer } from 'node:tls';
+import { readFileSync } from 'node:fs';
+import postgres from 'postgres';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
+import { waitFor } from '../helpers/wait-for.ts';
+import { withEnv } from '../helpers/with-env.ts';
const url = process.env.DATABASE_URL;
describe.skipIf(!url)('Postgres process-separated journal concurrency', () => {
@@ -17,3 +27,545 @@ describe.skipIf(!url)('Postgres process-separated journal concurrency', () => {
expect(result.soak.verified).toBe(64);
}, 120_000);
});
+
+describe.skipIf(!url)('Postgres cancellation ownership', () => {
+ async function fixture(run: (ctx: {
+ engine: PostgresEngine; observer: postgres.Sql; proxyUrl: string;
+ cancelHeld: () => boolean; releaseCancel: () => void;
+ stopAccepting: () => Promise<void>; restart: () => Promise<void>;
+ closeQueryConnections: () => void;
+ pauseQueries: () => void; resumeQueries: () => void; failNextStartup: () => void;
+ }) => Promise<void>, options: { tls?: boolean; targetUrl?: string; observerUrl?: string } = {}) {
+ assertSafeE2eDatabaseUrl(options.targetUrl ?? url!);
+ assertSafeE2eDatabaseUrl(options.observerUrl ?? url!);
+ const target = new URL(options.targetUrl ?? url!);
+ const sockets = new Set<Socket>();
+ const querySockets = new Set<Socket>();
+ let held: (() => void) | undefined;
+ let rejectStartup = false;
+ const accept = (client: Socket) => {
+ sockets.add(client);
+ client.once('close', () => { sockets.delete(client); querySockets.delete(client); });
+ client.on('error', () => {});
+ const chunks: Buffer[] = [];
+ const receive = (data: Buffer) => {
+ chunks.push(data);
+ const initial = Buffer.concat(chunks);
+ if (initial.length < 8) return;
+ client.removeListener('data', receive);
+ client.pause();
+ if (rejectStartup && initial.readInt32BE(4) === 196608) {
+ rejectStartup = false;
+ const body = Buffer.from('SFATAL\0C28000\0Msynthetic startup rejection\0\0');
+ const length = Buffer.alloc(4);
+ length.writeUInt32BE(body.length + 4);
+ client.end(Buffer.concat([Buffer.from('E'), length, body]));
+ return;
+ }
+ const forward = () => {
+ const upstream = createConnection({ host: target.hostname, port: Number(target.port) || 5432 });
+ sockets.add(upstream);
+ upstream.once('close', () => { sockets.delete(upstream); querySockets.delete(upstream); });
+ upstream.on('error', () => client.destroy());
+ client.on('error', () => upstream.destroy());
+ upstream.once('connect', () => {
+ upstream.write(initial);
+ client.pipe(upstream);
+ upstream.pipe(client);
+ client.resume();
+ });
+ return upstream;
+ };
+ if (initial.readInt32BE(0) === 16 && initial.readInt32BE(4) === 80877102) held = () => { if (!client.destroyed) forward(); };
+ else { querySockets.add(client); querySockets.add(forward()); }
+ };
+ client.on('data', receive);
+ };
+ const server = options.tls ? createTlsServer({
+ cert: readFileSync(new URL('../fixtures/guarded-http-localhost.crt', import.meta.url)),
+ key: readFileSync(new URL('../fixtures/guarded-http-localhost.key', import.meta.url)),
+ ALPNProtocols: ['postgresql'],
+ }, accept) : createServer(accept);
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
+ const address = server.address();
+ if (!address || typeof address === 'string') throw new Error('Missing test proxy port');
+ const proxy = new URL(options.targetUrl ?? url!);
+ proxy.hostname = '127.0.0.1';
+ proxy.port = String(address.port);
+ const engine = new PostgresEngine();
+ const observer = postgres(options.observerUrl ?? url!, { max: 1, prepare: false });
+ const releaseCancel = () => { const release = held; held = undefined; release?.(); };
+ try {
+ await withEnv({ GBRAIN_DIRECT_DATABASE_URL: undefined }, () => run({
+ engine, observer, proxyUrl: proxy.toString(), cancelHeld: () => !!held, releaseCancel,
+ stopAccepting: () => new Promise<void>(resolve => server.close(() => resolve())),
+ restart: () => new Promise<void>(resolve => server.listen(address.port, '127.0.0.1', resolve)),
+ closeQueryConnections: () => { for (const socket of querySockets) socket.destroy(); },
+ pauseQueries: () => { for (const socket of querySockets) socket.pause(); },
+ resumeQueries: () => { for (const socket of querySockets) socket.resume(); },
+ failNextStartup: () => { rejectStartup = true; },
+ }));
+ } finally {
+ releaseCancel();
+ await engine.disconnect();
+ await observer.end();
+ for (const socket of sockets) socket.destroy();
+ if (server.listening) await new Promise<void>(resolve => server.close(() => resolve()));
+ }
+ }
+
+ for (const route of ['ordinary', 'direct', 'transaction', 'tls'] as const) {
+ test(`${route} parameterized queries retain ownership until a delayed CancelRequest settles`, () => fixture(async ctx => {
+ await withEnv({ GBRAIN_DIRECT_DATABASE_URL: route === 'direct' ? ctx.proxyUrl : undefined }, async () => {
+ const target = new URL(route === 'direct' ? url! : ctx.proxyUrl);
+ if (route === 'tls') { target.searchParams.set('sslmode', 'require'); target.searchParams.set('sslnegotiation', 'direct'); }
+ await ctx.engine.connect({ database_url: target.toString(), poolSize: 1 });
+ const execute = route === 'direct' ? ctx.engine.executeRawDirect.bind(ctx.engine) : ctx.engine.executeRaw.bind(ctx.engine);
+ const [{ pid }] = await execute<{ pid: number }>('SELECT pg_backend_pid() AS pid');
+ const abort = new AbortController();
+ let firstSettled = false;
+ let successorStarted = false;
+ const run = async (engine: PostgresEngine) => {
+ const call = route === 'direct' ? engine.executeRawDirect.bind(engine) : engine.executeRaw.bind(engine);
+ await call('SELECT pg_sleep($1) AS cancellation_victim', [0.2], { signal: abort.signal });
+ firstSettled = true;
+ successorStarted = true;
+ return call('SELECT 42 AS answer');
+ };
+ const work = route === 'transaction' ? ctx.engine.transaction(tx => run(tx as PostgresEngine)) : run(ctx.engine);
+ void work.catch(() => {});
+ try {
+ await waitFor(async () => (await ctx.observer`SELECT query FROM pg_stat_activity WHERE pid=${pid} AND state='active'`)[0]?.query.includes('cancellation_victim'), { timeoutMs: 5000 });
+ abort.abort();
+ await waitFor(ctx.cancelHeld, { timeoutMs: 5000 });
+ await waitFor(async () => (await ctx.observer`SELECT state FROM pg_stat_activity WHERE pid=${pid}`)[0]?.state.startsWith('idle'), { timeoutMs: 5000 });
+ expect(firstSettled).toBe(false);
+ expect(successorStarted).toBe(false);
+ ctx.releaseCancel();
+ expect(await work).toEqual([{ answer: 42 }]);
+ } finally { ctx.releaseCancel(); await work.catch(() => {}); }
+ });
+ }, { tls: route === 'tls' }), 30000);
+ }
+
+ test('active parameterized queries are cancelled without poisoning the next statement', () => fixture(async ctx => {
+ await ctx.engine.connect({ database_url: ctx.proxyUrl, poolSize: 1 });
+ const [{ pid }] = await ctx.engine.executeRaw<{ pid: number }>('SELECT pg_backend_pid() AS pid');
+ const abort = new AbortController();
+ const work = ctx.engine.executeRaw('SELECT pg_sleep($1) AS cancellation_victim', [10], { signal: abort.signal }).catch(error => error);
+ await waitFor(async () => (await ctx.observer`SELECT query FROM pg_stat_activity WHERE pid=${pid} AND state='active'`)[0]?.query.includes('cancellation_victim'), { timeoutMs: 5000 });
+ abort.abort();
+ await waitFor(ctx.cancelHeld, { timeoutMs: 5000 });
+ ctx.releaseCancel();
+ expect(await work).toMatchObject({ code: '57014' });
+ expect(await ctx.engine.executeRaw('SELECT 42 AS answer')).toEqual([{ answer: 42 }]);
+ }), 30000);
+
+ test('a cancelled queued empty query cannot supply an unrelated read with its response', () => fixture(async ctx => {
+ await ctx.engine.connect({ database_url: ctx.proxyUrl, poolSize: 1 });
+ const [{ pid }] = await ctx.engine.executeRaw<{ pid: number }>('SELECT pg_backend_pid() AS pid');
+ await ctx.observer`SELECT pg_advisory_lock(${pid},5406)`;
+ const gate = ctx.engine.executeRaw(`SELECT pg_advisory_xact_lock(${pid},5406)`);
+ try {
+ await waitFor(async () => (await ctx.observer`SELECT wait_event FROM pg_stat_activity WHERE pid=${pid}`)[0]?.wait_event === 'advisory');
+ const abort = new AbortController();
+ const cancelled = ctx.engine.executeRaw('SELECT 1 WHERE false', undefined, { signal: abort.signal }).catch(error => error);
+ const successor = ctx.engine.executeRaw('SELECT 42 AS answer');
+ await Bun.sleep(30);
+ abort.abort();
+ expect(await cancelled).toMatchObject({ name: 'AbortError' });
+ await ctx.observer`SELECT pg_advisory_unlock(${pid},5406)`;
+ await gate;
+ expect(await successor).toEqual([{ answer: 42 }]);
+ expect(ctx.cancelHeld()).toBe(false);
+ } finally { await ctx.observer`SELECT pg_advisory_unlock(${pid},5406)`; await gate; }
+ }), 30000);
+
+ test.skipIf(!process.env.GBRAIN_PGBOUNCER_URL || !process.env.GBRAIN_PGBOUNCER_DIRECT_URL)('a late pooler cancellation cannot hit another client reusing the same backend', async () => {
+ const direct = process.env.GBRAIN_PGBOUNCER_DIRECT_URL!;
+ assertSafeE2eDatabaseUrl(direct);
+ const admin = postgres(direct, { max: 1, prepare: false });
+ const database = `gbrain_test_cancel_pool_${randomUUID().replaceAll('-', '')}`;
+ const pooled = new URL(process.env.GBRAIN_PGBOUNCER_URL!);
+ pooled.pathname = `/${database}`;
+ try {
+ await admin.unsafe(`CREATE DATABASE ${database}`);
+ await fixture(async ctx => {
+ const other = postgres(pooled.toString(), { max: 1, prepare: false });
+ try {
+ await ctx.engine.connect({ database_url: ctx.proxyUrl, poolSize: 1 });
+ const [{ pid }] = await ctx.engine.executeRaw<{ pid: number }>('SELECT pg_backend_pid() AS pid');
+ const abort = new AbortController();
+ const first = ctx.engine.executeRaw('SELECT pg_sleep($1) AS cancellation_victim', [0.2], { signal: abort.signal });
+ void first.catch(() => {});
+ await waitFor(async () => (await ctx.observer`SELECT query FROM pg_stat_activity WHERE pid=${pid} AND state='active'`)[0]?.query.includes('cancellation_victim'));
+ abort.abort();
+ await waitFor(ctx.cancelHeld);
+ await waitFor(async () => (await ctx.observer`SELECT state FROM pg_stat_activity WHERE pid=${pid}`)[0]?.state === 'idle');
+ const competitor = other.unsafe('SELECT pg_backend_pid() AS pid, pg_sleep(0.3) AS pooler_successor').execute();
+ void competitor.catch(() => {});
+ await waitFor(async () => (await ctx.observer`SELECT query FROM pg_stat_activity WHERE pid=${pid} AND state='active'`)[0]?.query.includes('pooler_successor'));
+ ctx.releaseCancel();
+ await first;
+ expect((await competitor)[0].pid).toBe(pid);
+ expect(await ctx.engine.executeRaw('SELECT 42 AS answer')).toEqual([{ answer: 42 }]);
+ } finally { ctx.releaseCancel(); await other.end({ timeout: 1 }); }
+ }, { targetUrl: pooled.toString(), observerUrl: direct });
+ } finally { await admin.unsafe(`DROP DATABASE IF EXISTS ${database} WITH (FORCE)`); await admin.end(); }
+ }, 30000);
+
+ test('transaction cancellation fences concurrent tagged queries and nested savepoints', () => fixture(async ctx => {
+ await ctx.engine.connect({ database_url: ctx.proxyUrl, poolSize: 1 });
+ const [{ pid }] = await ctx.engine.executeRaw<{ pid: number }>('SELECT pg_backend_pid() AS pid');
+ const abort = new AbortController();
+ let taggedSettled = false, nestedSettled = false;
+ const submitted = Promise.withResolvers<void>();
+ const work = ctx.engine.transaction(async tx => {
+ const first = tx.executeRaw('SELECT pg_sleep($1) AS cancellation_victim', [0.2], { signal: abort.signal });
+ await waitFor(async () => (await ctx.observer`SELECT query FROM pg_stat_activity WHERE pid=${pid} AND state='active'`)[0]?.query.includes('cancellation_victim'), { timeoutMs: 5000 });
+ const tagged = (tx as PostgresEngine).sql`SELECT 42 AS answer`.then(rows => { taggedSettled = true; return rows; });
+ const nested = tx.transaction(inner => inner.executeRaw('SELECT 7 AS answer')).then(rows => { nestedSettled = true; return rows; });
+ submitted.resolve();
+ return Promise.all([first, tagged, nested]);
+ });
+ void work.catch(error => submitted.reject(error));
+ void work.catch(() => {});
+ try {
+ await submitted.promise;
+ abort.abort();
+ await waitFor(ctx.cancelHeld, { timeoutMs: 5000 });
+ await waitFor(async () => (await ctx.observer`SELECT state FROM pg_stat_activity WHERE pid=${pid}`)[0]?.state === 'idle in transaction', { timeoutMs: 5000 });
+ expect([taggedSettled, nestedSettled]).toEqual([false, false]);
+ ctx.releaseCancel();
+ const result = await work;
+ expect(Array.from(result[1])).toEqual([{ answer: 42 }]);
+ expect(result[2]).toEqual([{ answer: 7 }]);
+ } finally { ctx.releaseCancel(); await work.catch(() => {}); }
+ }), 30000);
+
+ test('cancelling an unsent transaction query drains its followers without a CancelRequest', () => fixture(async ctx => {
+ await ctx.engine.connect({ database_url: ctx.proxyUrl, poolSize: 1 });
+ const [{ pid }] = await ctx.engine.executeRaw<{ pid: number }>('SELECT pg_backend_pid() AS pid');
+ const abort = new AbortController();
+ let follower: unknown;
+ const result = await ctx.engine.transaction(async tx => {
+ const previous = tx.executeRaw('SELECT pg_sleep($1) AS cancellation_predecessor', [0.2]);
+ const cancelled = tx.executeRaw('SELECT pg_sleep($1)', [10], { signal: abort.signal }).catch(error => error);
+ await waitFor(async () => (await ctx.observer`SELECT query FROM pg_stat_activity WHERE pid=${pid} AND state='active'`)[0]?.query.includes('cancellation_predecessor'), { timeoutMs: 5000 });
+ abort.abort();
+ expect(await cancelled).toMatchObject({ code: '57014' });
+ const next = tx.executeRaw('SELECT 42 AS answer');
+ await previous;
+ follower = await next;
+ }).catch(error => error);
+ expect(result).toMatchObject({ code: '57014' });
+ expect(follower).toEqual([{ answer: 42 }]);
+ expect(ctx.cancelHeld()).toBe(false);
+ expect(await ctx.engine.executeRaw('SELECT 7 AS answer')).toEqual([{ answer: 7 }]);
+ }), 30000);
+
+ test('a cancellation transport timeout retires the transaction and rejects queued followers', () => fixture(async ctx => {
+ const pool = postgres(ctx.proxyUrl, { max: 1, prepare: false, connect_timeout: 1 });
+ try {
+ const [{ pid }] = await pool`SELECT pg_backend_pid() AS pid`;
+ const submitted = Promise.withResolvers<void>();
+ let first: postgres.PendingQuery<postgres.Row[]>;
+ const work = pool.begin(async tx => {
+ first = tx.unsafe<postgres.Row[]>('SELECT pg_sleep($1) AS cancellation_victim', [0.2], { cancelFence: true }).execute();
+ await waitFor(async () => (await ctx.observer`SELECT query FROM pg_stat_activity WHERE pid=${pid} AND state='active'`)[0]?.query.includes('cancellation_victim'), { timeoutMs: 5000 });
+ const follower = tx`SELECT 42 AS answer`.execute();
+ void follower.catch(() => {});
+ submitted.resolve();
+ await first;
+ return follower;
+ }).catch(error => error);
+ await submitted.promise;
+ const cancellation = first!.cancel().catch(error => error);
+ await waitFor(ctx.cancelHeld);
+ expect(await cancellation).toMatchObject({ code: 'CONNECT_TIMEOUT' });
+ expect(await work).toMatchObject({ code: 'CONNECTION_CLOSED' });
+ const [{ pid: replacement }] = await pool`SELECT pg_backend_pid() AS pid`;
+ expect(replacement).not.toBe(pid);
+ } finally { ctx.releaseCancel(); await pool.end({ timeout: 1 }); }
+ }), 30000);
+
+ test('multi-host cancellation connection errors cannot masquerade as acknowledgement', () => fixture(async ctx => {
+ const port = Number(new URL(ctx.proxyUrl).port);
+ const pool = postgres(ctx.proxyUrl, { host: '127.0.0.1,127.0.0.1', port, max: 1, prepare: false });
+ try {
+ const owned = await pool.reserve();
+ const [{ pid }] = await owned`SELECT pg_backend_pid() AS pid`;
+ const first = owned.unsafe('SELECT pg_sleep($1) AS cancellation_victim', [0.2], { cancelFence: true }).execute();
+ await waitFor(async () => (await ctx.observer`SELECT query FROM pg_stat_activity WHERE pid=${pid} AND state='active'`)[0]?.query.includes('cancellation_victim'));
+ const stopped = ctx.stopAccepting();
+ const cancellation = first.cancel().catch(error => error);
+ await first;
+ expect(await cancellation).toMatchObject({ code: 'ECONNREFUSED' });
+ owned.release();
+ await stopped;
+ await ctx.restart();
+ expect((await pool`SELECT pg_backend_pid() AS pid`)[0].pid).not.toBe(pid);
+ } finally { await pool.end({ timeout: 1 }); }
+ }), 30000);
+
+ test('a failed cancellation connection retires only its completed query connection', () => fixture(async ctx => {
+ await ctx.engine.connect({ database_url: ctx.proxyUrl, poolSize: 1 });
+ const [{ pid }] = await ctx.engine.executeRaw<{ pid: number }>('SELECT pg_backend_pid() AS pid');
+ const abort = new AbortController();
+ const work = ctx.engine.executeRaw('SELECT pg_sleep($1) AS cancellation_victim', [0.2], { signal: abort.signal });
+ void work.catch(() => {});
+ await waitFor(async () => (await ctx.observer`SELECT query FROM pg_stat_activity WHERE pid=${pid} AND state='active'`)[0]?.query.includes('cancellation_victim'), { timeoutMs: 5000 });
+ const stopped = ctx.stopAccepting();
+ abort.abort();
+ await work;
+ await stopped;
+ await ctx.restart();
+ const [{ pid: replacement }] = await ctx.engine.executeRaw<{ pid: number }>('SELECT pg_backend_pid() AS pid');
+ expect(replacement).not.toBe(pid);
+ }), 30000);
+
+ test('late cancellation cleanup cannot release a replacement connection after socket loss', () => fixture(async ctx => {
+ await ctx.engine.connect({ database_url: ctx.proxyUrl, poolSize: 1 });
+ const [{ pid }] = await ctx.engine.executeRaw<{ pid: number }>('SELECT pg_backend_pid() AS pid');
+ const abort = new AbortController();
+ const work = ctx.engine.executeRaw('SELECT pg_sleep($1) AS cancellation_victim', [0.2], { signal: abort.signal });
+ void work.catch(() => {});
+ await waitFor(async () => (await ctx.observer`SELECT query FROM pg_stat_activity WHERE pid=${pid} AND state='active'`)[0]?.query.includes('cancellation_victim'), { timeoutMs: 5000 });
+ abort.abort();
+ await waitFor(ctx.cancelHeld, { timeoutMs: 5000 });
+ await waitFor(async () => (await ctx.observer`SELECT state FROM pg_stat_activity WHERE pid=${pid}`)[0]?.state === 'idle', { timeoutMs: 5000 });
+ ctx.closeQueryConnections();
+ const replacement = ctx.engine.executeRaw<{ pid: number }>('SELECT pg_backend_pid() AS pid, pg_sleep($1) AS replacement_owner', [0.2], { signal: new AbortController().signal });
+ void replacement.catch(() => {});
+ await waitFor(async () => (await ctx.observer`SELECT pid FROM pg_stat_activity WHERE pid<>${pid} AND state='active' AND query LIKE '%AS replacement_owner'`).length === 1, { timeoutMs: 5000 });
+ ctx.releaseCancel();
+ await work;
+ expect((await replacement)[0].pid).not.toBe(pid);
+ expect(await ctx.engine.executeRaw('SELECT 42 AS answer')).toEqual([{ answer: 42 }]);
+ }), 30000);
+
+ const drivers = { esm: postgres, commonjs: createRequire(import.meta.url)('../../node_modules/postgres/cjs/src/index.js') as typeof postgres };
+ for (const [name, driver] of Object.entries(drivers)) {
+ test(`${name} releasing a lease during pool shutdown cannot grant its waiter`, async () => {
+ assertSafeE2eDatabaseUrl(url!);
+ const pool = driver(url!, { max: 1, prepare: false });
+ const lease = await pool.reserve();
+ let granted: postgres.ReservedSql | undefined;
+ try {
+ const active = lease`SELECT pg_sleep(0.1)`.execute();
+ await waitFor(() => Reflect.get(active, 'active') === true);
+ const waiting = pool.reserve().then(value => { granted = value; return value; });
+ void waiting.catch(() => {});
+ const ending = pool.end({ timeout: 1 });
+ await active; lease.release();
+ await ending;
+ await expect(waiting).rejects.toMatchObject({ code: 'CONNECTION_ENDED' });
+ expect(granted).toBeUndefined();
+ } finally { lease.discard(); granted?.discard(); await pool.end({ timeout: 1 }); }
+ }, 30000);
+
+ test(`${name} ending a pool rejects a pending reservation without reconnecting`, async () => {
+ assertSafeE2eDatabaseUrl(url!);
+ const pool = driver(url!, { max: 1, prepare: false });
+ let granted: postgres.ReservedSql | undefined;
+ try {
+ await pool`SELECT 1`;
+ const active = pool`SELECT pg_sleep(0.1)`.execute();
+ await waitFor(() => Reflect.get(active, 'active') === true);
+ const waiting = pool.reserve({ signal: new AbortController().signal }).then(lease => { granted = lease; return lease; });
+ void waiting.catch(() => {});
+ await pool.end({ timeout: 1 });
+ await active;
+ await expect(waiting).rejects.toMatchObject({ code: 'CONNECTION_ENDED' });
+ expect(granted).toBeUndefined();
+ } finally { granted?.discard(); await pool.end({ timeout: 1 }); }
+ }, 30000);
+
+ test(`${name} unfenced transaction followers resume pipelining after a parameter description`, async () => {
+ assertSafeE2eDatabaseUrl(url!);
+ const pool = driver(url!, { max: 1, prepare: false });
+ try {
+ await pool.begin(async tx => {
+ const previous = tx`SELECT pg_sleep(${0.1})`.execute();
+ const first = tx`SELECT pg_sleep(0.1)`.execute();
+ const follower = tx`SELECT 42 AS answer`.execute();
+ await previous;
+ expect(Reflect.get(first, 'state')).not.toBeNull();
+ expect(Reflect.get(follower, 'state')).not.toBeNull();
+ await first;
+ expect(Array.from(await follower)).toEqual([{ answer: 42 }]);
+ });
+ } finally { await pool.end({ timeout: 1 }); }
+ }, 30000);
+
+ for (const warm of [false, true]) {
+ test(`${name} reservation opens ${warm ? 'after reconnect without another type fetch' : 'with type fetching disabled'}`, async () => {
+ assertSafeE2eDatabaseUrl(url!);
+ const closed = Promise.withResolvers<void>();
+ const pool = driver(url!, { max: 1, prepare: false, fetch_types: warm, onclose: () => closed.resolve() });
+ const observer = postgres(url!, { max: 1, prepare: false });
+ const abort = new AbortController();
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ if (warm) {
+ const [{ pid }] = await pool`SELECT pg_backend_pid() AS pid`;
+ await observer`SELECT pg_terminate_backend(${pid})`;
+ await closed.promise;
+ }
+ timer = setTimeout(() => abort.abort(), 2000);
+ const lease = await pool.reserve({ signal: abort.signal });
+ expect(Array.from(await lease`SELECT 42 AS answer`)).toEqual([{ answer: 42 }]);
+ lease.release();
+ } finally { clearTimeout(timer); await pool.end({ timeout: 1 }); await observer.end({ timeout: 1 }); }
+ }, 30000);
+ }
+
+ test(`${name} cancelling a completed cursor settles without a new cancel request`, async () => {
+ assertSafeE2eDatabaseUrl(url!);
+ const pool = driver(url!, { max: 1, prepare: false });
+ try {
+ const lease = await pool.reserve();
+ const query = lease`SELECT generate_series(1, 2) AS n`;
+ const values: number[] = [];
+ for await (const rows of query.cursor(1)) values.push(...rows.map(row => row.n));
+ expect(values).toEqual([1, 2]);
+ expect(await Promise.race([query.cancel().then(() => true), Bun.sleep(50).then(() => false)])).toBe(true);
+ expect(Array.from(await lease`SELECT 42 AS answer`)).toEqual([{ answer: 42 }]);
+ lease.release();
+ } finally { await pool.end({ timeout: 1 }); }
+ }, 30000);
+
+ test(`${name} a saved savepoint handle cannot enter a replacement transaction`, async () => {
+ assertSafeE2eDatabaseUrl(url!);
+ const pool = driver(url!, { max: 1, prepare: false });
+ const entered = Promise.withResolvers<void>(), release = Promise.withResolvers<void>();
+ let stale: postgres.TransactionSql | undefined;
+ let replacement: Promise<unknown> | undefined;
+ try {
+ await pool.begin(async tx => { stale = tx; await tx`SELECT 1`; });
+ replacement = pool.begin(async tx => { entered.resolve(); await release.promise; return tx`SELECT 7 AS answer`; });
+ void replacement.catch(() => {});
+ await entered.promise;
+ await expect(stale!.savepoint(tx => tx`SELECT 42 AS answer`)).rejects.toMatchObject({ code: 'CONNECTION_CLOSED' });
+ stale!.discard();
+ release.resolve();
+ expect(Array.from(await replacement as postgres.Row[])).toEqual([{ answer: 7 }]);
+ } finally { release.resolve(); await replacement?.catch(() => {}); await pool.end({ timeout: 1 }); }
+ }, 30000);
+
+ test(`${name} an ended pool rejects a new reservation without waiting`, async () => {
+ assertSafeE2eDatabaseUrl(url!);
+ const pool = driver(url!, { max: 1, prepare: false });
+ await pool`SELECT 1`;
+ await pool.end();
+ await expect(pool.reserve()).rejects.toMatchObject({ code: 'CONNECTION_ENDED' });
+ }, 30000);
+
+ test(`${name} transaction ownership survives actual socket backpressure`, () => fixture(async ctx => {
+ const pool = driver(ctx.proxyUrl, { max: 1, prepare: false });
+ const write = Socket.prototype.write;
+ let backpressure = false;
+ const writes = spyOn(Socket.prototype, 'write').mockImplementation(function(this: Socket, ...args: unknown[]) {
+ const ready = Reflect.apply(write, this, args);
+ if (!ready && this.remotePort === Number(new URL(ctx.proxyUrl).port) && args[0] instanceof Uint8Array && args[0].byteLength > 65536) backpressure = true;
+ return ready;
+ });
+ let work: Promise<unknown> | undefined;
+ try {
+ await pool`SELECT 1`;
+ ctx.pauseQueries();
+ work = pool.begin(' '.repeat(8 * 1024 * 1024), tx => tx`SELECT 42 AS answer`);
+ void work.catch(() => {});
+ await waitFor(() => backpressure, { label: 'actual write backpressure' });
+ ctx.resumeQueries();
+ const rows = await work as postgres.Row[];
+ expect(Array.from(rows)).toEqual([{ answer: 42 }]);
+ expect(backpressure).toBe(true);
+ } finally { ctx.resumeQueries(); writes.mockRestore(); await work?.catch(() => {}); await pool.end({ timeout: 1 }); }
+ }), 30000);
+
+ test(`${name} a rejected cold reservation cannot consume the replacement connection`, () => fixture(async ctx => {
+ const pool = driver(ctx.proxyUrl, { max: 1, prepare: false });
+ try {
+ ctx.failNextStartup();
+ await expect(pool.reserve()).rejects.toMatchObject({ code: '28000' });
+ const abort = new AbortController();
+ const timer = setTimeout(() => abort.abort(), 2000);
+ try {
+ const next = await pool.reserve({ signal: abort.signal });
+ expect(Array.from(await next`SELECT 42 AS answer`)).toEqual([{ answer: 42 }]);
+ next.release();
+ } finally { clearTimeout(timer); }
+ } finally { await pool.end({ timeout: 1 }); }
+ }), 30000);
+
+ test(`${name} a granted reservation excludes a competing transaction continuation`, () => fixture(async ctx => {
+ const pool = driver(ctx.proxyUrl, { max: 1, prepare: false });
+ const release = Promise.withResolvers<void>();
+ let lease: postgres.ReservedSql | undefined;
+ let competing: Promise<unknown> | undefined;
+ try {
+ const [{ pid }] = await pool`SELECT pg_backend_pid() AS pid`;
+ const previous = pool`SELECT pg_sleep(0.1) AS reservation_predecessor`.execute();
+ await waitFor(async () => (await ctx.observer`SELECT query FROM pg_stat_activity WHERE pid=${pid} AND state='active'`)[0]?.query.includes('reservation_predecessor'));
+ let entered = false;
+ competing = previous.then(() => pool.begin(async tx => { entered = true; await release.promise; return tx`SELECT 7 AS answer`; }));
+ void competing.catch(() => {});
+ lease = await pool.reserve();
+ expect(Array.from(await lease`SELECT 42 AS answer`)).toEqual([{ answer: 42 }]);
+ await Bun.sleep(30);
+ expect(entered).toBe(false);
+ lease.release();
+ lease = undefined;
+ await waitFor(() => entered);
+ release.resolve();
+ expect(Array.from(await competing as postgres.Row[])).toEqual([{ answer: 7 }]);
+ } finally { lease?.release(); release.resolve(); await competing?.catch(() => {}); await pool.end({ timeout: 1 }); }
+ }), 30000);
+
+ for (const timing of ['waiting', 'granted'] as const) {
+ test(`${name} aborting a ${timing} reservation returns the only connection`, async () => {
+ assertSafeE2eDatabaseUrl(url!);
+ const pool = driver(url!, { max: 1, prepare: false });
+ try {
+ const held = await pool.reserve();
+ const abort = new AbortController();
+ const waiting = pool.reserve({ signal: abort.signal });
+ if (timing === 'granted') held.release();
+ abort.abort();
+ if (timing === 'waiting') held.release();
+ await expect(waiting).rejects.toMatchObject({ name: 'AbortError' });
+ const successor = await pool.reserve();
+ expect(Array.from(await successor`SELECT 42 AS answer`)).toEqual([{ answer: 42 }]);
+ successor.release();
+ } finally { await pool.end({ timeout: 1 }); }
+ }, 30000);
+ }
+
+ test(`${name} stale reservations cannot query, release or discard a replacement owner`, async () => {
+ assertSafeE2eDatabaseUrl(url!);
+ const pool = driver(url!, { max: 1, prepare: false });
+ const observer = driver(url!, { max: 1, prepare: false });
+ let replacement: postgres.ReservedSql | undefined;
+ try {
+ const original = await pool.reserve();
+ const [{ pid }] = await original`SELECT pg_backend_pid() AS pid`;
+ await observer`SELECT pg_terminate_backend(${pid})`;
+ replacement = await pool.reserve();
+ const [{ pid: nextPid }] = await replacement`SELECT pg_backend_pid() AS pid`;
+ expect(nextPid).not.toBe(pid);
+ original.release();
+ original.discard();
+ await expect(original`SELECT 1`.execute()).rejects.toMatchObject({ code: 'CONNECTION_CLOSED' });
+ let acquired = false;
+ const waiting = pool.reserve().then(value => { acquired = true; return value; });
+ await Bun.sleep(30);
+ expect(acquired).toBe(false);
+ expect(Array.from(await replacement`SELECT 42 AS answer`)).toEqual([{ answer: 42 }]);
+ replacement.release();
+ replacement = undefined;
+ (await waiting).release();
+ } finally { replacement?.release(); await pool.end({ timeout: 1 }); await observer.end(); }
+ }, 30000);
+ }
+});
diff --git a/test/e2e/persistence-http-liveness.test.ts b/test/e2e/persistence-http-liveness.test.ts
new file mode 100644
index 0000000000..cb56116a14
--- /dev/null
+++ b/test/e2e/persistence-http-liveness.test.ts
@@ -0,0 +1,403 @@
+import { beforeAll, afterAll, afterEach, describe, expect, test } from 'bun:test';
+import { spawn, spawnSync, type ChildProcess } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { createServer } from 'node:net';
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { keylessBrainEnv } from '../helpers/provider-env.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { waitFor } from '../helpers/wait-for.ts';
+import { cliDiagnostic, fixtureDiagnostic } from '../helpers/fixture-diagnostics.ts';
+import { initializeFixtures, fixtures, selectFixtureHost, assertConservation, type HarnessConfig } from '../../scripts/persistence/harness.ts';
+import { acquireWorktree } from '../../src/core/persistence/ownership.ts';
+import type { WriteRequest } from '../../src/core/persistence/model.ts';
+
+const url = process.env.DATABASE_URL;
+const oldBinary = process.env.GBRAIN_TEST_OLD_BINARY;
+describe.skipIf(!url)('authenticated PostgreSQL HTTP accepted-write liveness', () => {
+ let pg: Awaited<ReturnType<typeof isolatedPersistencePostgres>>;
+ let home: string;
+ let config: HarnessConfig;
+ let env: Record<string, string>;
+ let base: string;
+ let server: ChildProcess | undefined;
+ let restoreOwner = false;
+ const clients: Client[] = [];
+ const tokens: string[] = [];
+ let oauthId: string;
+ let oauthSecret: string;
+ let stderr = '';
+ const content = (text: string) => `---\ntitle: Synthetic note\ntype: note\n---\n\n${text}`;
+
+ function cli(args: string[]): string {
+ const result = spawnSync('bun', ['--no-env-file', 'run', 'src/cli.ts', ...args], { env, encoding: 'utf8', timeout: 60000 });
+ if (result.status !== 0) throw new Error(cliDiagnostic(args[0], { exitCode: result.status ?? -1, stdout: result.stdout, stderr: result.stderr }));
+ return result.stdout;
+ }
+ async function start(binary?: string) {
+ stderr = '';
+ const args = ['serve', '--http', '--surface', 'full', '--bind', '127.0.0.1', '--port', new URL(base).port,
+ '--public-url', base, '--suppress-bootstrap-token'];
+ server = spawn(binary ?? 'bun', binary ? args : ['--no-env-file', 'run', 'src/cli.ts', ...args],
+ { env, stdio: ['ignore', 'ignore', 'pipe'] });
+ server.stderr?.on('data', chunk => { stderr += String(chunk); });
+ await waitFor(async () => {
+ if (server?.exitCode != null) throw new Error(fixtureDiagnostic('HTTP owner exited', stderr, tokens));
+ try { return (await fetch(`${base}/health`, { signal: AbortSignal.timeout(500) })).ok; } catch { return false; }
+ }, { timeoutMs: 30000 });
+ }
+ async function stop(signal: 'SIGTERM' | 'SIGKILL' = 'SIGTERM') {
+ for (const client of clients.splice(0)) await client.close().catch(() => {});
+ if (!server || server.exitCode != null || server.signalCode != null) return;
+ const child = server;
+ await new Promise<void>(resolve => {
+ const timer = setTimeout(() => child.kill('SIGKILL'), 10000);
+ child.once('exit', () => { clearTimeout(timer); resolve(); });
+ child.kill(signal);
+ });
+ }
+ async function connect(token: string) {
+ const client = new Client({ name: 'synthetic-persistence-client', version: '1' });
+ await client.connect(new StreamableHTTPClientTransport(new URL(`${base}/mcp`), {
+ requestInit: { headers: { Authorization: `Bearer ${token}` } },
+ }));
+ clients.push(client);
+ return client;
+ }
+ async function call(client: Client, name: string, args: Record<string, unknown>) {
+ const result = await client.callTool({ name, arguments: args }, undefined, { timeout: 30000 });
+ const body = JSON.parse((result.content as Array<{ text: string }>)[0].text);
+ return { result, body };
+ }
+ async function receipt(client: Client, id: string) {
+ return (await call(client, 'get_write_request', { request_id: id })).body;
+ }
+ async function committed(client: Client, id: string) {
+ let current: any;
+ await waitFor(async () => { current = await receipt(client, id); return current.state === 'committed'; }, { timeoutMs: 20000 });
+ return current;
+ }
+ beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-http-liveness-'));
+ pg = await isolatedPersistencePostgres(url!);
+ config = { kind: 'postgres', root: home, dataDir: join(home, 'unused'), hostId: randomUUID(), seed: 5406,
+ schedules: 0, operations: 0, sourceIds: ['http-source', 'http-other'], principalIds: [randomUUID()] };
+ await withEnv({ GBRAIN_HOME: home, GBRAIN_PERSISTENCE_FIXTURE_HOME: home }, async () => {
+ selectFixtureHost(config.hostId);
+ await initializeFixtures(pg.engine, config);
+ });
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'postgres', database_url: pg.databaseUrl, embedding_disabled: true }));
+ env = keylessBrainEnv(process.env, home, { DATABASE_URL: pg.databaseUrl, GBRAIN_DATABASE_URL: pg.databaseUrl,
+ GBRAIN_ENGINE: 'postgres', GBRAIN_SOURCE: undefined, GBRAIN_BRAIN_ID: undefined, GBRAIN_SKIP_STARTUP_HOOKS: '1',
+ GBRAIN_MCP_FORCE_SURFACE: undefined, GBRAIN_REMOTE_CLIENT_SECRET: undefined, GBRAIN_REMOTE_PRIVATE_PAGES: undefined });
+ const legacy = cli(['auth', 'create', 'synthetic-http-writer', '--scopes', 'read,write']);
+ tokens.push(legacy.match(/gbrain_[a-f0-9]{64}/)![0]);
+ await pg.engine.executeRaw("UPDATE access_tokens SET permissions=jsonb_set(COALESCE(permissions,'{}'::jsonb),'{source_id}',to_jsonb($1::text)) WHERE name='synthetic-http-writer'", [config.sourceIds[0]]);
+ const oauth = cli(['auth', 'register-client', 'synthetic-oauth-writer', '--grant-types', 'client_credentials',
+ '--scopes', 'read write', '--source', config.sourceIds[0]]);
+ oauthId = oauth.match(/Client ID:\s+(gbrain_cl_\S+)/)![1];
+ oauthSecret = oauth.match(/Client Secret:\s+(gbrain_cs_\S+)/)![1];
+ const probe = createServer();
+ await new Promise<void>(resolve => probe.listen(0, '127.0.0.1', resolve));
+ base = `http://127.0.0.1:${(probe.address() as { port: number }).port}`;
+ await new Promise<void>(resolve => probe.close(() => resolve()));
+ await start();
+ const minted = await fetch(`${base}/token`, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ body: new URLSearchParams({ grant_type: 'client_credentials', client_id: oauthId, client_secret: oauthSecret, scope: 'read write' }) });
+ expect(minted.ok).toBe(true);
+ tokens.push((await minted.json() as { access_token: string }).access_token);
+ await connect(tokens[0]); await connect(tokens[1]);
+ }, 120000);
+ afterAll(async () => { await stop(); await pg?.close(); if (home) rmSync(home, { recursive: true, force: true }); }, 30000);
+ afterEach(async () => {
+ if (!restoreOwner) return;
+ restoreOwner = false;
+ await stop('SIGKILL'); await start(); await connect(tokens[0]); await connect(tokens[1]);
+ }, 30000);
+
+ for (const [index, auth] of ['legacy', 'oauth'].entries()) test(`${auth} put_page and remember preserve UUIDs through contention and restart`, async () => {
+ const client = clients[index];
+ const source = (await fixtures(pg.engine, config))[0];
+ const entity = `notes/entity-${auth}`;
+ expect((await call(client, 'put_page', { slug: entity, source_id: source.id, content: content('Entity fixture'), request_id: randomUUID() })).result.isError).not.toBe(true);
+ const lock = await acquireWorktree(source.binding, 1000);
+ expect(lock).not.toBeNull();
+ const put = { slug: `notes/queued-${auth}`, source_id: source.id, content: content(`Original ${auth} fixture`), request_id: randomUUID() };
+ const memory = { fact: `Synthetic ${auth} durable fact`, provenance: `synthetic fixture ${auth}`, entity, source_id: source.id, request_id: randomUUID() };
+ try {
+ const pending = await call(client, 'put_page', put);
+ expect(pending.result.isError).toBe(true);
+ expect(pending.body.write_request.request_id).toBe(put.request_id);
+ expect(pending.body.write_request.diagnostic).toBeDefined();
+ const remembered = await call(client, 'remember', memory);
+ expect(remembered.result.isError).toBe(true);
+ expect(remembered.body.protocol_version).toBe(1);
+ expect(remembered.body.write_request.request_id).toBe(memory.request_id);
+ expect((await receipt(client, memory.request_id)).diagnostic.reason).toBe('waiting_on_earlier_write');
+ expect(await pg.engine.readPageSnapshot(put.slug, { sourceId: source.id })).toBeNull();
+ expect(await pg.engine.executeRaw('SELECT id FROM facts WHERE source_id=$1 AND fact=$2', [source.id, memory.fact])).toHaveLength(0);
+ await pg.engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('gbrain.persistence_protocol','2',true)");
+ await tx.executeRaw("UPDATE persistence_requests SET created_at=now()-interval '3 minutes' WHERE request_id=$1", [put.request_id]);
+ });
+ const aged = await receipt(client, put.request_id);
+ expect(aged.diagnostic.next_action).toBe('inspect_owner');
+ expect(aged.retry_after_ms).toBe(30000);
+ expect((await call(client, 'put_page', put)).body.suggestion).toContain('inspect');
+ await stop('SIGKILL');
+ } finally { await lock!.release(); }
+ await start();
+ await connect(tokens[0]); await connect(tokens[1]);
+ const replacement = clients[index];
+ await committed(replacement, put.request_id);
+ await committed(replacement, memory.request_id);
+ const before = await pg.engine.executeRaw('SELECT key,lifetime_ids,terminal_bytes FROM persistence_counters ORDER BY key');
+ const snapshot = await pg.engine.readPageSnapshot(put.slug, { sourceId: source.id });
+ expect(snapshot?.page.compiled_truth).toBe(`Original ${auth} fixture`);
+ expect(readFileSync(join(source.root, `${put.slug}.md`), 'utf8')).toContain(`Original ${auth} fixture`);
+ expect((await call(replacement, 'put_page', put)).body.revision).toBe(snapshot!.revision);
+ expect((await call(replacement, 'remember', memory)).body.status).toBe('inserted');
+ expect(await pg.engine.executeRaw('SELECT fact,source,source_id FROM facts WHERE fact=$1', [memory.fact])).toEqual([
+ { fact: memory.fact, source: memory.provenance, source_id: source.id },
+ ]);
+ expect((await call(replacement, 'put_page', { ...put, content: content('Changed intent') })).body.error).toBe('idempotency_conflict');
+ expect(await pg.engine.executeRaw('SELECT key,lifetime_ids,terminal_bytes FROM persistence_counters ORDER BY key')).toEqual(before);
+ await assertConservation(pg.engine);
+ }, 90000);
+
+ test('44 synthetic pages over three authenticated clients reconcile exactly', async () => {
+ const third = await connect(tokens[0]);
+ const writers = [clients[0], clients[1], third];
+ const pages = Array.from({ length: 44 }, (_, index) => ({ slug: `notes/import-${index}`, source_id: config.sourceIds[0],
+ content: content(`fixture ${index}\n${'synthetic '.repeat(index === 43 ? 24900 : 400 + index * 150).trimEnd()}`), request_id: randomUUID() }));
+ await Promise.all(writers.map(async (client, worker) => {
+ for (let index = worker; index < pages.length; index += writers.length) {
+ const result = await call(client, 'put_page', pages[index]);
+ expect(result.body.request_id ?? result.body.write_request?.request_id).toBe(pages[index].request_id);
+ const done = await committed(client, pages[index].request_id);
+ const snapshot = await pg.engine.readPageSnapshot(pages[index].slug, { sourceId: config.sourceIds[0] });
+ expect(snapshot!.revision).toBe(done.revision);
+ expect(snapshot!.page.compiled_truth).toBe(pages[index].content.split('---\n\n')[1]);
+ }
+ }));
+ expect(await pg.engine.executeRaw("SELECT count(*)::int AS count FROM pages WHERE source_id=$1 AND slug LIKE 'notes/import-%'", [config.sourceIds[0]])).toEqual([{ count: 44 }]);
+ await assertConservation(pg.engine);
+ }, 120000);
+
+ test('a lost HTTP acknowledgement preserves accepted identity rather than inventing another write', async () => {
+ const client = clients[0];
+ const source = (await fixtures(pg.engine, config))[0];
+ const lock = await acquireWorktree(source.binding, 1000);
+ expect(lock).not.toBeNull();
+ const args = { slug: 'notes/lost-acknowledgement', source_id: source.id, content: content('Lost response fixture'), request_id: randomUUID() };
+ const abort = new AbortController();
+ const reply = client.callTool({ name: 'put_page', arguments: args }, undefined, { signal: abort.signal, timeout: 30000 });
+ const rejected = reply.then(() => false, () => true);
+ try {
+ await waitFor(async () => (await pg.engine.executeRaw('SELECT id FROM persistence_requests WHERE request_id=$1::uuid', [args.request_id])).length === 1);
+ abort.abort();
+ expect(await rejected).toBe(true);
+ expect((await receipt(client, args.request_id)).request_id).toBe(args.request_id);
+ expect(await pg.engine.readPageSnapshot(args.slug, { sourceId: source.id })).toBeNull();
+ } finally { abort.abort(); await lock!.release(); }
+ await committed(client, args.request_id);
+ const first = (await call(client, 'put_page', args)).body;
+ expect((await call(client, 'put_page', args)).body.revision).toBe(first.revision);
+ expect(await pg.engine.executeRaw('SELECT count(*)::int AS count FROM persistence_requests WHERE request_id=$1::uuid', [args.request_id])).toEqual([{ count: 1 }]);
+ await assertConservation(pg.engine);
+ }, 30000);
+
+ test('the same UUID under authenticated principals retains separate authorized results', async () => {
+ const request_id = randomUUID();
+ for (let index = 0; index < 2; index++) {
+ const args = { request_id, source_id: config.sourceIds[0], slug: `notes/principal-${index}`, content: content(`Principal fixture ${index}`) };
+ expect((await call(clients[index], 'put_page', args)).result.isError).not.toBe(true);
+ expect((await receipt(clients[index], request_id)).slug).toBe(args.slug);
+ }
+ });
+
+ test('private targets and changed source identity hide authenticated receipts immediately', async () => {
+ const own = { slug: 'notes/visibility-fence', content: content('Synthetic visibility fixture'), request_id: randomUUID() };
+ await call(clients[1], 'put_page', own);
+ const [page] = await pg.engine.executeRaw<{ id: number; frontmatter: unknown }>('SELECT id,frontmatter FROM pages WHERE source_id=$1 AND slug=$2', [config.sourceIds[0], own.slug]);
+ const [source] = await pg.engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1', [config.sourceIds[0]]);
+ const change = async (sql: string, params: unknown[]) => pg.engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true),set_config('gbrain.write_sources',$1,true),set_config('gbrain.persistence_protocol','2',true)", [JSON.stringify([config.sourceIds[0]])]);
+ await tx.executeRaw(sql, params);
+ });
+ const hidden = async () => {
+ expect(await receipt(clients[1], own.request_id)).toEqual(await receipt(clients[1], randomUUID()));
+ const listing = await call(clients[1], 'list_write_requests', { source_id: config.sourceIds[0], limit: 100 });
+ expect(JSON.stringify(listing.body)).not.toContain(own.request_id);
+ };
+ try {
+ await change("UPDATE pages SET frontmatter=jsonb_set(frontmatter,'{visibility}','\"private\"'::jsonb) WHERE id=$1", [page.id]);
+ await hidden();
+ await change('UPDATE pages SET frontmatter=$2::jsonb WHERE id=$1', [page.id, JSON.stringify(page.frontmatter)]);
+ await change('UPDATE sources SET archived=true WHERE id=$1', [config.sourceIds[0]]);
+ await hidden();
+ await change('UPDATE sources SET archived=false WHERE id=$1', [config.sourceIds[0]]);
+ await change('UPDATE persistence_requests SET source_incarnation=$2::uuid WHERE request_id=$1', [own.request_id, randomUUID()]);
+ await hidden();
+ } finally {
+ await change('UPDATE pages SET frontmatter=$2::jsonb WHERE id=$1', [page.id, JSON.stringify(page.frontmatter)]);
+ await change('UPDATE sources SET archived=false WHERE id=$1', [config.sourceIds[0]]);
+ await change('UPDATE persistence_requests SET source_incarnation=$2::uuid WHERE request_id=$1', [own.request_id, source.incarnation]);
+ }
+ expect((await receipt(clients[1], own.request_id)).state).toBe('committed');
+ });
+
+ test.skipIf(!oldBinary)('compatible old and new owners drain original UUIDs after quiesced handoffs', async () => {
+ restoreOwner = true;
+ const source = (await fixtures(pg.engine, config))[0];
+ for (const oldFirst of [true, false]) {
+ await stop();
+ await start(oldFirst ? oldBinary : undefined);
+ const producer = await connect(tokens[0]);
+ const lock = await acquireWorktree(source.binding, 1000);
+ expect(lock).not.toBeNull();
+ const args = { slug: `notes/compatible-${oldFirst}`, content: content(`Compatible owner ${oldFirst}`), request_id: randomUUID() };
+ try {
+ expect((await call(producer, 'put_page', args)).body.write_request.request_id).toBe(args.request_id);
+ expect(await pg.engine.readPageSnapshot(args.slug, { sourceId: source.id })).toBeNull();
+ await stop();
+ } finally { await lock!.release(); }
+ await start(oldFirst ? undefined : oldBinary);
+ const successor = await connect(tokens[0]);
+ const done = await committed(successor, args.request_id);
+ expect((await call(successor, 'put_page', args)).body.revision).toBe(done.revision);
+ const snapshot = await pg.engine.readPageSnapshot(args.slug, { sourceId: source.id });
+ expect(snapshot!.page.compiled_truth).toBe(`Compatible owner ${oldFirst}`);
+ expect(snapshot!.revision).toBe(done.revision);
+ expect(await pg.engine.executeRaw('SELECT count(*)::int AS count FROM persistence_requests WHERE request_id=$1', [args.request_id])).toEqual([{ count: 1 }]);
+ await assertConservation(pg.engine);
+ }
+ await stop(); await start(); await connect(tokens[0]); await connect(tokens[1]);
+ const lock = await acquireWorktree(source.binding, 1000);
+ expect(lock).not.toBeNull();
+ const request = { slug: 'notes/old-client-new-receipt', content: content('Retained client fixture'), request_id: randomUUID() };
+ try {
+ expect((await call(clients[1], 'put_page', request)).body.write_request.diagnostic).toBeDefined();
+ const clientHome = join(home, 'retained-client');
+ mkdirSync(join(clientHome, '.gbrain'), { recursive: true });
+ writeFileSync(join(clientHome, '.gbrain', 'config.json'), JSON.stringify({ engine: 'postgres', remote_mcp: {
+ issuer_url: base, mcp_url: `${base}/mcp`, oauth_client_id: oauthId,
+ } }), { mode: 0o600 });
+ await pg.engine.transaction(async tx => {
+ await waitFor(async () => (await tx.executeRaw(`SELECT id FROM persistence_requests
+ WHERE request_id=$1::uuid AND state='queued' FOR SHARE SKIP LOCKED`, [request.request_id])).length === 1,
+ { label: 'retained client queued receipt' });
+ const result = spawnSync(oldBinary!, ['write-request', request.request_id, '--json'], {
+ env: keylessBrainEnv(env, clientHome, { DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined,
+ GBRAIN_REMOTE_CLIENT_SECRET: oauthSecret }), encoding: 'utf8', timeout: 30000,
+ });
+ if (result.status !== 0) throw new Error(fixtureDiagnostic('retained HTTP client failed', result.stderr, [...tokens, oauthSecret]));
+ expect(JSON.parse(result.stdout)).toMatchObject({ request_id: request.request_id, state: 'queued' });
+ });
+ } finally { await lock!.release(); }
+ await committed(clients[1], request.request_id);
+ }, 120000);
+
+ for (const oldFirst of [true, false]) for (const boundary of ['running', 'recovery'] as const) {
+ test.skipIf(!oldBinary)(`${oldFirst ? 'old-to-new' : 'new-to-old'} owner handoff retains a real ${boundary} row`, async () => {
+ restoreOwner = true;
+ const source = (await fixtures(pg.engine, config))[0];
+ await stop(); await start(oldFirst ? oldBinary : undefined);
+ const producer = await connect(tokens[0]);
+ const slug = `notes/retained-${oldFirst}-${boundary}`;
+ const initial = await call(producer, 'put_page', { slug, content: content('Before owner handoff'), request_id: randomUUID() });
+ expect(initial.result.isError).not.toBe(true);
+ const before = (await pg.engine.readPageSnapshot(slug, { sourceId: source.id }))!;
+ const path = join(source.root, `${slug}.md`);
+ const originalBytes = readFileSync(path);
+ const versions = await pg.engine.executeRaw('SELECT id FROM page_versions WHERE page_id=$1', [before.page.id]);
+ const args = { slug, content: content(`After ${oldFirst} ${boundary} handoff`), expected_revision: before.revision, request_id: randomUUID() };
+ const native = await acquireWorktree(source.binding, 1000);
+ expect(native).not.toBeNull();
+ const held = Promise.withResolvers<void>(), release = Promise.withResolvers<void>();
+ let holding: Promise<unknown> | undefined;
+ let retained: WriteRequest;
+ const read = async () => (await pg.engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE request_id=$1::uuid', [args.request_id]))[0];
+ try {
+ expect((await call(producer, 'put_page', args)).body.write_request.request_id).toBe(args.request_id);
+ holding = pg.engine.transaction(async tx => {
+ if (boundary === 'running') await tx.executeRaw('LOCK TABLE pages IN ACCESS EXCLUSIVE MODE');
+ else await tx.lockPageKeys([{ sourceId: source.id, slug }]);
+ held.resolve(); await release.promise;
+ });
+ await Promise.race([held.promise, holding]);
+ await native!.release();
+ await waitFor(async () => {
+ const row = await read();
+ return row.state === 'running' && (boundary === 'running' ? row.recovery === null : row.recovery !== null);
+ }, { timeoutMs: 10000, label: `actual ${boundary} owner boundary` });
+ await stop('SIGKILL');
+ retained = await read();
+ expect(retained.state).toBe('running');
+ expect(retained.execution_token).not.toBeNull();
+ expect(retained.publication_started).toBe(false);
+ expect(Boolean(retained.recovery)).toBe(boundary === 'recovery');
+ expect(Number(retained.recovery_bytes) > 0).toBe(boundary === 'recovery');
+ expect(readFileSync(path)).toEqual(originalBytes);
+ } finally { release.resolve(); await holding; await native!.release(); }
+ const exclusion = await acquireWorktree(source.binding, 1000);
+ expect(exclusion).not.toBeNull();
+ await exclusion!.release();
+ expect((await pg.engine.readPageSnapshot(slug, { sourceId: source.id }))!.revision).toBe(before.revision);
+ const counters = await pg.engine.executeRaw('SELECT key,lifetime_ids,terminal_bytes FROM persistence_counters ORDER BY key');
+ await assertConservation(pg.engine);
+ if (boundary === 'running') await pg.engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('gbrain.persistence_protocol','2',true)");
+ await tx.executeRaw("UPDATE persistence_requests SET claim_expires_at=now()-interval '1 second' WHERE id=$1::uuid", [retained.id]);
+ });
+ await start(oldFirst ? undefined : oldBinary);
+ const successor = await connect(tokens[0]);
+ const done = await committed(successor, args.request_id);
+ await waitFor(async () => {
+ const row = await read();
+ return row.state === 'committed' && row.recovery === null && Number(row.recovery_bytes) === 0;
+ }, { timeoutMs: 5000, label: 'retained owner recovery cleanup' });
+ const final = await read();
+ expect(final).toMatchObject({ id: retained.id, request_id: args.request_id, digest: retained.digest,
+ source_id: source.id, source_incarnation: retained.source_incarnation, state: 'committed', recovery: null });
+ expect(Number(final.recovery_bytes)).toBe(0);
+ const snapshot = (await pg.engine.readPageSnapshot(slug, { sourceId: source.id }))!;
+ expect(snapshot.page.id).toBe(before.page.id);
+ expect(snapshot.page.compiled_truth).toBe(`After ${oldFirst} ${boundary} handoff`);
+ expect(snapshot.revision).toBe(done.revision);
+ expect(readFileSync(path, 'utf8')).toContain(snapshot.page.compiled_truth);
+ expect((await call(successor, 'put_page', args)).body.revision).toBe(done.revision);
+ expect(await pg.engine.executeRaw('SELECT id FROM persistence_requests WHERE request_id=$1::uuid', [args.request_id])).toEqual([{ id: retained.id }]);
+ expect(await pg.engine.executeRaw('SELECT id FROM page_versions WHERE page_id=$1', [before.page.id])).toHaveLength(versions.length + 1);
+ expect(await pg.engine.executeRaw('SELECT key,lifetime_ids,terminal_bytes FROM persistence_counters ORDER BY key')).toEqual(counters);
+ await assertConservation(pg.engine);
+ }, 90000);
+ }
+
+ test('foreign and narrowed OAuth receipts remain opaque without granting helper access', async () => {
+ const own = { slug: 'notes/oauth-private-id', content: content('Synthetic scoped fixture'), request_id: randomUUID() };
+ await call(clients[1], 'put_page', own);
+ const foreign = await receipt(clients[0], own.request_id);
+ const missing = await receipt(clients[0], randomUUID());
+ expect(foreign).toEqual(missing);
+ await pg.engine.executeRaw('UPDATE oauth_clients SET allowed_operations=$2::text[] WHERE client_id=$1', [oauthId, ['put_page', 'remember']]);
+ expect((await call(clients[1], 'get_write_request', { request_id: own.request_id })).result.isError).toBe(true);
+ expect((await call(clients[1], 'put_page', own)).body.state).toBe('committed');
+ await pg.engine.executeRaw('UPDATE oauth_clients SET bound_slug_prefixes=$2::text[] WHERE client_id=$1', [oauthId, ['different-prefix']]);
+ expect((await call(clients[1], 'put_page', own)).result.isError).toBe(true);
+ await pg.engine.executeRaw('UPDATE oauth_clients SET deleted_at=now() WHERE client_id=$1', [oauthId]);
+ await pg.engine.executeRaw("UPDATE access_tokens SET revoked_at=now() WHERE name='synthetic-http-writer'");
+ for (const token of tokens) {
+ const response = await fetch(`${base}/mcp`, { method: 'POST', headers: { Authorization: `Bearer ${token}`,
+ 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 100, method: 'tools/call', params: { name: 'get_write_request', arguments: { request_id: own.request_id } } }) });
+ expect(response.status).toBe(401);
+ expect(await response.text()).not.toContain(own.request_id);
+ }
+ });
+});
diff --git a/test/e2e/persistence-phase-liveness.test.ts b/test/e2e/persistence-phase-liveness.test.ts
new file mode 100644
index 0000000000..f808f1f145
--- /dev/null
+++ b/test/e2e/persistence-phase-liveness.test.ts
@@ -0,0 +1,419 @@
+import { describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { createServer, connect, type Socket } from 'node:net';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { waitFor } from '../helpers/wait-for.ts';
+import { admission, assertCommittedSnapshot, assertConservation, fixtures, initializeFixtures, prepared, selectFixtureHost, type HarnessConfig } from '../../scripts/persistence/harness.ts';
+import { admitWrite, claimNextWrite, getWriteRequestById, prepareRecovery, renewWriteClaim } from '../../src/core/persistence/journal.ts';
+import { PersistenceConsumer } from '../../src/core/persistence/consumer.ts';
+import { disposePersistenceConsumer, startPersistenceConsumer, waitForWrite } from '../../src/core/persistence/service.ts';
+import { sha256 } from '../../src/core/persistence/digest.ts';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import postgres from 'postgres';
+
+const url = process.env.DATABASE_URL;
+describe.skipIf(!url)('PostgreSQL persistence phase cancellation', () => {
+ async function fixture(run: (pg: Awaited<ReturnType<typeof isolatedPersistencePostgres>>, config: HarnessConfig) => Promise<void>) {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-phase-liveness-'));
+ const pg = await isolatedPersistencePostgres(url!);
+ const config: HarnessConfig = { kind: 'postgres', root, dataDir: join(root, 'unused'), hostId: randomUUID(),
+ seed: 5406, schedules: 0, operations: 0, sourceIds: ['phase-first', 'phase-other'], principalIds: [randomUUID()] };
+ try {
+ await withEnv({ GBRAIN_HOME: root, GBRAIN_PERSISTENCE_FIXTURE_HOME: root }, async () => {
+ selectFixtureHost(config.hostId);
+ await initializeFixtures(pg.engine, config);
+ await run(pg, config);
+ });
+ } finally { await pg.close(); rmSync(root, { recursive: true, force: true }); }
+ }
+
+ test('stopping before driver dispatch recognizes its prefixed cancellation error', () => fixture(async ({ engine }, config) => {
+ await engine.executeRaw('SELECT 1');
+ const errors: unknown[] = [];
+ let cancellation: unknown;
+ let stopping: Promise<void> | undefined;
+ let consumer: PersistenceConsumer;
+ const proxy = new Proxy(engine, { get(target, key) {
+ if (key === 'executeRaw') return (...args: Parameters<typeof engine.executeRaw>) => {
+ const work = target.executeRaw(...args);
+ if (args[2]?.signal) queueMicrotask(() => { stopping = consumer.stop(); });
+ return work.catch(error => { cancellation = error; throw error; });
+ };
+ const value = Reflect.get(target, key);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ consumer = new PersistenceConsumer(proxy, { engine: 'postgres' }, async () => { throw new Error('unexpected preparation'); },
+ { hostId: config.hostId, onError: error => errors.push(error) });
+ try {
+ await consumer.tick(); await stopping;
+ expect(cancellation).toMatchObject({ code: '57014', message: '57014: canceling statement due to user request' });
+ expect(errors).toEqual([]);
+ expect(consumer.status().last_error).toBeUndefined();
+ expect(await engine.executeRaw('SELECT 42 AS answer')).toEqual([{ answer: 42 }]);
+ } finally { await consumer.stop(); }
+ }), 30000);
+
+ test('a slow PostgreSQL receipt read cannot hide an independently committed request', () => fixture(async ({ engine }, config) => {
+ const sources = await fixtures(engine, config);
+ const first = await admitWrite(engine, admission(config, sources[0], 'slow-receipt', 'first body'));
+ const second = await admitWrite(engine, admission(config, sources[1], 'independent-receipt', 'second body'));
+ const publisher = new PersistenceConsumer(engine, { engine: 'postgres' }, async (_e, row) => prepared(row, sources),
+ { hostId: config.hostId });
+ try {
+ publisher.start();
+ await waitFor(async () => (await getWriteRequestById(engine, second.id))?.state === 'committed', { timeoutMs: 5000 });
+ } finally { await publisher.stop(); }
+ let entered = false;
+ const proxy = new Proxy(engine, { get(target, key) {
+ if (key === 'executeRaw') return async (...args: Parameters<typeof engine.executeRaw>) => {
+ if (args[0] === 'SELECT * FROM persistence_requests WHERE id=$1::uuid' && args[1]?.[0] === first.id) {
+ entered = true;
+ return target.executeRaw('SELECT r.* FROM persistence_requests r CROSS JOIN pg_sleep(20) WHERE r.id=$1::uuid', args[1], args[2]);
+ }
+ return target.executeRaw(...args);
+ };
+ const value = Reflect.get(target, key);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ const consumer = startPersistenceConsumer(proxy, { engine: 'postgres' });
+ (consumer as unknown as { doTick(): Promise<void> }).doTick = async () => {};
+ const stalled = waitForWrite(proxy, first, { engine: 'postgres' });
+ try {
+ await waitFor(() => entered);
+ const found = await waitForWrite(proxy, second, { engine: 'postgres' }, 1000);
+ expect(found.id).toBe(second.id);
+ expect(found.state).toBe('committed');
+ await assertCommittedSnapshot(engine, found);
+ } finally { await disposePersistenceConsumer(proxy); await stalled; }
+ await assertConservation(engine);
+ }), 30000);
+
+ test('an expired locked head does not stall independent roots or skip its own follower', () => fixture(async ({ engine }, config) => {
+ const sources = await fixtures(engine, config);
+ const head = await admitWrite(engine, admission(config, sources[0], 'locked-head', 'head'));
+ expect((await claimNextWrite(engine, config.hostId))?.id).toBe(head.id);
+ await engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('gbrain.persistence_protocol','2',true)");
+ await tx.executeRaw("UPDATE persistence_requests SET claim_expires_at=now()-interval '1 minute' WHERE id=$1::uuid", [head.id]);
+ });
+ const follower = await admitWrite(engine, admission(config, sources[0], 'follower', 'follower'));
+ const independent = await admitWrite(engine, admission(config, sources[1], 'independent', 'independent'));
+ const held = Promise.withResolvers<void>(), release = Promise.withResolvers<void>();
+ const holding = engine.transaction(async tx => {
+ await tx.executeRaw('SELECT id FROM persistence_requests WHERE id=$1::uuid FOR UPDATE', [head.id]);
+ held.resolve(); await release.promise;
+ });
+ await held.promise;
+ const consumer = new PersistenceConsumer(engine, { engine: 'postgres' }, async (_e, row) => prepared(row, sources),
+ { hostId: config.hostId, pollMs: 100, phaseMs: 200 });
+ try {
+ consumer.start();
+ await waitFor(async () => (await getWriteRequestById(engine, independent.id))?.state === 'committed', { timeoutMs: 4000 });
+ expect((await getWriteRequestById(engine, follower.id))?.state).toBe('queued');
+ expect((await getWriteRequestById(engine, head.id))?.state).toBe('running');
+ release.resolve(); await holding;
+ await waitFor(async () => (await getWriteRequestById(engine, follower.id))?.state === 'committed', { timeoutMs: 5000 });
+ for (const row of [head, follower, independent]) await assertCommittedSnapshot(engine, (await getWriteRequestById(engine, row.id))!);
+ await assertConservation(engine);
+ } finally { release.resolve(); await holding; await consumer.stop(); }
+ }), 30000);
+
+ for (const [phase, table] of [['refresh_roots', 'persistence_brain'], ['recovery_scan', 'persistence_worktrees']] as const) {
+ test(`${phase} stopping cancels its blocked query without reporting a storage failure`, () => fixture(async ({ engine, databaseUrl }, config) => {
+ const observer = postgres(databaseUrl, { max: 1, prepare: false });
+ const held = Promise.withResolvers<void>(), release = Promise.withResolvers<void>();
+ const holding = engine.transaction(async tx => {
+ await tx.executeRaw(`LOCK TABLE ${table} IN ACCESS EXCLUSIVE MODE`);
+ held.resolve(); await release.promise;
+ });
+ await held.promise;
+ const errors: unknown[] = [];
+ const consumer = new PersistenceConsumer(engine, { engine: 'postgres' }, async () => { throw new Error('unexpected preparation'); },
+ { hostId: config.hostId, phaseMs: 10000, pollMs: 60000, onError: error => errors.push(error) });
+ try {
+ consumer.start();
+ await waitFor(async () => (await observer.unsafe<{ waiting: boolean }[]>(
+ "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE datname=current_database() AND pid<>pg_backend_pid() AND wait_event_type='Lock' AND query LIKE $1) AS waiting", [`%${table}%`]))[0].waiting && consumer.status().phase?.name === phase,
+ { timeoutMs: 5000 });
+ const stopping = consumer.stop();
+ await waitFor(() => consumer.status().phase === null, { timeoutMs: 2000, label: 'cancelled phase settlement before releasing its blocker' });
+ expect(errors).toEqual([]);
+ expect(consumer.status().last_error).toBeUndefined();
+ expect(consumer.status().phase).toBeNull();
+ release.resolve(); await holding; await stopping;
+ expect(await engine.executeRaw('SELECT 42 AS answer')).toEqual([{ answer: 42 }]);
+ } finally { release.resolve(); await holding; await consumer.stop(); await observer.end(); }
+ }), 30000);
+
+ test(`${phase} cancels a real table-lock wait and retains fail-closed scheduling`, () => fixture(async ({ engine }, config) => {
+ const sources = await fixtures(engine, config);
+ const row = await admitWrite(engine, admission(config, sources[0], `waiting-${phase}`, 'phase fixture'));
+ const held = Promise.withResolvers<void>(), release = Promise.withResolvers<void>();
+ const holding = engine.transaction(async tx => {
+ await tx.executeRaw(`LOCK TABLE ${table} IN ACCESS EXCLUSIVE MODE`);
+ held.resolve(); await release.promise;
+ });
+ await held.promise;
+ const errors: unknown[] = [];
+ const consumer = new PersistenceConsumer(engine, { engine: 'postgres' }, async (_e, current) => prepared(current, sources),
+ { hostId: config.hostId, phaseMs: 150, pollMs: 100, onError: error => errors.push(error) });
+ try {
+ let settled = false;
+ const tick = consumer.tick().then(() => { settled = true; });
+ await waitFor(() => settled, { timeoutMs: 2000 });
+ await tick;
+ expect(errors).toHaveLength(1);
+ expect((await getWriteRequestById(engine, row.id))?.state).toBe('queued');
+ release.resolve(); await holding;
+ consumer.start();
+ await waitFor(async () => (await getWriteRequestById(engine, row.id))?.state === 'committed', { timeoutMs: 5000 });
+ await assertCommittedSnapshot(engine, (await getWriteRequestById(engine, row.id))!);
+ } finally { release.resolve(); await holding; await consumer.stop(); }
+ }), 30000);
+ }
+
+ test('a blocked recovery operation keeps reservations and retries after its SQL bound', () => fixture(async ({ engine }, config) => {
+ const sources = await fixtures(engine, config);
+ const accepted = await admitWrite(engine, admission(config, sources[0], 'recovery-bound', 'recovery fixture'));
+ const row = (await claimNextWrite(engine, config.hostId))!;
+ expect(row.id).toBe(accepted.id);
+ await prepareRecovery(engine, row, { version: 1, root: sources[0].root, path: join(sources[0].root, 'recovery-bound.md'),
+ before: null, beforeHash: null, afterHash: sha256('recovery fixture'), mode: null,
+ ownerEpoch: String(sources[0].binding.owner_epoch), attempt: row.execution_token! }, 1024);
+ const held = Promise.withResolvers<void>(), release = Promise.withResolvers<void>();
+ const holding = engine.transaction(async tx => {
+ await tx.executeRaw('SELECT id FROM persistence_requests WHERE id=$1::uuid FOR UPDATE', [row.id]);
+ held.resolve(); await release.promise;
+ });
+ await held.promise;
+ const errors: unknown[] = [];
+ const consumer = new PersistenceConsumer(engine, { engine: 'postgres' }, async (_e, current) => prepared(current, sources),
+ { hostId: config.hostId, concurrency: 0, onError: error => errors.push(error) });
+ try {
+ let settled = false;
+ const tick = consumer.tick().then(() => { settled = true; });
+ await waitFor(() => settled, { timeoutMs: 7000 }); await tick;
+ expect(errors.length).toBeGreaterThan(0);
+ expect(Number((await getWriteRequestById(engine, row.id))?.recovery_bytes)).toBe(1024);
+ release.resolve(); await holding;
+ await assertConservation(engine);
+ } finally { release.resolve(); await holding; await consumer.stop(); }
+ const retry = new PersistenceConsumer(engine, { engine: 'postgres' }, async (_e, current) => prepared(current, sources), { hostId: config.hostId });
+ try {
+ retry.start(); await waitFor(async () => (await getWriteRequestById(engine, row.id))?.state === 'committed', { timeoutMs: 5000 });
+ await assertConservation(engine);
+ } finally { await retry.stop(); }
+ }), 30000);
+
+ test('ordinary pool saturation cancels queued scheduler reads without accumulating work', () => fixture(async ({ engine }, config) => {
+ const release = Promise.withResolvers<void>();
+ let held = 0;
+ const holding = Array.from({ length: 4 }, () => engine.transaction(async tx => {
+ await tx.executeRaw('SELECT 1'); held++; await release.promise;
+ }));
+ await waitFor(() => held === 4);
+ const errors: unknown[] = [];
+ const consumer = new PersistenceConsumer(engine, { engine: 'postgres' }, async () => { throw new Error('No claim may pass unavailable capacity'); },
+ { hostId: config.hostId, phaseMs: 100, onError: error => errors.push(error) });
+ try {
+ for (let i = 0; i < 3; i++) {
+ await consumer.tick();
+ expect(engine.getPoolDiagnostics()?.tracked.raw).toBe(0);
+ expect(engine.getPoolDiagnostics()?.tracked.tx).toBe(4);
+ }
+ expect(errors).toHaveLength(3);
+ } finally { release.resolve(); await Promise.all(holding); await consumer.stop(); }
+ expect(engine.getPoolDiagnostics()?.tracked).toEqual({ raw: 0, direct: 0, reserved: 0, tx: 0 });
+ }), 30000);
+
+ test('capacity marking names and cancels its real row-lock wait before shutdown', () => fixture(async ({ engine, databaseUrl }, config) => {
+ const sources = await fixtures(engine, config);
+ const row = await admitWrite(engine, admission(config, sources[0], 'capacity-bound', 'capacity fixture'));
+ const held = Promise.withResolvers<void>(), release = Promise.withResolvers<void>();
+ const holding = engine.transaction(async tx => {
+ await tx.executeRaw('SELECT id FROM persistence_requests WHERE id=$1::uuid FOR UPDATE', [row.id]);
+ held.resolve(); await release.promise;
+ });
+ await held.promise;
+ const worker = new PostgresEngine();
+ await worker.connect({ database_url: databaseUrl, poolSize: 1 });
+ let entered = false;
+ let abortedPhase: ReturnType<PersistenceConsumer['status']>['phase'] = null;
+ let consumer: PersistenceConsumer;
+ const proxy = new Proxy(worker, { get(target, key) {
+ if (key === 'sql') return target.sql;
+ if (key === 'executeRaw') return async (...args: Parameters<typeof worker.executeRaw>) => {
+ if (args[0].startsWith("UPDATE persistence_requests SET blocked_reason='writer_pool_capacity'")) {
+ entered = true;
+ args[2]?.signal?.addEventListener('abort', () => { abortedPhase = consumer.status().phase; }, { once: true });
+ }
+ return target.executeRaw(...args);
+ };
+ const value = Reflect.get(target, key);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ const errors: unknown[] = [];
+ consumer = new PersistenceConsumer(proxy, { engine: 'postgres' }, async () => { throw new Error('Capacity cannot prepare'); },
+ { hostId: config.hostId, phaseMs: 150, onError: error => errors.push(error) });
+ try {
+ const tick = consumer.tick();
+ await waitFor(() => entered);
+ expect(consumer.status().phase?.name).toBe('capacity');
+ await waitFor(() => errors.length > 0);
+ await tick;
+ expect(abortedPhase).toMatchObject({ name: 'capacity', deadline_exceeded: true });
+ expect(consumer.status().last_error).toMatchObject({ phase: 'capacity', code: '57014' });
+ let stopped = false;
+ const stopping = consumer.stop().then(() => { stopped = true; });
+ await waitFor(() => stopped); await stopping;
+ expect(worker.getPoolDiagnostics()?.tracked).toEqual({ raw: 0, direct: 0, reserved: 0, tx: 0 });
+ expect((await getWriteRequestById(engine, row.id))?.blocked_reason).toBeNull();
+ } finally { release.resolve(); await holding; await consumer.stop(); await worker.disconnect(); }
+ expect((await getWriteRequestById(engine, row.id))?.blocked_reason).toBeNull();
+ await assertConservation(engine);
+ }), 30000);
+
+ test('a queued direct-pool BEGIN stays tracked and cannot prepare after shutdown', () => fixture(async ({ engine, databaseUrl }, config) => {
+ await withEnv({ GBRAIN_DIRECT_DATABASE_URL: databaseUrl, GBRAIN_DISABLE_DIRECT_POOL: '0', GBRAIN_DIRECT_POOL_SIZE: '1' }, async () => {
+ const worker = new PostgresEngine();
+ await worker.connect({ database_url: databaseUrl, poolSize: 4 });
+ const direct = await worker.connectionManager!.ddl();
+ expect(direct).not.toBe(worker.sql);
+ const sources = await fixtures(engine, config);
+ const row = await admitWrite(engine, admission(config, sources[0], 'queued-begin', 'direct pool fixture'));
+ const held = Promise.withResolvers<void>(), release = Promise.withResolvers<void>();
+ const holding = direct.begin(async tx => { await tx`SELECT 1`; held.resolve(); await release.promise; });
+ await held.promise;
+ let attempts = 0, stopped = false;
+ const consumer = new PersistenceConsumer(worker, { engine: 'postgres' }, async (_e, current) => {
+ attempts++; return prepared(current, sources);
+ }, { hostId: config.hostId, phaseMs: 100, pollMs: 60000 });
+ try {
+ const tick = consumer.tick();
+ await waitFor(() => consumer.status().phase?.name === 'claim' && consumer.status().phase?.deadline_exceeded === true);
+ expect(worker.getPoolDiagnostics()?.tracked.tx).toBeGreaterThanOrEqual(1);
+ const stopping = consumer.stop().then(() => { stopped = true; });
+ await Bun.sleep(50);
+ expect(stopped).toBe(false);
+ expect((await getWriteRequestById(engine, row.id))?.state).toBe('queued');
+ release.resolve(); await holding; await tick; await stopping;
+ expect(attempts).toBe(0);
+ expect((await getWriteRequestById(engine, row.id))?.state).toBe('queued');
+ expect(worker.getPoolDiagnostics()?.tracked.tx).toBe(0);
+ } finally { release.resolve(); await holding; await consumer.stop(); await worker.disconnect(); }
+ });
+ }), 30000);
+
+ for (const outcome of ['delayed', 'rejected'] as const) test(`a ${outcome} cold direct initialization remains observed until settlement`, () => fixture(async ({ engine, databaseUrl }, config) => {
+ const target = new URL(databaseUrl);
+ const sockets = new Set<Socket>();
+ const pending: Array<() => void> = [];
+ let released = false, connections = 0;
+ const gateway = createServer(socket => {
+ connections++;
+ sockets.add(socket);
+ socket.once('close', () => sockets.delete(socket));
+ socket.on('error', () => {});
+ const buffered: Buffer[] = [];
+ const buffer = (chunk: Buffer) => buffered.push(chunk);
+ socket.on('data', buffer);
+ const route = () => {
+ const upstream = connect({ host: target.hostname, port: Number(target.port) });
+ sockets.add(upstream);
+ upstream.once('close', () => sockets.delete(upstream));
+ upstream.on('error', () => socket.destroy());
+ socket.once('close', () => upstream.destroy());
+ upstream.once('connect', () => {
+ socket.off('data', buffer);
+ for (const chunk of buffered.splice(0)) upstream.write(chunk);
+ socket.pipe(upstream); upstream.pipe(socket);
+ });
+ };
+ if (released) route();
+ else pending.push(() => {
+ if (outcome === 'delayed') return route();
+ const body = Buffer.from('SFATAL\0C28000\0Msynthetic cold initialization rejection\0\0');
+ const length = Buffer.alloc(4);
+ length.writeUInt32BE(body.length + 4);
+ socket.end(Buffer.concat([Buffer.from('E'), length, body]));
+ });
+ });
+ await new Promise<void>(resolve => gateway.listen(0, '127.0.0.1', resolve));
+ const directUrl = new URL(databaseUrl);
+ directUrl.hostname = '127.0.0.1';
+ directUrl.port = String((gateway.address() as { port: number }).port);
+ const release = () => { released = true; for (const resume of pending.splice(0)) resume(); };
+ try {
+ await withEnv({ GBRAIN_DIRECT_DATABASE_URL: directUrl.toString(), GBRAIN_DISABLE_DIRECT_POOL: '0', GBRAIN_DIRECT_POOL_SIZE: '1' }, async () => {
+ const worker = new PostgresEngine();
+ await worker.connect({ database_url: databaseUrl, poolSize: 4 });
+ expect(connections).toBe(0);
+ const sources = await fixtures(engine, config);
+ const row = await admitWrite(engine, admission(config, sources[0], `cold-${outcome}`, 'cold route fixture'));
+ let attempts = 0, stopped = false, settled = false, querySettled = false;
+ const errors: Array<ReturnType<PersistenceConsumer['status']>['last_error']> = [];
+ const consumer = new PersistenceConsumer(worker, { engine: 'postgres' }, async (_e, current) => {
+ attempts++; return prepared(current, sources);
+ }, { hostId: config.hostId, phaseMs: 100, pollMs: 60000, onError: () => errors.push(consumer.status().last_error) });
+ try {
+ const tick = consumer.tick().then(() => { settled = true; });
+ await waitFor(() => connections === 1 && consumer.status().phase?.name === 'claim' && consumer.status().phase?.deadline_exceeded === true);
+ const abort = new AbortController();
+ const query = worker.executeRawDirect('SELECT pg_sleep(10)', undefined, { signal: abort.signal })
+ .then(() => { querySettled = true; return null; }, error => { querySettled = true; return error; });
+ abort.abort();
+ const joining = consumer.tick();
+ const stopping = consumer.stop().then(() => { stopped = true; });
+ await Bun.sleep(50);
+ expect(consumer.status().phase).toMatchObject({ name: 'claim', deadline_exceeded: true });
+ expect([settled, stopped, querySettled]).toEqual([false, false, false]);
+ expect(connections).toBe(1);
+ expect((await getWriteRequestById(engine, row.id))?.state).toBe('queued');
+ expect(attempts).toBe(0);
+ release();
+ await Promise.all([tick, joining, stopping]);
+ expect(await query).toMatchObject(outcome === 'delayed' ? { name: 'AbortError' } : { code: '28000' });
+ if (outcome === 'delayed') expect(errors).toHaveLength(0);
+ else expect(errors.some(error => error?.phase === 'claim' && error.code === '28000')).toBe(true);
+ expect(consumer.status().phase).toBeNull();
+ expect(attempts).toBe(0);
+ expect((await getWriteRequestById(engine, row.id))?.state).toBe('queued');
+ expect(worker.getPoolDiagnostics()?.tracked).toEqual({ raw: 0, direct: 0, reserved: 0, tx: 0 });
+ expect(await worker.connectionManager!.ddl()).not.toBe(worker.sql);
+ const retry = new PersistenceConsumer(worker, { engine: 'postgres' }, async (_e, current) => prepared(current, sources), { hostId: config.hostId });
+ try {
+ retry.start();
+ await waitFor(async () => (await getWriteRequestById(engine, row.id))?.state === 'committed', { timeoutMs: 5000 });
+ await assertCommittedSnapshot(engine, (await getWriteRequestById(engine, row.id))!);
+ await assertConservation(engine);
+ } finally { await retry.stop(); }
+ } finally { release(); await consumer.stop(); await worker.disconnect(); }
+ });
+ } finally {
+ release();
+ for (const socket of sockets) socket.destroy();
+ await new Promise<void>(resolve => gateway.close(() => resolve()));
+ }
+ }), 30000);
+
+ test('claim renewal cancels its actual SQL wait without a late lease extension', () => fixture(async ({ engine }, config) => {
+ const sources = await fixtures(engine, config);
+ await admitWrite(engine, admission(config, sources[0], 'renewal-bound', 'renewal fixture'));
+ const row = (await claimNextWrite(engine, config.hostId))!;
+ const held = Promise.withResolvers<void>(), release = Promise.withResolvers<void>();
+ const holding = engine.transaction(async tx => {
+ await tx.executeRaw('SELECT id FROM persistence_requests WHERE id=$1::uuid FOR UPDATE', [row.id]);
+ held.resolve(); await release.promise;
+ });
+ await held.promise;
+ try {
+ await expect(renewWriteClaim({ executeRaw: engine.executeRawDirect.bind(engine) }, row.id, row.execution_token!, 30000,
+ AbortSignal.timeout(100))).rejects.toMatchObject({ code: '57014' });
+ } finally { release.resolve(); await holding; }
+ expect((await getWriteRequestById(engine, row.id))?.claim_expires_at).toEqual(row.claim_expires_at);
+ }), 30000);
+});
diff --git a/test/helpers/managed-atom-regressions.ts b/test/helpers/managed-atom-regressions.ts
index 6bbbe8f350..820b461ce3 100644
--- a/test/helpers/managed-atom-regressions.ts
+++ b/test/helpers/managed-atom-regressions.ts
@@ -102,7 +102,7 @@ export async function exerciseAtomRetryFence(engine: BrainEngine, state: typeof
};
if (key === 'readPageSnapshot') return async (...args: Parameters<BrainEngine['readPageSnapshot']>) => {
const snapshot = await current.readPageSnapshot(...args);
- if (retrying && !inTransaction && args[0] === slugs[0] && args[1]?.includeDeleted) {
+ if (retrying && !inTransaction && args[0] === slugs[0] && args[1]?.sourceId === sourceId && args[1]?.includeDeleted) {
targetReads++;
if (!injected && (edit === 'after_validation' && targetReads === 1 || edit === 'before_admission' && targetReads === 2)) await independentlyEdit();
}
@@ -110,7 +110,7 @@ export async function exerciseAtomRetryFence(engine: BrainEngine, state: typeof
};
if (key === 'transaction') return async <T>(fn: (tx: BrainEngine) => Promise<T>): Promise<T> => {
const result = await current.transaction(tx => fn(observe(tx, true)));
- if (retrying && !injected && edit === 'after_admission' && Array.isArray(result) && result.some(row => row.intent?.kind === 'managed_atom_page')) await independentlyEdit();
+ if (retrying && !injected && edit === 'after_admission' && Array.isArray(result) && result.some(row => row.source_id === sourceId && row.intent?.kind === 'managed_atom_page')) await independentlyEdit();
return result;
};
const value = Reflect.get(current, key);
diff --git a/test/helpers/persistence-postgres.ts b/test/helpers/persistence-postgres.ts
index 5386a6d44e..9b366aa121 100644
--- a/test/helpers/persistence-postgres.ts
+++ b/test/helpers/persistence-postgres.ts
@@ -4,7 +4,7 @@ import { PostgresEngine } from '../../src/core/postgres-engine.ts';
import { assertSafeE2eDatabaseUrl } from './db-guard.ts';
/** Permanent receipt IDs deliberately survive source deletion; use a fresh test brain. */
-export async function isolatedPersistencePostgres(databaseUrl:string, connectionStyle:'instance'|'module'='instance'):Promise<{engine:PostgresEngine;close:()=>Promise<void>}> {
+export async function isolatedPersistencePostgres(databaseUrl:string, connectionStyle:'instance'|'module'='instance'):Promise<{engine:PostgresEngine;databaseUrl:string;close:()=>Promise<void>}> {
assertSafeE2eDatabaseUrl(databaseUrl);
const database=`gbrain_test_persistence_${randomUUID().replace(/-/g,'')}`;
const admin=postgres(databaseUrl,{max:1,prepare:false});
@@ -12,6 +12,6 @@ export async function isolatedPersistencePostgres(databaseUrl:string, connection
const url=new URL(databaseUrl);url.pathname=`/${database}`;
const engine=new PostgresEngine();
const close=async()=>{await engine.disconnect();await admin.unsafe(`DROP DATABASE ${database} WITH (FORCE)`);await admin.end();};
- try {await engine.connect({database_url:url.toString(),poolSize:connectionStyle==='module'?undefined:4});await engine.initSchema();return{engine,close};}
+ try {await engine.connect({database_url:url.toString(),poolSize:connectionStyle==='module'?undefined:4});await engine.initSchema();return{engine,databaseUrl:url.toString(),close};}
catch(error){await close();throw error;}
}
diff --git a/test/mcp-client-hardening.test.ts b/test/mcp-client-hardening.test.ts
index 63a531c04a..3334c64fd6 100644
--- a/test/mcp-client-hardening.test.ts
+++ b/test/mcp-client-hardening.test.ts
@@ -191,6 +191,19 @@ describe('extractToolErrorDetail', () => {
expect(parsed.write_request).toEqual(PENDING_WRITE);
});
+ test('preserves the optional health contract while stripping private nested metadata', () => {
+ const diagnostic = { age_ms: 120000, observed_at: '2026-09-23T00:00:00.000Z',
+ assessment: 'stalled', reason: 'cause_unknown', next_action: 'inspect_owner' } as const;
+ const parsed = extractToolErrorDetail(JSON.stringify({ error: 'unavailable', write_request: {
+ ...PENDING_WRITE, diagnostic: { ...diagnostic, predecessor_id: 'PRIVATE_PREDECESSOR', raw_error: 'PRIVATE_ERROR' },
+ } }));
+ expect(parsed.write_request).toEqual({ ...PENDING_WRITE, diagnostic });
+ expect(JSON.stringify(parsed)).not.toContain('PRIVATE_');
+ expect(extractToolErrorDetail(JSON.stringify({ error: 'unavailable', write_request: {
+ ...PENDING_WRITE, diagnostic: { ...diagnostic, age_ms: -1 },
+ } }))).toEqual({ code: 'unavailable' });
+ });
+
test('retains backward compatibility with plain text tool errors', () => {
expect(extractToolErrorDetail('missing scope write')).toEqual({ code: 'missing_scope' });
expect(extractToolErrorDetail('failed')).toEqual({});
diff --git a/test/mcp-expose.test.ts b/test/mcp-expose.test.ts
index b3103a5e9e..fac6cb1e15 100644
--- a/test/mcp-expose.test.ts
+++ b/test/mcp-expose.test.ts
@@ -4,6 +4,7 @@
* path lives in a tmpdir. No network, no real supervisor, no process.env writes.
*/
import { afterEach, describe, expect, spyOn, test } from 'bun:test';
+import * as dnsPromises from 'node:dns/promises';
import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync, mkdirSync } from 'node:fs';
import { createServer } from 'node:net';
import { tmpdir } from 'node:os';
@@ -2587,6 +2588,48 @@ describe('scoped off + honest recovery (adversarial-review batch)', () => {
expect(isUnresolvedLookupError(new Error('Unable to connect. Is the computer able to access the url?'))).toBe(false);
});
+ test('the default resolver rejects reserved invalid names without consulting system DNS', async () => {
+ const lookup = spyOn(dnsPromises, 'lookup').mockResolvedValue({ address: '127.0.0.1', family: 4 });
+ try {
+ for (const host of ['invalid', 'INVALID', 'invalid.', 'INVALID.', 'gbrain.invalid', 'gbrain.INVALID.', 'nested.gbrain.invalid.']) {
+ await expect(defaultLookup(host)).rejects.toMatchObject({ code: 'ENOTFOUND' });
+ }
+ expect(lookup).not.toHaveBeenCalled();
+ } finally {
+ lookup.mockRestore();
+ }
+ });
+
+ test('the default resolver preserves invalid label boundaries and delegates other names', async () => {
+ const lookup = spyOn(dnsPromises, 'lookup').mockResolvedValue({ address: '127.0.0.1', family: 4 });
+ const hosts = ['notinvalid', 'notinvalid.', 'gbrain.notinvalid', 'invalid.example', 'gbrain.invalid.example', 'invalid.example.'];
+ try {
+ for (const host of hosts) await expect(defaultLookup(host)).resolves.toBeUndefined();
+ expect(lookup.mock.calls.map(([host]) => host)).toEqual(hosts);
+ } finally {
+ lookup.mockRestore();
+ }
+ });
+
+ test('the default resolver still resolves localhost through the system resolver', async () => {
+ await expect(defaultLookup('localhost')).resolves.toBeUndefined();
+ });
+
+ test('an unanswered lookup and unclassified resolver errors remain unknown', async () => {
+ const deps = {
+ fetch: async () => { throw Object.assign(new Error('Unable to connect. Is the computer able to access the url?'), { code: 'ConnectionRefused' }); },
+ tcpProbe: async () => false,
+ lookup: async () => new Promise<void>(() => {}),
+ now: () => new Date(), sleep: async () => {}, healthIntervalMs: 1,
+ };
+ const url = 'https://diagnostic.example/health';
+ expect(await tryFetch(deps, url, 25)).toEqual({ res: null, unresolved: false });
+ for (const code of ['ETIMEDOUT', 'ESERVFAIL', 'ECANCELLED']) {
+ expect(await tryFetch({ ...deps, lookup: async () => { throw Object.assign(new Error(code), { code }); } }, url, 25))
+ .toEqual({ res: null, unresolved: false });
+ }
+ });
+
test('the real default resolver: a .invalid name never resolves (RFC 6761; a resolver outage classifies as unresolved too), so Bun\'s refused-looking rejection is reported as unresolved', async () => {
const url = 'https://gbrain-unresolvable-test.invalid/health';
const outcome = await tryFetch({
diff --git a/test/persistence-consumer-scheduling.test.ts b/test/persistence-consumer-scheduling.test.ts
index a2cd87c94d..e85d71526f 100644
--- a/test/persistence-consumer-scheduling.test.ts
+++ b/test/persistence-consumer-scheduling.test.ts
@@ -11,6 +11,7 @@ import { acquireWorktree } from '../src/core/persistence/ownership.ts';
import { admission, assertCommittedSnapshot, assertConservation, fixtures, initializeFixtures, prepared, selectFixtureHost, type HarnessConfig } from '../scripts/persistence/harness.ts';
import { withEnv } from './helpers/with-env.ts';
import { waitFor } from './helpers/wait-for.ts';
+import { disposePersistenceConsumer, startPersistenceConsumer, waitForWrite } from '../src/core/persistence/service.ts';
const home = mkdtempSync(join(tmpdir(), 'gbrain-consumer-scheduling-'));
const config: HarnessConfig = {
@@ -34,6 +35,263 @@ afterAll(async () => {
rmSync(home, { recursive: true, force: true });
});
+test('simultaneous bounded waiters retain one unresolved receipt read until settlement', async () => withEnv(env, async () => {
+ const release = Promise.withResolvers<never[]>();
+ let reads = 0;
+ const proxy = new Proxy(engine, { get(target, key) {
+ if (key === 'executeRaw') return async (sql: string, params?: unknown[]) => {
+ if (sql === 'SELECT * FROM persistence_requests WHERE id=$1::uuid') { reads++; return release.promise; }
+ return target.executeRaw(sql, params);
+ };
+ const value = Reflect.get(target, key);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ const consumer = startPersistenceConsumer(proxy, { engine: 'pglite' });
+ (consumer as unknown as { doTick(): Promise<void> }).doTick = async () => {};
+ const row = { id: randomUUID(), request_id: randomUUID(), state: 'queued' } as import('../src/core/persistence/model.ts').WriteRequest;
+ try {
+ const results = await Promise.all(Array.from({ length: 12 }, () => waitForWrite(proxy, row, { engine: 'pglite' }, 100)));
+ expect(results.every(value => value === row)).toBe(true);
+ expect(reads).toBe(1);
+ await waitForWrite(proxy, row, { engine: 'pglite' }, 100);
+ expect(reads).toBe(1);
+ } finally {
+ release.resolve([]);
+ await disposePersistenceConsumer(proxy);
+ }
+}), 5000);
+
+test('shutdown drains an uncancellable receipt read without scheduling another', async () => withEnv(env, async () => {
+ const release = Promise.withResolvers<never[]>();
+ let reads = 0, stopped = false;
+ const proxy = new Proxy(engine, { get(target, key) {
+ if (key === 'executeRaw') return async (sql: string, params?: unknown[]) => {
+ if (sql === 'SELECT * FROM persistence_requests WHERE id=$1::uuid') { reads++; return release.promise; }
+ return target.executeRaw(sql, params);
+ };
+ const value = Reflect.get(target, key);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ const consumer = startPersistenceConsumer(proxy, { engine: 'pglite' });
+ (consumer as unknown as { doTick(): Promise<void> }).doTick = async () => {};
+ const row = { id: randomUUID(), request_id: randomUUID(), state: 'queued' } as import('../src/core/persistence/model.ts').WriteRequest;
+ const waiter = waitForWrite(proxy, row, { engine: 'pglite' }, 500);
+ try {
+ await waitFor(() => reads === 1);
+ const stopping = disposePersistenceConsumer(proxy).then(() => { stopped = true; });
+ await Bun.sleep(30);
+ expect(stopped).toBe(false);
+ release.resolve([]);
+ await stopping;
+ await waiter;
+ expect(reads).toBe(1);
+ } finally { release.resolve([]); await waiter; await disposePersistenceConsumer(proxy); }
+}), 5000);
+
+test.each(['queued', 'committed'] as const)('coalesced receipt reads preserve each result while the first waiter is %s', firstState => withEnv(env, async () => {
+ const rows = Array.from({ length: 2 }, () => ({ id: randomUUID(), request_id: randomUUID(), state: 'queued' } as import('../src/core/persistence/model.ts').WriteRequest));
+ const proxy = new Proxy(engine, { get(target, key) {
+ if (key === 'executeRaw') return async (sql: string, params?: unknown[]) => {
+ if (sql === 'SELECT * FROM persistence_requests WHERE id=$1::uuid') {
+ await Bun.sleep(20);
+ return [{ ...rows.find(row => row.id === params?.[0]), state: params?.[0] === rows[0].id ? firstState : 'committed' }];
+ }
+ return target.executeRaw(sql, params);
+ };
+ const value = Reflect.get(target, key);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ const consumer = startPersistenceConsumer(proxy, { engine: 'pglite' });
+ (consumer as unknown as { doTick(): Promise<void> }).doTick = async () => {};
+ try {
+ const results = await Promise.all(rows.map(row => waitForWrite(proxy, row, { engine: 'pglite' }, 1000)));
+ expect(results.map(row => row.id)).toEqual(rows.map(row => row.id));
+ expect(results.map(row => row.state)).toEqual([firstState, 'committed']);
+ } finally { await disposePersistenceConsumer(proxy); }
+}), 5000);
+
+test('a stalled receipt read does not hide another request that already committed', async () => withEnv(env, async () => {
+ const release = Promise.withResolvers<never[]>();
+ const rows = Array.from({ length: 2 }, () => ({ id: randomUUID(), request_id: randomUUID(), state: 'queued' } as import('../src/core/persistence/model.ts').WriteRequest));
+ let entered = false;
+ const proxy = new Proxy(engine, { get(target, key) {
+ if (key === 'executeRaw') return async (sql: string, params?: unknown[]) => {
+ if (sql === 'SELECT * FROM persistence_requests WHERE id=$1::uuid') {
+ if (params?.[0] === rows[0].id) { entered = true; return release.promise; }
+ return [{ ...rows[1], state: 'committed' }];
+ }
+ return target.executeRaw(sql, params);
+ };
+ const value = Reflect.get(target, key);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ const consumer = startPersistenceConsumer(proxy, { engine: 'pglite' });
+ (consumer as unknown as { doTick(): Promise<void> }).doTick = async () => {};
+ const stalled = waitForWrite(proxy, rows[0], { engine: 'pglite' }, 1000);
+ try {
+ await waitFor(() => entered);
+ const found = await waitForWrite(proxy, rows[1], { engine: 'pglite' }, 250);
+ expect(found.id).toBe(rows[1].id);
+ expect(found.state).toBe('committed');
+ } finally { release.resolve([]); await disposePersistenceConsumer(proxy); await stalled; }
+}), 5000);
+
+test.each([false, true])('a shorter receipt waiter cannot abort another caller\'s read (same ID=%s)', sameId => withEnv(env, async () => {
+ const release = Promise.withResolvers<never[]>();
+ const row = { id: randomUUID(), request_id: randomUUID(), state: 'queued' } as import('../src/core/persistence/model.ts').WriteRequest;
+ const other = sameId ? row : { ...row, id: randomUUID(), request_id: randomUUID() };
+ let ownerSignal: AbortSignal | undefined;
+ const proxy = new Proxy(engine, { get(target, key) {
+ if (key === 'kind') return 'postgres';
+ if (key === 'executeRaw') return async (...args: Parameters<typeof engine.executeRaw>) => {
+ if (args[0] === 'SELECT * FROM persistence_requests WHERE id=$1::uuid') {
+ if (args[1]?.[0] === row.id) ownerSignal = args[2]?.signal;
+ return release.promise;
+ }
+ return target.executeRaw(...args);
+ };
+ const value = Reflect.get(target, key);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ const consumer = startPersistenceConsumer(proxy, { engine: 'postgres' });
+ (consumer as unknown as { doTick(): Promise<void> }).doTick = async () => {};
+ const owner = waitForWrite(proxy, row, { engine: 'postgres' }, 1000);
+ try {
+ await waitFor(() => ownerSignal !== undefined);
+ expect(await waitForWrite(proxy, other, { engine: 'postgres' }, 100)).toBe(other);
+ expect(ownerSignal!.aborted).toBe(false);
+ } finally { release.resolve([]); await disposePersistenceConsumer(proxy); await owner; }
+}), 5000);
+
+test('distinct stalled receipt reads stay capped and shutdown drains every retained read', async () => withEnv(env, async () => {
+ const releases = Array.from({ length: 4 }, () => Promise.withResolvers<never[]>());
+ let reads = 0, stopped = false;
+ const proxy = new Proxy(engine, { get(target, key) {
+ if (key === 'executeRaw') return async (sql: string, params?: unknown[]) => {
+ if (sql === 'SELECT * FROM persistence_requests WHERE id=$1::uuid') {
+ const release = releases[reads++];
+ expect(release).toBeDefined();
+ return release.promise;
+ }
+ return target.executeRaw(sql, params);
+ };
+ const value = Reflect.get(target, key);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ const consumer = startPersistenceConsumer(proxy, { engine: 'pglite' });
+ (consumer as unknown as { doTick(): Promise<void> }).doTick = async () => {};
+ const rows = Array.from({ length: 20 }, () => ({ id: randomUUID(), request_id: randomUUID(), state: 'queued' } as import('../src/core/persistence/model.ts').WriteRequest));
+ try {
+ expect(await Promise.all(rows.map(row => waitForWrite(proxy, row, { engine: 'pglite' }, 100)))).toEqual(rows);
+ expect(reads).toBe(4);
+ await waitForWrite(proxy, rows.at(-1)!, { engine: 'pglite' }, 100);
+ expect(reads).toBe(4);
+ const stopping = disposePersistenceConsumer(proxy).then(() => { stopped = true; });
+ for (const release of releases.slice(0, -1)) release.resolve([]);
+ await Bun.sleep(30);
+ expect(stopped).toBe(false);
+ releases.at(-1)!.resolve([]);
+ await stopping;
+ expect(stopped).toBe(true);
+ expect(reads).toBe(4);
+ } finally { for (const release of releases) release.resolve([]); await disposePersistenceConsumer(proxy); }
+}), 5000);
+
+for (const cooperates of [true, false]) test(`preparation deadline retains tracking and fences late results (cooperative=${cooperates})`, async () => withEnv(env, async () => {
+ const sources = await fixtures(engine, config);
+ const row = await admitWrite(engine, admission(config, sources[0], `deadline-${cooperates}`, 'deadline body'));
+ const release = Promise.withResolvers<void>();
+ let attempts = 0;
+ let aborted = false;
+ const consumer = new PersistenceConsumer(engine, { engine: 'pglite' }, async (_e, current, _c, signal?: AbortSignal) => {
+ attempts++;
+ signal?.addEventListener('abort', () => { aborted = true; if (cooperates) release.resolve(); }, { once: true });
+ await release.promise;
+ if (cooperates) signal?.throwIfAborted();
+ return prepared(current, sources);
+ }, { hostId: config.hostId, pollMs: 60_000, preparationMs: 50 });
+ try {
+ consumer.start();
+ await waitFor(() => attempts === 1);
+ await Bun.sleep(150);
+ expect(aborted).toBe(true);
+ expect(attempts).toBe(1);
+ if (!cooperates) {
+ expect(consumer.status().active_preparations).toBe(1);
+ expect((await getWriteRequestById(engine, row.id))?.state).toBe('running');
+ }
+ release.resolve();
+ await waitFor(() => consumer.status().active_preparations === 0);
+ expect((await getWriteRequestById(engine, row.id))?.state).toBe('queued');
+ expect(await engine.readPageSnapshot(row.slug, { sourceId: row.source_id })).toBeNull();
+ await assertConservation(engine);
+ } finally {
+ release.resolve();
+ await consumer.stop();
+ await cancelWriteRequest(engine, { kind: 'local_cli', id: config.principalIds[0] }, row.request_id);
+ }
+}), 5000);
+
+test('publication entering before the preparation deadline keeps its protected terminal outcome', async () => withEnv(env, async () => {
+ const sources = await fixtures(engine, config);
+ const row = await admitWrite(engine, admission(config, sources[0], 'publication-wins', 'protected body'));
+ let entered = false;
+ const release = Promise.withResolvers<void>();
+ const consumer = new PersistenceConsumer(engine, { engine: 'pglite' }, async (_e, current) => {
+ const mutation = prepared(current, sources);
+ return { ...mutation, apply: async tx => { entered = true; await release.promise; return mutation.apply(tx); } };
+ }, { hostId: config.hostId, pollMs: 60_000, preparationMs: 50 });
+ try {
+ consumer.start();
+ await waitFor(() => entered);
+ await Bun.sleep(100);
+ release.resolve();
+ await waitFor(async () => (await getWriteRequestById(engine, row.id))?.state === 'committed');
+ await assertCommittedSnapshot(engine, (await getWriteRequestById(engine, row.id))!);
+ await assertConservation(engine);
+ } finally { release.resolve(); await consumer.stop(); }
+}), 5000);
+
+test.each([false, true])('a synchronous late preparation cannot outrun its delayed abort timer (reject=%s)', reject => withEnv(env, async () => {
+ const sources = await fixtures(engine, config);
+ const row = await admitWrite(engine, admission(config, sources[0], `synchronous-deadline-${reject}`, 'unpublished body'));
+ const consumer = new PersistenceConsumer(engine, { engine: 'pglite' }, async (_e, current) => {
+ const until = performance.now() + 60;
+ while (performance.now() < until) {}
+ if (reject) throw new DOMException('Synthetic late abort', 'AbortError');
+ return prepared(current, sources);
+ }, { hostId: config.hostId, pollMs: 60000, preparationMs: 20 });
+ try {
+ await consumer.tick();
+ await waitFor(() => consumer.status().active_preparations === 0);
+ expect((await getWriteRequestById(engine, row.id))?.state).toBe('queued');
+ expect(await engine.readPageSnapshot(row.slug, { sourceId: row.source_id })).toBeNull();
+ } finally { await consumer.stop(); await cancelWriteRequest(engine, { kind: 'local_cli', id: config.principalIds[0] }, row.request_id); }
+}), 5000);
+
+test('shutdown does not finish while an abort-ignoring preparer remains active', async () => withEnv(env, async () => {
+ const sources = await fixtures(engine, config);
+ const row = await admitWrite(engine, admission(config, sources[0], 'stop-ignoring-abort', 'unpublished body'));
+ const release = Promise.withResolvers<void>();
+ let aborted = false, entered = false, stopped = false;
+ const consumer = new PersistenceConsumer(engine, { engine: 'pglite' }, async (_e, current, _cfg, signal) => {
+ entered = true;
+ signal?.addEventListener('abort', () => { aborted = true; }, { once: true });
+ await release.promise;
+ return prepared(current, sources);
+ }, { hostId: config.hostId, pollMs: 60_000 });
+ try {
+ consumer.start(); await waitFor(() => entered);
+ const stop = consumer.stop().then(() => { stopped = true; });
+ await Bun.sleep(50);
+ expect(aborted).toBe(true); expect(stopped).toBe(false);
+ expect(consumer.status().active_preparations).toBe(1);
+ release.resolve(); await stop;
+ expect((await getWriteRequestById(engine, row.id))?.state).toBe('queued');
+ expect(await engine.readPageSnapshot(row.slug, { sourceId: row.source_id })).toBeNull();
+ } finally { release.resolve(); await consumer.stop(); await cancelWriteRequest(engine, { kind: 'local_cli', id: config.principalIds[0] }, row.request_id); }
+}), 5000);
+
test('an immediate wake-up during an active tick is retained until that tick finishes', async () => {
const release = Promise.withResolvers<void>();
const consumer = new PersistenceConsumer(engine, { engine: 'pglite' }, async () => { throw new Error('No writes in scheduler probe'); },
@@ -55,6 +313,48 @@ test('an immediate wake-up during an active tick is retained until that tick fin
}
});
+test('process-local diagnostic errors never retain arbitrary driver codes or messages', async () => {
+ const consumer = new PersistenceConsumer(engine, { engine: 'pglite' }, async () => { throw new Error('No preparation'); },
+ { hostId: config.hostId, onError: () => {} });
+ (consumer as unknown as { doTick(): Promise<void> }).doTick = async () => {
+ throw Object.assign(new Error('PRIVATE_DRIVER_MESSAGE'), { code: 'PRIVATE_DRIVER_CODE' });
+ };
+ try {
+ await consumer.tick();
+ expect(consumer.status().last_error?.code).toBe('storage_error');
+ expect(JSON.stringify(consumer.status())).not.toContain('PRIVATE_');
+ } finally { await consumer.stop(); }
+});
+
+test('an uncancellable PGLite scheduler phase stays observed and awaited through stop', async () => withEnv(env, async () => {
+ const release = Promise.withResolvers<never[]>();
+ let entered = false, stopped = false;
+ const proxy = new Proxy(engine, { get(target, key) {
+ if (key === 'executeRaw') return async (...args: Parameters<typeof engine.executeRaw>) => {
+ if (args[0] === 'SELECT brain_id,enabled FROM persistence_brain WHERE singleton=1') {
+ expect(args[2]?.signal).toBeUndefined();
+ entered = true; return release.promise;
+ }
+ return target.executeRaw(...args);
+ };
+ const value = Reflect.get(target, key);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ const consumer = new PersistenceConsumer(proxy, { engine: 'pglite' }, async () => { throw new Error('No late preparation'); },
+ { hostId: config.hostId, phaseMs: 20 });
+ try {
+ const tick = consumer.tick();
+ await waitFor(() => entered && consumer.status().phase?.deadline_exceeded === true);
+ expect(consumer.status().phase?.name).toBe('refresh_roots');
+ const stopping = consumer.stop().then(() => { stopped = true; });
+ await Bun.sleep(40);
+ expect(stopped).toBe(false);
+ expect(consumer.status().phase?.deadline_exceeded).toBe(true);
+ release.resolve([]); await tick; await stopping;
+ expect(consumer.status().phase).toBeNull();
+ } finally { release.resolve([]); await consumer.stop(); }
+}), 5000);
+
for (const outcome of ['committed', 'failed'] as const) test(`a ${outcome} write preempts idle polling and drains the next FIFO request`, async () => withEnv(env, async () => {
const sources = await fixtures(engine, config);
const first = await admitWrite(engine, admission(config, sources[0], `first-${outcome}`, 'first body'));
diff --git a/test/persistence-diagnostics.test.ts b/test/persistence-diagnostics.test.ts
index fb2dd605b8..240864fc1a 100644
--- a/test/persistence-diagnostics.test.ts
+++ b/test/persistence-diagnostics.test.ts
@@ -2,13 +2,17 @@ import { afterAll, beforeAll, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../src/core/engine.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runMigrations } from '../src/core/migrate.ts';
import type { OperationContext } from '../src/core/ops/contract.ts';
import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
import { submissionAuthority } from '../src/core/persistence/authority.ts';
-import { admitWrite } from '../src/core/persistence/journal.ts';
+import { admitWrite, writeHealthFacts } from '../src/core/persistence/journal.ts';
+import type { WriteRequest } from '../src/core/persistence/model.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { writerDiagnostics } from '../src/core/persistence/control.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { waitFor } from './helpers/wait-for.ts';
+import { readWriterDiagnostics, WRITER_NEXT_ACTIONS } from '../src/core/persistence/diagnostics.ts';
const engines: BrainEngine[] = [];
let closePostgres: (() => Promise<void>) | undefined;
@@ -24,6 +28,82 @@ afterAll(async () => {
await closePostgres?.();
});
+test('optional health enrichment bounds unresolved work and never invents fresh observations', async () => {
+ const release = Promise.withResolvers<Record<string, unknown>[]>();
+ let queries = 0;
+ const engine = { kind: 'pglite', executeRaw: async () => { queries++; return release.promise; } } as unknown as BrainEngine;
+ const rows = Array.from({ length: 100 }, (_, index) => ({ id: randomUUID(), state: 'queued',
+ worktree_id: null, source_incarnation: 'd7599b95-65c2-4d54-aa4e-cb5745af90cf', sequence: index + 1 } as WriteRequest));
+ try {
+ expect((await writeHealthFacts(engine, [])).size).toBe(0);
+ expect((await writeHealthFacts(engine, rows.map(row => ({ ...row, state: 'committed' })))).size).toBe(0);
+ expect(queries).toBe(0);
+ const started = performance.now();
+ expect((await writeHealthFacts(engine, rows)).size).toBe(0);
+ expect(performance.now() - started).toBeLessThan(1500);
+ expect(queries).toBe(1);
+ await Promise.all(Array.from({ length: 20 }, () => writeHealthFacts(engine, rows)));
+ expect(queries).toBe(1);
+ await expect(writeHealthFacts(engine, [...rows, rows[0]])).rejects.toThrow(RangeError);
+ } finally { release.resolve([]); }
+ await Bun.sleep(0);
+ await writeHealthFacts(engine, rows);
+ expect(queries).toBe(2);
+});
+
+test('failed optional enrichment returns no facts without making database writes', async () => {
+ const engine = { kind: 'postgres', executeRaw: async (sql: string) => {
+ expect(sql).not.toMatch(/UPDATE|INSERT|DELETE/);
+ throw new Error('PRIVATE_DRIVER_MARKER');
+ } } as unknown as BrainEngine;
+ expect((await writeHealthFacts(engine, [{ state: 'queued', source_incarnation: randomUUID() } as WriteRequest])).size).toBe(0);
+});
+
+for (const reason of ['writer_busy', 'database_contention']) test.each([0, 180000])(`trusted ${reason} advice agrees with health at age %d`, async age => {
+ const row = { request_id: randomUUID(), state: 'queued', blocked_reason: reason, error_code: null,
+ worktree_id: null, created_at: new Date(Date.now() - age) };
+ const engine = { kind: 'pglite', executeRaw: async (sql: string) =>
+ sql.startsWith('SELECT request_id,worktree_id,state,blocked_reason') ? [row] : [] } as unknown as BrainEngine;
+ const [blocker] = (await readWriterDiagnostics(engine)).blockers;
+ expect(blocker.diagnostic?.next_action).toBe(age >= 120000 ? 'inspect_owner' : 'poll');
+ expect(blocker.next_action).toContain(WRITER_NEXT_ACTIONS[reason]);
+ if (age >= 120000) expect(blocker.next_action).toContain('Inspect gbrain sources writer status');
+ else expect(blocker.next_action).toBe(WRITER_NEXT_ACTIONS[reason]);
+});
+
+test('fresh and upgraded engines agree on the database-only pending index', async () => {
+ for (const engine of engines) {
+ const [fresh] = await engine.executeRaw<{ indexdef: string }>(
+ "SELECT indexdef FROM pg_indexes WHERE indexname='persistence_requests_database_pending'");
+ expect(fresh.indexdef).toContain('source_incarnation, sequence');
+ expect(fresh.indexdef).toContain('worktree_id IS NULL');
+ await engine.executeRaw('DROP INDEX persistence_requests_database_pending');
+ if (engine.kind === 'postgres') {
+ const held = Promise.withResolvers<void>(), release = Promise.withResolvers<void>();
+ const holding = engine.transaction(async tx => {
+ await tx.executeRaw('LOCK TABLE persistence_requests IN ROW EXCLUSIVE MODE');
+ held.resolve(); await release.promise;
+ });
+ await held.promise;
+ const abort = new AbortController();
+ const interrupted = engine.executeRawDirect(fresh.indexdef.replace('CREATE INDEX ', 'CREATE INDEX CONCURRENTLY '), [], { signal: abort.signal })
+ .then(() => false, () => true);
+ try {
+ await waitFor(async () => (await engine.executeRaw<{ indisvalid: boolean }>(
+ "SELECT indisvalid FROM pg_index WHERE indexrelid=to_regclass('persistence_requests_database_pending')"))[0]?.indisvalid === false);
+ abort.abort();
+ expect(await interrupted).toBe(true);
+ } finally { abort.abort(); release.resolve(); await holding; await interrupted; }
+ }
+ await engine.setConfig('version', '164');
+ expect(await runMigrations(engine)).toEqual({ applied: 1, current: 165 });
+ const [upgraded] = await engine.executeRaw<{ indexdef: string }>(
+ "SELECT indexdef FROM pg_indexes WHERE indexname='persistence_requests_database_pending'");
+ expect(upgraded.indexdef).toBe(fresh.indexdef);
+ expect(await engine.getConfig('version')).toBe('165');
+ }
+}, 15000);
+
test('admin diagnostics account for queued work and configured limits without exposing intent', async () => {
for (const engine of engines) {
const ctx: OperationContext = { engine, config: { engine: engine.kind }, sourceId: 'default',
diff --git a/test/persistence-ipc.test.ts b/test/persistence-ipc.test.ts
index 3ad36e91a4..3177ab322f 100644
--- a/test/persistence-ipc.test.ts
+++ b/test/persistence-ipc.test.ts
@@ -153,6 +153,24 @@ describe('dedicated persistence IPC', () => {
}
});
+ test('optional safe health survives IPC without private nested fields', async () => {
+ const path = socketPath();
+ const diagnostic = { age_ms: 120000, assessment: 'stalled' as const,
+ reason: 'cause_unknown' as const, next_action: 'inspect_owner' as const };
+ await bind(path, async () => {
+ const error = new OperationError('write_pending', 'Still pending.');
+ error.writeRequest = { request_id: ID, state: 'queued', retry_after_ms: 30000,
+ diagnostic: { ...diagnostic, ...{ predecessor_id: 'PRIVATE_PREDECESSOR' } } };
+ throw error;
+ });
+ try { await requestPersistenceOperation(path, request()); throw new Error('Expected pending error.'); }
+ catch (error) {
+ const body = (error as OperationError).toJSON();
+ expect(body).toMatchObject({ write_request: { request_id: ID, diagnostic } });
+ expect(JSON.stringify(body)).not.toContain('PRIVATE_PREDECESSOR');
+ }
+ });
+
test('lost acknowledgement is unknown, keeps original ID, and never auto-retries', async () => {
const path = socketPath();
let calls = 0;
diff --git a/test/persistence-journal.test.ts b/test/persistence-journal.test.ts
index faa8fd8e86..c7113f4ec3 100644
--- a/test/persistence-journal.test.ts
+++ b/test/persistence-journal.test.ts
@@ -133,6 +133,56 @@ describe('durable mutation journal', () => {
await cancelWriteRequest(engine, a.principal, a.requestId!);
});
+ test('contended admissions release PostgreSQL pool capacity for reads before the counter unlocks', async () => {
+ const engine = engines.find(candidate => candidate.kind === 'postgres');
+ if (!engine) return;
+ const inputs = await Promise.all(Array.from({ length: 3 }, (_, i) => admission(engine, `admission-reader-capacity-${i}`)));
+ await engine.executeRaw("INSERT INTO persistence_counters(key) VALUES('brain') ON CONFLICT DO NOTHING");
+ const [before] = await engine.executeRaw<{ lifetime_ids: string }>("SELECT lifetime_ids::text FROM persistence_counters WHERE key='brain'");
+ let release!: () => void; let held!: () => void; let attempted!: () => void;
+ const released = new Promise<void>(resolve => { release = resolve; });
+ const ready = new Promise<void>(resolve => { held = resolve; });
+ const attemptsReady = new Promise<void>(resolve => { attempted = resolve; });
+ const attempts = new Set<string>();
+ const blocker = engine.transaction(async tx => {
+ await tx.executeRaw("SELECT key FROM persistence_counters WHERE key='brain' FOR UPDATE");
+ held(); await released;
+ });
+ const writes: Promise<Awaited<ReturnType<typeof admitWrite>>>[] = [];
+ let read: Promise<unknown> | undefined;
+ try {
+ await ready;
+ for (const input of inputs) {
+ const observed = new Proxy(engine, { get(target, property) {
+ if (property === 'transaction') return (run: (tx: BrainEngine) => Promise<unknown>) => target.transaction(tx => run(new Proxy(tx, { get(t, p) {
+ if (p === 'executeRaw') return (sql: string, params?: unknown[], opts?: { signal?: AbortSignal }) => {
+ if (sql.startsWith('INSERT INTO persistence_counters') && params?.[0] === 'brain') {
+ attempts.add(input.requestId!);
+ if (attempts.size === inputs.length) attempted();
+ }
+ return t.executeRaw(sql, params, opts);
+ };
+ const value = Reflect.get(t, p); return typeof value === 'function' ? value.bind(t) : value;
+ } })));
+ const value = Reflect.get(target, property); return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ writes.push(admitWrite(observed, input));
+ }
+ expect(await Promise.race([attemptsReady.then(() => true), Bun.sleep(2000).then(() => false)])).toBe(true);
+ read = engine.executeRaw('SELECT 1 AS reader_progress');
+ expect(await Promise.race([read.then(() => true), Bun.sleep(200).then(() => false)])).toBe(true);
+ } finally { release(); await blocker; await Promise.allSettled(writes); await read; }
+ const accepted = await Promise.all(writes);
+ const [after] = await engine.executeRaw<{ lifetime_ids: string }>("SELECT lifetime_ids::text FROM persistence_counters WHERE key='brain'");
+ expect(Number(after.lifetime_ids) - Number(before.lifetime_ids)).toBe(inputs.length);
+ for (let i = 0; i < inputs.length; i++) {
+ expect(accepted[i].request_id).toBe(inputs[i].requestId!);
+ expect(accepted[i].state).toBe('queued');
+ expect((await admitWrite(engine, inputs[i])).id).toBe(accepted[i].id);
+ await cancelWriteRequest(engine, inputs[i].principal, inputs[i].requestId!);
+ }
+ }, 15000);
+
test('activation rejects legacy canonical writers but accepts guarded publication', async () => {
for (const engine of engines) {
await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
diff --git a/test/persistence-memory-mutations.test.ts b/test/persistence-memory-mutations.test.ts
index 83d7493cbb..c3ea5aa9bc 100644
--- a/test/persistence-memory-mutations.test.ts
+++ b/test/persistence-memory-mutations.test.ts
@@ -11,7 +11,9 @@ import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
import { registerLocalWriter } from '../src/core/persistence/identity.ts';
import { submissionAuthority } from '../src/core/persistence/authority.ts';
-import { admitWrite, claimNextWrite, getWriteRequest } from '../src/core/persistence/journal.ts';
+import { admitWrite, claimNextWrite, getWriteRequest, getWriteRequestById, receiptFor } from '../src/core/persistence/journal.ts';
+import { PersistenceConsumer } from '../src/core/persistence/consumer.ts';
+import { waitFor } from './helpers/wait-for.ts';
import { publishMutation } from '../src/core/persistence/coordinator.ts';
import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';
@@ -55,6 +57,82 @@ afterAll(async () => {
});
describe('journaled memory publication, both engines', () => {
+ test('remember provider preparation cooperatively aborts without terminal failure and retries the same receipt', async () => {
+ for (const engine of engines) {
+ await disposePersistenceConsumer(engine);
+ const slug = 'people/deadline-example';
+ const snapshot = await setupPage(engine, slug);
+ const authority = await submissionAuthority(context(engine), 'remember', sourceId, snapshot.sourceIncarnation, slug);
+ const intent = { fact: 'Synthetic provider deadline fact', provenance: 'deadline fixture', entity_slug: slug,
+ visibility: 'world', fence: true, valid_from: new Date().toISOString(), valid_until: null };
+ const row = await admitWrite(engine, { principal: authority.principal, operation: 'remember', sourceId,
+ sourceIncarnation: snapshot.sourceIncarnation, slug, pageId: snapshot.page.id, callerIntent: intent, intent, authority, requestId: randomUUID() });
+ let aborted = false;
+ const release = Promise.withResolvers<void>();
+ const provider = Bun.serve({ hostname: '127.0.0.1', port: 0, fetch: async () => {
+ await release.promise;
+ return Response.json({ embeddings: [[1, ...Array(1535).fill(0)]], usage: { tokens: 0 } });
+ } });
+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: { OPENAI_API_KEY: 'sk-test' } });
+ __setEmbedTransportForTests(async options => {
+ try { return await (await fetch(provider.url, { signal: options.abortSignal })).json() as never; }
+ catch (error) { aborted = options.abortSignal!.aborted; throw error; }
+ });
+ const consumer = new PersistenceConsumer(engine, context(engine).config, prepareMemoryMutation, { pollMs: 60000, preparationMs: 50 });
+ try {
+ consumer.start();
+ await waitFor(() => aborted && consumer.status().active_preparations === 0);
+ expect((await getWriteRequestById(engine, row.id))?.state).toBe('queued');
+ expect(await engine.executeRaw('SELECT id FROM facts WHERE source_id=$1 AND fact=$2', [sourceId, intent.fact])).toHaveLength(0);
+ } finally { release.resolve(); provider.stop(true); await consumer.stop(); __setEmbedTransportForTests(null); configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} }); }
+ const retry = new PersistenceConsumer(engine, context(engine).config, prepareMemoryMutation, { pollMs: 50 });
+ try {
+ retry.start();
+ await waitFor(async () => (await getWriteRequestById(engine, row.id))?.state === 'committed');
+ expect(await engine.executeRaw('SELECT fact,source FROM facts WHERE source_id=$1 AND fact=$2', [sourceId, intent.fact]))
+ .toEqual([{ fact: intent.fact, source: intent.provenance }]);
+ } finally { await retry.stop(); }
+ }
+ }, 15000);
+ test('slow healthy loopback preparation keeps an aged receipt nonterminal and replays without a provider call', async () => {
+ for (const engine of engines) {
+ await disposePersistenceConsumer(engine);
+ const slug = 'people/slow-provider-example';
+ await setupPage(engine, slug);
+ const release = Promise.withResolvers<void>();
+ let calls = 0;
+ const provider = Bun.serve({ hostname: '127.0.0.1', port: 0, fetch: async () => {
+ calls++;
+ await release.promise;
+ return Response.json({ embeddings: [[1, ...Array(1535).fill(0)]], usage: { tokens: 0 } });
+ } });
+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: { OPENAI_API_KEY: 'sk-test' } });
+ __setEmbedTransportForTests(async options => await (await fetch(provider.url, { signal: options.abortSignal })).json() as never);
+ const params = { fact: 'Synthetic slow healthy fact', provenance: 'slow loopback fixture', entity: slug, request_id: randomUUID() };
+ const completion = submitRememberMutation(context(engine), params, 10000);
+ try {
+ await waitFor(async () => calls > 0 && (await engine.executeRaw<{ state: string }>(
+ 'SELECT state FROM persistence_requests WHERE request_id=$1', [params.request_id]))[0]?.state === 'running');
+ await engine.executeRaw("UPDATE persistence_requests SET created_at=now()-interval '3 minutes' WHERE request_id=$1", [params.request_id]);
+ const [pending] = await engine.executeRaw<import('../src/core/persistence/model.ts').WriteRequest>('SELECT * FROM persistence_requests WHERE request_id=$1', [params.request_id]);
+ expect(pending.state).toBe('running');
+ expect(receiptFor(pending).diagnostic).toMatchObject({ reason: 'cause_unknown', next_action: 'inspect_owner' });
+ expect(await engine.executeRaw('SELECT id FROM facts WHERE source_id=$1 AND fact=$2', [sourceId, params.fact])).toHaveLength(0);
+ release.resolve();
+ const result = await completion;
+ expect(result.state).toBe('committed');
+ await disposePersistenceConsumer(engine);
+ const callsBeforeReplay = calls;
+ expect(await submitRememberMutation(context(engine), params)).toEqual(result);
+ expect(calls).toBe(callsBeforeReplay);
+ expect(await engine.executeRaw('SELECT fact,source FROM facts WHERE source_id=$1 AND fact=$2', [sourceId, params.fact]))
+ .toEqual([{ fact: params.fact, source: params.provenance }]);
+ } finally {
+ release.resolve(); await completion.catch(() => {}); await disposePersistenceConsumer(engine);
+ provider.stop(true); __setEmbedTransportForTests(null); configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });
+ }
+ }
+ }, 20000);
test('same-ID remember replays frozen fields after entity and fact removal', async () => {
for (const engine of engines) {
const slug = 'people/replay-example';
diff --git a/test/persistence-performance.test.ts b/test/persistence-performance.test.ts
index ea4df724fe..72404146c8 100644
--- a/test/persistence-performance.test.ts
+++ b/test/persistence-performance.test.ts
@@ -1,13 +1,42 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, spyOn, test } from 'bun:test';
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { overlapPercent, summarizeReadRuns } from '../scripts/persistence/read-metrics.ts';
import { runReadPerformance } from '../scripts/persistence/performance.ts';
+import { runReadLatencyWorkload } from '../scripts/persistence/read-workload.ts';
import { WriteTimingRecorder } from '../scripts/persistence/read-admission.ts';
+import { withEnv } from './helpers/with-env.ts';
import { childEnvironment } from '../scripts/persistence/validate.ts';
describe('read-load evidence', () => {
+ test.each([false, true])('unavailable RSS stays explicit without invalidating real reads and writes (all=%s)', async all => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-read-rss-'));
+ const original = process.memoryUsage;
+ let calls = 0;
+ const memory = spyOn(process, 'memoryUsage').mockImplementation(Object.assign(() => {
+ if (++calls === 1 || all) throw new Error('Failed to get memory usage');
+ return original.call(process);
+ }, { rss: original.rss }));
+ try {
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ const result = await runReadLatencyWorkload({ pages: 4, queries: 200, writers: 1, writesPerWriter: 100 });
+ expect(result.ok).toBe(true);
+ expect(result.phase_b.writes_completed).toBeGreaterThan(0);
+ expect(result.phase_b.writes_failed).toBe(0);
+ expect(result.rss_unavailable_samples).toBeGreaterThan(0);
+ expect(result.metrics[0].rss_bytes).toBeNull();
+ if (all) {
+ expect(result.metrics.every((sample: { rss_bytes: number | null }) => sample.rss_bytes === null)).toBe(true);
+ expect(result.peak_rss_bytes).toBeNull();
+ } else {
+ expect(result.rss_unavailable_samples).toBe(1);
+ expect(result.peak_rss_bytes).toBeGreaterThan(0);
+ }
+ });
+ } finally { memory.mockRestore(); rmSync(home, { recursive: true, force: true }); }
+ }, 60000);
+
test('rejects invalid workload sizes before opening a datastore', async () => {
await expect(runReadPerformance({ pages: 0 })).rejects.toThrow('Invalid pages');
});
diff --git a/test/persistence-read-diagnostics.serial.test.ts b/test/persistence-read-diagnostics.serial.test.ts
index 8230618278..c787cb55a6 100644
--- a/test/persistence-read-diagnostics.serial.test.ts
+++ b/test/persistence-read-diagnostics.serial.test.ts
@@ -116,6 +116,56 @@ test('RSS failure retains partial reads and safe stage/errno; a successful later
expect(result.metrics.length).toBeGreaterThan(0);
}, 120_000);
+test('late known Bun RSS unavailability is included in final sample counts and peaks', async () => {
+ const result = await child(`
+ import { PGLiteEngine } from ${engineImport};
+ import { runReadLatencyWorkload } from ${workloadImport};
+ import { WriteTimingRecorder } from ${admissionImport};
+ let loaded = false; let releaseCommit;
+ const committed = new Promise(resolve => { releaseCommit = resolve; });
+ const complete = WriteTimingRecorder.prototype.complete;
+ WriteTimingRecorder.prototype.complete = function(...args) {
+ const result = complete.apply(this, args);
+ if (loaded) releaseCommit();
+ return result;
+ };
+ const keyword = PGLiteEngine.prototype.searchKeyword; let reads = 0;
+ PGLiteEngine.prototype.searchKeyword = async function(...args) {
+ if (++reads === 22) { loaded = true; await committed; }
+ return keyword.apply(this, args);
+ };
+ const interval = globalThis.setInterval;
+ let sampler; let late = false; let injected = false;
+ globalThis.setInterval = function(fn, ms, ...args) {
+ if (ms === 250) sampler = fn;
+ return interval(fn, ms, ...args);
+ };
+ const memory = process.memoryUsage;
+ process.memoryUsage = Object.assign(function() {
+ if (late && !injected) {
+ injected = true;
+ throw Object.assign(new Error('Failed to get memory usage'), { name: 'SystemError', syscall: 'memoryUsage', errno: 2 });
+ }
+ return memory();
+ }, memory);
+ const execute = PGLiteEngine.prototype.executeRaw;
+ PGLiteEngine.prototype.executeRaw = async function(sql, ...args) {
+ if (sql === 'SELECT count(*)::integer AS n FROM pages') { late = true; sampler(); }
+ return execute.call(this, sql, ...args);
+ };
+ const result = await runReadLatencyWorkload(${options});
+ console.log(JSON.stringify({ diagnostic_test: true, result: { ...result, injected } }));
+ `);
+ expect(result.injected).toBe(true);
+ expect(result.ok).toBe(true);
+ expect(result.rss_unavailable_samples).toBe(1);
+ expect(result.metrics.filter((sample: any) => sample.rss_bytes === null)).toHaveLength(1);
+ expect(result.peak_rss_bytes).toBe(Math.max(...result.metrics.flatMap((sample: any) => sample.rss_bytes === null ? [] : [sample.rss_bytes])));
+ expect(result.peak_queue_age_ms).toBe(Math.max(0, ...result.metrics.map((sample: any) => sample.queue_age_ms)));
+ expect(result.peak_recovery_bytes).toBe(Math.max(0, ...result.metrics.map((sample: any) => sample.recovery_bytes)));
+ expect(result.diagnostics.failures.total).toBe(0);
+}, 120_000);
+
test('failed loaded lexical arm remains invalid and retains its partial query without raw errors', async () => {
const result = await child(`
import { PGLiteEngine } from ${engineImport};
diff --git a/test/persistence-receipt-operations.test.ts b/test/persistence-receipt-operations.test.ts
index 96e466e8de..e27d06bd0a 100644
--- a/test/persistence-receipt-operations.test.ts
+++ b/test/persistence-receipt-operations.test.ts
@@ -60,6 +60,83 @@ async function call(name: string, params: Record<string, unknown>, local = owner
}
describe('own-principal write receipt operations', () => {
+ test('one hundred authorized receipts use one projected diagnostic query', async () => {
+ for (let i = 0; i < 100; i++) await accept(owner, `allowed/batch-${i}`);
+ let queries = 0;
+ const proxy = new Proxy(engine, { get(target, key) {
+ if (key === 'executeRaw') return async (...args: Parameters<typeof engine.executeRaw>) => {
+ if (args[0].includes('WITH roots AS')) {
+ queries++;
+ expect(args[0]).not.toContain('r.*');
+ expect(args[0]).not.toContain('intent');
+ expect((args[1]![0] as string[])).toHaveLength(1);
+ }
+ return target.executeRaw(...args);
+ };
+ const value = Reflect.get(target, key);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ const result = await call('list_write_requests', { limit: 100 }, owner, context(proxy));
+ expect(result.requests).toHaveLength(100);
+ expect(queries).toBe(1);
+ expect(result.requests.every((row: any) => row.diagnostic.observed_at)).toBe(true);
+ expect(JSON.stringify(result)).not.toContain('PRIVATE_');
+ await expect(call('get_write_request', { request_id: randomUUID() }, foreign, context(proxy))).rejects.toMatchObject({ code: 'not_found' });
+ expect(queries).toBe(1);
+ });
+ test('a foreign FIFO head yields only a coarse dependency after own authorization', async () => {
+ const first = await accept(foreign, 'PRIVATE_FOREIGN_HEAD');
+ const own = await accept(owner, 'allowed/follower');
+ const receipt = await call('get_write_request', { request_id: own.request_id });
+ expect(receipt.diagnostic).toMatchObject({ assessment: 'blocked', reason: 'waiting_on_earlier_write', next_action: 'poll' });
+ expect(receipt.retry_after_ms).toBe(5000);
+ expect(JSON.stringify(receipt)).not.toContain(first.request_id);
+ expect(JSON.stringify(receipt)).not.toContain('PRIVATE_');
+ });
+ test('another source sharing a worktree contributes no predecessor identity to health', async () => {
+ const first = await accept(foreign, 'PRIVATE_OTHER_SOURCE_HEAD', otherSource);
+ const own = await accept();
+ const worktree = randomUUID();
+ await engine.executeRaw('INSERT INTO persistence_worktrees(id,owner_host_id) VALUES($1,$2)', [worktree, randomUUID()]);
+ await engine.executeRaw('UPDATE persistence_requests SET worktree_id=$2 WHERE id=ANY($1::uuid[])', [[first.id, own.id], worktree]);
+ const result = await call('list_write_requests', {});
+ expect(result.requests).toHaveLength(1);
+ expect(result.requests[0].diagnostic.reason).toBe('waiting_on_earlier_write');
+ for (const hidden of [first.id, first.request_id, otherSource, 'PRIVATE_OTHER_SOURCE_HEAD']) expect(JSON.stringify(result)).not.toContain(hidden);
+ expect(result.next).toBeNull();
+ });
+ test('source incarnation and delegated namespace changes refuse before enrichment', async () => {
+ const row = await accept();
+ let queries = 0;
+ const proxy = new Proxy(engine, { get(target, key) {
+ if (key === 'executeRaw') return async (...args: Parameters<typeof engine.executeRaw>) => {
+ if (args[0].includes('WITH roots AS')) queries++;
+ return target.executeRaw(...args);
+ };
+ const value = Reflect.get(target, key);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ await expect(call('get_write_request', { request_id: row.request_id }, owner,
+ { ...context(proxy), viaSubagent: true, allowedSlugPrefixes: ['different/*'] })).rejects.toMatchObject({ code: 'not_found' });
+ await engine.executeRaw('UPDATE sources SET incarnation=$2 WHERE id=$1', [source, randomUUID()]);
+ await expect(call('get_write_request', { request_id: row.request_id }, owner, context(proxy))).rejects.toMatchObject({ code: 'not_found' });
+ expect(queries).toBe(0);
+ });
+ test('authorization query failures fail closed rather than using optional diagnostic fallback', async () => {
+ const row = await accept();
+ let queries = 0;
+ const proxy = new Proxy(engine, { get(target, key) {
+ if (key === 'executeRaw') return async (...args: Parameters<typeof engine.executeRaw>) => {
+ if (args[0].includes('WITH roots AS')) queries++;
+ if (args[0].startsWith('SELECT incarnation,archived FROM sources')) throw new Error('AUTHORIZATION_DATABASE_UNAVAILABLE');
+ return target.executeRaw(...args);
+ };
+ const value = Reflect.get(target, key);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ await expect(call('get_write_request', { request_id: row.request_id }, owner, context(proxy))).rejects.toThrow('AUTHORIZATION_DATABASE_UNAVAILABLE');
+ expect(queries).toBe(0);
+ });
test('get_write_request returns public metadata and never journal payload, execution or recovery bytes', async () => {
const row = await accept();
await engine.executeRaw('UPDATE persistence_requests SET execution_token=$2,recovery=$3::jsonb,error_message=$4,error_code=$5 WHERE id=$1',
diff --git a/test/persistence-sync-receipt-diagnostics.test.ts b/test/persistence-sync-receipt-diagnostics.test.ts
index 16e17df1dd..bc1769fa78 100644
--- a/test/persistence-sync-receipt-diagnostics.test.ts
+++ b/test/persistence-sync-receipt-diagnostics.test.ts
@@ -69,6 +69,24 @@ test.each(['queued', 'running', 'recovering'] as const)('%s cannot look committe
expect(body.write_request).not.toHaveProperty('revision');
});
+test('CLI JSON and frozen error serialization retain the same allowlisted health', async () => {
+ const diagnostic = { age_ms: 120000, assessment: 'stalled' as const,
+ reason: 'cause_unknown' as const, next_action: 'inspect_owner' as const };
+ const error = frozenVerbWriteError({ request_id: requestId, state: 'queued', retry_after_ms: 30000,
+ diagnostic: { ...diagnostic, ...{ raw_error: 'PRIVATE_DRIVER_ERROR' } } }, 'write_pending');
+ const stderr = spyOn(console, 'error').mockImplementation(() => {});
+ let stdout = '';
+ try {
+ expect(await reportPersistenceCliError(error, true, async text => { stdout += text; })).toBe(true);
+ const body = JSON.parse(stdout);
+ expect(body.write_request.diagnostic).toEqual(diagnostic);
+ expect(body.suggestion).toContain(requestId);
+ expect(body.suggestion).toContain('gbrain sources writer status');
+ expect(stdout).not.toContain('PRIVATE_DRIVER_ERROR');
+ expect(validateAgainstSchema(body, ERROR_SCHEMA)).toEqual([]);
+ } finally { stderr.mockRestore(); }
+});
+
test('unrecognized errors cannot echo private content, absolute paths, or credentials', () => {
const privateMessage = '/private/source/example.md contains secret private fixture content with credential=redacted';
for (const code of ['source_changed', 'storage_error', 'invalid_params', 'unknown_error']) {
diff --git a/test/persistence-write-contracts.test.ts b/test/persistence-write-contracts.test.ts
index c3b9fa63fa..33c8236e95 100644
--- a/test/persistence-write-contracts.test.ts
+++ b/test/persistence-write-contracts.test.ts
@@ -5,6 +5,9 @@ import { validateAgainstSchema } from '../src/core/verbs/conformance.ts';
import { parseMutationPrecondition } from '../src/core/persistence/preconditions.ts';
import { committedVerbOutcome, frozenVerbWriteError } from '../src/core/persistence/verb-errors.ts';
import { isWriteReceipt, publicWriteReceipt, type WriteReceipt } from '../src/core/persistence/types.ts';
+import { receiptFor } from '../src/core/persistence/journal.ts';
+import type { WriteRequest } from '../src/core/persistence/model.ts';
+import { writeHealth, pendingWriteHint } from '../src/core/persistence/health.ts';
const REQUEST_ID = 'd7599b95-65c2-4d54-aa4e-cb5745af90cf';
const receipt = (state: WriteReceipt['state']): WriteReceipt => ({
@@ -32,6 +35,58 @@ describe('mutation preconditions', () => {
});
describe('public write receipts', () => {
+ test.each([[0, 1000], [29999, 1000], [30000, 5000], [30001, 5000], [119999, 5000], [120000, 30000], [120001, 30000]])('age %d has advisory poll %d', (age, retry) => {
+ const health = writeHealth({ state: 'running', created_at: new Date(0) }, {}, age);
+ expect(health.retry_after_ms).toBe(retry);
+ expect(health.diagnostic?.age_ms).toBe(age);
+ expect(health.diagnostic?.next_action).toBe(age >= 120000 ? 'inspect_owner' : 'poll');
+ });
+
+ test('clock movement, terminal state and unknown internal reasons remain conservative', () => {
+ expect(writeHealth({ state: 'queued', created_at: new Date(1000) }, {}, 0).diagnostic?.age_ms).toBe(0);
+ expect(writeHealth({ state: 'committed', created_at: new Date(0) }, {}, 999999)).toEqual({ retry_after_ms: null });
+ const health = writeHealth({ state: 'queued', created_at: new Date(0), blocked_reason: 'PRIVATE_UNKNOWN_MARKER' }, {}, 120000);
+ expect(health.diagnostic?.reason).toBe('cause_unknown');
+ expect(JSON.stringify(health)).not.toContain('PRIVATE_');
+ expect(health.diagnostic).not.toHaveProperty('observed_at');
+ });
+
+ test('nested diagnostics are validated and explicitly redacted', () => {
+ const health = writeHealth({ state: 'queued', created_at: new Date(0), blocked_reason: 'unexpected_file_bytes' }, { observed_at: '2026-01-01T00:00:00.000Z' }, 100);
+ const value = { ...receipt('queued'), ...health };
+ expect(isWriteReceipt(value)).toBe(true);
+ expect(value.diagnostic?.next_action).toBe('inspect_owner');
+ expect(pendingWriteHint(value)).toContain('inspect');
+ expect(frozenVerbWriteError(value).suggestion).toBe(pendingWriteHint(value));
+ expect(validateAgainstSchema(frozenVerbWriteError(value).toJSON(), ERROR_SCHEMA)).toEqual([]);
+ for (const patch of [{ age_ms: -1 }, { age_ms: 1.5 }, { age_ms: NaN }, { age_ms: Infinity },
+ { age_ms: '1' }, { assessment: 'dead' }, { reason: 'PRIVATE' }, { next_action: 'transfer' },
+ { observed_at: 'yesterday' }, { observed_at: '2026-02-30T00:00:00.000Z' }]) {
+ expect(isWriteReceipt({ ...value, diagnostic: { ...value.diagnostic, ...patch } })).toBe(false);
+ }
+ for (const diagnostic of [null, [], 'pending']) expect(isWriteReceipt({ ...value, diagnostic })).toBe(false);
+ expect(isWriteReceipt({ ...receipt('committed'), diagnostic: value.diagnostic })).toBe(false);
+ const extra = { ...value, diagnostic: { ...value.diagnostic!, path: 'PRIVATE_MARKER' } };
+ expect(JSON.stringify(publicWriteReceipt(extra))).not.toContain('PRIVATE_MARKER');
+ });
+ test('accepted contention survives public serialization with actionable polling', () => {
+ const row = { request_id: REQUEST_ID, state: 'queued', blocked_reason: 'database_contention',
+ created_at: new Date(), updated_at: new Date() } as WriteRequest;
+ expect(publicWriteReceipt(receiptFor(row))).toMatchObject({ retry_after_ms: 5000,
+ diagnostic: { assessment: 'blocked', reason: 'database_contention', next_action: 'poll' } });
+ });
+
+ test('renewed aged requests request inspection without inventing owner failure', () => {
+ const row = { request_id: REQUEST_ID, state: 'running', created_at: new Date(Date.now() - 130_000),
+ updated_at: new Date() } as WriteRequest;
+ expect(publicWriteReceipt(receiptFor(row))).toMatchObject({ retry_after_ms: 30000,
+ diagnostic: { assessment: 'stalled', reason: 'cause_unknown', next_action: 'inspect_owner' } });
+ });
+ test.each([29999, 30000, 119999, 120000, 120001])('known contention remains blocked while its advice ages at %d', age => {
+ expect(writeHealth({ state: 'queued', created_at: new Date(0), blocked_reason: 'database_contention' }, {}, age))
+ .toMatchObject({ retry_after_ms: age >= 120000 ? 30000 : 5000,
+ diagnostic: { assessment: 'blocked', reason: 'database_contention', next_action: age >= 120000 ? 'inspect_owner' : 'poll' } });
+ });
test('serialization excludes journal payload and execution details', () => {
const internal = { ...receipt('recovering'), payload: 'private content', claim_token: 'private token', recovery_path: '/private/root' };
const error = new OperationError('recovery_required', 'Publication is recovering.');