Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(dream): report a drain window that closes before a batch starts as a window stop, not atom_drain_no_progress (#7826)

garrytandbccaffedfa9
diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.md
index 79fc5778a8..25206c1e61 100644
--- a/docs/architecture/key-files/core-cycle.md
+++ b/docs/architecture/key-files/core-cycle.md
@@ -17,7 +17,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/cycle/extract-atoms-cost-gate.ts` — cost-gate decision for the extract_atoms `BudgetTracker`, shared with the Life Chronicle `chronicle` phase through `settleExtractAtomsCostGate`'s `target` (phase name, refusal key prefix `chronicle.no_pricing.`, no rollup). `resolveExtractAtomsCostGate(extractModel, embedModel, overrides?, {explicitBudget?})` (pure) returns `{enforceCap, unpricedModel?, unpricedKind?, refusal?}`: 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). A DEFAULT cap is dropped for an unpriced route (warn and run). When the operator SET `cycle.extract_atoms.budget_usd` (`explicitBudget`), an unpriced chat model or embed route yields `refusal` (the shared `no_pricing` guidance). `settleExtractAtomsCostGate` acts before any work item: it warns on a dropped cap; on a refusal it returns the phase's `warn` result (`details.reason: 'no_pricing'`, `details.no_pricing`, no model call), records the guidance at `cycle.extract_atoms.no_pricing.<source>` and upserts the rollup as an expected limit, not a halt; any run past the gate clears the source's record (dry runs record nothing). `readExtractAtomsNoPricing` + `withExtractAtomsNoPricing` overlay doctor's `extract_health` (wired in `doctor/checks/local-audits.ts`) with a `warn` naming the model and `register_command`. Pinned by `test/extract-atoms-embed-cost-gate.test.ts` and `test/extract-atoms-explicit-cap-no-pricing.test.ts`.
-- `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|budget`); `budget` (#6425) stops after the first batch that reports `budgetSkipped > 0` (the attempt's one tracker is spent) and carries `spent_usd`/`budget_usd`, which `dream --drain` renders as the spend, the cap and an `atom_drain_budget` notice whose paid fix raises `cycle.extract_atoms.budget_usd`; the Minion handler completes it normally; 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. One `runExtractAtomsDrainForSource` call is one drain attempt: its batches share one `BudgetTracker` (the per-run `cycle.extract_atoms.budget_usd` cap is the attempt's cap) and one `MaintenanceWriteWait` (`persistence/maintenance-wait.ts`, bounded by `deadlineAtMs`). `structuralAtomRefusal` maps an `owner_unavailable`/`permission_denied` refusal from the atom session preflight to `STRUCTURAL_REFUSAL_PREFIX` text; the `extract-atoms-drain` Minion handler (`src/core/minions/handlers/extract-atoms-drain.ts`) throws it as `UnrecoverableError`, so the job dead-letters once with no model call and the auto-drain cap does not count it. `last_error` and the typed failure records pass through `sanitizeFailureText` (secret/DSN redaction, bounded). #7514: a record whose write did not commit also carries `request_id` and `code`; the adapter leaves such items out of `providerFailure` and its class (they never reached a provider), and a batch whose only progress is write-failure strikes (`writeStrikes`) is not `no_progress`, so the drain moves on and the strikes reach their hold in the same window. A `provider_failure` result carries `provider_failure_class` (`batchProviderFailureClass`: the phase's `aborted_global_error` halt class `auth`/`billing`/`model_not_found`/`rate_limit`, `content_block` when every failure is a provider content block, else `transient`). `formatDrainProviderFailure(result, {final?})` renders the handler's `provider_failure` throw; the handler throws `UnrecoverableError` on `deadline`, on a provider failure `drainOutcome` marks not retryable, 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-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|budget`); `budget` (#6425) stops after the first batch that reports `budgetSkipped > 0` (the attempt's one tracker is spent) and carries `spent_usd`/`budget_usd`, which `dream --drain` renders as the spend, the cap and an `atom_drain_budget` notice whose paid fix raises `cycle.extract_atoms.budget_usd`; the Minion handler completes it normally; 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. One `runExtractAtomsDrainForSource` call is one drain attempt: its batches share one `BudgetTracker` (the per-run `cycle.extract_atoms.budget_usd` cap is the attempt's cap) and one `MaintenanceWriteWait` (`persistence/maintenance-wait.ts`, bounded by `deadlineAtMs`). `structuralAtomRefusal` maps an `owner_unavailable`/`permission_denied` refusal from the atom session preflight to `STRUCTURAL_REFUSAL_PREFIX` text; the `extract-atoms-drain` Minion handler (`src/core/minions/handlers/extract-atoms-drain.ts`) throws it as `UnrecoverableError`, so the job dead-letters once with no model call and the auto-drain cap does not count it. `last_error` and the typed failure records pass through `sanitizeFailureText` (secret/DSN redaction, bounded). #7514: a record whose write did not commit also carries `request_id` and `code`; the adapter leaves such items out of `providerFailure` and its class (they never reached a provider), and a batch whose only progress is write-failure strikes (`writeStrikes`) is not `no_progress` (nor is a 0/0 batch started after the window closed: that is `window`), so the drain moves on and the strikes reach their hold in the same window. A `provider_failure` result carries `provider_failure_class` (`batchProviderFailureClass`: the phase's `aborted_global_error` halt class `auth`/`billing`/`model_not_found`/`rate_limit`, `content_block` when every failure is a provider content block, else `transient`). `formatDrainProviderFailure(result, {final?})` renders the handler's `provider_failure` throw; the handler throws `UnrecoverableError` on `deadline`, on a provider failure `drainOutcome` marks not retryable, 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-drain-outcome.ts` — #6817: `drainOutcome(result)`, the one mapping from a drain stop to exit code, JSON `status` (never `ok` for an incomplete stop), `retryable`, `code` and `reason`, read from the error registry (`atom_drain_incomplete` exit 11, `atom_drain_provider_failure` exit 1 with `rate_limit`/`transient` overridden to retryable exit 11, `atom_drain_no_progress` exit 1; a null count is always `atom_drain_incomplete`/`count_unavailable`). Used by `dream --drain` and the `extract-atoms-drain` Minion handler; type-only import of the drain module. Tests: `test/extract-atoms-drain-outcome.test.ts`, `test/dream-drain-failure-summary.serial.test.ts`, `test/extract-atoms-drain-handler.test.ts`.
- `src/core/cycle/extract-atoms-budget-notice.ts` — #6425: `drainBudgetNotice(result)` renders the `atom_drain_budget` notice a `budget`-stopped drain carries in `gbrain dream --drain --json` (spend, per-run cap, pages left; paid fix `gbrain config set cycle.extract_atoms.budget_usd <USD>`, verify `gbrain config get`), and `usd` formats the amounts for the stderr stop line. Dynamically imported by `dream.ts` so its notice-rendering imports stay out of the CLI flag scan. Tests: `test/dream-drain-failure-summary.serial.test.ts`.
diff --git a/src/core/cycle/extract-atoms-drain.ts b/src/core/cycle/extract-atoms-drain.ts
index 9387cb2403..492acc1a03 100644
--- a/src/core/cycle/extract-atoms-drain.ts
+++ b/src/core/cycle/extract-atoms-drain.ts
@@ -421,6 +421,8 @@ export async function runExtractAtomsDrain(
// 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) {
+ // #7826: the window closed before this batch started its first item; that is a window stop, not a stall.
+ if (soft.signal.aborted) { stopped = 'window'; break; }
const after = await count();
if (hard.signal.aborted) break;
if (after !== null) lastCount = after;
diff --git a/test/extract-atoms-drain-stops.test.ts b/test/extract-atoms-drain-stops.test.ts
index bd24ebf7da..97f59ebdc7 100644
--- a/test/extract-atoms-drain-stops.test.ts
+++ b/test/extract-atoms-drain-stops.test.ts
@@ -124,6 +124,29 @@ describe('soft stop: the window', () => {
expect(batches).toBe(1);
expect(result).toMatchObject({ stopped: 'window', extracted: 1, remaining: 5 });
});
+
+ it('#7826: a window that closes after the loop check but before the batch starts is a window stop, not no_progress', async () => {
+ let clock = 0;
+ let counts = 0;
+ let batchSawStop: boolean | null = null;
+ const result = await runExtractAtomsDrain(
+ {
+ withLock: (work) => work(new AbortController().signal),
+ countRemaining: async () => {
+ if (++counts === 1) { await new Promise(resolve => setTimeout(resolve, 80)); clock = 1_000; }
+ return 5;
+ },
+ runBatch: async ({ stopSignal }) => {
+ batchSawStop = stopSignal.aborted;
+ return { extracted: 0, skipped: 0 };
+ },
+ now: () => clock,
+ },
+ { windowMs: 20 },
+ );
+ expect(batchSawStop as boolean | null).toBe(true);
+ expect(result).toMatchObject({ stopped: 'window', batches: 1, extracted: 0, remaining: 5 });
+ });
});
describe('bounded backlog counts', () => {