Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(dream): stop extract_atoms on job timeout, lost cycle lock and deadline; window becomes a hard deadline (#5809, #5832)

garrytanab2f8d1aa81e
diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.md
index d9cd78cfb0..a1b11e2486 100644
--- a/docs/architecture/key-files/core-cycle.md
+++ b/docs/architecture/key-files/core-cycle.md
@@ -17,9 +17,9 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/cycle/extract-atoms-cost-gate.ts` — pure cost-gate decision for the extract_atoms `BudgetTracker`. `resolveExtractAtomsCostGate(extractModel, embedModel, overrides?, {explicitBudget?})` returns `{enforceCap, unpricedModel?, unpricedKind?, zeroPricedEmbedModel?, pricingOverrides?}`: the cap is enforceable only when EVERY model billed under the phase's tracker is priceable — the extraction chat model AND the embedding model the atom import (`importFromContent`, inside the same `withBudgetTracker` scope) calls — with operator `pricing.overrides` consulted first, matching `BudgetTracker.reserve()`. `resolveEmbedModelForCostGate()` mirrors the write site's `isAvailable('embedding')` gate (null when embedding is unavailable, so the import runs `noEmbed` and nothing embeds). Only a DEFAULT cap may be dropped that way: when the operator SET `cycle.extract_atoms.budget_usd` (`explicitBudget`), an unpriced EMBED route keeps the cap and is priced at $0 via the returned `pricingOverrides` (the caller's map plus the $0 row); an unpriced CHAT model drops the cap either way. The phase passes the decision into `maxCostUsd` and hands the gate's overrides (or its own) to the tracker; it warns once either way (unpriced: kind + model + the `pricing.overrides` remedy, running uncapped rather than latching `budget_exhausted` on the first item; zero-priced: the embed model + the rate remedy). Pinned by `test/extract-atoms-embed-cost-gate.test.ts` (pure cases + a PGLite round-trip with a $0 chat model and an unpriced embed route).
-- `src/core/cycle/extract-atoms-drain.ts` — pure single-hold bounded drain for the silent lens-phase backlog. `runExtractAtomsDrain(deps, opts)` over injected deps (`withLock`, `runBatch`, `countRemaining`, `now`, optional `onBatch`) loops bounded batches under ONE continuous lock hold, **rediscovering eligibility each batch** (idempotent NOT-EXISTS-on-`source_hash`, so content mutated by a concurrent process simply doesn't match — no cross-window stale cursor), until the backlog is empty OR the time window elapses. Returns `{phase, status, extracted, skipped, remaining, batches, stopped}`. Backs `gbrain dream --phase extract_atoms --drain`. Takes the SAME `cycleLockIdFor(sourceId)` the routine cycle takes (a concurrent autopilot tick genuinely defers with `cycle_already_running`); NO release/reacquire-between-windows primitive. The shared wiring helper `runExtractAtomsDrainForSource(engine, {sourceId, windowSeconds, brainDir?, maxBatches?, onBatch?})` owns the lock+batch+count+defer wiring (dynamic imports of db-lock/cycle/extract-atoms keep the pure loop cheap to unit-test) and is the ONE drain path for three callers — `gbrain dream --drain` (which calls it), the `extract-atoms-drain` Minion handler, and autopilot auto-drain — so lock id / window / defer-on-busy can't drift. `sourceId: undefined` → legacy `gbrain-cycle` lock + `'default'` extraction; a real id → `gbrain-cycle:<id>`. `LockUnavailableError` propagates to the caller (each reports the busy case its own way). Pinned by `test/extract-atoms-drain.test.ts`. The summary's `last_error` always passes through `sanitizeFailureText` (secret/DSN redaction, whitespace collapse, bounded): typed failure records use the source/reason caps, and the count-only `firstError` compatibility path is sanitized to the combined bound, so a provider payload cannot ride either path into `--json` output. `formatDrainProviderFailure(result)` renders the Minion handler's `provider_failure` throw (batches/remaining + `last_error`), so the dead-lettered job's `error_text` names the cause.
+- `src/core/cycle/extract-atoms-drain.ts` — pure single-hold bounded drain for the silent lens-phase backlog. `runExtractAtomsDrain(deps, opts)` over injected deps (`withLock`, `runBatch`, `countRemaining`, `now`, optional `onBatch`) loops bounded batches under ONE lock hold, rediscovering eligibility each batch (idempotent NOT-EXISTS-on-`source_hash`; no cross-window cursor), until the backlog is empty or the window ends. Two stop signals: HARD (job `signal` + the lock's lease-loss signal + `deadlineAtMs`) reaches the chat call, the pacing pause and every backlog count; SOFT (hard + the window timer) is checked only between batches and items, so the item in flight finishes. Counts are cancellable and bounded (`countTimeoutMs`, capped by the remaining deadline). `stopped` is a `DrainStop` (`drained|window|deadline|lock_lost|aborted|no_progress|max_batches|provider_failure`); a hard stop skips `onBatch` and the recount and reports the last count as `remaining`, and the lease loss `withRefreshingLock` rethrows becomes `lock_lost` with the partial counters. Backs `gbrain dream --phase extract_atoms --drain` under the SAME `cycleLockIdFor(sourceId)` the routine cycle takes (a concurrent tick defers with `cycle_already_running`). `runExtractAtomsDrainForSource(engine, {sourceId, windowSeconds, brainDir?, maxBatches?, onBatch?, signal?, deadlineAtMs?})` owns the lock+batch+count wiring for all three callers — `dream --drain`, the `extract-atoms-drain` Minion handler, autopilot auto-drain. `sourceId: undefined` → legacy `gbrain-cycle` lock + `'default'`; a real id → `gbrain-cycle:<id>`. `LockUnavailableError` propagates. `last_error` and the typed failure records pass through `sanitizeFailureText` (secret/DSN redaction, bounded). `formatDrainProviderFailure(result, {final?})` renders the handler's `provider_failure` throw; the handler throws `UnrecoverableError` on `deadline` or any failure at/past `deadlineAtMs`, the job's abort reason on `aborted`, and a retryable error on `lock_lost`. Tests: `test/extract-atoms-drain*.test.ts`.
-- `src/core/cycle/extract-atoms.ts` — the extract_atoms lens phase: mines eligible pages into `atoms/<date>/<stem>-<hash>` pages. Eligibility reads source-incarnation/page/full-hash-keyed derived scan state; scan and failure markers do not mutate canonical frontmatter. Managed extraction checks source-wide local authority and owner readiness before provider work, admits outputs plus a completion request together, and replays retained output without another model call. Managed atom files keep provisional source hashes; only the source-incarnation/page/full-hash durable completion receipt excludes an item from discovery and backlog counts. Unmanaged atom completion flips and their cardinality check share a transaction after provenance links persist, so a partial match rolls back and stays retryable. An undated source dates its atoms by the source page's creation date (`undated` for transcripts), never the run date. After an unmanaged item completes, `retireStaleAtoms` soft-deletes that source's atoms from earlier extractions (other or provisional `source_hash`) that this extraction did not re-produce.
+- `src/core/cycle/extract-atoms.ts` — the extract_atoms lens phase: mines eligible pages into `atoms/<date>/<stem>-<hash>` pages. Eligibility reads source-incarnation/page/full-hash-keyed derived scan state; scan and failure markers do not mutate canonical frontmatter. Managed extraction checks source-wide local authority and owner readiness before provider work, admits outputs plus a completion request together, and replays retained output without another model call. Managed atom files keep provisional source hashes; only the source-incarnation/page/full-hash durable completion receipt excludes an item from discovery and backlog counts. Unmanaged atom completion flips and their cardinality check share a transaction after provenance links persist, so a partial match rolls back and stays retryable. An undated source dates its atoms by the source page's creation date (`undated` for transcripts), never the run date. After an unmanaged item completes, `retireStaleAtoms` soft-deletes that source's atoms from earlier extractions (other or provisional `source_hash`) that this extraction did not re-produce. Hard `opts.signal` (chat call, pacing, checks before each item and commit) leaves no strike, receipt or rollup; soft `opts.stopSignal` stops before the next item.
Managed completion admits revision-pinned `managed_atom_delete` children alongside replacement pages, removes canonical files through the page deletion path, and commits its checkpoint only after every publication and retirement commits.
Both paths prevent LLM-chosen titles that drift between extractions from piling up.
Atom identity: page-derived atoms fold the source-page slug into the slug hash (8 chars, NUL-separated) so two same-date pages emitting the same title get DISTINCT slugs; the source CONTENT hash is deliberately NOT folded (a reworded source still upserts rather than duping); transcript atoms keep the legacy title-only 6-char hash. `resolvePageAtomSlug` adopts a legacy-slug atom with a compatible binding in place on re-extraction (upgrade idempotency — no migration, no duplicate), while `assertAtomImportBinding` fail-closed refuses to reuse a slug bound to a DIFFERENT source locator. Both share `isCompatibleAtomBinding(frontmatter, sourcePageSlug)` — the ONE definition of compatible: bound to THIS source page, or carrying no `source_slug`/`source_path` at all (pre-binding-era adoption, not a clobber); a `source_path`-bound legacy transcript atom or a different `source_slug` is a different origin, and a non-atom page squatting on the slug is refused. `source_quote` is verified at extraction time against the exact `truncateUtf8` prompt prefix the model saw (`locateQuote` advances by full code points): located quotes persist original characters + [start,end) offsets + `source_quote_verified`; unlocatable quotes are dropped with the atom kept. Edges write before the completion flip; per-item drain failures stay typed (bounded, sanitized, reconcilable). Transcript items carry the same failure-count/tombstone machinery as pages, in the `extract_atoms_transcript_state` table (migration `extract_atoms_transcript_state_table`; keyed `(source_id, file_path, content_hash)` with the 16-char hash prefix, so an edit is a new row and re-eligibilizes): `recordItemFailureCount` counts a transcript's malformed output toward `MAX_DETERMINISTIC_FAILURES`, a zero-yield transcript tombstones immediately (the same zero-yield policy as pages), and `tombstonedTranscriptsForHashes` is the batch read-side gate mirroring `atomsExistingForHashes` (fail-open on error). Reported as `tombstoned_transcripts` (paths), separate from the page-slug `tombstoned_for_failures`. Malformed managed output requires a newly approved protected-job retry identity; publication retry reuses retained output and original/current grants.
diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.md
index ac7937e2c9..64a069143c 100644
--- a/docs/architecture/key-files/core-utilities-1.md
+++ b/docs/architecture/key-files/core-utilities-1.md
@@ -19,7 +19,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/config.ts:ensureGitignore` — idempotent retroactive writer of `~/.gbrain/.gitignore` (single line `*`). Called from `saveConfig()` so every config-writing path lays it down, AND from `runPostUpgrade()` so existing users pick it up on `gbrain upgrade`. Never clobbers a user-customized `.gitignore` (checks file exists + content non-empty before writing). Scope: blocks casual `git add ~/.gbrain` from inside an enclosing worktree, but does NOT cover already-tracked files, screenshots, backups (Time Machine / iCloud / Dropbox), or `git add -f`. The doctor check `home_dir_in_worktree` surfaces what `.gitignore` can't.
-- `src/core/cycle.ts` — brain maintenance cycle primitive (23 phases; `ALL_PHASES` is the ordered source of truth). `runCycle(engine: BrainEngine | null, opts: CycleOpts): Promise<CycleReport>` composes phases in semantic order along the core spine lint → backlinks → sync → synthesize → extract → patterns → recompute_emotional_weight → embed → orphans, with the extraction/graph/consolidation phases (extract_facts, extract_atoms, resolve_symbol_edges, …) slotted between per the ordering comments on `ALL_PHASES`. `synthesize` runs after sync (cross-references see a fresh brain) and before extract (auto-link materializes its writes); `patterns` runs after extract so it reads a fresh graph (subagent put_page sets `ctx.remote=true` and skips auto-link/timeline by default, so extract is the canonical materialization); `recompute_emotional_weight` sees the union of `syncPagesAffected` + `synthesizeWrittenSlugs` incrementally, or all pages when neither anchor is set (full backfill via `gbrain dream --phase recompute_emotional_weight`). `CycleReport.schema_version: "1"` is stable; `totals` is additive (`pages_emotional_weight_recomputed`, `transcripts_processed`, `synth_pages_written`, `patterns_written`). Three callers: `gbrain dream` CLI, `gbrain autopilot` daemon inline path, the Minions `autopilot-cycle` handler. Coordination via `gbrain_cycle_locks` DB table + `~/.gbrain/cycle.lock` file lock with PID-liveness for PGLite; the two handles compose into ONE lock whose `refresh()` treats the fenced DB row as the authoritative multi-writer identity and the file half as best-effort freshness — the file lock is refreshed ONLY while the fenced DB refresh reports ownership, so a losing holder can never clobber the successor's file lock on the very tick it detects the steal. A dedicated serialized refresher — `startCycleLockRefresher(lock, controller, lockId)` (exported; unref'd `setInterval` at `max(15s, TTL/6)`, env-only override `GBRAIN_CYCLE_LOCK_REFRESH_MS`, in-flight guard so a slow refresh never overlaps the next tick) — heartbeats the lock through long phases (synthesis/patterns/consolidation waits routinely outlive the TTL with no other heartbeat). A fenced miss aborts the controller with `LockStolenError`; that steal signal combines with the worker's external signal via the exported `anyAbortSignal(signals)` (`src/core/abort-signals.ts`, re-exported; duck-type-tolerant — stubs without `addEventListener` are observed by poll; returns `{signal, dispose}` and dispose detaches the caller-signal listener + clears the poll timer so daemons don't leak), and the run stops at the next phase boundary with a structured partial report carrying `reason: 'lock_stolen'` (for the 5 long phases — synthesize / extract_atoms / patterns / synthesize_concepts / consolidate — the steal races the phase promise and stops the WAIT immediately; their in-flight work runs to its own bounded timeout because their opts can't carry a signal yet). Transient refresh errors log and retry next tick (the TTL stays the backstop). `yieldBetweenPhases` runs between phases; `yieldDuringPhase` is in-phase keepalive. Engine nullable; lock-skip on read-only phase selections. `CycleOpts.signal?: AbortSignal` propagates the worker's abort signal with `checkAborted()` between every phase. `CycleOpts.deadlineAtMs` (the enclosing minion job's ABSOLUTE wall-clock deadline, threaded from `MinionJobContext.deadlineAtMs` by the autopilot-cycle handler; null for direct `gbrain dream` callers) flows into patterns, propose_takes, AND synthesize so time-spending phases derive their deadlines from the REAL remaining job budget instead of duplicated literals that collide with the job's own kill timer. Pinned by `test/cycle-lock-steal.serial.test.ts` (mid-run steal → partial report, no further phases, successor row intact) + `test/cycle-any-abort-signal.test.ts` + `test/db-lock-fencing.test.ts`. `runPhaseSync` returns `pagesAffected` via `SyncPhaseResult` (threaded to `runPhaseExtract` as the 4th arg) and takes `willRunExtractPhase: boolean` setting `noExtract: phases.includes('extract')` so `gbrain dream --phase sync` doesn't silently lose extraction. The extract phase calls `runExtractCore` and `extractStaleFromDB` with `quiet: true` (and `jsonMode: false`), so the helpers' human summaries never land on stdout ahead of the `dream --json` CycleReport while batch-loss diagnostics stay human-readable on stderr (`quiet` is its own knob on `ExtractOpts` — using `jsonMode: true` as a stand-in flipped the stderr channel to JSON events in a plain `gbrain dream`); `totals.pages_extracted` counts pages (`pages_processed` from the targeted pass + `stale_pages_drained`), not links created. `resolveSourceForDir(engine, brainDir)` threads `sourceId` to `performSync()` so sync reads the per-source `sources.last_commit` anchor (not the drift-prone global `config.sync.last_commit`). `CycleOpts.brainDir` is `string | null`; when null (checkout-less postgres/Supabase brain) the 6 filesystem phases (lint/backlinks/sync/synthesize/extract/patterns) skip with `details.reason: 'no_brain_dir'` and the DB-only phases run; `resolveSourceForDir` is null-tolerant. `cycleSourceId = opts.sourceId ?? resolveSourceForDir(engine, brainDir)` is the canonical per-source scope for `extract_facts`/`extract_atoms`/calibration — and for `synthesize` (threaded as `SynthesizePhaseOpts.sourceId` so synthesized pages land in the cycle's resolved source, not `'default'`) — so `gbrain dream --source repo-a` reconciles repo-a's facts even with no checkout (instead of scoping to `'default'` while stamping repo-a fresh). `deriveStatus` counts `edges_resolved`/`edges_ambiguous` as work so an edges-only cycle reports `ok` not `clean`, and scores ONLY attempted phases — the implicit source-cycle exclusion skip-records are bookkeeping and never dilute failure aggregation; the `jobs.ts` `autopilot-cycle` + phase-wrapper handlers pass `null` (not `'.'`) when no repo is configured. The cycle is SPLIT for autopilot fan-out along the `PHASE_SCOPE` taxonomy in `src/core/cycle/phase-scope.ts` (see its entry): cycle.ts derives `SOURCE_PHASES` / `MIXED_PHASES` / `GLOBAL_PHASES` / `MAINTENANCE_PHASES` (mixed ∪ global, original cycle order) plus `SOURCE_FRESHNESS_PHASES` (deterministic, non-LLM: lint/backlinks/sync/extract/extract_facts/recompute_emotional_weight — defined in phase-scope.ts) and `SOURCE_BACKGROUND_PHASES` (LLM-backed/unbounded source work = SOURCE minus FRESHNESS). `resolveCyclePhases(requested, sourceId)` at the shared runCycle boundary: default/no-source → `requested ?? ALL_PHASES` (the canonical `default` cycle remains full); a named non-default source with NO explicit phases → `SOURCE_FRESHNESS_PHASES` only (the freshness keeper's implicit `dream --source X` path must stamp freshness without first draining LLM-backed maintenance); explicit phase lists are honored VERBATIM — `dream --source X --phase synthesize` (and `--input <file>`, which implies synthesize) is deliberate operator intent, and `--phase orphans --source X` still narrows orphans via `forceGlobalOrphans`. The N-way duplication guard lives at the QUEUE boundary instead: the `autopilot-cycle` handler intersects queued per-source payloads with `SOURCE_FRESHNESS_PHASES` (queued payloads may carry mixed+background phases; an all-rejected or empty list is an explicit no-op skip with reason `all_phases_rejected_by_normalization`, never an implicit run, and rejected phases surface on the job result as `phases_rejected_by_normalization`). On the implicit path, excluded phases surface as `skipped` with `details.reason: 'excluded_from_implicit_source_cycle'` + `phase_scope`. Per-source `autopilot-cycle` jobs enqueue `phases: SOURCE_FRESHNESS_PHASES` and stamp `last_source_cycle_at`; the single `autopilot-global-maintenance` job runs `MAINTENANCE_PHASES` (no `sourceId`) and stamps the brain-level `autopilot.last_global_at` config key (`LAST_GLOBAL_AT_KEY`). SOURCE_BACKGROUND phases have NO automatic lane on multi-source brains (the legacy full-cycle job fires only when the brain has no sources rows) — run them explicitly (`gbrain dream --source X --phase extract_atoms`) until the background lane lands (see TODOS). The freshness stamp gate is `opts.sourceId && phases.length > 0 && engine && !dryRun && !aborted && status ∈ {ok, clean, partial}`; `last_full_cycle_at` is still written alongside `last_source_cycle_at` on a per-source success for doctor/legacy readers (not a gate for the brain-wide phases). Pinned by `test/dream-postgres.serial.test.ts` + `test/jobs-autopilot-cycle-braindir.serial.test.ts` + `test/autopilot-global-maintenance.test.ts` + `test/cycle-enabled-phase-completeness.test.ts`. `runPhaseLint` + `runPhaseBacklinks` carry the `export` keyword so behavioral tests can drive them directly (internal helpers exposed for test-only consumption; downstream code should NOT depend on them). Pinned by `test/cycle-legacy-phases.test.ts` (11 cases across both phases: clean run → status='ok', partial fix → status='warn' with `dryRun` in details, dry-run path doesn't write, throw-from-lib → status='fail' with the wrapper's try/catch envelope populated). with `src/core/cycle/extract-atoms.ts` + `src/core/cycle/synthesize-concepts.ts` + `src/commands/extract.ts` + `src/commands/doctor.ts` + `src/core/op-checkpoint.ts`: six daily-driver ops behaviors. (1) Batch idempotency: `atomsExistingForHashes(engine, sourceId, hashes[])` (exported from `src/core/cycle/extract-atoms.ts`) answers in one batched SQL roundtrip (never a per-hash loop) returning already-extracted `content_hash16` values; fail-open (SQL error → empty set, extraction proceeds); powered by migration v104 `pages_atom_source_hash_idx` (partial expression index on `frontmatter->>'source_hash'` for atom rows where `deleted_at IS NULL`; Postgres `CREATE INDEX CONCURRENTLY` with invalid-remnant pre-drop, PGLite plain). (2) Cycle lock TTL + heartbeat: `LOCK_TTL_MINUTES = 5`; `buildYieldDuringPhase(lock, outer)` (exported, with `LockHandle`) calls `lock.refresh()` + any external hook on every fire, throttled to 30s via `maybeYield`, firing both in the main loop AND immediately after every `await chat(...)`; `synthesize_concepts` uses the same throttled hook. A crashed cycle releases its lock within one short TTL, while the dedicated `startCycleLockRefresher` interval (see the coordination sentence above) keeps a healthy long-running cycle alive even across a single multi-minute `await chat(...)` — the timer fires during awaits, so no single slow call can silently expire the lock. (3) Progress wiring: `progress?: ProgressReporter` opt on `ExtractAtomsOpts` and `SynthesizeConceptsOpts`; cycle.ts passes its phase-level reporter down (NOT a child reporter, which would collide on `cycle.extract_atoms.extract_atoms.work`); phases only call `tick()`/`heartbeat()`, cycle.ts owns `start()`/`finish()`. (4) `by-mention` resume: `mentionsFingerprint({source, type, since, gazetteerHash})` in `src/core/op-checkpoint.ts` — the gazetteer hash (`hashGazetteer` in `src/core/by-mention.ts` — every entry's source_id/slug/title/tokens, not just the first-token bucket keys, so a new "Acme Labs" beside an existing "Acme Corp" moves it) is load-bearing (adding entity pages mid-pause shifts the hash → new fingerprint → fresh scan against the new gazetteer, never silent skip); `findMentionedEntities` keys its self-link guard and first-mention dedup on `(source_id, slug)`, so under `link_resolution.cross_source` a foreign namesake of the scanning page is a real target and same-slug pages in two sources both link; the gazetteer itself is entity-page titles PLUS live-verified `page_aliases` entries joined to entity-typed pages (ambiguous aliases and alias-vs-title collisions within a source are skipped), so body mentions of a documented alias link too; `gbrain extract links --by-mention` resumes via `op_checkpoints` with `flushAndCheckpoint` ordering (links flush to DB FIRST, page keys commit to checkpoint SECOND, persist THIRD, so a crash mid-batch leaves the page un-checkpointed and resume re-scans it); persist every 1000 items OR 30s; clean exit clears the checkpoint; `--dry-run` skips both load and write. (5) `sync_consolidation` doctor check (multi-source brains see a paste-ready `gbrain sync --all --parallel 4 --workers 4 --skip-failed`; single-source "not applicable"; SQL errors return `warn` via the check's own try/catch). (6) Test-isolation: `test/cycle-last-full-cycle-at.test.ts` + `test/schema-cli.test.ts` use per-test `GBRAIN_HOME=tempdir`. Pinned by `test/cycle/extract-atoms-batch.test.ts`, `test/core/cycle.serial.test.ts` (5-minute DB-lock and file-lock TTL behavior), `test/op-checkpoint-mentions-fingerprint.test.ts`, `test/cycle/extract-atoms-progress.test.ts`, `test/cycle/synthesize-concepts-progress.test.ts`, `test/cycle/yield-during-phase-refresh.test.ts`, `test/cycle/yield-during-phase-throttle.test.ts`, `test/extract-by-mention-resume.test.ts`, `test/doctor-sync-consolidation.test.ts`. Companion `sync --all` recipe block in `skills/cron-scheduler/SKILL.md`. `synthesize_concepts` writes concept pages through `importFromContent` (the same parse→chunk→embed pipeline put_page uses, with put_page's `isAvailable('embedding')` → `noEmbed` gate) so `concepts/` pages carry `content_chunks` + embeddings and are reachable by retrieval (where `source-boost.ts` weights them 1.3×). `purge` phase (soft-delete TTLs) also GCs stale `op_checkpoints` rows older than 7 days. Non-fatal on pre-v67 brains (DROP-target-table check before DELETE). The cycle threads its abort signal into the embed phase (`runPhaseEmbed(engine, dryRun, signal)`) so a timed-out cycle's long embed phase honors cancellation and releases `gbrain_cycle_locks` right away instead of after a full backlog run. The `extract_facts` phase runs the S9 conflict sweep as its tail (`ai/decide/sweep.ts` `conflictSweepTail`) only when `decide.slots.conflict.mode` is not off, adding `details.decide_conflict`; with the slot off the phase output is unchanged.
+- `src/core/cycle.ts` — brain maintenance cycle primitive (23 phases; `ALL_PHASES` is the ordered source of truth). `runCycle(engine: BrainEngine | null, opts: CycleOpts): Promise<CycleReport>` composes phases in semantic order along the core spine lint → backlinks → sync → synthesize → extract → patterns → recompute_emotional_weight → embed → orphans, with the extraction/graph/consolidation phases (extract_facts, extract_atoms, resolve_symbol_edges, …) slotted between per the ordering comments on `ALL_PHASES`. `synthesize` runs after sync (cross-references see a fresh brain) and before extract (auto-link materializes its writes); `patterns` runs after extract so it reads a fresh graph (subagent put_page sets `ctx.remote=true` and skips auto-link/timeline by default, so extract is the canonical materialization); `recompute_emotional_weight` sees the union of `syncPagesAffected` + `synthesizeWrittenSlugs` incrementally, or all pages when neither anchor is set (full backfill via `gbrain dream --phase recompute_emotional_weight`). `CycleReport.schema_version: "1"` is stable; `totals` is additive (`pages_emotional_weight_recomputed`, `transcripts_processed`, `synth_pages_written`, `patterns_written`). Three callers: `gbrain dream` CLI, `gbrain autopilot` daemon inline path, the Minions `autopilot-cycle` handler. Coordination via `gbrain_cycle_locks` DB table + `~/.gbrain/cycle.lock` file lock with PID-liveness for PGLite; the two handles compose into ONE lock whose `refresh()` treats the fenced DB row as the authoritative multi-writer identity and the file half as best-effort freshness — the file lock is refreshed ONLY while the fenced DB refresh reports ownership, so a losing holder can never clobber the successor's file lock on the very tick it detects the steal. A dedicated serialized refresher — `startCycleLockRefresher(lock, controller, lockId)` (exported; unref'd `setInterval` at `max(15s, TTL/6)`, env-only override `GBRAIN_CYCLE_LOCK_REFRESH_MS`, in-flight guard so a slow refresh never overlaps the next tick) — heartbeats the lock through long phases (synthesis/patterns/consolidation waits routinely outlive the TTL with no other heartbeat). A fenced miss aborts the controller with `LockStolenError`; that steal signal combines with the worker's external signal via the exported `anyAbortSignal(signals)` (`src/core/abort-signals.ts`, re-exported; duck-type-tolerant — stubs without `addEventListener` are observed by poll; returns `{signal, dispose}` and dispose detaches the caller-signal listener + clears the poll timer so daemons don't leak), and the run stops at the next phase boundary with a structured partial report carrying `reason: 'lock_stolen'` (for the 5 long phases — synthesize / extract_atoms / patterns / synthesize_concepts / consolidate — the steal races the phase promise and stops the WAIT immediately; extract_atoms also receives the cycle signal as a real `AbortSignal` and stops at its next item, the others run to their own bounded timeout). Transient refresh errors log and retry next tick (the TTL stays the backstop). `yieldBetweenPhases` runs between phases; `yieldDuringPhase` is in-phase keepalive. Engine nullable; lock-skip on read-only phase selections. `CycleOpts.signal?: AbortSignal` propagates the worker's abort signal with `checkAborted()` between every phase. `CycleOpts.deadlineAtMs` (the enclosing minion job's ABSOLUTE wall-clock deadline, threaded from `MinionJobContext.deadlineAtMs` by the autopilot-cycle handler; null for direct `gbrain dream` callers) flows into patterns, propose_takes, AND synthesize so time-spending phases derive their deadlines from the REAL remaining job budget instead of duplicated literals that collide with the job's own kill timer. Pinned by `test/cycle-lock-steal.serial.test.ts` (mid-run steal → partial report, no further phases, successor row intact) + `test/cycle-any-abort-signal.test.ts` + `test/db-lock-fencing.test.ts`. `runPhaseSync` returns `pagesAffected` via `SyncPhaseResult` (threaded to `runPhaseExtract` as the 4th arg) and takes `willRunExtractPhase: boolean` setting `noExtract: phases.includes('extract')` so `gbrain dream --phase sync` doesn't silently lose extraction. The extract phase calls `runExtractCore` and `extractStaleFromDB` with `quiet: true` (and `jsonMode: false`), so the helpers' human summaries never land on stdout ahead of the `dream --json` CycleReport while batch-loss diagnostics stay human-readable on stderr (`quiet` is its own knob on `ExtractOpts` — using `jsonMode: true` as a stand-in flipped the stderr channel to JSON events in a plain `gbrain dream`); `totals.pages_extracted` counts pages (`pages_processed` from the targeted pass + `stale_pages_drained`), not links created. `resolveSourceForDir(engine, brainDir)` threads `sourceId` to `performSync()` so sync reads the per-source `sources.last_commit` anchor (not the drift-prone global `config.sync.last_commit`). `CycleOpts.brainDir` is `string | null`; when null (checkout-less postgres/Supabase brain) the 6 filesystem phases (lint/backlinks/sync/synthesize/extract/patterns) skip with `details.reason: 'no_brain_dir'` and the DB-only phases run; `resolveSourceForDir` is null-tolerant. `cycleSourceId = opts.sourceId ?? resolveSourceForDir(engine, brainDir)` is the canonical per-source scope for `extract_facts`/`extract_atoms`/calibration — and for `synthesize` (threaded as `SynthesizePhaseOpts.sourceId` so synthesized pages land in the cycle's resolved source, not `'default'`) — so `gbrain dream --source repo-a` reconciles repo-a's facts even with no checkout (instead of scoping to `'default'` while stamping repo-a fresh). `deriveStatus` counts `edges_resolved`/`edges_ambiguous` as work so an edges-only cycle reports `ok` not `clean`, and scores ONLY attempted phases — the implicit source-cycle exclusion skip-records are bookkeeping and never dilute failure aggregation; the `jobs.ts` `autopilot-cycle` + phase-wrapper handlers pass `null` (not `'.'`) when no repo is configured. The cycle is SPLIT for autopilot fan-out along the `PHASE_SCOPE` taxonomy in `src/core/cycle/phase-scope.ts` (see its entry): cycle.ts derives `SOURCE_PHASES` / `MIXED_PHASES` / `GLOBAL_PHASES` / `MAINTENANCE_PHASES` (mixed ∪ global, original cycle order) plus `SOURCE_FRESHNESS_PHASES` (deterministic, non-LLM: lint/backlinks/sync/extract/extract_facts/recompute_emotional_weight — defined in phase-scope.ts) and `SOURCE_BACKGROUND_PHASES` (LLM-backed/unbounded source work = SOURCE minus FRESHNESS). `resolveCyclePhases(requested, sourceId)` at the shared runCycle boundary: default/no-source → `requested ?? ALL_PHASES` (the canonical `default` cycle remains full); a named non-default source with NO explicit phases → `SOURCE_FRESHNESS_PHASES` only (the freshness keeper's implicit `dream --source X` path must stamp freshness without first draining LLM-backed maintenance); explicit phase lists are honored VERBATIM — `dream --source X --phase synthesize` (and `--input <file>`, which implies synthesize) is deliberate operator intent, and `--phase orphans --source X` still narrows orphans via `forceGlobalOrphans`. The N-way duplication guard lives at the QUEUE boundary instead: the `autopilot-cycle` handler intersects queued per-source payloads with `SOURCE_FRESHNESS_PHASES` (queued payloads may carry mixed+background phases; an all-rejected or empty list is an explicit no-op skip with reason `all_phases_rejected_by_normalization`, never an implicit run, and rejected phases surface on the job result as `phases_rejected_by_normalization`). On the implicit path, excluded phases surface as `skipped` with `details.reason: 'excluded_from_implicit_source_cycle'` + `phase_scope`. Per-source `autopilot-cycle` jobs enqueue `phases: SOURCE_FRESHNESS_PHASES` and stamp `last_source_cycle_at`; the single `autopilot-global-maintenance` job runs `MAINTENANCE_PHASES` (no `sourceId`) and stamps the brain-level `autopilot.last_global_at` config key (`LAST_GLOBAL_AT_KEY`). SOURCE_BACKGROUND phases have NO automatic lane on multi-source brains (the legacy full-cycle job fires only when the brain has no sources rows) — run them explicitly (`gbrain dream --source X --phase extract_atoms`) until the background lane lands (see TODOS). The freshness stamp gate is `opts.sourceId && phases.length > 0 && engine && !dryRun && !aborted && status ∈ {ok, clean, partial}`; `last_full_cycle_at` is still written alongside `last_source_cycle_at` on a per-source success for doctor/legacy readers (not a gate for the brain-wide phases). Pinned by `test/dream-postgres.serial.test.ts` + `test/jobs-autopilot-cycle-braindir.serial.test.ts` + `test/autopilot-global-maintenance.test.ts` + `test/cycle-enabled-phase-completeness.test.ts`. `runPhaseLint` + `runPhaseBacklinks` carry the `export` keyword so behavioral tests can drive them directly (internal helpers exposed for test-only consumption; downstream code should NOT depend on them). Pinned by `test/cycle-legacy-phases.test.ts` (11 cases across both phases: clean run → status='ok', partial fix → status='warn' with `dryRun` in details, dry-run path doesn't write, throw-from-lib → status='fail' with the wrapper's try/catch envelope populated). with `src/core/cycle/extract-atoms.ts` + `src/core/cycle/synthesize-concepts.ts` + `src/commands/extract.ts` + `src/commands/doctor.ts` + `src/core/op-checkpoint.ts`: six daily-driver ops behaviors. (1) Batch idempotency: `atomsExistingForHashes(engine, sourceId, hashes[])` (exported from `src/core/cycle/extract-atoms.ts`) answers in one batched SQL roundtrip (never a per-hash loop) returning already-extracted `content_hash16` values; fail-open (SQL error → empty set, extraction proceeds); powered by migration v104 `pages_atom_source_hash_idx` (partial expression index on `frontmatter->>'source_hash'` for atom rows where `deleted_at IS NULL`; Postgres `CREATE INDEX CONCURRENTLY` with invalid-remnant pre-drop, PGLite plain). (2) Cycle lock TTL + heartbeat: `LOCK_TTL_MINUTES = 5`; `buildYieldDuringPhase(lock, outer)` (exported, with `LockHandle`) calls `lock.refresh()` + any external hook on every fire, throttled to 30s via `maybeYield`, firing both in the main loop AND immediately after every `await chat(...)`; `synthesize_concepts` uses the same throttled hook. A crashed cycle releases its lock within one short TTL, while the dedicated `startCycleLockRefresher` interval (see the coordination sentence above) keeps a healthy long-running cycle alive even across a single multi-minute `await chat(...)` — the timer fires during awaits, so no single slow call can silently expire the lock. (3) Progress wiring: `progress?: ProgressReporter` opt on `ExtractAtomsOpts` and `SynthesizeConceptsOpts`; cycle.ts passes its phase-level reporter down (NOT a child reporter, which would collide on `cycle.extract_atoms.extract_atoms.work`); phases only call `tick()`/`heartbeat()`, cycle.ts owns `start()`/`finish()`. (4) `by-mention` resume: `mentionsFingerprint({source, type, since, gazetteerHash})` in `src/core/op-checkpoint.ts` — the gazetteer hash (`hashGazetteer` in `src/core/by-mention.ts` — every entry's source_id/slug/title/tokens, not just the first-token bucket keys, so a new "Acme Labs" beside an existing "Acme Corp" moves it) is load-bearing (adding entity pages mid-pause shifts the hash → new fingerprint → fresh scan against the new gazetteer, never silent skip); `findMentionedEntities` keys its self-link guard and first-mention dedup on `(source_id, slug)`, so under `link_resolution.cross_source` a foreign namesake of the scanning page is a real target and same-slug pages in two sources both link; the gazetteer itself is entity-page titles PLUS live-verified `page_aliases` entries joined to entity-typed pages (ambiguous aliases and alias-vs-title collisions within a source are skipped), so body mentions of a documented alias link too; `gbrain extract links --by-mention` resumes via `op_checkpoints` with `flushAndCheckpoint` ordering (links flush to DB FIRST, page keys commit to checkpoint SECOND, persist THIRD, so a crash mid-batch leaves the page un-checkpointed and resume re-scans it); persist every 1000 items OR 30s; clean exit clears the checkpoint; `--dry-run` skips both load and write. (5) `sync_consolidation` doctor check (multi-source brains see a paste-ready `gbrain sync --all --parallel 4 --workers 4 --skip-failed`; single-source "not applicable"; SQL errors return `warn` via the check's own try/catch). (6) Test-isolation: `test/cycle-last-full-cycle-at.test.ts` + `test/schema-cli.test.ts` use per-test `GBRAIN_HOME=tempdir`. Pinned by `test/cycle/extract-atoms-batch.test.ts`, `test/core/cycle.serial.test.ts` (5-minute DB-lock and file-lock TTL behavior), `test/op-checkpoint-mentions-fingerprint.test.ts`, `test/cycle/extract-atoms-progress.test.ts`, `test/cycle/synthesize-concepts-progress.test.ts`, `test/cycle/yield-during-phase-refresh.test.ts`, `test/cycle/yield-during-phase-throttle.test.ts`, `test/extract-by-mention-resume.test.ts`, `test/doctor-sync-consolidation.test.ts`. Companion `sync --all` recipe block in `skills/cron-scheduler/SKILL.md`. `synthesize_concepts` writes concept pages through `importFromContent` (the same parse→chunk→embed pipeline put_page uses, with put_page's `isAvailable('embedding')` → `noEmbed` gate) so `concepts/` pages carry `content_chunks` + embeddings and are reachable by retrieval (where `source-boost.ts` weights them 1.3×). `purge` phase (soft-delete TTLs) also GCs stale `op_checkpoints` rows older than 7 days. Non-fatal on pre-v67 brains (DROP-target-table check before DELETE). The cycle threads its abort signal into the embed phase (`runPhaseEmbed(engine, dryRun, signal)`) so a timed-out cycle's long embed phase honors cancellation and releases `gbrain_cycle_locks` right away instead of after a full backlog run. The `extract_facts` phase runs the S9 conflict sweep as its tail (`ai/decide/sweep.ts` `conflictSweepTail`) only when `decide.slots.conflict.mode` is not off, adding `details.decide_conflict`; with the slot off the phase output is unchanged.
- `src/core/doctor-cause-rank.ts` — pure cause-ranking for `gbrain doctor`. `rankIssues(checks)` returns non-ok checks ordered fail-before-warn then root-before-symptom then name (deterministic). `ROOT_CAUSE_CHECKS` / `SYMPTOM_CHECKS` are ORDERING ONLY — tier membership asserts no causality. `downstream_of` is set ONLY from a small map of KNOWN grounded edges (`queue_health` / `supervisor` → `worker_oom_loop`, since they read the same `aborted: watchdog` / `rss_watchdog` source) AND only when the named root is itself failing — never a root×symptom cartesian (co-occurrence never implies causality). `fix` prefers `details.fix_hint` else the message. `CAUSE_GRAPH_NAMES` + `allKnownCheckNames()` back a drift guard asserting every graphed name is a real check. Consumed by `computeDoctorReport` (`top_issues` field, additive, schema_version stays 2) + the "Top issues (ranked by cause)" header in `outputResults`. Pinned by `test/doctor-cause-rank.test.ts`.
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.ts
index f853f42803..f162187527 100644
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@ -306,6 +306,8 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"src/core/persistence/grandfather.ts": ["test/e2e/persistence-git-coalescing-5530-postgres.test.ts", "test/e2e/grandfather-projection-postgres.test.ts"],
"src/core/timeline-marker.ts": ["test/e2e/timeline-materialize.test.ts"],
"src/commands/source-reconcile.ts": ["test/e2e/reconcile-crash.test.ts", "test/e2e/reconcile-crash-unactivated.test.ts", "test/e2e/reconcile-pgbouncer.test.ts"],
+ // fix wave GBRA-35 lane C (#5809/#5832): drain hard stops, bounded counts and lease loss on Postgres.
+ "src/core/cycle/extract-atoms-drain.ts": ["test/e2e/extract-atoms-drain-postgres.test.ts"],
"src/core/cycle/extract-atoms.ts": ["test/e2e/extract-atoms-page-state.test.ts", "test/e2e/cycle.test.ts", "test/e2e/dream.test.ts", "test/e2e/multi-source-bug-class.test.ts", "test/e2e/managed-extract-atoms.test.ts", "test/e2e/managed-atom-regressions.test.ts", "test/e2e/managed-atom-compaction.test.ts"],
"src/core/cycle/synthesize*.ts": ["test/e2e/managed-maintenance.test.ts", "test/e2e/managed-synthesis-postprocess.test.ts", "test/e2e/managed-writers-w3.test.ts"],
"src/core/cycle/concept-publication.ts": ["test/e2e/managed-writers-w3.test.ts"],
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index e182ee4df0..825ab9ffa5 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -33,9 +33,9 @@ src/core/check-resolvable.ts checkResolvable 419 seed: W5 baseline, refactor wav
src/core/config.ts loadConfigWithEngine 360 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/context-engine.ts createGBrainContextEngine 519 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/context/retrieval-reflex.ts resolveEntitiesToPointers 355 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
-src/core/cycle.ts runCycle 1229 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
-src/core/cycle/extract-atoms.ts runPhaseExtractAtoms 810 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
-src/core/cycle/extract-atoms.ts runPhaseExtractAtoms>withBudgetTracker(#1) 305 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
+src/core/cycle.ts runCycle 1234 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +5 #5809: extract_atoms phase gets a real abort signal
+src/core/cycle/extract-atoms.ts runPhaseExtractAtoms 822 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +12 #5809/#5832: hard/soft stop checks, chat-call signal, abortable pacing, no post-stop writes
+src/core/cycle/extract-atoms.ts runPhaseExtractAtoms>withBudgetTracker(#1) 316 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +11 #5809/#5832: per-item and pre-commit abort checks, chat-call signal, abortable pacing, catch-side stop
src/core/cycle/extract-facts.ts runExtractFacts 505 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/cycle/grade-takes.ts GradeTakesPhase.process 402 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/cycle/patterns.ts runPhasePatterns 303 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 968dde78dc..ab78905824 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -13,9 +13,9 @@ src/commands/jobs.ts 658 ratchet refactor wave 1 split target (W4 jobs, cut line
src/commands/serve-http.ts 915 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts
src/core/ai/gateway.ts 4365 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state)
src/commands/sync.ts 473 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals)
-src/core/cycle.ts 3180 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts
+src/core/cycle.ts 3185 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal
src/core/cycle/synthesize.ts 3291 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge
-src/core/cycle/extract-atoms.ts 1802 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts)
+src/core/cycle/extract-atoms.ts 1832 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count
src/core/engine.ts 2674 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option
src/core/import-file.ts 2230 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode)
src/core/migrate.ts 599 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3)
diff --git a/src/core/cycle.ts b/src/core/cycle.ts
index a5ffefd354..5b9c37f469 100644
--- a/src/core/cycle.ts
+++ b/src/core/cycle.ts
@@ -2369,6 +2369,10 @@ export async function runCycle(
...(synthesizeWrittenSlugs ?? []),
]
: undefined;
+ // #5833: a real signal (cycleSignal can be the raw duck-typed
+ // opts.signal) so a timeout or lock steal stops the phase at its next
+ // item instead of extracting on after the race below has returned.
+ const xaSignal = cycleSignal ? anyAbortSignal([cycleSignal]) : null;
const { result, duration_ms } = await racedTimePhase(() => runPhaseExtractAtoms(engine, {
brainDir: brainDir ?? undefined,
sourceId: xaSourceId,
@@ -2379,7 +2383,8 @@ export async function runCycle(
// v0.41.19.0 (T4): pass same reporter (not a child — cycle.ts
// owns start/finish; phase only ticks).
progress,
- }), 'extract_atoms');
+ signal: xaSignal?.signal,
+ }), 'extract_atoms').finally(() => xaSignal?.dispose());
result.duration_ms = duration_ms;
phaseResults.push(result);
progress.finish();
diff --git a/src/core/cycle/extract-atoms-drain.ts b/src/core/cycle/extract-atoms-drain.ts
index 83bd6f4407..1147bbeb0d 100644
--- a/src/core/cycle/extract-atoms-drain.ts
+++ b/src/core/cycle/extract-atoms-drain.ts
@@ -15,18 +15,25 @@
* match — no cross-window cursor of page lists.
* - BOUNDED by a wallclock window; reports `remaining` so a cron/agent loop
* knows whether to run again.
+ * - Two stop signals (#5809/#5832). HARD = caller signal (Minion job) + the
+ * lock's lease-loss signal + the job deadline: reaches the chat call, the
+ * pacing pause and every backlog count, and stops before the next commit.
+ * SOFT = hard + window: checked only between batches and items, so a
+ * window stop never aborts an in-flight paid call.
*
* Pure over injected deps: no DB, no LLM, no lock primitive imported here, so
* the loop logic is unit-testable. Its only static imports are pure text
- * sanitizers (#4730). The wiring helper `runExtractAtomsDrainForSource`
- * (below) builds the real deps; it uses DYNAMIC imports so the pure-loop unit
- * tests don't drag in db-lock / cycle.
+ * sanitizers (#4730) and the leaf signal combiner (`abort-signals.ts`). The
+ * wiring helper `runExtractAtomsDrainForSource` (below) builds the real deps;
+ * it uses DYNAMIC imports so the pure-loop unit tests don't drag in db-lock /
+ * cycle.
*/
import type { BrainEngine } from '../engine.ts';
import { redactConnectionInfo } from '../audit/redact-connection-info.ts';
import { redactFindings } from '../secret-scan.ts';
import { ensureWellFormed, truncateUtf8 } from '../text-safe.ts';
+import { anyAbortSignal } from '../abort-signals.ts';
/** #4730: bounded operator-facing failure detail; totals stay exact above the cap. */
export const MAX_DRAIN_FAILURE_RECORDS = 25;
@@ -70,9 +77,11 @@ export interface ExtractAtomsDrainDeps {
* via `withRefreshingLock`. MUST throw when the lock is held by another
* process (e.g. `LockUnavailableError`) — the drain lets that propagate so
* the caller can report `cycle_already_running` and exit, matching the
- * routine cycle's skip contract.
+ * routine cycle's skip contract. `work` receives the lock's signal, which
+ * aborts when the lease is lost (#5832); the drain maps that loss, even
+ * when the helper rethrows it after `work` settled, to `stopped: 'lock_lost'`.
*/
- withLock: <T>(work: () => Promise<T>) => Promise<T>;
+ withLock: <T>(work: (signal: AbortSignal) => Promise<T>) => Promise<T>;
/**
* Process one bounded batch (rediscovers eligibility). Returns counts, plus
* `providerFailure` (issue #3218) when EVERY item the batch attempted threw
@@ -87,8 +96,11 @@ export interface ExtractAtomsDrainDeps {
* reconcilable from `--json` — pre-#4730 everything but ONE representative
* error was dropped and the operator had to re-run the work to see the
* other reasons.
+ *
+ * `signal` is the hard stop and `stopSignal` the soft one (see the module
+ * header); the batch hands both to `runPhaseExtractAtoms`.
*/
- runBatch: () => Promise<{
+ runBatch: (signals: { signal: AbortSignal; stopSignal: AbortSignal }) => Promise<{
extracted: number;
skipped: number;
providerFailure?: boolean;
@@ -96,8 +108,12 @@ export interface ExtractAtomsDrainDeps {
firstError?: string;
failures?: Array<{ source: string; reason: string }>;
}>;
- /** Count remaining eligible-but-unextracted pages, or null on query error. */
- countRemaining: () => Promise<number | null>;
+ /**
+ * Count remaining eligible-but-unextracted pages, or null on query error.
+ * `signal` fires on a hard stop or when the count outlives its bound; the
+ * drain stops waiting at that point even if the query ignores it.
+ */
+ countRemaining: (signal: AbortSignal) => Promise<number | null>;
/** Injectable clock. Production: Date.now. */
now: () => number;
/** Optional progress sink (one line per batch). */
@@ -105,12 +121,35 @@ export interface ExtractAtomsDrainDeps {
}
export interface ExtractAtomsDrainOpts {
- /** Wallclock budget in ms. The loop stops after this elapses. */
+ /**
+ * Wallclock window in ms, a hard deadline for starting work: no batch or
+ * item starts after it, while the item in flight finishes (soft signal).
+ */
windowMs: number;
/** Hard cap on batches (belt-and-suspenders against a 0-progress loop). Default 1000. */
maxBatches?: number;
+ /** Caller's cancellation signal (the Minion job's timeout/cancel signal, #5809). */
+ signal?: AbortSignal;
+ /** Absolute job deadline (epoch ms, `deadlineAtMs` clock); a hard stop at that instant. */
+ deadlineAtMs?: number | null;
+ /** Upper bound on one backlog count; the remaining deadline caps it further. Default 60 s. */
+ countTimeoutMs?: number;
}
+/**
+ * Why a drain stopped. `window`/`no_progress`/`max_batches` are soft stops
+ * after a final recount; `deadline` (job deadline), `lock_lost` (cycle lock
+ * lease lost) and `aborted` (job cancelled or shutting down) are hard stops
+ * whose `remaining` is the last count taken before the stop.
+ */
+export type DrainStop =
+ | 'drained' | 'window' | 'deadline' | 'lock_lost' | 'aborted'
+ | 'no_progress' | 'max_batches' | 'provider_failure';
+
+export const DRAIN_COUNT_TIMEOUT_MS = 60_000;
+/** setTimeout fires at once past 2^31-1 ms; a longer window or deadline waits the maximum. */
+const MAX_TIMER_MS = 2 ** 31 - 1;
+
export interface ExtractAtomsDrainResult {
phase: 'extract_atoms';
/**
@@ -123,12 +162,11 @@ export interface ExtractAtomsDrainResult {
status: 'ok' | 'provider_failure';
extracted: number;
skipped: number;
- /** Eligible pages still pending after the window. null if the count errored. */
+ /** Eligible pages still pending (see DrainStop for hard stops). null if no count succeeded. */
remaining: number | null;
/** Batches actually processed. */
batches: number;
- /** Why the loop stopped: drained | window | no_progress | max_batches | provider_failure. */
- stopped: 'drained' | 'window' | 'no_progress' | 'max_batches' | 'provider_failure';
+ stopped: DrainStop;
/**
* #4539: total per-item failures across every batch in this run. 0 for a
* clean run. Included in `--json` verbatim; dream.ts prints a stderr line
@@ -162,11 +200,12 @@ export interface ExtractAtomsDrainResult {
*/
export function formatDrainProviderFailure(
result: Pick<ExtractAtomsDrainResult, 'batches' | 'remaining' | 'last_error'>,
+ opts: { final?: boolean } = {},
): string {
return (
`extract-atoms-drain: all provider calls failed this batch ` +
`(batches=${result.batches}, remaining=${result.remaining ?? '?'})` +
- `${result.last_error ? `; last error: ${result.last_error}` : ''} — retrying`
+ `${result.last_error ? `; last error: ${result.last_error}` : ''}${opts.final ? '' : ' — retrying'}`
);
}
@@ -175,120 +214,187 @@ export async function runExtractAtomsDrain(
opts: ExtractAtomsDrainOpts,
): Promise<ExtractAtomsDrainResult> {
const maxBatches = opts.maxBatches ?? 1000;
- return deps.withLock(async () => {
- const deadline = deps.now() + opts.windowMs;
- let extracted = 0;
- let skipped = 0;
- let batches = 0;
- let stopped: ExtractAtomsDrainResult['stopped'] = 'window';
- // issue #3218: latched once any batch reports providerFailure — drives
- // the returned `status`, independent of how `stopped` reads after the
- // final (possibly overriding) remaining-count check below.
- let providerFailure = false;
- // #4539: accumulate per-item failure visibility across batches.
- let failureCount = 0;
- // #4730: bounded typed per-item records (batch order, sanitized).
- const failures: ExtractAtomsDrainFailure[] = [];
- let lastError: string | null = null;
+ const countTimeoutMs = opts.countTimeoutMs ?? DRAIN_COUNT_TIMEOUT_MS;
+ // Counters live outside the locked work so a lease loss the lock helper
+ // rethrows after `work` settled still reports the partial progress.
+ let extracted = 0;
+ let skipped = 0;
+ let batches = 0;
+ // issue #3218: latched once any batch reports providerFailure — drives
+ // the returned `status`, independent of how `stopped` reads after the
+ // final (possibly overriding) remaining-count check below.
+ let providerFailure = false;
+ // #4539: accumulate per-item failure visibility across batches.
+ let failureCount = 0;
+ // #4730: bounded typed per-item records (batch order, sanitized).
+ const failures: ExtractAtomsDrainFailure[] = [];
+ let lastError: string | null = null;
+ let lastCount: number | null = null;
+ let lockSignal: AbortSignal | null = null;
+ const result = (stopped: DrainStop, remaining: number | null): ExtractAtomsDrainResult => ({
+ phase: 'extract_atoms',
+ status: providerFailure ? 'provider_failure' : 'ok',
+ extracted,
+ skipped,
+ remaining,
+ batches,
+ stopped,
+ failure_count: failureCount,
+ failures,
+ omitted_failure_count: failureCount - failures.length,
+ last_error: lastError,
+ });
+ try {
+ return await deps.withLock(async (signal) => {
+ lockSignal = signal;
+ const windowEnd = deps.now() + opts.windowMs;
+ const deadlineStop = new AbortController();
+ const windowStop = new AbortController();
+ const deadlineTimer = opts.deadlineAtMs == null ? undefined : setTimeout(
+ () => deadlineStop.abort(new Error('extract-atoms-drain: job deadline reached')),
+ Math.min(MAX_TIMER_MS, Math.max(0, opts.deadlineAtMs - deps.now())),
+ );
+ const windowTimer = setTimeout(
+ () => windowStop.abort(new Error('extract-atoms-drain: window elapsed')),
+ Math.min(MAX_TIMER_MS, opts.windowMs),
+ );
+ deadlineTimer?.unref?.();
+ windowTimer.unref?.();
+ const hard = anyAbortSignal([...(opts.signal ? [opts.signal] : []), signal, deadlineStop.signal]);
+ const soft = anyAbortSignal([hard.signal, windowStop.signal]);
+ const hardStop = (): DrainStop => signal.aborted ? 'lock_lost'
+ : deadlineStop.signal.aborted || (opts.deadlineAtMs != null && deps.now() >= opts.deadlineAtMs) ? 'deadline'
+ : 'aborted';
+ // E15: a count that blocks must not keep the lock refreshing, so it is
+ // bounded by the remaining deadline and abandoned on a hard stop.
+ const count = async (): Promise<number | null> => {
+ const bound = opts.deadlineAtMs == null ? countTimeoutMs
+ : Math.min(countTimeoutMs, Math.max(0, opts.deadlineAtMs - deps.now()));
+ const timeout = new AbortController();
+ const timer = setTimeout(() => timeout.abort(new Error('extract-atoms-drain: backlog count timed out')), bound);
+ const bounded = anyAbortSignal([hard.signal, timeout.signal]);
+ try {
+ if (bounded.signal.aborted) return null;
+ return await new Promise<number | null>((resolve, reject) => {
+ bounded.signal.addEventListener('abort', () => resolve(null), { once: true });
+ deps.countRemaining(bounded.signal).then(resolve, reject);
+ });
+ } finally {
+ clearTimeout(timer);
+ bounded.dispose();
+ }
+ };
+ try {
+ let stopped: DrainStop = 'window';
+ while (deps.now() < windowEnd && !soft.signal.aborted) {
+ if (batches >= maxBatches) { stopped = 'max_batches'; break; }
- while (deps.now() < deadline) {
- if (batches >= maxBatches) { stopped = 'max_batches'; break; }
+ const before = await count();
+ if (hard.signal.aborted) break;
+ if (before !== null) lastCount = before;
+ if (before === 0) { stopped = 'drained'; break; }
- const before = await deps.countRemaining();
- if (before === 0) { stopped = 'drained'; break; }
+ const r = await deps.runBatch({ signal: hard.signal, stopSignal: soft.signal });
+ extracted += r.extracted;
+ skipped += r.skipped;
+ batches++;
+ // #4730: preserve typed per-item records (bounded, sanitized) while
+ // keeping failure_count exact and reconcilable — count-only adapters
+ // (the #4539 shape) still contribute to the total via failureCount.
+ const batchFailures = Array.isArray(r.failures)
+ ? r.failures.filter(
+ (f): f is { source: string; reason: string } =>
+ f != null &&
+ typeof f === 'object' &&
+ typeof f.source === 'string' &&
+ typeof f.reason === 'string',
+ )
+ : [];
+ const reportedFailureCount =
+ typeof r.failureCount === 'number' && Number.isFinite(r.failureCount) && r.failureCount > 0
+ ? Math.floor(r.failureCount)
+ : 0;
+ failureCount += Math.max(reportedFailureCount, batchFailures.length);
+ for (const f of batchFailures) {
+ if (failures.length >= MAX_DRAIN_FAILURE_RECORDS) break;
+ failures.push({
+ batch: batches,
+ source: sanitizeFailureText(f.source, MAX_DRAIN_FAILURE_SOURCE_CHARS),
+ reason: sanitizeFailureText(f.reason, MAX_DRAIN_FAILURE_REASON_CHARS),
+ });
+ }
+ const representative = batchFailures[0];
+ if (representative) {
+ lastError =
+ `${sanitizeFailureText(representative.source, MAX_DRAIN_FAILURE_SOURCE_CHARS)}: ` +
+ `${sanitizeFailureText(representative.reason, MAX_DRAIN_FAILURE_REASON_CHARS)}`;
+ } else if (typeof r.firstError === 'string' && r.firstError.trim()) {
+ // #4539 compatibility: count-only adapters still surface their
+ // representative error — through the SAME sanitizer as the typed
+ // records (secret/DSN redaction, whitespace collapse, bounded), so a
+ // provider payload cannot ride the fallback path into --json output.
+ lastError = sanitizeFailureText(
+ r.firstError,
+ MAX_DRAIN_FAILURE_SOURCE_CHARS + 2 + MAX_DRAIN_FAILURE_REASON_CHARS,
+ );
+ }
+ if (hard.signal.aborted) break;
+ deps.onBatch?.({ batch: batches, extracted: r.extracted, remaining: before });
- const r = await deps.runBatch();
- extracted += r.extracted;
- skipped += r.skipped;
- batches++;
- // #4730: preserve typed per-item records (bounded, sanitized) while
- // keeping failure_count exact and reconcilable — count-only adapters
- // (the #4539 shape) still contribute to the total via failureCount.
- const batchFailures = Array.isArray(r.failures)
- ? r.failures.filter(
- (f): f is { source: string; reason: string } =>
- f != null &&
- typeof f === 'object' &&
- typeof f.source === 'string' &&
- typeof f.reason === 'string',
- )
- : [];
- const reportedFailureCount =
- typeof r.failureCount === 'number' && Number.isFinite(r.failureCount) && r.failureCount > 0
- ? Math.floor(r.failureCount)
- : 0;
- failureCount += Math.max(reportedFailureCount, batchFailures.length);
- for (const f of batchFailures) {
- if (failures.length >= MAX_DRAIN_FAILURE_RECORDS) break;
- failures.push({
- batch: batches,
- source: sanitizeFailureText(f.source, MAX_DRAIN_FAILURE_SOURCE_CHARS),
- reason: sanitizeFailureText(f.reason, MAX_DRAIN_FAILURE_REASON_CHARS),
- });
- }
- const representative = batchFailures[0];
- if (representative) {
- lastError =
- `${sanitizeFailureText(representative.source, MAX_DRAIN_FAILURE_SOURCE_CHARS)}: ` +
- `${sanitizeFailureText(representative.reason, MAX_DRAIN_FAILURE_REASON_CHARS)}`;
- } else if (typeof r.firstError === 'string' && r.firstError.trim()) {
- // #4539 compatibility: count-only adapters still surface their
- // representative error — through the SAME sanitizer as the typed
- // records (secret/DSN redaction, whitespace collapse, bounded), so a
- // provider payload cannot ride the fallback path into --json output.
- lastError = sanitizeFailureText(
- r.firstError,
- MAX_DRAIN_FAILURE_SOURCE_CHARS + 2 + MAX_DRAIN_FAILURE_REASON_CHARS,
- );
- }
- deps.onBatch?.({ batch: batches, extracted: r.extracted, remaining: before });
+ // issue #3218: every item this batch attempted failed (0 succeeded, >=1
+ // error) — a total provider outage, not ordinary no-op/partial progress.
+ // Stop immediately (same hot-loop guard as no_progress below) and flag
+ // it so the caller can retry via its own policy instead of treating the
+ // drain as a clean completion.
+ if (r.providerFailure) {
+ providerFailure = true;
+ stopped = 'provider_failure';
+ break;
+ }
- // issue #3218: every item this batch attempted failed (0 succeeded, >=1
- // error) — a total provider outage, not ordinary no-op/partial progress.
- // Stop immediately (same hot-loop guard as no_progress below) and flag
- // it so the caller can retry via its own policy instead of treating the
- // drain as a clean completion.
- if (r.providerFailure) {
- providerFailure = true;
- stopped = 'provider_failure';
- break;
- }
+ // Stop if a batch made zero forward progress — extraction is failing or
+ // everything left is ineligible (e.g. all skipped). Prevents a hot loop
+ // that spends budget without draining.
+ //
+ // #2144: a zero-ATOM batch can still be progress — tombstoned
+ // zero-yield pages shrink the backlog without producing atoms. Only
+ // stop when the backlog count genuinely didn't move.
+ if (r.extracted === 0 && r.skipped === 0) {
+ const after = await count();
+ if (hard.signal.aborted) break;
+ if (after !== null) lastCount = after;
+ if (after === null || before === null || after >= before) { stopped = 'no_progress'; break; }
+ }
+ }
- // Stop if a batch made zero forward progress — extraction is failing or
- // everything left is ineligible (e.g. all skipped). Prevents a hot loop
- // that spends budget without draining.
- //
- // #2144: a zero-ATOM batch can still be progress — tombstoned
- // zero-yield pages shrink the backlog without producing atoms. Only
- // stop when the backlog count genuinely didn't move.
- if (r.extracted === 0 && r.skipped === 0) {
- const after = await deps.countRemaining();
- if (after === null || before === null || after >= before) { stopped = 'no_progress'; break; }
+ // Hard stops write nothing and skip the recount (it would outlive the
+ // deadline or run without the lock); `remaining` is the last count.
+ if (hard.signal.aborted) return result(hardStop(), lastCount);
+ const remaining = await count();
+ if (hard.signal.aborted) return result(hardStop(), lastCount);
+ lastCount = remaining;
+ // issue #3218 (codex P2): don't let a final remaining===0 recount
+ // overwrite 'provider_failure' back to 'drained' — that would report the
+ // contradictory {status: 'provider_failure', stopped: 'drained'} and
+ // mislead the CLI/JSON consumer (dream.ts prints both fields verbatim).
+ // status already takes precedence for the Minion handler's retry
+ // decision; keep `stopped` consistent with it once a failure latched.
+ if (!providerFailure && remaining === 0) stopped = 'drained';
+ return result(stopped, remaining);
+ } finally {
+ clearTimeout(deadlineTimer);
+ clearTimeout(windowTimer);
+ soft.dispose();
+ hard.dispose();
}
- }
-
- const remaining = await deps.countRemaining();
- // issue #3218 (codex P2): don't let a final remaining===0 recount
- // overwrite 'provider_failure' back to 'drained' — that would report the
- // contradictory {status: 'provider_failure', stopped: 'drained'} and
- // mislead the CLI/JSON consumer (dream.ts prints both fields verbatim).
- // status already takes precedence for the Minion handler's retry
- // decision; keep `stopped` consistent with it once a failure latched.
- if (!providerFailure && remaining === 0) stopped = 'drained';
- return {
- phase: 'extract_atoms',
- status: providerFailure ? 'provider_failure' : 'ok',
- extracted,
- skipped,
- remaining,
- batches,
- stopped,
- failure_count: failureCount,
- failures,
- omitted_failure_count: failureCount - failures.length,
- last_error: lastError,
- };
- });
+ });
+ } catch (err) {
+ // E8: `withRefreshingLock` rethrows the recorded lease loss from its
+ // finally, replacing whatever `work` returned or threw.
+ const lock = lockSignal as AbortSignal | null;
+ if (lock?.aborted && err === lock.reason) return result('lock_lost', lastCount);
+ throw err;
+ }
}
// ─── Shared wiring helper (v0.42.x #1685 DECISION 5A) ──────────────────────
@@ -326,6 +432,10 @@ export interface DrainForSourceOpts {
maxBatches?: number;
/** Optional per-batch progress sink (stderr line in dream; job progress in the handler). */
onBatch?: ExtractAtomsDrainDeps['onBatch'];
+ /** #5809: the Minion job's signal (see ExtractAtomsDrainOpts.signal). */
+ signal?: AbortSignal;
+ /** #5809: the Minion job's `deadlineAtMs`. */
+ deadlineAtMs?: number | null;
}
export async function runExtractAtomsDrainForSource(
@@ -341,12 +451,14 @@ export async function runExtractAtomsDrainForSource(
return runExtractAtomsDrain(
{
- withLock: (work) => withRefreshingLock(engine, lockId, work, { ttlMinutes: 5 }),
- runBatch: async () => {
+ withLock: (work) => withRefreshingLock(engine, lockId, (signal) => work(signal), { ttlMinutes: 5 }),
+ runBatch: async ({ signal, stopSignal }) => {
const r = await runPhaseExtractAtoms(engine, {
sourceId: extractionSourceId,
dryRun: false,
brainDir: opts.brainDir,
+ signal,
+ stopSignal,
});
const d = (r.details ?? {}) as Record<string, unknown>;
// issue #3218: `r.status` collapses to 'warn' whether ONE item failed
@@ -382,10 +494,15 @@ export async function runExtractAtomsDrainForSource(
failures: typedFailures,
};
},
- countRemaining: () => countExtractAtomsBacklog(engine, extractionSourceId),
+ countRemaining: (signal) => countExtractAtomsBacklog(engine, extractionSourceId, { signal }),
now: Date.now,
onBatch: opts.onBatch,
},
- { windowMs: opts.windowSeconds * 1000, maxBatches: opts.maxBatches },
+ {
+ windowMs: opts.windowSeconds * 1000,
+ maxBatches: opts.maxBatches,
+ signal: opts.signal,
+ deadlineAtMs: opts.deadlineAtMs,
+ },
);
}
diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.ts
index 614025eac6..55dd8fd40d 100644
--- a/src/core/cycle/extract-atoms.ts
+++ b/src/core/cycle/extract-atoms.ts
@@ -71,7 +71,9 @@ import { truncateUtf8 } from '../text-safe.ts';
import { BudgetExhausted, BudgetTracker, loadPricingOverrides } from '../budget/budget-tracker.ts';
import { resolveExtractAtomsCostGate, resolveEmbedModelForCostGate } from './extract-atoms-cost-gate.ts';
import { writeReceipt } from '../extract/receipt-writer.ts';
-import { upsertExtractRollup } from '../extract/rollup-writer.ts';
+import { classifyRunStop, upsertExtractRollup } from '../extract/rollup-writer.ts';
+import { abortableSleep } from '../retry.ts';
+import { throwIfAborted } from '../abort-check.ts';
import { createHash } from 'crypto';
import { slugifySegment } from '../sync.ts';
import { resolveTierDefault } from '../model-config.ts';
@@ -214,6 +216,20 @@ export interface ExtractAtomsOpts {
* `heartbeat()` on the passed reporter.
*/
progress?: ProgressReporter;
+ /**
+ * #5809/#5832: hard stop (the drain's job + cycle-lock + deadline signals,
+ * or the routine cycle's signal). Passed to the chat call and the pacing
+ * pause, checked before each item and before each item's commit. Once
+ * aborted the run writes nothing more: the interrupted item takes no
+ * failure strike and the receipt/rollup writes are skipped.
+ */
+ signal?: AbortSignal;
+ /**
+ * Soft stop (the drain window): checked only before an item starts, so an
+ * in-flight item and its paid call finish and commit. Booked as an expected
+ * limit in the rollup, like a budget stop.
+ */
+ stopSignal?: AbortSignal;
}
interface ExtractedAtom {
@@ -446,11 +462,13 @@ export async function discoverExtractablePages(
* at runtime; this count covers DB pages only. Callers label that caveat.
*
* Fail-soft: returns null on error so the doctor check can report a warn
- * (query failed) rather than a misleading 0.
+ * (query failed) rather than a misleading 0. `opts.signal` cancels the query
+ * (the drain bounds it by its remaining deadline); a cancelled count is null.
*/
export async function countExtractAtomsBacklog(
engine: BrainEngine,
sourceId?: string,
+ opts: { signal?: AbortSignal } = {},
): Promise<number | null> {
try {
// Two modes: scoped (the phase's per-source `remaining`) vs brain-wide
@@ -498,7 +516,7 @@ export async function countExtractAtomsBacklog(
const params = scoped
? [sourceId, extractableTypes, MIN_PAGE_CHARS_FOR_EXTRACTION]
: [extractableTypes, MIN_PAGE_CHARS_FOR_EXTRACTION];
- const rows = await engine.executeRaw<{ cnt: string | number }>(sql, params);
+ const rows = await engine.executeRaw<{ cnt: string | number }>(sql, params, { signal: opts.signal });
return Number(rows[0]?.cnt ?? 0);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
@@ -1073,8 +1091,10 @@ export async function runPhaseExtractAtoms(
}
}
+ let stoppedEarly = false;
await withBudgetTracker(budgetTracker, async () => {
for (const item of work) {
+ if (opts.signal?.aborted || opts.stopSignal?.aborted) { stoppedEarly = true; break; }
await maybeYield();
if (budgetExhausted || budgetTracker.totalSpent >= budgetCap) {
if (item.kind === 'transcript') transcriptsSkipped++;
@@ -1093,6 +1113,7 @@ export async function runPhaseExtractAtoms(
const origin: AtomOrigin | null = managed ? await readAtomOrigin(engine, managed, item) : null;
const visibility = origin?.visibility ?? effectiveVisibility(item.kind === 'transcript' ? { kind: 'transcript' } // #5525
: { kind: 'page', page: await engine.getPage(item.slug, { sourceId }) });
+ throwIfAborted(opts.signal, 'extract_atoms');
if (!opts.dryRun && managed && origin && await resumeManagedAtoms(engine, managed, origin)) {
duplicatesSkipped++;
continue;
@@ -1107,6 +1128,7 @@ export async function runPhaseExtractAtoms(
},
],
maxTokens: maxOutputTokens, responseSchema: ATOMS_RESPONSE_SCHEMA,
+ abortSignal: opts.signal,
});
// Post-await yield: closes the "long LLM call past TTL" hazard
// codex flagged. The 30s throttle inside maybeYield bounds the
@@ -1115,7 +1137,8 @@ export async function runPhaseExtractAtoms(
llmHalt.reset();
// #4540: optional per-item pacing between successful LLM calls.
// setTimeout (not setImmediate) so the lock-refresh interval fires.
- if (pacingMs > 0) await new Promise<void>((r) => setTimeout(r, pacingMs));
+ if (pacingMs > 0) await abortableSleep(pacingMs, opts.signal);
+ throwIfAborted(opts.signal, 'extract_atoms');
estimatedSpendUsd = budgetTracker.totalSpent;
@@ -1306,6 +1329,7 @@ export async function runPhaseExtractAtoms(
// the deterministic slugs make the retry converge.
if (managed && origin) {
for (const atom of managedAtoms) atom.links = provenanceLinks.filter(link => link.to_slug === atom.slug);
+ throwIfAborted(opts.signal, 'extract_atoms');
const published = await publishManagedAtoms(engine, managed, origin, managedAtoms);
writeRequests.push(...published);
if (published.some(receipt => receipt.state !== 'committed')) writesPending++;
@@ -1318,6 +1342,7 @@ export async function runPhaseExtractAtoms(
// after every atom AND provenance edge persisted), then stamp the
// source page. A crash between flip and stamp degrades to the legacy
// atom-rows-mean-done semantics — safe, not lossy.
+ throwIfAborted(opts.signal, 'extract_atoms');
await completeAtomReceipts(engine, sourceId, importedSlugs, hash16, item.kind === 'page' ? item : undefined);
// C-14: atoms are keyed by LLM-chosen titles, which drift between
// extractions. Once this extraction is complete, retire the atoms an
@@ -1339,6 +1364,11 @@ export async function runPhaseExtractAtoms(
} catch (err) {
if (err instanceof OperationError && err.writeRequest) writeRequests.push(err.writeRequest);
if (acceptedPendingReceipt(err)) { writesPending++; continue; }
+ if (opts.signal?.aborted) {
+ stoppedEarly = true;
+ console.error(`[extract_atoms] ${originLabel}: stopped by abort (${err instanceof Error ? err.message : String(err)})`);
+ break;
+ }
if (err instanceof BudgetExhausted) {
budgetExhausted = true;
if (item.kind === 'transcript') transcriptsSkipped++;
@@ -1383,7 +1413,8 @@ export async function runPhaseExtractAtoms(
// v0.42 Wave B2: write extract receipt + rollup row when the phase
// actually extracted atoms. Both are best-effort per F-OUT-19 —
// audit-trail / search-visibility surfaces don't block the phase result.
- if (!opts.dryRun && !managed && totalAtomsExtracted > 0) {
+ const hardStopped = opts.signal?.aborted === true;
+ if (!opts.dryRun && !managed && totalAtomsExtracted > 0 && !hardStopped) {
const runId = `atoms-${Date.now().toString(36)}-${sourceId.slice(0, 4)}`;
try {
await writeReceipt(engine, {
@@ -1402,7 +1433,7 @@ export async function runPhaseExtractAtoms(
console.error(`[extract_atoms] receipt write failed: ${(err as Error).message}`);
}
}
- if (!opts.dryRun) {
+ if (!opts.dryRun && !hardStopped) {
// gbrain#4148 / TRANSIENT_EXTRACT_ERROR_RE: transient provider/infra
// failures (rate limits, timeouts, 5xx, network) are "retryable, never
// counted" by design — count only hardFailureCount here, not
@@ -1413,8 +1444,7 @@ export async function runPhaseExtractAtoms(
kind: 'atoms',
source_id: sourceId,
cost_delta: estimatedSpendUsd,
- round_completed_delta: hardFailureCount === 0 ? 1 : 0,
- halt_delta: hardFailureCount > 0 ? 1 : 0,
+ ...classifyRunStop({ deadline_hit: stoppedEarly, error: hardFailureCount > 0 }),
});
}
diff --git a/src/core/minions/handlers/extract-atoms-drain.ts b/src/core/minions/handlers/extract-atoms-drain.ts
index dfd0044e0c..29cff5f3c6 100644
--- a/src/core/minions/handlers/extract-atoms-drain.ts
+++ b/src/core/minions/handlers/extract-atoms-drain.ts
@@ -29,12 +29,30 @@ export function makeExtractAtomsDrainHandler(engine: BrainEngine): MinionHandler
typeof job.data.repoPath === 'string'
? job.data.repoPath
: ((await engine.getConfig('sync.repo_path')) ?? undefined);
+ const { UnrecoverableError } = await import('../errors.ts');
+ // #5809: at or past the job's deadline the worker dead-letters the row
+ // anyway; a retry would hold the cycle lock for another full timeout.
+ const pastDeadline = () => job.deadlineAtMs != null && Date.now() >= job.deadlineAtMs;
try {
const result = await runExtractAtomsDrainForSource(engine, {
sourceId,
windowSeconds,
brainDir: repoPath,
+ signal: job.signal,
+ deadlineAtMs: job.deadlineAtMs,
});
+ const counts = `batches=${result.batches}, extracted=${result.extracted}, remaining=${result.remaining ?? '?'}`;
+ if (result.stopped === 'deadline') {
+ throw new UnrecoverableError(`extract-atoms-drain: stopped at the job deadline (${counts})`);
+ }
+ // Cancel/pause/shutdown: the worker's own abort handling decides the row.
+ if (result.stopped === 'aborted') {
+ throw job.signal.reason instanceof Error ? job.signal.reason : new Error(`extract-atoms-drain: aborted (${counts})`);
+ }
+ // #5832: another holder took the cycle lock; retry under the job's backoff.
+ if (result.stopped === 'lock_lost') {
+ throw new Error(`extract-atoms-drain: lost the cycle lock lease (${counts})`);
+ }
// issue #3218: every item the drain attempted failed (0 succeeded, >=1
// provider error) — completing this job normally would mark the
// durable job done while the backlog sits untouched, and no retry
@@ -43,6 +61,9 @@ export function makeExtractAtomsDrainHandler(engine: BrainEngine): MinionHandler
// over instead — matching the existing behavior for every other
// handler failure. Partial success (>=1 item extracted) keeps
// completing normally, unchanged.
+ if (result.status === 'provider_failure' && pastDeadline()) {
+ throw new UnrecoverableError(formatDrainProviderFailure(result, { final: true }));
+ }
if (result.status === 'provider_failure') {
throw new Error(formatDrainProviderFailure(result));
}
@@ -51,7 +72,8 @@ export function makeExtractAtomsDrainHandler(engine: BrainEngine): MinionHandler
if (e instanceof LockUnavailableError) {
return { phase: 'extract_atoms', status: 'skipped', deferred: true, reason: 'cycle_already_running' };
}
- throw e;
+ if (e instanceof UnrecoverableError || !pastDeadline()) throw e;
+ throw new UnrecoverableError(e instanceof Error ? e.message : String(e));
}
};
}
diff --git a/test/cycle-extract-atoms-signal.test.ts b/test/cycle-extract-atoms-signal.test.ts
new file mode 100644
index 0000000000..d15564b612
--- /dev/null
+++ b/test/cycle-extract-atoms-signal.test.ts
@@ -0,0 +1,91 @@
+/**
+ * #5833 adjacent: the routine cycle's extract_atoms phase honors the cycle
+ * signal.
+ *
+ * Protects: an autopilot-cycle timeout (external signal) or a duck-typed stub
+ * signal flipped mid-phase stops extract_atoms before its next page, with no
+ * failure strike on the interrupted page. Regression caught: the phase got no
+ * signal at all, so after a timeout it kept extracting (and refreshing the
+ * cycle lock) through the rest of its work list. Existing cycle abort tests
+ * only check phase boundaries, never the inside of a running phase.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runCycle } from '../src/core/cycle.ts';
+import { __setChatTransportForTests, type ChatResult } from '../src/core/ai/gateway.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { emptyHome, withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+let brainDir: string;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ brainDir = mkdtempSync(join(tmpdir(), 'gbrain-xa-signal-'));
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+ rmSync(brainDir, { recursive: true, force: true });
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+});
+
+const atomsAnswer = (): ChatResult => {
+ const text = JSON.stringify([{ title: 'A durable decision', atom_type: 'insight', body: 'The decision body prose.' }]);
+ return {
+ text, blocks: [{ type: 'text', text }], stopReason: 'end',
+ usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic',
+ } as ChatResult;
+};
+
+async function cycleWithSignal(signal: AbortSignal, onFirstCall: () => void): Promise<{ calls: number; failCounts: number[] }> {
+ for (const slug of ['notes/xa-one', 'notes/xa-two', 'notes/xa-three']) {
+ await engine.putPage(slug, {
+ type: 'note', title: slug, compiled_truth: 'A durable decision recorded in prose. '.repeat(20),
+ } as never, { sourceId: 'default' });
+ }
+ let calls = 0;
+ __setChatTransportForTests(async () => {
+ calls++;
+ if (calls === 1) onFirstCall();
+ await new Promise((r) => setTimeout(r, 150));
+ return atomsAnswer();
+ });
+ try {
+ await withEnv({ GBRAIN_HOME: emptyHome(), GBRAIN_SCHEMA_PACK: 'gbrain-creator' }, () =>
+ runCycle(engine, { brainDir, phases: ['extract_atoms'], signal }).catch(() => undefined));
+ // An unsignalled phase keeps running after the cycle returns; give it room.
+ await new Promise((r) => setTimeout(r, 600));
+ } finally {
+ __setChatTransportForTests(null);
+ }
+ const rows = await engine.executeRaw<{ fail_count: number }>('SELECT fail_count FROM extract_atoms_page_state');
+ return { calls, failCounts: rows.map((r) => Number(r.fail_count)) };
+}
+
+describe('routine cycle extract_atoms honors the cycle signal', () => {
+ test('an aborted cycle signal stops the phase before the next page, with no failure strike', async () => {
+ const controller = new AbortController();
+ const { calls, failCounts } = await cycleWithSignal(controller.signal, () => controller.abort(new Error('timeout')));
+ expect(calls).toBe(1);
+ expect(failCounts.filter((n) => n > 0)).toEqual([]);
+ }, 60_000);
+
+ test('a duck-typed { aborted } stub flipped mid-phase also stops it', async () => {
+ const stub = { aborted: false, reason: undefined as unknown } as unknown as AbortSignal;
+ const { calls } = await cycleWithSignal(stub, () => {
+ (stub as unknown as { aborted: boolean; reason: unknown }).aborted = true;
+ (stub as unknown as { aborted: boolean; reason: unknown }).reason = new Error('timeout');
+ });
+ expect(calls).toBe(1);
+ }, 60_000);
+});
diff --git a/test/e2e/extract-atoms-drain-postgres.test.ts b/test/e2e/extract-atoms-drain-postgres.test.ts
new file mode 100644
index 0000000000..3c74140ded
--- /dev/null
+++ b/test/e2e/extract-atoms-drain-postgres.test.ts
@@ -0,0 +1,85 @@
+/**
+ * #5809 / #5832 on real Postgres: the drain's hard stop cancels a blocked
+ * backlog count server-side and releases the cycle lock, and a lease taken
+ * over mid-batch comes back as `stopped: 'lock_lost'` through the real lock
+ * helper. PGLite cannot show either (no server-side cancel, one connection).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { withRefreshingLock } from '../../src/core/db-lock.ts';
+import { runExtractAtomsDrain } from '../../src/core/cycle/extract-atoms-drain.ts';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
+
+const url = process.env.DATABASE_URL;
+
+describe.skipIf(!url)('extract_atoms drain stops on Postgres', () => {
+ let engine: PostgresEngine;
+ beforeAll(async () => {
+ assertSafeE2eDatabaseUrl(url!);
+ engine = new PostgresEngine();
+ await engine.connect({ database_url: url, poolSize: 4 });
+ await engine.initSchema();
+ }, 120_000);
+ afterAll(async () => { await engine?.disconnect(); });
+
+ const sleepers = async () => Number((await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM pg_stat_activity
+ WHERE state = 'active' AND pid <> pg_backend_pid() AND query LIKE 'SELECT pg_sleep(30)%'`,
+ ))[0].n);
+
+ test('a job abort during a blocked final recount cancels the query and releases the cycle lock', async () => {
+ const lockId = 'gbrain-cycle:e2e-drain-bound';
+ const job = new AbortController();
+ let calls = 0;
+ const started = Date.now();
+ const result = await runExtractAtomsDrain(
+ {
+ withLock: (work) => withRefreshingLock(engine, lockId, (signal) => work(signal), { ttlMinutes: 5 }),
+ countRemaining: async (signal) => {
+ calls++;
+ if (calls === 1) return 9;
+ setTimeout(() => job.abort(new Error('timeout')), 300);
+ await engine.executeRaw('SELECT pg_sleep(30)', [], { signal });
+ return 0;
+ },
+ runBatch: async () => ({ extracted: 1, skipped: 0 }),
+ now: Date.now,
+ },
+ { windowMs: 1_000_000, maxBatches: 1, signal: job.signal },
+ );
+ expect(Date.now() - started).toBeLessThan(10_000);
+ expect(result).toMatchObject({ stopped: 'aborted', remaining: 9, batches: 1, extracted: 1 });
+ expect(await engine.executeRaw('SELECT id FROM gbrain_cycle_locks WHERE id = $1', [lockId])).toEqual([]);
+ let left = await sleepers();
+ for (let i = 0; i < 30 && left > 0; i++) {
+ await new Promise((r) => setTimeout(r, 100));
+ left = await sleepers();
+ }
+ expect(left).toBe(0);
+ }, 30_000);
+
+ test('a lease taken over mid-batch returns lock_lost with the partial counters', async () => {
+ const lockId = 'gbrain-cycle:e2e-drain-lease';
+ let reason: unknown = null;
+ try {
+ const result = await runExtractAtomsDrain(
+ {
+ withLock: (work) => withRefreshingLock(engine, lockId, (signal) => work(signal), { ttlMinutes: 0.02, refreshIntervalMs: 100 }),
+ countRemaining: async () => 6,
+ runBatch: async ({ signal }) => {
+ await engine.executeRaw('UPDATE gbrain_cycle_locks SET acquisition_token = gen_random_uuid() WHERE id = $1', [lockId]);
+ await new Promise<void>((resolve) => signal.addEventListener('abort', () => resolve(), { once: true }));
+ reason = signal.reason;
+ return { extracted: 2, skipped: 0 };
+ },
+ now: Date.now,
+ },
+ { windowMs: 1_000_000 },
+ );
+ expect(result).toMatchObject({ stopped: 'lock_lost', batches: 1, extracted: 2, remaining: 6 });
+ expect((reason as Error).name).toBe('LockStolenError');
+ } finally {
+ await engine.executeRaw('DELETE FROM gbrain_cycle_locks WHERE id = $1', [lockId]);
+ }
+ }, 30_000);
+});
diff --git a/test/extract-atoms-drain-errors.test.ts b/test/extract-atoms-drain-errors.test.ts
index 6fb2e42986..15e7b01160 100644
--- a/test/extract-atoms-drain-errors.test.ts
+++ b/test/extract-atoms-drain-errors.test.ts
@@ -23,7 +23,7 @@ import {
type ExtractAtomsDrainDeps,
} from '../src/core/cycle/extract-atoms-drain.ts';
-const passThroughLock: ExtractAtomsDrainDeps['withLock'] = (work) => work();
+const passThroughLock: ExtractAtomsDrainDeps['withLock'] = (work) => work(new AbortController().signal);
describe('extract_atoms drain error surfacing (#4539)', () => {
it('accumulates failure_count and keeps the most recent firstError', async () => {
@@ -349,7 +349,7 @@ describe('runExtractAtomsDrainForSource forwards typed per-item failures (#4730)
'utf8',
);
it('maps d.failures {source, error} → {source, reason} and returns them on the batch', () => {
- const runBatchBlock = src.slice(src.indexOf('runBatch: async () => {'));
+ const runBatchBlock = src.slice(src.indexOf('runBatch: async ({ signal, stopSignal }) => {'));
expect(runBatchBlock).toContain(".map(({ source, error }) => ({ source, reason: error }))");
expect(runBatchBlock).toContain('failures: typedFailures');
});
diff --git a/test/extract-atoms-drain-handler.test.ts b/test/extract-atoms-drain-handler.test.ts
index d00330a298..68686b7913 100644
--- a/test/extract-atoms-drain-handler.test.ts
+++ b/test/extract-atoms-drain-handler.test.ts
@@ -7,8 +7,13 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { MinionQueue } from '../src/core/minions/queue.ts';
import { MinionWorker } from '../src/core/minions/worker.ts';
import { registerBuiltinHandlers } from '../src/commands/jobs.ts';
+import { makeExtractAtomsDrainHandler } from '../src/core/minions/handlers/extract-atoms-drain.ts';
+import type { MinionJobContext } from '../src/core/minions/types.ts';
+import { __setChatTransportForTests } from '../src/core/ai/gateway.ts';
+import { UnrecoverableError } from '../src/core/minions/errors.ts';
import {
formatDrainProviderFailure,
+ runExtractAtomsDrainForSource,
type ExtractAtomsDrainResult,
} from '../src/core/cycle/extract-atoms-drain.ts';
@@ -28,6 +33,7 @@ afterAll(async () => {
beforeEach(async () => {
await engine.executeRaw('DELETE FROM minion_jobs');
+ await engine.executeRaw('DELETE FROM gbrain_cycle_locks');
});
describe('extract-atoms-drain handler', () => {
@@ -72,4 +78,78 @@ describe('extract-atoms-drain handler', () => {
// A clean-run shape (no representative error) keeps the original message.
expect(formatDrainProviderFailure({ ...result, last_error: null })).not.toContain('last error');
});
+
+ // The handler's own contract text: a deadline failure is final, so the
+ // dead-lettered job's error must not promise a retry.
+ test('the final provider_failure text drops "retrying"', () => {
+ const result = { status: 'provider_failure', batches: 2, remaining: 5, last_error: null } as ExtractAtomsDrainResult;
+ expect(formatDrainProviderFailure(result)).toContain('retrying');
+ expect(formatDrainProviderFailure(result, { final: true })).not.toContain('retrying');
+ });
+
+ // #5809: at timeout_ms the worker aborts job.signal and dead-letters the
+ // row, but an inline handler keeps running (and keeps refreshing the source's
+ // cycle lock) unless the drain observes that signal.
+ const drainJob = (signal: AbortSignal, deadlineAtMs: number | null = null) => ({
+ id: 1, name: 'extract-atoms-drain', attempts_made: 0,
+ data: { sourceId: 'default', window: 120 },
+ signal, deadlineAtMs, shutdownSignal: new AbortController().signal,
+ }) as unknown as MinionJobContext;
+ const seedEligiblePage = (slug: string) => engine.putPage(slug, {
+ type: 'note', title: slug, compiled_truth: 'A durable decision recorded in prose. '.repeat(20),
+ } as never, { sourceId: 'default' });
+ const lockRows = () => engine.executeRaw(`SELECT id FROM gbrain_cycle_locks WHERE id = 'gbrain-cycle:default'`);
+
+ test('a job aborted before its deadline throws the abort reason and leaves the cycle lock free', async () => {
+ const controller = new AbortController();
+ controller.abort(new Error('shutdown'));
+ const err = await makeExtractAtomsDrainHandler(engine)(drainJob(controller.signal)).then(() => null, (e: unknown) => e);
+ expect(err).toBeInstanceOf(Error);
+ expect((err as Error).message).toBe('shutdown');
+ expect(err).not.toBeInstanceOf(UnrecoverableError);
+ expect(await lockRows()).toEqual([]);
+ });
+
+ test('the job deadline reaches the in-flight model call, strikes nothing and is final', async () => {
+ await seedEligiblePage('notes/deadline-probe');
+ const callSignals: Array<AbortSignal | undefined> = [];
+ __setChatTransportForTests(async (o) => {
+ callSignals.push(o.abortSignal);
+ await new Promise<void>((resolve) => o.abortSignal?.addEventListener('abort', () => resolve(), { once: true }));
+ throw new Error('claude-cli adapter aborted');
+ });
+ let err: unknown;
+ try {
+ err = await makeExtractAtomsDrainHandler(engine)(drainJob(new AbortController().signal, Date.now() + 300))
+ .then(() => null, (e: unknown) => e);
+ } finally {
+ __setChatTransportForTests(null);
+ }
+ expect(err).toBeInstanceOf(UnrecoverableError);
+ expect((err as Error).message).toContain('stopped at the job deadline');
+ expect((err as Error).message).not.toContain('retrying');
+ expect(callSignals).toHaveLength(1);
+ expect(callSignals[0]?.aborted).toBe(true);
+ expect(await engine.executeRaw('SELECT page_id FROM extract_atoms_page_state')).toEqual([]);
+ expect(await lockRows()).toEqual([]);
+ });
+
+ // #5832: withRefreshingLock aborts the signal it hands its work when the
+ // cycle lock's lease is lost; that signal must reach the model call even for
+ // a caller that passes no signal of its own (gbrain dream --drain).
+ test('the cycle lock signal reaches the model call when the caller passes none', async () => {
+ await seedEligiblePage('notes/lock-probe');
+ const callSignals: Array<AbortSignal | undefined> = [];
+ __setChatTransportForTests(async (o) => {
+ callSignals.push(o.abortSignal);
+ throw new Error('provider unavailable');
+ });
+ try {
+ await runExtractAtomsDrainForSource(engine, { sourceId: 'default', windowSeconds: 120 });
+ } finally {
+ __setChatTransportForTests(null);
+ }
+ expect(callSignals.length).toBeGreaterThan(0);
+ for (const signal of callSignals) expect(signal).toBeInstanceOf(AbortSignal);
+ });
});
diff --git a/test/extract-atoms-drain-stops.test.ts b/test/extract-atoms-drain-stops.test.ts
new file mode 100644
index 0000000000..128956c60a
--- /dev/null
+++ b/test/extract-atoms-drain-stops.test.ts
@@ -0,0 +1,225 @@
+/**
+ * #5809 / #5832 — how the extract_atoms drain stops.
+ *
+ * Protects: a drain job's timeout/cancel, the cycle lock's lease loss and the
+ * job deadline stop the drain (hard stop) and are reported as
+ * `stopped: aborted | lock_lost | deadline` with the partial counters, while
+ * the window (soft stop) never interrupts the batch in flight. Backlog counts
+ * are bounded so a blocked count cannot keep the cycle lock refreshing.
+ * Regression caught: the drain ignored every signal and only checked the
+ * window between batches, so one long batch held `gbrain-cycle:<source>` for
+ * hours and nightly dream skipped. Existing drain tests inject a lock that
+ * never aborts and a clock-only window, so they cannot see any of this.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { withRefreshingLock } from '../src/core/db-lock.ts';
+import { __setChatTransportForTests, type ChatResult } from '../src/core/ai/gateway.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import {
+ runExtractAtomsDrain,
+ runExtractAtomsDrainForSource,
+ type ExtractAtomsDrainDeps,
+} from '../src/core/cycle/extract-atoms-drain.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+});
+
+const untilAborted = (signal: AbortSignal, capMs = 5_000) => new Promise<void>((resolve, reject) => {
+ if (signal.aborted) { resolve(); return; }
+ const t = setTimeout(() => reject(new Error('signal never aborted')), capMs);
+ signal.addEventListener('abort', () => { clearTimeout(t); resolve(); }, { once: true });
+});
+
+describe('hard stops: job signal and lock lease', () => {
+ it.each([
+ { aborts: 'job', stopped: 'aborted', abortDuringBatch: 0, expectedBatches: 0 },
+ { aborts: 'job', stopped: 'aborted', abortDuringBatch: 1, expectedBatches: 1 },
+ { aborts: 'lock', stopped: 'lock_lost', abortDuringBatch: 0, expectedBatches: 0 },
+ { aborts: 'lock', stopped: 'lock_lost', abortDuringBatch: 1, expectedBatches: 1 },
+ ])('a $aborts abort (batch $abortDuringBatch) stops with $stopped, reports the last count, skips progress', async ({ aborts, stopped, abortDuringBatch, expectedBatches }) => {
+ const job = new AbortController();
+ const lock = new AbortController();
+ const aborting = aborts === 'job' ? job : lock;
+ const reason = new Error(`${aborts} aborted`);
+ if (abortDuringBatch === 0) aborting.abort(reason);
+ let batches = 0;
+ let lockSettled = false;
+ const progress: number[] = [];
+ const seen: AbortSignal[] = [];
+ const result = await runExtractAtomsDrain(
+ {
+ withLock: async (work) => { try { return await work(lock.signal); } finally { lockSettled = true; } },
+ countRemaining: async () => 7,
+ runBatch: async ({ signal }) => {
+ batches++;
+ seen.push(signal);
+ if (batches === abortDuringBatch) aborting.abort(reason);
+ return { extracted: 2, skipped: 0 };
+ },
+ now: () => 0,
+ onBatch: ({ batch }) => progress.push(batch),
+ },
+ { windowMs: 1_000_000, signal: job.signal },
+ );
+ expect(result).toMatchObject({ stopped, batches: expectedBatches, extracted: expectedBatches * 2, status: 'ok' });
+ expect(result.remaining).toBe(expectedBatches ? 7 : null);
+ expect(seen.map((s) => s.reason)).toEqual(Array(expectedBatches).fill(reason));
+ expect(progress).toEqual([]);
+ expect(lockSettled).toBe(true);
+ });
+
+ it('the job deadline reaches the batch in flight and stops with deadline', async () => {
+ const counts: number[] = [];
+ const result = await runExtractAtomsDrain(
+ {
+ withLock: (work) => work(new AbortController().signal),
+ countRemaining: async () => { counts.push(1); return 12; },
+ runBatch: async ({ signal }) => {
+ await untilAborted(signal);
+ expect((signal.reason as Error).message).toContain('job deadline reached');
+ return { extracted: 3, skipped: 0 };
+ },
+ now: Date.now,
+ },
+ { windowMs: 1_000_000, deadlineAtMs: Date.now() + 50 },
+ );
+ expect(result).toMatchObject({ stopped: 'deadline', batches: 1, extracted: 3, remaining: 12 });
+ expect(counts).toHaveLength(1);
+ });
+});
+
+describe('soft stop: the window', () => {
+ it('a window ending mid-batch stops the batch at its next item without aborting the call in flight', async () => {
+ let hardAbortedAtWindow: boolean | null = null;
+ let batches = 0;
+ const result = await runExtractAtomsDrain(
+ {
+ withLock: (work) => work(new AbortController().signal),
+ countRemaining: async () => 5,
+ runBatch: async ({ signal, stopSignal }) => {
+ batches++;
+ await untilAborted(stopSignal);
+ hardAbortedAtWindow = signal.aborted;
+ return { extracted: 1, skipped: 0 };
+ },
+ now: Date.now,
+ },
+ { windowMs: 50 },
+ );
+ expect(hardAbortedAtWindow as boolean | null).toBe(false);
+ expect(batches).toBe(1);
+ expect(result).toMatchObject({ stopped: 'window', extracted: 1, remaining: 5 });
+ });
+});
+
+describe('bounded backlog counts', () => {
+ it('a count that never answers is abandoned at its bound and reported as unknown', async () => {
+ let calls = 0;
+ const started = Date.now();
+ const result = await runExtractAtomsDrain(
+ {
+ withLock: (work) => work(new AbortController().signal),
+ countRemaining: (signal) => {
+ calls++;
+ return calls === 1 ? Promise.resolve(4) : new Promise(() => { void signal; });
+ },
+ runBatch: async () => ({ extracted: 1, skipped: 0 }),
+ now: Date.now,
+ },
+ { windowMs: 1_000_000, maxBatches: 1, countTimeoutMs: 100 },
+ );
+ expect(Date.now() - started).toBeLessThan(2_000);
+ expect(result).toMatchObject({ stopped: 'max_batches', remaining: null, batches: 1 });
+ });
+
+ it('cancelling while the final recount is blocked releases the real cycle lock within the bound', async () => {
+ const job = new AbortController();
+ let calls = 0;
+ let countSignal: AbortSignal | null = null;
+ const started = Date.now();
+ const result = await runExtractAtomsDrain(
+ {
+ withLock: (work) => withRefreshingLock(engine, 'gbrain-cycle:drain-bound', (signal) => work(signal), { ttlMinutes: 5 }),
+ countRemaining: (signal) => {
+ calls++;
+ if (calls === 1) return Promise.resolve(9);
+ countSignal = signal;
+ setTimeout(() => job.abort(new Error('timeout')), 50);
+ return new Promise(() => {});
+ },
+ runBatch: async () => ({ extracted: 1, skipped: 0 }),
+ now: Date.now,
+ },
+ { windowMs: 1_000_000, maxBatches: 1, signal: job.signal },
+ );
+ expect(Date.now() - started).toBeLessThan(5_000);
+ expect(result).toMatchObject({ stopped: 'aborted', remaining: 9, batches: 1, extracted: 1 });
+ expect((countSignal as AbortSignal | null)?.aborted).toBe(true);
+ expect(await engine.executeRaw(`SELECT id FROM gbrain_cycle_locks WHERE id = 'gbrain-cycle:drain-bound'`)).toEqual([]);
+ });
+});
+
+describe('lease loss through the real lock helper', () => {
+ it('a lease taken over mid-batch returns lock_lost with the partial counters instead of throwing', async () => {
+ const lockId = 'gbrain-cycle:drain-lease';
+ let batchSignalReason: unknown = null;
+ const deps: ExtractAtomsDrainDeps = {
+ withLock: (work) => withRefreshingLock(engine, lockId, (signal) => work(signal), { ttlMinutes: 0.01, refreshIntervalMs: 50 }),
+ countRemaining: async () => 6,
+ runBatch: async ({ signal }) => {
+ await engine.executeRaw(`UPDATE gbrain_cycle_locks SET acquisition_token = gen_random_uuid() WHERE id = $1`, [lockId]);
+ await untilAborted(signal);
+ batchSignalReason = signal.reason;
+ return { extracted: 2, skipped: 0 };
+ },
+ now: Date.now,
+ };
+ const result = await runExtractAtomsDrain(deps, { windowMs: 1_000_000 });
+ expect(result).toMatchObject({ stopped: 'lock_lost', batches: 1, extracted: 2, remaining: 6, status: 'ok' });
+ expect((batchSignalReason as Error).name).toBe('LockStolenError');
+ });
+});
+
+describe('the drain window on the real phase', () => {
+ it('a 1 s window stops within one page: the straddling page finishes and counts, the next never starts', async () => {
+ for (const slug of ['notes/window-a', 'notes/window-b']) {
+ await engine.putPage(slug, {
+ type: 'note', title: slug, compiled_truth: 'A durable decision recorded in prose. '.repeat(20),
+ } as never, { sourceId: 'default' });
+ }
+ const calls: Array<{ abortedAtEnd: boolean | undefined }> = [];
+ __setChatTransportForTests(async (o) => {
+ await new Promise((r) => setTimeout(r, 1_300));
+ calls.push({ abortedAtEnd: o.abortSignal?.aborted });
+ const text = JSON.stringify([{ title: 'A durable decision', atom_type: 'insight', body: 'The decision body prose.' }]);
+ return {
+ text, blocks: [{ type: 'text', text }], stopReason: 'end',
+ usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic',
+ } as ChatResult;
+ });
+ let result;
+ try {
+ result = await runExtractAtomsDrainForSource(engine, { sourceId: 'default', windowSeconds: 1 });
+ } finally {
+ __setChatTransportForTests(null);
+ }
+ expect(calls).toEqual([{ abortedAtEnd: false }]);
+ expect(result).toMatchObject({ stopped: 'window', batches: 1, extracted: 1, remaining: 1 });
+ expect(await engine.executeRaw(`SELECT id FROM gbrain_cycle_locks`)).toEqual([]);
+ }, 30_000);
+});
diff --git a/test/extract-atoms-drain.test.ts b/test/extract-atoms-drain.test.ts
index b6bc03c0f2..7fae5f209c 100644
--- a/test/extract-atoms-drain.test.ts
+++ b/test/extract-atoms-drain.test.ts
@@ -23,7 +23,7 @@ function seq(values: Array<number | null>): () => Promise<number | null> {
return async () => values[Math.min(i++, values.length - 1)];
}
-const passThroughLock: ExtractAtomsDrainDeps['withLock'] = (work) => work();
+const passThroughLock: ExtractAtomsDrainDeps['withLock'] = (work) => work(new AbortController().signal);
describe('runExtractAtomsDrain (issue #1678)', () => {
it('drains to empty and reports stopped=drained', async () => {
@@ -198,7 +198,7 @@ describe('shared wiring helper holds the cycle lock (5A)', () => {
// not from `r.status` (which collapses partial and total failure into the
// same 'warn' value — the exact discard the issue reports).
it('runBatch derives providerFailure from failures.length + zero processed items, not r.status', () => {
- const runBatchBlock = src.slice(src.indexOf('runBatch: async () => {'));
+ const runBatchBlock = src.slice(src.indexOf('runBatch: async ({ signal, stopSignal }) => {'));
expect(runBatchBlock).toContain('d.failures');
expect(runBatchBlock).toContain('transcripts_processed');
expect(runBatchBlock).toContain('pages_processed');
@@ -226,10 +226,7 @@ describe('extract-atoms-drain Minion handler retries on provider_failure (issue
const jobsSrc = surfaceFileSource('jobs', 'src/commands/jobs.ts');
// W4 jobs: the handler body moved into its own module; jobs.ts keeps the registration.
const handlerSrc = surfaceFileSource('jobs', 'src/core/minions/handlers/extract-atoms-drain.ts');
- const handlerBlock = handlerSrc.slice(
- handlerSrc.indexOf('export function makeExtractAtomsDrainHandler('),
- handlerSrc.indexOf('export function makeExtractAtomsDrainHandler(') + 2200,
- );
+ const handlerBlock = handlerSrc.slice(handlerSrc.indexOf('export function makeExtractAtomsDrainHandler('));
it('jobs.ts registers the extract-atoms-drain handler module', () => {
expect(jobsSrc).toContain("registerBuiltinJob(worker, engine, 'extract-atoms-drain', makeExtractAtomsDrainHandler(engine))");
diff --git a/test/extract-atoms-failure-classes.test.ts b/test/extract-atoms-failure-classes.test.ts
index ee536618c7..d6852fa64b 100644
--- a/test/extract-atoms-failure-classes.test.ts
+++ b/test/extract-atoms-failure-classes.test.ts
@@ -436,3 +436,76 @@ describe('runPhaseExtractAtoms — completion receipt (gbrain#4148)', () => {
expect(done.map(p => p.slug)).not.toContain('meetings/2026-04-03');
});
});
+
+// #5809 / #5832: the drain's hard signal (job timeout/cancel, cycle-lock lease
+// loss, job deadline) reaches the in-flight model call and stops the run
+// before the next commit; the interrupted page takes no strike and nothing is
+// written after the stop (no atoms, no scan state, no rollup row). The soft
+// signal (drain window) lets the page in flight finish and commit, then stops
+// before the next page, booked as an expected limit.
+describe('runPhaseExtractAtoms — hard and soft stops (#5809)', () => {
+ const mkPages = (slugs: string[]) =>
+ slugs.map((slug, i) => ({ slug, content: 'prose', contentHash: String(i + 1).repeat(16) }));
+ const atomPages = async () =>
+ Number((await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM pages WHERE type = 'atom'`))[0].n);
+ const rollup = async () => (await engine.executeRaw<{ round_completed_count: number; expected_limit_count: number; halt_count: number }>(
+ `SELECT round_completed_count, expected_limit_count, halt_count FROM extract_rollup_7d WHERE kind = 'atoms' AND source_id = 'default'`,
+ ))[0];
+
+ test.each([
+ { callOutcome: 'throws', pacingMs: null },
+ { callOutcome: 'still answers', pacingMs: null },
+ { callOutcome: 'still answers under per-item pacing', pacingMs: '60000' },
+ ])('a hard abort while the model call $callOutcome commits nothing and strikes nothing', async ({ callOutcome, pacingMs }) => {
+ if (pacingMs) await engine.setConfig('cycle.extract_atoms.pacing_ms', pacingMs);
+ await seedPage('note/ab1');
+ await seedPage('note/ab2');
+ const controller = new AbortController();
+ const callSignals: Array<AbortSignal | undefined> = [];
+ const result = await runPhaseExtractAtoms(engine, {
+ sourceId: 'default',
+ _transcripts: [],
+ _pages: mkPages(['note/ab1', 'note/ab2']),
+ signal: controller.signal,
+ _chat: async (o: ChatOpts) => {
+ callSignals.push(o.abortSignal);
+ controller.abort(new Error('timeout'));
+ if (callOutcome === 'throws') throw new Error('claude-cli adapter aborted');
+ return okChatResult(ATOM_JSON);
+ },
+ }).finally(() => engine.unsetConfig('cycle.extract_atoms.pacing_ms'));
+ expect(callSignals).toEqual([controller.signal]);
+ expect(result.details.failures).toEqual([]);
+ expect(result.details.pages_processed).toBe(0);
+ expect(await atomPages()).toBe(0);
+ expect(await stateOf('note/ab1')).toBeUndefined();
+ expect(await stateOf('note/ab2')).toBeUndefined();
+ expect(await rollup()).toBeUndefined();
+ }, 20_000);
+
+ test('a soft stop during a page lets that page commit, then stops before the next one', async () => {
+ await seedPage('note/sf1');
+ await seedPage('note/sf2');
+ const hard = new AbortController();
+ const soft = new AbortController();
+ const calls: Array<boolean | undefined> = [];
+ const result = await runPhaseExtractAtoms(engine, {
+ sourceId: 'default',
+ _transcripts: [],
+ _pages: mkPages(['note/sf1', 'note/sf2']),
+ signal: hard.signal,
+ stopSignal: soft.signal,
+ _chat: async (o: ChatOpts) => {
+ soft.abort(new Error('window'));
+ calls.push(o.abortSignal?.aborted);
+ return okChatResult(ATOM_JSON);
+ },
+ });
+ expect(calls).toEqual([false]);
+ expect(result.details.pages_processed).toBe(1);
+ expect(result.details.atoms_extracted).toBe(1);
+ expect((await stateOf('note/sf1'))?.tombstoned).toBe(true);
+ expect(await stateOf('note/sf2')).toBeUndefined();
+ expect(await rollup()).toMatchObject({ round_completed_count: 0, expected_limit_count: 1, halt_count: 0 });
+ });
+});