Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(refresh): a fence lock timeout is refresh_lock_timeout naming the holding transactions, not internal_error (GBRA-250)
garrytan54d5e52b5164
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 82a31654ad..a1f8b202ac 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,13 +12,16 @@ identifiers and attribution are available in the pre-removal Git revision## [Unreleased]-**When `gbrain sources refresh` hits an unexpected error (a database statement error, a code fault), it now prints a typed `internal_error` refusal with the error's stack in `why` and the refresh row it left, instead of a bare `internal_error` with neither. One failure leaves enough to diagnose it, and the next run resumes the row as before.**+**`gbrain sources refresh` no longer exits with a bare `internal_error` when another database transaction holds a row its fence needs. A fence that waits past its 5 s lock timeout now refuses as `refresh_lock_timeout`, and `why` names the open transactions holding those tables. Nothing moves, and a later run completes once the holder is gone. Any other unexpected error now prints a typed `internal_error` refusal with its stack in `why` and the refresh row it left, which the next run resumes.**++Before, a stuck transaction holding a source, worktree or brain row (a long-running job, for example) made an upstream-moved refresh fail after about 5 s with `canceling statement due to lock timeout`. That surfaced as a top-level `internal_error` with no `status`, no stack and no holder. If it happened after the drain, it also left a `draining` row for the next run to clean up.### Itemized changes-- `src/core/persistence/worktree-refresh.ts`: `refreshWorktree` turns any non-`OperationError` throw into `internal_error` with the error name, SQLSTATE and message (connection details and URLs redacted), the stack in `why`, and a fix naming the active refresh row and its state. The row is not changed. The already-current path no longer throws a `TypeError` of its own when a member sync rejects with a non-object.+- `src/core/persistence/worktree-refresh.ts`: Postgres `55P03` in either fence transaction (`fenceDraining`, `fenceAndMerge`) is the new `refresh_lock_timeout` refusal (registry, catalogue, `docs/guides/write-refusals.md`, `docs/guides/error-codes.md`). Its `why` lists up to five open transactions holding locks on `persistence_brain`, `persistence_worktrees` or `sources` (pid, application, state, seconds open, the start of the query). A refusal after the drain aborts the draining row as other fence refusals do.+- `src/core/persistence/worktree-refresh.ts`: `refreshWorktree` turns any other non-`OperationError` throw into `internal_error` with the error name, SQLSTATE and message (connection details and URLs redacted), the stack in `why`, and a fix naming the active refresh row and its state. The row is not changed. The already-current path no longer throws a `TypeError` of its own when a member sync rejects with a non-object.- `src/commands/sources-refresh.ts`: refusals print `why` (a `why` key under `--json`, a `Why:` line otherwise).-- Test: `test/worktree-refresh-unexpected-throw.test.ts` (PGLite, and Postgres under `DATABASE_URL`).+- Test: `test/worktree-refresh-unexpected-throw.test.ts` (PGLite, and Postgres under `DATABASE_URL`; the lock-timeout cases hold a source row from a second connection, before the fence and after the drain).## [0.60.528.0] - 2026-10-31diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.mdindex 2d85b2b151..83a7e0d67e 100644--- a/docs/architecture/key-files/commands-5.md+++ b/docs/architecture/key-files/commands-5.md@@ -45,7 +45,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/sources-strategy.ts` — `gbrain sources set-strategy <id> <markdown|code|auto>` (#4899, PR #5955): writes `sources.config.strategy` through `updateSourceConfig` (single-key merge; every other config key survives), the value `sync --all`, autopilot, the dream cycle and the MCP `sync` op pass to the per-source sync when the caller names no `--strategy`; unset means `markdown`. The one writer of that key (no `sources add --strategy`, no op param). Connector kinds refuse it. [R26]: refuses with `sync_run_unfinished` (exit 1) while the source has an unfinished `managed-sync` cursor, naming the resume and the orphan repair, because the frozen manifest was classified under the old strategy; re-stating the current value is allowed. `sources list --json` and `listSources` report `strategy` (`null` when unset). Pinned by `test/sources-strategy.test.ts`.- `src/commands/sources-add-next.ts` — GBRA-156: `noGrantFloorNext(engine, id)`, the federate step `sources add` prints when a new non-federated source leaves the no-grant floor (`localFederatedSourceIds(engine, 'default', 'seed_default')`, else `['default']`) holding no live page a remote read may show (private pages excluded when remote reads exclude them); returns `{ command, argv, why }` or null. One read, no write; `sources add` treats a failed read as no step.-- `src/commands/sources.ts` — `gbrain sources {list,add,remove,archive,restore,archived,purge,current,status,audit,refresh,set-calendar}`; `set-calendar` dispatches to `src/commands/sources-set-calendar.ts`, and `set-cr-mode` prints `contextualModeHint` after the write. `refresh` dispatches to `src/commands/sources-refresh.ts` (argument parsing, stdout text or `--json` result/refusal objects, exit 1 on refusal or an unfinished sync; protocol in `src/core/persistence/worktree-refresh.ts`, where an untyped throw becomes an `internal_error` refusal whose `why` carries the stack and whose fix names the refresh row it left for the next run to resume, GBRA-250). `current [--json]` calls `resolveSourceWithTier()` and prints `source_id`, `tier` (`flag | env | dotfile | local_path | brain_default | seed_default`), and optional `detail` (decision table in `skills/conventions/brain-routing.md`). `status [--json]` — read-only per-source dashboard (last sync, staleness, page count, embedding coverage, unacked failures); thin wrapper around `buildSyncStatusReport` + `printSyncStatusReport` from `src/commands/sync.ts`; `--json` emits stable `{schema_version: 1, sources, ...}` on stdout; filters input to `local_path IS NOT NULL AND archived IS NOT TRUE`. `audit <id> [--json]` — read-only dry-run disk scan for size distribution + would-blocks + junk-pattern hits WITHOUT touching the DB; walks `sources.local_path`, reads each markdown file, runs `assessContent()` from `src/core/content-sanity.ts`, aggregates by verdict (`ok | warn_oversize | hard_block_junk_pattern`). The live `runStatus` health table gains a `BACKFILL` column between `EMBED` and `FAILS` (`active(N)` beats `queued(N)` beats `idle`, from `SourceMetrics.backfill_active` / `backfill_queued` in `src/core/source-health.ts`) so operators see deferred `embed-backfill` minion work after `sync --all` exits 0; `jobCountsBySource` in `source-health.ts` widens its `minion_jobs` SQL with two `COUNT(*) FILTER (WHERE name = 'embed-backfill' AND ...)` aggregates (best-effort, all-0 on pre-minions brains). `remove` pre-checks OAuth-client referents (guided refusal via `formatClientReferentsBlock` — the raw FK violation never reaches the operator), then commits the row DELETE atomically with an in-tx referents re-check (a registration racing the pre-check maps to the same guided refusal); durability-scaffolding teardown (`unhardenBrainRepo`: hook/cron/credential) runs only AFTER the commit, so a refused delete leaves the scaffolding intact. `purge` runs the same referents pre-check before its hard DELETE. `add` without `--federated` or `--no-federated` stores the source non-federated and warns on stderr that a remote token or agent connection with no source grant cannot read it, naming `gbrain sources federate <id>` and `gbrain auth rescope --token <name> --sources <id>`; when the no-grant floor (the default source plus federated sources) then holds no live page it also prints `next: gbrain sources federate <id>` on stdout (`noGrantFloorNext` in `sources-add-next.ts`). `add --json` prints one object (`id`, `name`, `local_path`, `remote_url`, `federated`, and `next` with `command`/`argv`/`why` when that step applies) and moves the human lines to stderr (`test/sources-add-federation-warning.test.ts`). Pinned by `test/content-sanity.test.ts`, `test/import-file-content-sanity.test.ts`, `test/source-health.test.ts`.+- `src/commands/sources.ts` — `gbrain sources {list,add,remove,archive,restore,archived,purge,current,status,audit,refresh,set-calendar}`; `set-calendar` dispatches to `src/commands/sources-set-calendar.ts`, and `set-cr-mode` prints `contextualModeHint` after the write. `refresh` dispatches to `src/commands/sources-refresh.ts` (argument parsing, stdout text or `--json` result/refusal objects, exit 1 on refusal or an unfinished sync; protocol in `src/core/persistence/worktree-refresh.ts`, where a fence lock timeout (55P03) becomes `refresh_lock_timeout` naming the open transactions holding the fenced tables, and any other untyped throw becomes an `internal_error` refusal whose `why` carries the stack and whose fix names the refresh row it left for the next run to resume, GBRA-250). `current [--json]` calls `resolveSourceWithTier()` and prints `source_id`, `tier` (`flag | env | dotfile | local_path | brain_default | seed_default`), and optional `detail` (decision table in `skills/conventions/brain-routing.md`). `status [--json]` — read-only per-source dashboard (last sync, staleness, page count, embedding coverage, unacked failures); thin wrapper around `buildSyncStatusReport` + `printSyncStatusReport` from `src/commands/sync.ts`; `--json` emits stable `{schema_version: 1, sources, ...}` on stdout; filters input to `local_path IS NOT NULL AND archived IS NOT TRUE`. `audit <id> [--json]` — read-only dry-run disk scan for size distribution + would-blocks + junk-pattern hits WITHOUT touching the DB; walks `sources.local_path`, reads each markdown file, runs `assessContent()` from `src/core/content-sanity.ts`, aggregates by verdict (`ok | warn_oversize | hard_block_junk_pattern`). The live `runStatus` health table gains a `BACKFILL` column between `EMBED` and `FAILS` (`active(N)` beats `queued(N)` beats `idle`, from `SourceMetrics.backfill_active` / `backfill_queued` in `src/core/source-health.ts`) so operators see deferred `embed-backfill` minion work after `sync --all` exits 0; `jobCountsBySource` in `source-health.ts` widens its `minion_jobs` SQL with two `COUNT(*) FILTER (WHERE name = 'embed-backfill' AND ...)` aggregates (best-effort, all-0 on pre-minions brains). `remove` pre-checks OAuth-client referents (guided refusal via `formatClientReferentsBlock` — the raw FK violation never reaches the operator), then commits the row DELETE atomically with an in-tx referents re-check (a registration racing the pre-check maps to the same guided refusal); durability-scaffolding teardown (`unhardenBrainRepo`: hook/cron/credential) runs only AFTER the commit, so a refused delete leaves the scaffolding intact. `purge` runs the same referents pre-check before its hard DELETE. `add` without `--federated` or `--no-federated` stores the source non-federated and warns on stderr that a remote token or agent connection with no source grant cannot read it, naming `gbrain sources federate <id>` and `gbrain auth rescope --token <name> --sources <id>`; when the no-grant floor (the default source plus federated sources) then holds no live page it also prints `next: gbrain sources federate <id>` on stdout (`noGrantFloorNext` in `sources-add-next.ts`). `add --json` prints one object (`id`, `name`, `local_path`, `remote_url`, `federated`, and `next` with `command`/`argv`/`why` when that step applies) and moves the human lines to stderr (`test/sources-add-federation-warning.test.ts`). Pinned by `test/content-sanity.test.ts`, `test/import-file-content-sanity.test.ts`, `test/source-health.test.ts`.- `src/commands/status-funnel.ts` — `gbrain status --funnel [--json] [--enable | --delete]` (D8 adoption funnel): engine-free, dispatched from `src/cli/main.ts` before any connect so it works before `gbrain init` and on a thin client; reads and writes only the local record through `src/core/funnel.ts`. Guide: `docs/guides/adoption-funnel.md`. Tests: `test/funnel.test.ts`, `test/funnel-cli.test.ts`.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 85da49e76e..685531a3c9 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -3501,6 +3501,16 @@ More: [docs/guides/write-refusals.md#refresh_diverged](../../docs/guides/write-rMore: [docs/guides/write-refusals.md#refresh_drain_timeout](../../docs/guides/write-refusals.md#refresh_drain_timeout)+### refresh_lock_timeout++<a id="refresh_lock_timeout"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| Another database transaction held a row the refresh fence locks past the fence's 5 s lock timeout; nothing moved. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait briefly, then retry the same request (writes: reuse the same request_id). | agent | `repeat the read that failed` | 1 | yes |++More: [docs/guides/write-refusals.md#refresh_lock_timeout](../../docs/guides/write-refusals.md#refresh_lock_timeout)+### refresh_no_upstream<a id="refresh_no_upstream"></a>diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex e43d770ea2..7cb81cc2b6 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -553,6 +553,7 @@ this anchor (`--json` puts them in one object on stdout); the command exits 1.| <a id="sync_in_progress"></a>`sync_in_progress` | `sync_in_progress` | A managed sync of one of the checkout's sources has an unfinished cursor. Moving the checkout now would strand it, and the refresh never waits on a sync. `gbrain repair frontmatter --apply` refuses the same way while an unfinished cursor still names a selected file. | Run the printed `gbrain sync --source <source> --no-pull ...` resume command (it keeps the cursor's options), then retry (for a repair, preview again and approve the new hash). || <a id="refresh_in_progress"></a>`refresh_in_progress` | `refresh_in_progress` | Another refresh of the same checkout is active and its process is still running (the message names its holder's pid and host when the active refresh row is already readable), or a command that changes which sources share the checkout (`sources add`, `remove`, `archive`, `restore`, `reclone`) ran while one was active. A refresh whose process died is not a reason to refuse: the next refresh on the owner host finishes it first (`--dry-run` does not, so it still refuses while the orphan stands, and neither does a refresh that cannot read the checkout's HEAD: it leaves the orphan as it is and refuses until git can read HEAD again). A refresh whose holder is recorded on another host is never taken over either: writer status shows its `liveness` as `unknown`, and `gbrain sources refresh <source> --resume` on the owner host finishes it once that host's refresh is known to have stopped. Pending publication or topology recovery on the checkout refuses `refresh_recovery_required` first. An interrupted refresh that needs a reset decision refuses `refresh_recovery_required` instead. | Wait for the running refresh, or check it with `gbrain sources writer status <source>` (`liveness`, `holder`). `gbrain sources refresh <source> --resume` finishes an orphaned one now; then retry the source command with the same request ID. || <a id="refresh_drain_timeout"></a>`refresh_drain_timeout` | `refresh_drain_timeout` | Queued writes or Git effects on the checkout did not finish within `--wait-drain` (default 60 s; `sources.refresh_drain_wait_ms`; `GBRAIN_REFRESH_DRAIN_WAIT_MS`). The counts are in the message. The fence was lifted and HEAD did not move. | Retry, or wait longer with `--wait-drain <seconds>`. Inspect what is queued with `gbrain sources writer status <source> --json`. |+| <a id="refresh_lock_timeout"></a>`refresh_lock_timeout` | `refresh_lock_timeout` | The refresh fence locks the brain, worktree and source rows with a 5 s lock timeout, and another database transaction held one of them longer. `why` lists the open transactions holding locks on those tables (pid, application, state, how long the transaction has been open, the start of its query). Nothing moved: no fence was set, or the draining refresh was aborted, and HEAD did not move. | Retry `gbrain sources refresh <source>`. If it repeats, the transaction in `why` is stuck: find out what it is on the brain host before ending it. || <a id="refresh_sync_timeout"></a>`refresh_sync_timeout` | `refresh_sync_timeout` | Reported per source in a refresh's `sync_blocked`, not as a refusal: the source's managed sync committed nothing within its share of the refresh sync budget (each member gets an equal share of what is left; `sources.refresh_sync_budget_ms`, `GBRAIN_REFRESH_SYNC_BUDGET_MS`, default 5 min), for example because no consumer claimed its write. The message names that write and its state. The checkout is at the upstream commit, the refresh completed and released its lock, and the source is behind until its next sync. A sync stopped by the drain's own rules is reported with that stop's code instead (`drain_stalled` and the others). | Run the `resume` command (`gbrain sync --source <source> --no-pull`). If it stalls the same way, check the write it names with `gbrain sources writer status <source> --json`. || <a id="refresh_source_changed"></a>`refresh_source_changed` | `refresh_source_changed` | HEAD moved (an outside commit or checkout), or the checkout's ownership or set of sources changed, between the precheck and the merge. Nothing was merged and the fence was lifted. | Retry `gbrain sources refresh <source>`. || <a id="refresh_recovery_required"></a>`refresh_recovery_required` | `refresh_recovery_required` | Publication or source recovery is pending on the checkout, or a refresh was interrupted and HEAD is neither the commit it started from nor the verified upstream commit. Writes to the checkout stay refused until it is resolved; gbrain never adopts a HEAD it cannot verify. | `gbrain sources writer status <source>`, then `gbrain sources refresh <source> --resume`. When HEAD is unverified the fix names both ways out: reset to the start commit and run `--abandon`, or reset to the upstream commit and run `--resume`. Resetting is destructive, so ask the user first. |diff --git a/src/core/agent-output.ts b/src/core/agent-output.tsindex 29eefb2cc6..8b91459602 100644--- a/src/core/agent-output.ts+++ b/src/core/agent-output.ts@@ -545,7 +545,7 @@ function recoveryFix(p: EnvelopeParts, ctx: AgentErrorContext, fields?: ReceiptFconst REFRESH_REFUSALS: ReadonlySet<string> = new Set(['refresh_not_managed', 'refresh_not_owner', 'refresh_no_upstream', 'fetch_failed', 'refresh_diverged', 'refresh_dirty',- 'sync_in_progress', 'refresh_in_progress', 'refresh_drain_timeout', 'refresh_source_changed', 'refresh_recovery_required',+ 'sync_in_progress', 'refresh_in_progress', 'refresh_drain_timeout', 'refresh_lock_timeout', 'refresh_source_changed', 'refresh_recovery_required','worktree_refreshing',]);diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.tsindex 531a5df2e3..1dcbc8e087 100644--- a/src/core/error-catalogue.ts+++ b/src/core/error-catalogue.ts@@ -87,6 +87,7 @@ export const ERROR_CATALOGUE = {sync_in_progress: { code: 'sync_in_progress', docs: 'docs/guides/write-refusals.md#sync_in_progress' },refresh_in_progress: { code: 'refresh_in_progress', docs: 'docs/guides/write-refusals.md#refresh_in_progress' },refresh_drain_timeout: { code: 'refresh_drain_timeout', docs: 'docs/guides/write-refusals.md#refresh_drain_timeout' },+ refresh_lock_timeout: { code: 'refresh_lock_timeout', docs: 'docs/guides/write-refusals.md#refresh_lock_timeout' },refresh_sync_timeout: { code: 'refresh_sync_timeout', docs: 'docs/guides/write-refusals.md#refresh_sync_timeout' },refresh_source_changed: { code: 'refresh_source_changed', docs: 'docs/guides/write-refusals.md#refresh_source_changed' },refresh_recovery_required: { code: 'refresh_recovery_required', docs: 'docs/guides/write-refusals.md#refresh_recovery_required' },diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 950eadc398..8a6575475f 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -601,6 +601,7 @@ export const CODES = {refresh_dirty: { class: 'caller', summary: "The worktree has uncommitted changes." },refresh_diverged: { class: 'caller', summary: "The worktree diverged from its upstream; a fast-forward is impossible." },refresh_drain_timeout: { class: 'retryable', summary: "In-flight work did not drain before the refresh deadline." },+ refresh_lock_timeout: { class: 'retryable', summary: "Another database transaction held a row the refresh fence locks past the fence's 5 s lock timeout; nothing moved." },refresh_no_upstream: { class: 'caller', summary: "The worktree has no upstream to refresh from." },refresh_not_managed: { class: 'host_only', summary: "The source is not managed, so it cannot be refreshed." },refresh_not_owner: { class: 'host_only', summary: "This process does not own the worktree it would refresh." },diff --git a/src/core/persistence/worktree-refresh.ts b/src/core/persistence/worktree-refresh.tsindex c83ad12842..7d55f2894a 100644--- a/src/core/persistence/worktree-refresh.ts+++ b/src/core/persistence/worktree-refresh.ts@@ -588,12 +588,34 @@ async function fenceDraining(engine: BrainEngine, sourceId: string, plan: Plan,[plan.binding.worktree_id, plan.members, principal, String(current.owner_epoch), String(current.topology_generation),plan.oldHead, plan.targetHead, plan.upstreamRef, plan.preserved, JSON.stringify({ holder: refreshHolder() })]);return row;- })).catch(error => {+ })).catch(async error => {if ((error as { code?: string }).code === '23505' && !classifyOriginUniqueViolation(error)) throw inProgress('Another refresh of this worktree started first.', sourceId);+ if ((error as { code?: string }).code === LOCK_NOT_AVAILABLE) throw await lockTimeoutRefusal(engine, sourceId);throw error;});}+const LOCK_NOT_AVAILABLE = '55P03';+/**+ * GBRA-250: a fence transaction that waited past its lock_timeout for a row another transaction holds (Postgres 55P03) is a+ * typed refusal naming the open transactions that hold locks on the fenced tables, instead of an untyped internal_error.+ */+async function lockTimeoutRefusal(engine: BrainEngine, sourceId: string, refreshId?: string): Promise<OperationError> {+ const holders = engine.kind !== 'postgres' ? [] : await engine.executeRaw<{ pid: number; application_name: string; state: string | null; open_seconds: number; query: string | null }>(+ `SELECT a.pid, a.application_name, a.state, extract(epoch FROM now() - a.xact_start)::int AS open_seconds, left(a.query, 160) AS query+ FROM pg_stat_activity a+ WHERE a.pid <> pg_backend_pid() AND a.xact_start IS NOT NULL+ AND EXISTS (SELECT 1 FROM pg_locks l WHERE l.pid = a.pid AND l.granted+ AND l.relation IN ('persistence_brain'::regclass, 'persistence_worktrees'::regclass, 'sources'::regclass))+ ORDER BY a.xact_start LIMIT 5`).catch(() => []);+ const error = refusal('refresh_lock_timeout', `The refresh fence of source ${sourceId} waited past its 5 s lock timeout for a brain, worktree or source row another database transaction holds; nothing moved.`,+ `Retry gbrain sources refresh ${sourceId}. If it repeats, the transaction named in why is stuck: find out what it is on the brain host before ending it.`, refreshId);+ error.why = holders.length+ ? `Open transactions holding locks on those tables: ${holders.map(h => `pid ${h.pid} (${h.application_name || 'no application name'}, ${h.state ?? 'unknown state'}, open ${h.open_seconds} s): ${(h.query ?? '').replace(/\s+/g, ' ').trim()}`).join('; ')}`+ : 'No open transaction holding a lock on those tables was visible to this database role.';+ return error;+}+/** Steps 3-5 under the worktree native lock: recheck drained, fence, verify HEAD, ff-only merge, bookkeeping. */async function fenceAndMerge(engine: BrainEngine, git: Git, sourceId: string, plan: Plan, row: WorktreeRefreshRow, hooks?: RefreshHooks): Promise<WorktreeRefreshRow> {let fenced: WorktreeRefreshRow;@@ -612,7 +634,7 @@ async function fenceAndMerge(engine: BrainEngine, git: Git, sourceId: string, pl`Work reached the worktree after the drain check (${counts.requests} request(s), ${counts.effects} checkout effect(s), ${counts.recovery} recovery record(s)); nothing moved.`,`Retry gbrain sources refresh ${sourceId}`, row.id);if (!await transition(tx, row, ['draining'], 'fenced')) throw refusal('refresh_source_changed', 'The refresh record was moved by recovery while draining.', `gbrain sources refresh ${sourceId} --resume`, row.id);- });+ }).catch(async error => { throw (error as { code?: string }).code === LOCK_NOT_AVAILABLE ? await lockTimeoutRefusal(engine, sourceId, row.id) : error; });const current = await readRefresh(engine, row.id);await hooks?.boundary?.('fenced', current);const head = await headOf(git, plan.root);diff --git a/test/worktree-refresh-unexpected-throw.test.ts b/test/worktree-refresh-unexpected-throw.test.tsindex ad2b98ae44..6d694d5f4f 100644--- a/test/worktree-refresh-unexpected-throw.test.ts+++ b/test/worktree-refresh-unexpected-throw.test.ts@@ -4,9 +4,12 @@* internal_error with no stack and no refresh state, so a one-off failure left* nothing to diagnose. It is now a typed internal_error refusal whose `why`* carries the stack and whose fix names the refresh row it left, which the next- * run resumes.+ * run resumes. A fence that waits past its lock timeout on a row another+ * transaction holds (Postgres 55P03, the reproduced shape of that failure) is+ * refresh_lock_timeout naming the open transactions instead.*/import { afterAll, beforeAll, expect, test } from 'bun:test';+import postgres from '#postgres';import type { BrainEngine } from '../src/core/engine.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { OperationError } from '../src/core/ops/contract.ts';@@ -20,8 +23,9 @@ import { withEnv } from './helpers/with-env.ts';let engine: BrainEngine;let close: (() => Promise<void>) | undefined;+let databaseUrl = '';beforeAll(async () => {- if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engine = pg.engine; close = pg.close; return; }+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engine = pg.engine; close = pg.close; databaseUrl = pg.databaseUrl; return; }engine = new PGLiteEngine();await (engine as PGLiteEngine).connect({});await engine.initSchema();@@ -67,3 +71,61 @@ test('sources refresh prints an untyped throw as a refused document carrying theexpect(doc.why).toContain(statement.stack!.split('\n')[1]!.trim());expect(doc.fix).toContain('gbrain sources refresh source-a');});++/** Another connection holds `SELECT … FOR UPDATE` on one source row until `release` (a stuck transaction on the brain host). */+async function holdSourceRow(sourceId: string): Promise<{ pid: number; release: () => Promise<void> }> {+ const sql = postgres(databaseUrl, { max: 1, prepare: false });+ let release!: () => void;+ const released = new Promise<void>(resolve => { release = resolve; });+ let locked!: (pid: number) => void;+ const pid = new Promise<number>(resolve => { locked = resolve; });+ const tx = sql.begin(async t => {+ const [row] = await t`SELECT pg_backend_pid() AS pid FROM sources WHERE id=${sourceId} FOR UPDATE`;+ locked(Number(row!.pid));+ await released;+ });+ return { pid: await pid, release: async () => { release(); await tx; await sql.end(); } };+}++test.skipIf(!process.env.DATABASE_URL)('a source row held past the fence lock timeout is refresh_lock_timeout naming the holder, not internal_error', () => withRefreshFixture(engine, async f => {+ const before = f.head();+ const target = f.push('alpha/two.md', page('Alpha two', 'Upstream side.'));+ const held = await holdSourceRow(f.alpha);+ let failure: OperationError | null;+ const lines: string[] = [];+ try {+ failure = await refreshWorktree(f.engine, f.alpha).then(() => null, error => error);+ const log = console.log;+ console.log = (line: unknown) => { lines.push(String(line)); };+ try { await runSourcesRefresh(f.engine, [f.alpha, '--json']); expect(currentExitCode()).toBe(1); }+ finally { console.log = log; _resetCliExitVerdictForTests(); process.exitCode = 0; }+ } finally { await held.release(); }+ expect(failure).toBeInstanceOf(OperationError);+ expect(failure!.code).toBe('refresh_lock_timeout');+ expect(failure!.why).toContain(`pid ${held.pid} `);+ const doc = JSON.parse(lines[0]!);+ expect(doc.status).toBe('refused');+ expect(doc.code).toBe('refresh_lock_timeout');+ expect(doc.why).toContain(`pid ${held.pid} `);+ expect(await f.refreshRows()).toEqual([]);+ expect(f.head()).toBe(before);+ expect((await refreshWorktree(f.engine, f.alpha)).status).toBe('completed');+ expect(await f.lastCommit(f.alpha)).toBe(target);+}), 120_000);++test.skipIf(!process.env.DATABASE_URL)('a source row taken after the drain aborts the draining refresh as refresh_lock_timeout, and the next run completes', () => withRefreshFixture(engine, async f => {+ const before = f.head();+ const target = f.push('alpha/two.md', page('Alpha two', 'Upstream side.'));+ let held: Awaited<ReturnType<typeof holdSourceRow>> | undefined;+ const failure = await refreshWorktree(f.engine, f.alpha, { hooks: { boundary: async point => { if (point === 'drained') held = await holdSourceRow(f.alpha); } } })+ .then(() => null, error => error).finally(() => held?.release());+ expect(failure).toBeInstanceOf(OperationError);+ expect(failure.code).toBe('refresh_lock_timeout');+ expect(failure.why).toContain(`pid ${held!.pid} `);+ const [row] = await f.refreshRows();+ expect(failure.detail).toBe(`refresh_id=${row!.id}`);+ expect(row!.state).toBe('aborted');+ expect(f.head()).toBe(before);+ expect((await refreshWorktree(f.engine, f.alpha)).status).toBe('completed');+ expect(await f.lastCommit(f.alpha)).toBe(target);+}), 120_000);