Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

drop the #7187 holder-row deletion: master #7261's sweeps leave the drain-lease holder record

garrytan64428b417e00
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e84c5c639d..c5fb735627 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,14 +12,13 @@ identifiers and attribution are available in the pre-removal Git revision
## [0.60.405.0] - 2026-10-23
-**Writes on Postgres no longer fail because a transaction-mode pooler handed gbrain a server connection that another client left read-only, a stall sweep no longer stops on a dead drain holder, and a job whose phase failed no longer ends `completed`.**
+**Writes on Postgres no longer fail because a transaction-mode pooler handed gbrain a server connection that another client left read-only, and a job whose phase failed no longer ends `completed`.**
### What changed
| Situation | Before | Now |
|---|---|---|
| A pooled server connection defaults to read-only (another client's session-level `SET default_transaction_read_only = on`, or a role or database default) | sync, page writes, leases and the jobs queue failed with SQLSTATE 25006, reported as `storage_error` or `internal_error` | every transaction gbrain opens declares `READ WRITE`, an autocommit statement refused with 25006 runs once more inside a read-write transaction, and a refusal that persists (a read-only server) is `connection_inherited_read_only` in write receipts, `gbrain sync status` and the error envelope |
-| A drain-lease holder died without deleting its `gbrain-drain-lease` row | every stall sweep aborted on a table constraint, so jobs with expired locks stayed `active` | the sweep drops holder rows whose holder stopped renewing and reclaims stalled jobs |
| A job handler's result reports a failed phase, or a `failed` / `blocked_by_failures` status | the job ended `completed` | it ends `failed` (no retry); its error names the phase, and its result keeps `job_outcome` (`phase_failed` with `failed_phase`, or `failed`) |
| An `autopilot-cycle` job ends `phase_failed` | n/a | it does not count toward the source failure cooldown; a thrown handler, a timeout or stall and `blocked_by_failures` still do |
diff --git a/docs/architecture/key-files/core-minions-2.md b/docs/architecture/key-files/core-minions-2.md
index 98a4249cde..594b042817 100644
--- a/docs/architecture/key-files/core-minions-2.md
+++ b/docs/architecture/key-files/core-minions-2.md
@@ -3,7 +3,7 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `src/core/minions/queue.ts` — MinionQueue class (submit, claim, complete, fail, stall detection, parent-child, depth/child-cap, per-job timeouts, cascade-kill, attachments, idempotency keys, child_done inbox, removeOnComplete/Fail). `prune()` archives each completed `dream:synth%` subagent key into `dream_synthesis_completions` in the same statement that deletes the row, so pruning never re-arms paid synthesis. `add()` takes a 4th `trusted` arg (separate from `opts` to prevent spread leakage); protected names in `PROTECTED_JOB_NAMES` require `{allowProtectedSubmit: true}` and the check runs trim-normalized (whitespace-bypass safe). The same trusted arg carries `{allowPgliteInlineWorker: true}`, a narrowly scoped exception used only when `gbrain jobs submit embed-backfill --follow` starts and awaits a worker in that process. Before config, schema, policy, SQL, or transaction access, `add()` invokes the centralized embed-backfill admission gate; PGLite and unknown engine kinds refuse, while explicit Postgres preserves queued submission. `add()` plumbs `max_stalled` through with a `[1, 100]` clamp; omitted values let the schema DEFAULT (5) kick in. `handleWallClockTimeouts(lockDurationMs)` is Layer 3 kill shot for jobs where `FOR UPDATE SKIP LOCKED` stall detection and the timeout sweep both fail to evict (wedged worker holding a row lock via a pending transaction). The submission backpressure guard covers two options sharing one `pg_advisory_xact_lock` namespace keyed on `(name, queue, source)`: `maxWaiting` (rate cap, counts `waiting` only, NULL-source-as-wildcard scope) and `maxPending` (single-flight, counts `waiting` + live-lock `active` rows where `lock_until > now()`, EXACT source scope via `COALESCE(data->>'sourceId', data->>'source_id')` — an expired-lock active never suppresses, keeping the waitingClaimable wedge detectors fed). All three coalesce return paths (idempotency fast-path, cap-hit, ON CONFLICT race fallback) stamp non-persisted `coalesced: true` metadata on the returned job. Both filter on `queue` in addition to `name` so cross-queue same-name jobs don't suppress each other. `claim` and `renewLock` issue their UPDATE via `engine.executeRawDirect` (not `executeRaw`) so the lock heartbeat runs on the direct session-mode pool that the transaction pooler won't recycle mid-hold; on PGLite this is identical to `executeRaw`. The two terminal dead-letter paths (`handleWallClockTimeouts` wall-clock kill and the stall dead-letter CTE in the stall sweep) BOTH increment `attempts_made` so a long job killed there reads as an honest attempt instead of `attempts 0 / started N`; the stall path also bumps `stalled_counter`, surfaced by `gbrain jobs get` as `Attempts: M/N (started: X, stalled: S/MaxS)`. At submit, `add()` stamps a default `timeout_ms` via `defaultTimeoutMsFor(jobName)` (from `handler-timeouts.ts`) when the caller passed none, and `claim()` COALESCEs a still-NULL `timeout_ms` from `HANDLER_DEFAULT_TIMEOUT_MS` (raw-object jsonb bind) deriving `timeout_at` from the coalesced value — the durable invariant covering rows that predate submit-time stamping; an explicit `opts.timeout_ms` always wins. The lock lease follows the identical three-layer shape: `add()` stamps `opts.lock_duration_ms` (clamped [5s,1h] via the shared `clampLockDurationMs`; INSERT-only — an idempotency-key re-submit never mutates the first submitter's lease) else `defaultLockDurationMsFor(jobName)`; `claim()` derives `lock_until` from `COALESCE(lock_duration_ms, map, worker default)` and stamps the resolved lease, SQL-clamping the row/map-resolved value to [5s,1h] (the worker-default fallback passes through unclamped — operator-configured, and tests legitimately use sub-5s leases) so a bypass-written out-of-range row can't produce a pathological lease; `handleWallClockTimeouts`' null-timeout fallback uses `COALESCE(lock_duration_ms, worker default)`. `handleStalled(graceMsOverride?)` applies the stall-sweep reclaim grace (`GBRAIN_MINION_STALL_RECLAIM_GRACE_MS`, default 15s, 0 = legacy predicate, capped at 600s with a warn-once clamp so an oversized value can't disable stalled-job recovery) to all three sweep predicates — a lease that lapsed within the grace is a starved owner's head start, not a steal candidate. Guarded by `test/queue-lock-retry.test.ts` (claim never falls back to `executeRaw`), `test/postgres-execute-raw-direct.test.ts` (routing decision matrix), and `test/minions.test.ts` (attempt accounting + default-timeout stamping). `MinionQueue.add()` gates `subagent` jobs on capability, not provider: `data.model` is classified via `classifyCapabilities()` (lazy-imported from `src/core/ai/capabilities.ts` to keep queue's eager-load surface small) and rejected only when the model cannot run a tool loop (`unusable:no_tools`) or names an unknown provider; degraded verdicts pass through with a gateway cost warning. Layer 1 of the three-layer subagent capability enforcement (layers 2+3: `model-config.ts:enforceSubagentCapable` runtime fallback + `src/commands/doctor/checks/search-eval.ts` `subagent_capability` check). Pinned by `test/agent-cli.test.ts`. All three terminal reaper paths (stall dead-letter, wall-clock kill, cascade) route through the ONE private `killJobs(tx, rows, cause, message)` tail: it emits `child_done(outcome)` to each non-terminal parent's inbox and flips any `waiting-children` parent whose last open child just died back to `waiting` — so a dead-lettered child can never strand its aggregator parent. Callers lock parents FIRST via `lockParentsOrdered` (ascending-id row locks, matching `failJob`'s parent-before-child order) so the reapers and `failJob` can never deadlock on parent/child lock acquisition. An idempotent stranded-parent sweep runs once per stall tick (~30s): any `waiting-children` parent with zero non-terminal children flips back to `waiting` (single UPDATE, NOT EXISTS on an indexed FK) — self-heals every stranding class, including parents stranded before the sweep existed. Every automatic re-run path clears `started_at` (`failJob`'s delayed retry branch, the stall requeue, lease release, `promoteDelayed`, and the parent-unblock flips) so the per-attempt wall clock measures execution, not backoff/queue wait — a retried job can't be dead-lettered by the wall-clock sweep before executing a line. Pinned by `test/queue-stall-parent-unblock.test.ts` + `test/queue-started-at-retry.test.ts`. `renewLock` accepts optional `{signal}` forwarded to executeRawDirect so the renewal tick's timeout race CANCELS a hung UPDATE instead of orphaning a checked-out pool slot (best-effort — the token fence is the correctness authority; a late-landing renewal can only extend a lease nobody else claimed). Re-submitting an idempotency key held by a dead or cancelled row nulls that row's key and records it as `data.__released_idempotency_key`, so the dream paid-loop breaker and daily cap still see the death. The trusted arg's `spendAuthorization` stores a consent-gated producer's record in `spend_authorization` (never job data); a coalesced live row with no record or a `legacy_default` record adopts it by compare-and-set, an `authorized` row keeps its own. `claim()` sets `spend_claim_token = claim_generation + 1` (the fence the protocol trigger requires for spend-authorized rows, so older workers cannot claim them) and stamps NULL rows of `book-mirror:`/`enrich:`/`cli:enrich:` keys `legacy_default` in the same UPDATE. `claim(..., { excludeWatchdogSuspects })` skips jobs carrying `WATCHDOG_SUSPECT_MARK` (re-exported from `watchdog-attribution.ts`) for a worker with jobs in flight; `releaseWatchdogClaim` is the token-fenced uncharged release; `handleStalled` first passes its candidates to `requeueCoRunnerStalls`. A drain-lease holder row (`gbrain-drain-lease` queue, written by `persistence/sync-lease.ts`, never claimed so `attempts_started` 0) is not a job: `handleStalled` deletes one whose lock expired past the grace and returns it as `released`, and every sweep skips the queue, because dead-lettering it (`attempts_made + 1`) breaks `chk_attempts_order` and aborts the whole sweep (#7187, #7261; pinned by `test/minions-drain-holder-sweeps-7187.test.ts`). #7240: `add` passes job data through `jsonbSafeJson` (text-safe.ts: lone UTF-16 surrogates and U+0000 become U+FFFD), because Postgres refuses either inside a JSONB value (22P02/22P05) and one such character refused the whole insert; `failJob` takes an optional `result` (a refused job's `refusal`, #7239).
+- `src/core/minions/queue.ts` — MinionQueue class (submit, claim, complete, fail, stall detection, parent-child, depth/child-cap, per-job timeouts, cascade-kill, attachments, idempotency keys, child_done inbox, removeOnComplete/Fail). `prune()` archives each completed `dream:synth%` subagent key into `dream_synthesis_completions` in the same statement that deletes the row, so pruning never re-arms paid synthesis. `add()` takes a 4th `trusted` arg (separate from `opts` to prevent spread leakage); protected names in `PROTECTED_JOB_NAMES` require `{allowProtectedSubmit: true}` and the check runs trim-normalized (whitespace-bypass safe). The same trusted arg carries `{allowPgliteInlineWorker: true}`, a narrowly scoped exception used only when `gbrain jobs submit embed-backfill --follow` starts and awaits a worker in that process. Before config, schema, policy, SQL, or transaction access, `add()` invokes the centralized embed-backfill admission gate; PGLite and unknown engine kinds refuse, while explicit Postgres preserves queued submission. `add()` plumbs `max_stalled` through with a `[1, 100]` clamp; omitted values let the schema DEFAULT (5) kick in. `handleWallClockTimeouts(lockDurationMs)` is Layer 3 kill shot for jobs where `FOR UPDATE SKIP LOCKED` stall detection and the timeout sweep both fail to evict (wedged worker holding a row lock via a pending transaction). The submission backpressure guard covers two options sharing one `pg_advisory_xact_lock` namespace keyed on `(name, queue, source)`: `maxWaiting` (rate cap, counts `waiting` only, NULL-source-as-wildcard scope) and `maxPending` (single-flight, counts `waiting` + live-lock `active` rows where `lock_until > now()`, EXACT source scope via `COALESCE(data->>'sourceId', data->>'source_id')` — an expired-lock active never suppresses, keeping the waitingClaimable wedge detectors fed). All three coalesce return paths (idempotency fast-path, cap-hit, ON CONFLICT race fallback) stamp non-persisted `coalesced: true` metadata on the returned job. Both filter on `queue` in addition to `name` so cross-queue same-name jobs don't suppress each other. `claim` and `renewLock` issue their UPDATE via `engine.executeRawDirect` (not `executeRaw`) so the lock heartbeat runs on the direct session-mode pool that the transaction pooler won't recycle mid-hold; on PGLite this is identical to `executeRaw`. The two terminal dead-letter paths (`handleWallClockTimeouts` wall-clock kill and the stall dead-letter CTE in the stall sweep) BOTH increment `attempts_made` so a long job killed there reads as an honest attempt instead of `attempts 0 / started N`; the stall path also bumps `stalled_counter`, surfaced by `gbrain jobs get` as `Attempts: M/N (started: X, stalled: S/MaxS)`. At submit, `add()` stamps a default `timeout_ms` via `defaultTimeoutMsFor(jobName)` (from `handler-timeouts.ts`) when the caller passed none, and `claim()` COALESCEs a still-NULL `timeout_ms` from `HANDLER_DEFAULT_TIMEOUT_MS` (raw-object jsonb bind) deriving `timeout_at` from the coalesced value — the durable invariant covering rows that predate submit-time stamping; an explicit `opts.timeout_ms` always wins. The lock lease follows the identical three-layer shape: `add()` stamps `opts.lock_duration_ms` (clamped [5s,1h] via the shared `clampLockDurationMs`; INSERT-only — an idempotency-key re-submit never mutates the first submitter's lease) else `defaultLockDurationMsFor(jobName)`; `claim()` derives `lock_until` from `COALESCE(lock_duration_ms, map, worker default)` and stamps the resolved lease, SQL-clamping the row/map-resolved value to [5s,1h] (the worker-default fallback passes through unclamped — operator-configured, and tests legitimately use sub-5s leases) so a bypass-written out-of-range row can't produce a pathological lease; `handleWallClockTimeouts`' null-timeout fallback uses `COALESCE(lock_duration_ms, worker default)`. `handleStalled(graceMsOverride?)` applies the stall-sweep reclaim grace (`GBRAIN_MINION_STALL_RECLAIM_GRACE_MS`, default 15s, 0 = legacy predicate, capped at 600s with a warn-once clamp so an oversized value can't disable stalled-job recovery) to all three sweep predicates — a lease that lapsed within the grace is a starved owner's head start, not a steal candidate. Guarded by `test/queue-lock-retry.test.ts` (claim never falls back to `executeRaw`), `test/postgres-execute-raw-direct.test.ts` (routing decision matrix), and `test/minions.test.ts` (attempt accounting + default-timeout stamping). `MinionQueue.add()` gates `subagent` jobs on capability, not provider: `data.model` is classified via `classifyCapabilities()` (lazy-imported from `src/core/ai/capabilities.ts` to keep queue's eager-load surface small) and rejected only when the model cannot run a tool loop (`unusable:no_tools`) or names an unknown provider; degraded verdicts pass through with a gateway cost warning. Layer 1 of the three-layer subagent capability enforcement (layers 2+3: `model-config.ts:enforceSubagentCapable` runtime fallback + `src/commands/doctor/checks/search-eval.ts` `subagent_capability` check). Pinned by `test/agent-cli.test.ts`. All three terminal reaper paths (stall dead-letter, wall-clock kill, cascade) route through the ONE private `killJobs(tx, rows, cause, message)` tail: it emits `child_done(outcome)` to each non-terminal parent's inbox and flips any `waiting-children` parent whose last open child just died back to `waiting` — so a dead-lettered child can never strand its aggregator parent. Callers lock parents FIRST via `lockParentsOrdered` (ascending-id row locks, matching `failJob`'s parent-before-child order) so the reapers and `failJob` can never deadlock on parent/child lock acquisition. An idempotent stranded-parent sweep runs once per stall tick (~30s): any `waiting-children` parent with zero non-terminal children flips back to `waiting` (single UPDATE, NOT EXISTS on an indexed FK) — self-heals every stranding class, including parents stranded before the sweep existed. Every automatic re-run path clears `started_at` (`failJob`'s delayed retry branch, the stall requeue, lease release, `promoteDelayed`, and the parent-unblock flips) so the per-attempt wall clock measures execution, not backoff/queue wait — a retried job can't be dead-lettered by the wall-clock sweep before executing a line. Pinned by `test/queue-stall-parent-unblock.test.ts` + `test/queue-started-at-retry.test.ts`. `renewLock` accepts optional `{signal}` forwarded to executeRawDirect so the renewal tick's timeout race CANCELS a hung UPDATE instead of orphaning a checked-out pool slot (best-effort — the token fence is the correctness authority; a late-landing renewal can only extend a lease nobody else claimed). Re-submitting an idempotency key held by a dead or cancelled row nulls that row's key and records it as `data.__released_idempotency_key`, so the dream paid-loop breaker and daily cap still see the death. The trusted arg's `spendAuthorization` stores a consent-gated producer's record in `spend_authorization` (never job data); a coalesced live row with no record or a `legacy_default` record adopts it by compare-and-set, an `authorized` row keeps its own. `claim()` sets `spend_claim_token = claim_generation + 1` (the fence the protocol trigger requires for spend-authorized rows, so older workers cannot claim them) and stamps NULL rows of `book-mirror:`/`enrich:`/`cli:enrich:` keys `legacy_default` in the same UPDATE. `claim(..., { excludeWatchdogSuspects })` skips jobs carrying `WATCHDOG_SUSPECT_MARK` (re-exported from `watchdog-attribution.ts`) for a worker with jobs in flight; `releaseWatchdogClaim` is the token-fenced uncharged release; `handleStalled` first passes its candidates to `requeueCoRunnerStalls`. #7240: `add` passes job data through `jsonbSafeJson` (text-safe.ts: lone UTF-16 surrogates and U+0000 become U+FFFD), because Postgres refuses either inside a JSONB value (22P02/22P05) and one such character refused the whole insert; `failJob` takes an optional `result` (a refused job's `refusal`, #7239).
- `src/core/minions/queue-families.ts` — `queueFamilyStats(engine, since)` behind `MinionQueue.getStats().by_queue`: one row per queue (`waiting_now`/`active_now` now; `total`/`completed`/`failed`/`dead` among rows created in the window, the `by_type` semantics), with every per-run `dream-inline-*` queue folded into one `dream-inline` row whose `queues` counts them. `gbrain jobs stats` prints a line per row (`dream-inline (N queues)`) and carries `by_queue` in `--json`; `get_job_stats` spreads it too. `--queue <name>` still scopes the wedge block to one queue. Test: `test/jobs-stats-private-queue.serial.test.ts`.
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 28aa2a357f..a812868a15 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -24,7 +24,7 @@ src/core/pglite-engine.ts 3087 ratchet +5 agent operator gate fixes: repair-fail
src/core/postgres-engine.ts 3135 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107); +3 #7159: the frontmatter where clause in the two keyword typesClause sites and its import (SQL in search/frontmatter-where.ts; engine methods cannot move); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (3114 measured); +2 warm CLI socket (#7218): connectedDatabaseUrl getter (the URL the engine connected with, bound into the socket identity), composed over the GBRA-156 retrieval wave (3116 measured); +1 GBRA-133 PR 2b: transactionOn hands the outermost transaction its commit checks (page-state/transactions.ts withCommitChecks), composed with the warm CLI socket at the merge (3117 measured); +18 GBRA-156: the private readTransaction helper behind withScopedReadTransaction and jitOffRead answers a top-level read before its COMMIT settles (engine methods cannot move; 3135 measured); +1 GBRA-156: transactionOn and runUnsafe hold a per-search connection slot (import of search/connection-budget.ts; 3136 measured); +2 GBRA-156: transactionOn passes TransactionOptions.pipelineFirst to the pool begin as { first } (driver gate in vendor/postgres index.js begin); an engine method cannot move; composed with the warm CLI socket and GBRA-133 PR 2b at the master v0.60.344.0 merge (3119 measured); GBRA-151 #7183/#7187/#7188 re-summed at the v0.60.402.0 merge (3135 measured)
src/core/search/hybrid.ts 1562 ratchet +5 GBRA-81 item 5 per-stage search timings: HybridSearchOpts._timings (interface field) and the timer bindings and import in hybridSearch/hybridSearchCached (collector logic in search/stage-timings.ts); +2 W5 page-unit ranking cut: HybridSearchOpts.pageRankCut (logic in search/page-rank-cut.ts); +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured); +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook); lowered to 1562: LHF wave 2 item 3 peeled cosineReScore into search/cosine-rescore.ts
src/core/types.ts 2347 ratchet +4 Wave B PR 1 (1c): Page.body_storage/body_bytes (interface fields; guard logic in page-body/page-shape.ts); +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc); +11 large pages (Wave A): Chunk/ChunkInput projected_byte_start/end interface fields (span logic in chunkers/recursive.ts, page-window/document.ts); +4 wave 18b lane 2 (#6495): SearchOpts.keywordTimeoutCache, the skipped_after_timeout degraded reason and the useCache doc line; integrated at wave 18b: master 2319 + 4; +2 LHF wave 2 item 3: retrieval meta cosine_rescore field (js_fallback disclosure; logic in search/cosine-rescore.ts); +14 GBRA-154 ranking wave (#4612 #7153 #7156 #7162 #7164): SearchResult collapsed/redirect_to/image_page/rank_prior/rank_score/fused_score stamps and HybridSearchMeta.collapse (interface fields; logic in search/collapse.ts, rank-priors.ts, score-contract.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (2343 measured); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (2345 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.338.0 merge (2347 measured)
-src/core/minions/queue.ts 2547 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts); +5 GBRA-130 A-30: claim excludeWatchdogSuspects option (signature, doc and the mark parameter), the releaseWatchdogClaim delegate, and the co-runner stall call site in handleStalled (logic in minions/watchdog-attribution.ts); +5 GBRA-158 #7239/#7240: failJob result parameter (the #7216 hunk), jsonbSafeJson import and its call in add (sanitizer in text-safe.ts); +2 #7242 lane reservation: claim excludeNames option (doc line and the bound array; policy in minions/lanes.ts); +1 #7241 submitter label import (job-insight.ts) + 1 queue-families type import; #7252 x #7249 merge: both sides grew the file, re-summed (2544 measured); GBRA-151 #7183/#7187/#7188 re-summed at the v0.60.402.0 merge (2547 measured)
+src/core/minions/queue.ts 2544 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts); +5 GBRA-130 A-30: claim excludeWatchdogSuspects option (signature, doc and the mark parameter), the releaseWatchdogClaim delegate, and the co-runner stall call site in handleStalled (logic in minions/watchdog-attribution.ts); +5 GBRA-158 #7239/#7240: failJob result parameter (the #7216 hunk), jsonbSafeJson import and its call in add (sanitizer in text-safe.ts); +2 #7242 lane reservation: claim excludeNames option (doc line and the bound array; policy in minions/lanes.ts); +1 #7241 submitter label import (job-insight.ts) + 1 queue-families type import; #7252 x #7249 merge: both sides grew the file, re-summed (2544 measured)
src/commands/init.ts 1884 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts); +4 GBRA-81 item 1: --search-mode value flag, its parse line, module-level choice, help line (picker logic lives in init-mode-picker.ts); +2 D8 funnel: a fresh init counts one clean_install when the opt-in funnel is on (core/funnel.ts)
src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)
src/core/minions/handlers/subagent.ts 1925 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch; +7 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms read once and passed to the oneshot and gateway-loop paths (resolver lives in minions/handler-timeouts.ts)
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index f1d5a8da17..769aa66b70 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1037,7 +1037,6 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.330.0', text: 'The autopilot purge phase and the `purge` job no longer hard-delete a page that a managed sync soft-deleted unless another live page of the same source has identical content (#7130). Each sync deletion now leaves a durable record (op_checkpoints `sync-delete-tombstone`; a tombstone from before this release is recognized by its uncompacted `managed_sync_delete` receipt, and one whose receipt was compacted is not). Held pages are reported as `sync_delete_unreviewed` in the phase\'s `purged_pages_blocked` and counted in `held`, and the phase reports warn. `gbrain pages purge-deleted` still purges them after consent: its dry run reports `sync_unreviewed` and its consent text names how many of the set are sync deletions with no live twin and that a purged page can only come back from a backup. The purge phase\'s recovery window (pages and orphan clone temp dirs), and the `purge` job\'s default, now follow `purge.retention_hours` instead of a fixed 72 hours. It can only lengthen the window (default and minimum 72, so a 72-hour restore promise always holds); `gbrain config set` refuses a smaller value.' },
{ since: '0.60.330.0', text: 'New doctor check `uncommitted_sync_deletions` and explicit-only repair kind `gbrain repair uncommitted-deletions --source <id>` (#7130): on each managed source\'s owner host, doctor warns about soft-deleted pages a sync removed although Git never held their recorded file (`.gitignore` excludes it, or no commit holds it and it is not on the disk), bounded to 20,000 tombstones per source and 2,000 Git evidence reads per run. The repair previews each page (slug, recorded path, deletion time, evidence, whether a sync deleted it) with a hash; `--apply --expect <hash> --yes` restores exactly that set, each page live and database-only (detached: it forgets its recorded file and no file is written), so the next sync keeps it. Pages another writer deleted join only with `--include-ambiguous`; a sync deletion is recognized by its record or receipt for the page\'s current tombstone. A preview reads one bounded window, newest page id first, and `--after <page-id>` (named in the preview\'s `next_after` and in the doctor message) continues past it. It refuses off the owner host (`not_owner_host`) and a changed plan (`preview_changed`); without `--yes` a non-interactive run exits 3 and changes nothing. Pages already purged cannot be restored by this command; only a backup (pg_dump, or `gbrain backup create`) can bring them back. It never runs on upgrade or automatically.' },
{ since: '0.60.405.0', text: 'On Postgres, gbrain opens its transactions READ WRITE and runs an autocommit statement refused as read-only (SQLSTATE 25006) once more inside a READ WRITE transaction, so a server connection whose default is read-only (a session-level SET another client left on a transaction-mode pooler connection, or a role or database default) no longer stops sync, page writes, leases or the jobs queue. A refusal that persists (a read-only server) is now `connection_inherited_read_only` in the write receipt, `gbrain sync status` (systemic, needs the database operator) and the CLI and MCP error envelope, instead of `storage_error` or `internal_error`. Deliberately read-only transactions (graduation, export, sync pass reads) stay read-only.' },
- { since: '0.60.405.0', text: 'The worker stall detector no longer stops when a drain lease holder died without deleting its `gbrain-drain-lease` row: dead-lettering that row broke a table constraint and aborted every sweep, so every job left `active` with an expired lock stayed there. The sweep now deletes a holder row whose holder stopped renewing it (logged as dropped holder rows) and reclaims stranded jobs as before, and the wall-clock timeout sweep skips holder rows, which it used to fail on during any drain longer than its threshold.' },
{ since: '0.60.405.0', text: 'A Minions job whose handler result reports a failed phase or a `failed` / `blocked_by_failures` status now ends `failed` (no retry) instead of `completed`: its error names the phase, code and message, and its result is kept with `job_outcome` set (`phase_failed` plus `failed_phase` for a failed phase, `failed` otherwise); under `on_child_fail: fail_parent` it fails its parent. An `autopilot-cycle` job that ended `phase_failed` does not count toward the source failure cooldown, so one failing phase never backs off a source (or stops its sync); a thrown handler, a timeout or stall, and `blocked_by_failures` still do. A result that reports unfinished work without a failure (`status: partial` or `partial: true`) still completes, with `job_outcome: "partial"` added. Skips and clean results are unchanged.' },
// Wave B follow-ups lane F2 (#7106: a managed import or sync of a new page over 4 MiB replies at commit). `since` is stamped at the merge slot.
{ since: '0.60.331.0', text: 'A managed `gbrain import` or `gbrain sync` of a new page over 4 MiB stored in segments now replies when the write commits, before its search index is built, instead of waiting for that build (which on a loaded host outlasted the 30 s import wait and replied `write_pending`). The import result and the write\'s receipt say `searchable: "pending"` and `projection: "pending"`; the import result also carries the `request_id`, `searchable_retry_after_ms` and `searchable_fix`. Read the receipt again (`gbrain write-request -- <request_id>`, `get_write_request`) at that interval until it says `searchable: true`; search finds the page from then on. The build no longer holds up the source\'s next write either. A new page up to 4 MiB, and an edit of a page stored in segments, is still searchable when its import replies (`searchable: true`). A `put_page` of a new page over 4 MiB, whose receipt already said `searchable: "pending"`, now also replies at commit instead of after the build.' },
diff --git a/src/core/minions/drain-holder-rows.ts b/src/core/minions/drain-holder-rows.ts
deleted file mode 100644
index d9baa3b2c9..0000000000
--- a/src/core/minions/drain-holder-rows.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-/**
- * #7187: a drain lease's holder row (persistence/sync-lease.ts) is an `active` minion_jobs row in the
- * `gbrain-drain-lease` queue that no worker claims (attempts_started 0), renewed with the lease. It is not a job:
- * dead-lettering it (`attempts_made + 1`) breaks chk_attempts_order and aborts the whole sweep transaction, so the
- * stall sweep deletes one whose holder stopped renewing it and both sweeps leave the queue out of their candidates.
- */
-import type { BrainEngine } from '../engine.ts';
-import { LEASE_BEACON_QUEUE } from './protected-names.ts';
-import { rowToMinionJob, type MinionJob } from './types.ts';
-
-export { LEASE_BEACON_QUEUE as HOLDER_ROW_QUEUE };
-
-/** Delete the holder rows whose lock expired more than `graceMs` ago; returns them. */
-export async function releaseExpiredHolderRows(tx: Pick<BrainEngine, 'executeRaw'>, graceMs: number): Promise<MinionJob[]> {
- const rows = await tx.executeRaw<Record<string, unknown>>(
- `DELETE FROM minion_jobs WHERE id IN (
- SELECT id FROM minion_jobs WHERE queue = $1 AND status = 'active'
- AND lock_until < now() - ($2::double precision * interval '1 millisecond') FOR UPDATE SKIP LOCKED)
- RETURNING *`,
- [LEASE_BEACON_QUEUE, graceMs]);
- if (rows.length > 0) console.log(`Stall detector: dropped ${rows.length} drain-lease holder rows whose holder stopped renewing them`);
- return rows.map(rowToMinionJob);
-}
diff --git a/src/core/minions/queue.ts b/src/core/minions/queue.ts
index e48a8b65b0..7ec721c87c 100644
--- a/src/core/minions/queue.ts
+++ b/src/core/minions/queue.ts
@@ -16,7 +16,6 @@ import type {
} from './types.ts';
import { rowToMinionJob, rowToInboxMessage, rowToAttachment } from './types.ts';
import { WATCHDOG_SUSPECT_MARK, releaseWatchdogClaim, requeueCoRunnerStalls, unmarkedJobSql } from './watchdog-attribution.ts';
-import { releaseExpiredHolderRows } from './drain-holder-rows.ts';
export { WATCHDOG_SUSPECT_MARK } from './watchdog-attribution.ts';
import { coalesceOnIdempotencyKey, decideCoalesce, insertOrCoalesce } from './idempotency-coalesce.ts';
import { withSubmitterLabel } from './job-insight.ts';
@@ -1657,7 +1656,6 @@ export class MinionQueue {
* Threshold (ms):
* timeout_ms set -> timeout_ms * 2
* timeout_ms null -> 2 * lockDurationMs * max_stalled
- * Drain-lease holder rows are not jobs (drain-holder-rows.ts).
*/
async handleWallClockTimeouts(lockDurationMs: number): Promise<MinionJob[]> {
await assertNoUnreviewedJobs(this.engine);
@@ -2137,8 +2135,8 @@ export class MinionQueue {
return rows.map(rowToMinionJob);
}
- /** Detect and handle stalled jobs. Single CTE, no off-by-one. Returns affected jobs; `released`: dropped holder rows (drain-holder-rows.ts). */
- async handleStalled(graceMsOverride?: number): Promise<{ requeued: MinionJob[]; dead: MinionJob[]; released: MinionJob[] }> {
+ /** Detect and handle stalled jobs. Single CTE, no off-by-one. Returns affected jobs. */
+ async handleStalled(graceMsOverride?: number): Promise<{ requeued: MinionJob[]; dead: MinionJob[] }> {
await assertNoUnreviewedJobs(this.engine);
// W0 fix-wave (Tier-1 #4): the dead-letter branch previously emitted NO
// child_done and never unblocked aggregator parents — a child that died
@@ -2152,7 +2150,6 @@ export class MinionQueue {
// override; the worker sweep resolves from env/default.
const graceMs = graceMsOverride ?? resolveStallReclaimGraceMs();
return this.engine.transaction(async (tx) => {
- const released = await releaseExpiredHolderRows(tx, graceMs);
const candidates = await tx.executeRaw<{ id: number; parent_job_id: number | null; stalled_counter: number; max_stalled: number }>(
`SELECT id, parent_job_id, stalled_counter, max_stalled
FROM minion_jobs
@@ -2160,7 +2157,7 @@ export class MinionQueue {
AND lock_until < now() - ($1::double precision * interval '1 millisecond')`,
[graceMs]
);
- if (candidates.length === 0) return { requeued: [], dead: [], released };
+ if (candidates.length === 0) return { requeued: [], dead: [] };
// GBRA-130 A-30: the claims of a worker that held several (a kernel OOM kill) requeue marked, no stall counted.
const coRunners = await requeueCoRunnerStalls(tx, candidates, graceMs);
const ids = coRunners.rest.map(c => c.id);
@@ -2207,7 +2204,7 @@ export class MinionQueue {
// other terminal kill. Outcome 'dead' (not 'timeout') so consumers can
// distinguish "died via max-stall" from "timed out during run".
await this.killJobs(tx, deadRows, 'dead', 'max stalled count exceeded');
- return { requeued: [...coRunners.requeued, ...requeuedRows].map(rowToMinionJob), dead: deadRows.map(rowToMinionJob), released };
+ return { requeued: [...coRunners.requeued, ...requeuedRows].map(rowToMinionJob), dead: deadRows.map(rowToMinionJob) };
}).then(async (result) => {
// W0 ship-review (data-migration): the per-kill unblock above is
// forward-only — parents stranded in 'waiting-children' by PRE-upgrade
diff --git a/src/core/persistence/sync-lease.ts b/src/core/persistence/sync-lease.ts
index a6933ac989..0c93c7186a 100644
--- a/src/core/persistence/sync-lease.ts
+++ b/src/core/persistence/sync-lease.ts
@@ -230,9 +230,8 @@ export interface DrainLeaseOptions {
/**
* The holder record: one `gbrain-drain-lease` minion row per lease, keyed by the lease token, carrying the holder's
* kind, id and version. It doubles as the beacon an older binary's `liveSyncJob` sees, so an older autopilot backs off
- * while any holder drains. Application authority keeps it out of the unreviewed-job gate. It is renewed with the lease
- * and deleted on release; the worker's stall sweep deletes the row of a holder that stopped renewing it, and the
- * wall-clock sweep skips it (MinionQueue.handleStalled, #7187).
+ * while any holder drains. Application authority keeps it out of the unreviewed-job gate; `max_stalled` 0 and
+ * `remove_on_fail` drop a dead holder's row instead of queueing it. It is renewed with the lease and deleted on release.
*/
async function writeHolderRecord(engine: BrainEngine, sourceId: string, lease: DrainLease, holder: DrainHolderRef): Promise<void> {
// One statement: the insert reads the delete's count, so a former holder's row goes first.
diff --git a/test/e2e/pooler-inherited-read-only-7183.test.ts b/test/e2e/pooler-inherited-read-only-7183.test.ts
index b746885c9f..690ccdde16 100644
--- a/test/e2e/pooler-inherited-read-only-7183.test.ts
+++ b/test/e2e/pooler-inherited-read-only-7183.test.ts
@@ -1,5 +1,5 @@
/**
- * #7183 / #7187: gbrain writes through server connections whose transactions default to read-only.
+ * #7183: gbrain writes through server connections whose transactions default to read-only.
*
* A client that runs a session-level `SET default_transaction_read_only = on` through a transaction-mode pooler can
* leave that default on a server connection other clients then borrow; a role or database default does the same for
@@ -7,7 +7,8 @@
* session leak itself depends on the pooler build: PgBouncer 1.26 restores this setting per client), connects a fresh
* engine (through PgBouncer in the backend matrix's pooled pass), and checks that the engine's transactions, its
* autocommit statements, the database lease and the Minions queue still write, and that the stall detector reclaims an
- * `active` job left with an expired lock by a worker that died on the refused writes (#7187).
+ * `active` job left with an expired lock by a worker that died on the refused writes, leaving the drain-lease
+ * holder record to its lease (#7261).
*
* Listed in scripts/e2e-backend-matrix.txt: run once on direct Postgres and once through transaction-mode PgBouncer.
*/
@@ -107,7 +108,7 @@ describeDb(`writes on read-only-default server connections (${pooled ? 'pgbounce
expect((await queue.getJob(job.id))!.error_text).toBe('handler failure');
}, 60_000);
- test('#7187: the stall detector reclaims a job and drops a drain-lease holder row left active with expired locks', async () => {
+ test('the stall detector reclaims a job a worker left active with an expired lock, and leaves the drain-lease holder record (#7261)', async () => {
const job = await queue.add('ro-stuck', {}, { max_attempts: 3 });
const claimed = await queue.claim('dead-worker:1', 60_000, 'default', ['ro-stuck']);
expect(claimed?.id).toBe(job.id);
@@ -120,10 +121,10 @@ describeDb(`writes on read-only-default server connections (${pooled ? 'pgbounce
`INSERT INTO minion_jobs(name, queue, status, submission_authority, data, max_attempts, max_stalled, lock_token, lock_until, started_at, remove_on_complete, remove_on_fail)
VALUES ('sync', 'gbrain-drain-lease', 'active', '{"version":1,"kind":"application"}'::jsonb, '{"sourceId":"source-a"}'::jsonb, 1, 0,
'dead-lease-token', now() - interval '5 minutes', now() - interval '10 minutes', true, true) RETURNING id`);
- const { requeued, released } = await queue.handleStalled(0);
+ const { requeued, dead } = await queue.handleStalled(0);
expect(requeued.map(j => j.id)).toEqual([stuck.id]);
- expect(released.map(j => j.id)).toEqual([Number(beacon.id)]);
+ expect(dead).toEqual([]);
expect(await queue.getJob(stuck.id)).toMatchObject({ status: 'waiting', stalled_counter: 1, lock_token: null });
- expect(await queue.getJob(Number(beacon.id))).toBeNull();
+ expect(await queue.getJob(Number(beacon.id))).toMatchObject({ status: 'active', attempts_made: 0 });
});
});
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 423e28afd9..339a454488 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -6111,7 +6111,7 @@
"getJob: (id: number) => Promise<MinionJob | null>",
"getJobs: (opts?: { status?: MinionJobStatus; queue?: string; name?: string; limit?: number; offset?: number; ownerClientId?: string; }) => Promise<MinionJob[]>",
"getStats: (opts?: { since?: Date; queue?: string; }) => Promise<{ by_status: Record<string, number>; by_type: Array<{ name: string; total: number; completed: number; failed: number; dead: number; avg_duration_ms: number | null; drained_completed: number; drained_failed: number; drained_dead: number; drained_cancelled: number; waiting_now: number; oldest_waiting_minutes: number | null; }>; queue_health: { waiting: number; active: number; stalled: number; }; by_queue: QueueFamilyStats[]; wedge: { queue: string; active_healthy: number; waiting: number; last_completed_at: string | null; minutes_since_completion: number | null; }; }>",
- "handleStalled: (graceMsOverride?: number) => Promise<{ requeued: MinionJob[]; dead: MinionJob[]; released: MinionJob[]; }>",
+ "handleStalled: (graceMsOverride?: number) => Promise<{ requeued: MinionJob[]; dead: MinionJob[]; }>",
"handleTimeouts: () => Promise<MinionJob[]>",
"handleWaitingTTL: (opts?: { maxPerTick?: number; }) => Promise<{ cancelled: number; by_name: Record<string, number>; }>",
"handleWallClockTimeouts: (lockDurationMs: number) => Promise<MinionJob[]>",
diff --git a/test/minions-drain-holder-sweeps-7187.test.ts b/test/minions-drain-holder-sweeps-7187.test.ts
deleted file mode 100644
index 3860407745..0000000000
--- a/test/minions-drain-holder-sweeps-7187.test.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-/**
- * #7187: a drain lease's holder record (persistence/sync-lease.ts writeHolderRecord) is an `active` minion_jobs row in
- * the `gbrain-drain-lease` queue that no worker ever claims (attempts_started 0). The worker's sweeps dead-lettered it
- * with `attempts_made + 1`, which violates chk_attempts_order and aborted the whole sweep transaction on every tick: a
- * holder that died without deleting its row (its process died on refused writes, #7183) stopped the stall detector for
- * every job, and a live drain older than the wall-clock threshold stopped the wall-clock sweep.
- */
-import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
-import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import { MinionQueue } from '../src/core/minions/queue.ts';
-import { LEASE_BEACON_QUEUE } from '../src/core/persistence/sync-lease.ts';
-
-let engine: PGLiteEngine;
-let queue: MinionQueue;
-
-beforeAll(async () => {
- engine = new PGLiteEngine();
- await engine.connect({ database_url: '' });
- await engine.initSchema();
- queue = new MinionQueue(engine);
-});
-
-afterAll(async () => { await engine.disconnect(); });
-
-beforeEach(async () => { await engine.executeRaw('DELETE FROM minion_jobs'); });
-
-/** The row writeHolderRecord writes, with its lock renewed until `lockUntil`. */
-async function holderRow(token: string, lockUntil: string): Promise<number> {
- const [row] = await engine.executeRaw<{ id: number }>(
- `INSERT INTO minion_jobs(name, queue, status, submission_authority, data, max_attempts, max_stalled, lock_token, lock_until, started_at, remove_on_complete, remove_on_fail)
- VALUES ('sync', $1, 'active', '{"version":1,"kind":"application"}'::jsonb, '{"sourceId":"source-a"}'::jsonb, 1, 0, $2, ${lockUntil}, now() - interval '1 hour', true, true)
- RETURNING id`, [LEASE_BEACON_QUEUE, token]);
- return Number(row.id);
-}
-
-/** A claimed job whose worker died: its lock expired without renewal. */
-async function strandedJob(): Promise<number> {
- const job = await queue.add('stranded', {}, { max_attempts: 3 });
- expect((await queue.claim('dead-worker:1', 60_000, 'default', ['stranded']))?.id).toBe(job.id);
- await engine.executeRaw(`UPDATE minion_jobs SET lock_until = now() - interval '5 minutes', error_text = 'cannot execute INSERT in a read-only transaction' WHERE id = $1`, [job.id]);
- return job.id;
-}
-
-describe('#7187 drain-lease holder rows and the worker sweeps', () => {
- test('a dead holder row no longer stops the stall detector: the stranded job is reclaimed and the holder row dropped', async () => {
- const holder = await holderRow('dead-holder', "now() - interval '5 minutes'");
- const stranded = await strandedJob();
- const swept = await queue.handleStalled(0);
- expect(swept.requeued.map(j => j.id)).toEqual([stranded]);
- expect(swept.dead).toEqual([]);
- expect(swept.released.map(j => j.id)).toEqual([holder]);
- expect(await queue.getJob(stranded)).toMatchObject({ status: 'waiting', stalled_counter: 1, lock_token: null });
- expect(await queue.getJob(holder)).toBeNull();
- });
-
- test('a live holder row is left alone by the stall detector', async () => {
- const holder = await holderRow('live-holder', "now() + interval '5 minutes'");
- const swept = await queue.handleStalled(0);
- expect(swept).toEqual({ requeued: [], dead: [], released: [] });
- expect(await queue.getJob(holder)).toMatchObject({ status: 'active', lock_token: 'live-holder' });
- });
-
- test('a long-running live drain no longer stops the wall-clock sweep, and its holder row is not timed out', async () => {
- const holder = await holderRow('live-holder', "now() + interval '5 minutes'");
- const job = await queue.add('runaway', {}, { max_attempts: 3 });
- await queue.claim('worker-a:1', 60_000, 'default', ['runaway']);
- await engine.executeRaw(`UPDATE minion_jobs SET started_at = now() - interval '1 hour' WHERE id = $1`, [job.id]);
- const timedOut = await queue.handleWallClockTimeouts(30_000);
- expect(timedOut.map(j => j.id)).toEqual([job.id]);
- expect(await queue.getJob(holder)).toMatchObject({ status: 'active', lock_token: 'live-holder' });
- });
-});