Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(autopilot): resumable deadline-aware global maintenance, configurable deadline, global_maintenance_timeouts doctor check (#4578)
garrytan5e7cff18d8cf
diff --git a/docs/architecture/key-files/core-minions-1.md b/docs/architecture/key-files/core-minions-1.mdindex e9d8051dc6..87691d209b 100644--- a/docs/architecture/key-files/core-minions-1.md+++ b/docs/architecture/key-files/core-minions-1.md@@ -4,7 +4,7 @@Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.- `src/core/minions/` — Minions job queue: BullMQ-inspired, Postgres-native (queue, worker, backoff, types, protected-names, quiet-hours, handlers/shell). Private dream-inline-* queues carry an explicit lifecycle: owner job id + owner token + a renewable lease (columns on minion_jobs; `queue.ts` `reconcilePrivateQueue` terminalizes one queue through the normal cancelJobs bookkeeping and stamps every cancellation with the machine-readable `private_queue_reconciled:` reason family; `renewPrivateQueueLease` is MONOTONIC — GREATEST — so a default-horizon renewal can never shrink a creation-time lease; `reconcileOrphanedPrivateQueues` cancels only provably-orphaned queues: no healthy child lock, owner terminal/missing or lease expired; legacy unowned rows are left to Doctor/retriage; `classifyPrivateQueueForRecovery` is PUBLIC so the doctor orphan check buckets through the same verdict). Recovery runs in `gbrain jobs work` after driver/selected-child readiness and `ensureSchema`, for bare AND supervised workers (including autopilot spawns/respawns); the standalone parent does not recover queues in `beforeSpawn`. `maybeRunWorkerStartupRecovery(queue, process.env, true)` keeps this worker-owned ordering even under `GBRAIN_SUPERVISED=1`. Dream-cycle start also recovers (cycle.ts, next to the cycle lock reap — the ONLY lane on PGLite, which inlines every child). `deriveWedgeSignal` is queue-aware: a dream-inline queue is never 'wedged' (no shared worker can claim it) — it reports `private_queue: true` so jobs stats / get_job_stats / doctor all point at reconciliation instead of the impossible worker restart.-- `src/core/minions/handlers/sync.ts` (and the other built-in job handler modules: `embed`, `lint`, `lint-fix`, `extract`, `extract-conversation-facts`, `chronicle-extract`, `loops-extract`, `enrich`, `integrity`, `integrity-auto`, `sync-retry-failed`, `import`, `backlinks`, `facts-absorb`, `autopilot-cycle`, `autopilot-global-maintenance`, `reindex`, `repair-jsonb`, `orphans`, `purge`, `cycle-phase`, `extract-atoms-drain`, `extract-ner`, `extract-takes-from-pages`, `extract-timeline-from-meetings`, `embed-catch-up`, `unify-types`, plus `job-pull.ts`) — one module per built-in handler body, each a `make<Name>Handler(engine)` factory (or a `MinionHandler` const when it needs no engine). Registered in a fixed order by `registerBuiltinHandlers` in `src/commands/jobs.ts`, which keeps the registration kind (plain vs gateway-refreshing) and wrappers such as `withFactsAbsorbHaltCooldown`; `cycle-phase.ts` serves the six phase wrappers. Command cores are imported lazily inside each handler. `resolveJobPull` and the facts-absorb retry predicates are re-exported from `jobs.ts`.+- `src/core/minions/handlers/sync.ts` (and the other built-in job handler modules: `embed`, `lint`, `lint-fix`, `extract`, `extract-conversation-facts`, `chronicle-extract`, `loops-extract`, `enrich`, `integrity`, `integrity-auto`, `sync-retry-failed`, `import`, `backlinks`, `facts-absorb`, `autopilot-cycle`, `autopilot-global-maintenance`, `reindex`, `repair-jsonb`, `orphans`, `purge`, `cycle-phase`, `extract-atoms-drain`, `extract-ner`, `extract-takes-from-pages`, `extract-timeline-from-meetings`, `embed-catch-up`, `unify-types`, plus `job-pull.ts`) — one module per built-in handler body, each a `make<Name>Handler(engine)` factory (or a `MinionHandler` const when it needs no engine). Registered in a fixed order by `registerBuiltinHandlers` in `src/commands/jobs.ts`, which keeps the registration kind (plain vs gateway-refreshing) and wrappers such as `withFactsAbsorbHaltCooldown`; `cycle-phase.ts` serves the six phase wrappers. Command cores are imported lazily inside each handler. `resolveJobPull` and the facts-absorb retry predicates are re-exported from `jobs.ts`. `autopilot-global-maintenance` runs one `runCycle` call per maintenance phase and keeps its pass position in config `autopilot.global_maintenance.progress`: it stops starting a phase whose last measured duration would cross the job deadline (minus a 60 s reserve), the next job resumes at that phase, and a phase still marked running when an earlier job died is skipped for the rest of the pass; last_global_at is stamped only when a pass completes with no blocking phase. The deadline comes from `GBRAIN_GLOBAL_MAINTENANCE_TIMEOUT_MS` > `autopilot.global_maintenance_timeout_ms` > the autopilot default (`autopilot-fanout.ts:resolveGlobalMaintenanceTimeoutMs`); doctor `global_maintenance_timeouts` (`doctor/checks/global-maintenance-timeouts.ts`) warns after three consecutive deaths and names `gbrain dream --phase <name>` (`autopilot-global-maintenance-resume-4578.test.ts`).- `src/core/minions/admission.ts` — submit-side queue admission control (the drain-side pool-starvation half is the job-isolation work; claim fairness is a filed TODO, deliberately out of scope). Three primitives resolved per name via `resolveAdmissionPolicy` (config `minions.*` > per-name defaults tables, 60s in-process cache, fail-open with a once-per-process stderr warn; env kill-switch `GBRAIN_MINIONS_ADMISSION=0` disables all three): PARAM-COALESCING (`PARAM_COALESCE_DEFAULT` — on for `subagent`; `computeParamHash` = sha256 of stable-stringified payload excluding only `__param_hash` itself — `__owner_client_id` is deliberately INCLUDED so owner lanes never cross; parentless + waiting-only + age-bounded to ttl/2), WAITING-TTL (`WAITING_TTL_DEFAULT_HOURS` — 48h for `subagent`; swept by `MinionQueue.handleWaitingTTL` through `cancelJobs(ids, {reason, rootStatuses:['waiting']})` so descendants cancel, child_done lands, aggregator parents resolve, and the reason stamps ROOT ids only; ≤500/tick oldest-first; warn-before-act is `runWaitingTtlTick` — first tick counts affected + stamps `TTL_NOTICE_SHOWN_KEY` with an ISO timestamp, sweeping starts only after `ttlNoticeGraceMs()` (1h default, env `GBRAIN_MINIONS_TTL_NOTICE_GRACE_MS`) elapses; `gbrain upgrade` prints the same one-shot notice and starts the same clock; legacy `'true'` flag values sweep immediately), and NAME-GLOBAL QUOTA (`QUOTA_MAX_WAITING_DEFAULT` EMPTY by operator decision — activates only via `minions.quota_max_waiting.<name>`; counts the name across ALL queues so per-run `dream-inline-*` fanout queues can't dodge it, EXACT under concurrency via a `minion_quota:<name>` advisory xact lock taken only when a quota is configured; throws typed `QueueQuotaExceededError`, checked everywhere via `isQueueQuotaExceededError` — dream submitters record a phase skip, synthesize rolls back the current transcript's fresh chunks, agent fanout cancels the whole tree, `submit_agent` maps to a structured `rate_limited` OperationError). `TTL_REASON_PREFIX` is the single source for the sweep's error_text prefix and the stats/doctor LIKE patterns; `safeConfigSegment` gates untrusted job names out of copy-pasteable config hints. Alerting rides `getStats` (`drained_completed/failed/dead/cancelled` keyed on finished_at + `waiting_now` + `oldest_waiting_minutes`), the `jobs stats` DIVERGENT-QUEUE / waiting-TTL screams (`GBRAIN_QUEUE_DIVERGENCE_RATIO`=2, `GBRAIN_QUEUE_DIVERGENCE_MIN_WAITING`=50; divergence compares intake vs COMPLETED so TTL-cancel storms can't masquerade as throughput) + `--json`, and doctor `checkQueueHealth`. Pinned by `test/minions-admission.test.ts` + `test/jobs-stats-divergence.serial.test.ts`.diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex 5db0e92779..bd862d1429 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -182,3 +182,26 @@ previous statement while you report it:The guard is retired in the next release; that release prints a one-time noticewhen the inert setting is still present.++## Global maintenance timeouts++**Doctor warns `global_maintenance_timeouts`, or late maintenance phases+(orphans, purge, the brain-wide embed) never seem to run?** On a large brain+one `autopilot-global-maintenance` job may not fit every phase before its+deadline (30 minutes by default). Each job now stops starting phases that its+deadline would cut off and the next job resumes at that phase, so one pass can+span several jobs; the resume point is the config row+`autopilot.global_maintenance.progress`. A phase that was running when a job+died is skipped for the rest of that pass so the others still run, and doctor+warns once it has killed three jobs in a row (or the last three jobs all died+at the deadline).++1. Run the named phase in the foreground, without the job deadline:+ `gbrain dream --phase <name>` (for example `gbrain dream --phase embed`).+2. Give the job more time if your brain needs it:+ `gbrain config set autopilot.global_maintenance_timeout_ms 3600000`, or set+ `GBRAIN_GLOBAL_MAINTENANCE_TIMEOUT_MS` in the autopilot service environment+ (the variable wins over the config key; values below 60000 are ignored).+ Unset both to return to the default.+3. Confirm with `gbrain doctor`: `global_maintenance_timeouts` is `ok` after the+ next job finishes within its deadline.diff --git a/src/commands/autopilot-fanout.ts b/src/commands/autopilot-fanout.tsindex 2f39f4fe79..3b0d1d3b63 100644--- a/src/commands/autopilot-fanout.ts+++ b/src/commands/autopilot-fanout.ts@@ -658,6 +658,21 @@ export function isGlobalMaintenanceStale(lastGlobalAtIso: string | null, now = Dreturn (now - d.getTime()) / 60_000 >= floorMin;}+/**+ * #4578: the global maintenance job deadline. Precedence:+ * GBRAIN_GLOBAL_MAINTENANCE_TIMEOUT_MS > config autopilot.global_maintenance_timeout_ms+ * > the autopilot full-cycle default. Values below one minute are ignored.+ */+export async function resolveGlobalMaintenanceTimeoutMs(engine: BrainEngine, fallbackMs: number): Promise<number> {+ const parse = (raw: string | null | undefined) => {+ const n = raw ? Number(raw) : NaN;+ return Number.isSafeInteger(n) && n >= 60_000 ? n : null;+ };+ return parse(process.env.GBRAIN_GLOBAL_MAINTENANCE_TIMEOUT_MS)+ ?? parse(await engine.getConfig('autopilot.global_maintenance_timeout_ms'))+ ?? fallbackMs;+}+/*** #2194 fix #3 / #2227 bug #3 — dispatch the single brain-wide maintenance job* that runs the `mixed` + `global` cycle phases ONCE per@@ -688,6 +703,7 @@ export async function dispatchGlobalMaintenance(return { dispatched: false, reason: 'fresh' };}+ const timeoutMs = await resolveGlobalMaintenanceTimeoutMs(engine, opts.timeoutMs);const job = await queue.add('autopilot-global-maintenance',{ repoPath: opts.repoPath, phases: MAINTENANCE_PHASES },@@ -698,7 +714,7 @@ export async function dispatchGlobalMaintenance(// brain-wide pass is still in flight — so duplicates never stack.idempotency_key: `autopilot-global:${opts.slot}`,max_attempts: 2,- timeout_ms: opts.timeoutMs,+ timeout_ms: timeoutMs,maxPending: 1,},);diff --git a/src/commands/doctor/checks/global-maintenance-timeouts.ts b/src/commands/doctor/checks/global-maintenance-timeouts.tsnew file mode 100644index 0000000000..ce8ccb6fa4--- /dev/null+++ b/src/commands/doctor/checks/global-maintenance-timeouts.ts@@ -0,0 +1,65 @@+/**+ * global_maintenance_timeouts doctor check (#4578): the brain-wide maintenance+ * job (`autopilot-global-maintenance`) keeps dying at its deadline. Warns when+ * its last three finished jobs were all timeout deaths, or when one phase was+ * running in three consecutive job deaths (the handler then skips it each+ * pass). The fix runs the phase alone, without the job deadline, and the+ * deadline itself is configurable.+ */+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { readGlobalMaintenanceProgress } from '../../../core/minions/handlers/autopilot-global-maintenance.ts';++const DOCS = 'docs/guides/troubleshooting.md#global-maintenance-timeouts';+const DEATHS = 3;++export async function globalMaintenanceTimeoutsCheck(engine: BrainEngine): Promise<Check> {+ try {+ const recent = await engine.executeRaw<{ id: number; status: string; error_text: string | null }>(+ `SELECT id, status, error_text FROM minion_jobs+ WHERE name = 'autopilot-global-maintenance' AND status IN ('completed', 'failed', 'dead', 'cancelled')+ ORDER BY finished_at DESC NULLS LAST, id DESC LIMIT ${DEATHS}`);+ const timeoutDeaths = recent.length === DEATHS+ && recent.every(job => job.status === 'dead' && /timeout exceeded/.test(job.error_text ?? ''));+ const progress = await readGlobalMaintenanceProgress(engine);+ const phases = Object.entries(progress.timeouts ?? {})+ .filter(([, t]) => t.count >= DEATHS)+ .map(([phase, t]) => ({ phase, consecutive_deaths: t.count, last_at: t.last_at }));+ const phase = phases[0]?.phase ?? progress.running_phase ?? progress.next_phase;+ if (!timeoutDeaths && phases.length === 0) {+ return { name: 'global_maintenance_timeouts', status: 'ok', message: 'Brain-wide maintenance jobs are finishing within their deadline.' };+ }+ const fix = phase+ ? { kind: 'run_command', argv: ['gbrain', 'dream', '--phase', phase] }+ : { kind: 'run_command', argv: ['gbrain', 'config', 'set', 'autopilot.global_maintenance_timeout_ms', '3600000'] };+ const cause = phases.length > 0+ ? `phase ${phases.map(p => p.phase).join(', ')} was running in ${DEATHS}+ consecutive autopilot-global-maintenance job deaths and is skipped each pass`+ : `the last ${DEATHS} autopilot-global-maintenance jobs (${recent.map(j => `#${j.id}`).join(', ')}) died at their deadline`;+ return {+ name: 'global_maintenance_timeouts',+ status: 'warn',+ message: `Brain-wide maintenance is not finishing: ${cause}. `+ + (phase ? `Run the phase without the job deadline: gbrain dream --phase ${phase}. ` : '')+ + `Raise the job deadline with: gbrain config set autopilot.global_maintenance_timeout_ms <ms> (or GBRAIN_GLOBAL_MAINTENANCE_TIMEOUT_MS). See ${DOCS}.`,+ details: { code: 'global_maintenance_timeouts', cause, fix, docs: DOCS, recent_job_ids: recent.map(j => j.id), phases,+ resume_phase: progress.next_phase ?? null },+ };+ } catch (error) {+ return { name: 'global_maintenance_timeouts', status: 'warn', message: `Global maintenance history could not be read: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,+ details: { health: 'unknown' } };+ }+}++async function runGlobalMaintenanceTimeouts(ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ const { status, message, details } = await globalMaintenanceTimeoutsCheck(connectedEngine(ctx));+ checks.push({ name: 'global_maintenance_timeouts', status, message, details });+ return checks;+}++export const globalMaintenanceTimeoutsEntry: DoctorEntry = {+ name: 'global_maintenance_timeouts',+ emits: ['global_maintenance_timeouts'],+ run: runGlobalMaintenanceTimeouts,+};diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex ee99f4414a..fc2a8716fb 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -78,6 +78,7 @@ import {salienceEntry,} from './checks/knowledge-health.ts';import { queueHealthEntry, indexAuditEntry, imageAssetsEntry } from './checks/queue-assets.ts';+import { globalMaintenanceTimeoutsEntry } from './checks/global-maintenance-timeouts.ts';import { legacyJobAuthorityEntry } from './checks/legacy-job-authority.ts';import { syncFreshnessEntry, searchModeEntry } from './checks/sync-search.ts';import { decideHealthEntry } from './checks/decide.ts';@@ -133,6 +134,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [effectiveDateEntry,salienceEntry,queueHealthEntry,+ globalMaintenanceTimeoutsEntry,legacyJobAuthorityEntry,indexAuditEntry,imageAssetsEntry,diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex 314d3a7d19..f8bf00171b 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -2980,6 +2980,9 @@ export async function runCycle(// work it never actually did. Treat an aborted signal as a non-success run:// skip the freshness stamp and report status 'partial' with reason 'aborted'.const aborted = cycleSignal?.aborted === true;+ // A steal during the last selected phase has no later boundary to throw at;+ // attribute it the same way (#4578 runs one phase per runCycle call).+ if (aborted && isLockStolenAbort(stolen?.signal, externalSignal)) lockStolenAbort = true;// #1972 (Decision 7A gating): attribute force-evicts. The minion worker// force-evicts a job 30s after abort and logs "handler ignored abort signal";diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 331e55f8ba..3d70c692cc 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -228,6 +228,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set(['pool_budget','progressive_batch_audit_health','queue_health',+ // #4578: brain-wide maintenance jobs dying at their deadline.+ 'global_maintenance_timeouts',// #5157: queued jobs from before the v0.50 authority cutover block every worker.'legacy_job_authority','reranker_health',diff --git a/src/core/minions/handlers/autopilot-global-maintenance.ts b/src/core/minions/handlers/autopilot-global-maintenance.tsindex 3a1e55f973..27e60c0c10 100644--- a/src/core/minions/handlers/autopilot-global-maintenance.ts+++ b/src/core/minions/handlers/autopilot-global-maintenance.ts@@ -3,12 +3,66 @@*/import type { BrainEngine } from '../../engine.ts';import type { MinionHandler } from '../types.ts';+import type { CycleReport, PhaseResult } from '../../cycle.ts';++/**+ * #4578: one pass over the maintenance phases may span several jobs. The+ * handler runs one phase per runCycle call, records which phase is running,+ * and stops starting phases when the job deadline would cut the next one off+ * (using that phase's last measured duration). The next job resumes at the+ * recorded phase. A phase that was running when a job died (timeout or crash)+ * is skipped for the rest of that pass so later phases still run; doctor's+ * `global_maintenance_timeouts` check reports it and names+ * `gbrain dream --phase <name>` to run it without the job deadline.+ */+export const GLOBAL_MAINTENANCE_PROGRESS_KEY = 'autopilot.global_maintenance.progress';+/** Kept free at the end of a job for bookkeeping; phases budget sub-work against the deadline minus this. */+const DEADLINE_RESERVE_MS = 60_000;++export interface GlobalMaintenanceProgress {+ /** Phase the next job starts at; absent at the start of a pass. */+ next_phase?: string;+ /** Phase running right now, and the job running it. Left set when a job dies mid-phase. */+ running_phase?: string;+ running_job?: string;+ /** Last measured duration per phase (ms). */+ durations?: Record<string, number>;+ /** Phases that were running when a job died, with consecutive death counts. Cleared when the phase completes. */+ timeouts?: Record<string, { count: number; last_at: string }>;+ /** Phases skipped in the current pass because they killed a job. */+ skip_this_pass?: string[];+ /** A phase in the current pass failed; the pass does not stamp last_global_at. */+ pass_failed?: boolean;+}++export async function readGlobalMaintenanceProgress(engine: BrainEngine): Promise<GlobalMaintenanceProgress> {+ try {+ const raw = await engine.getConfig(GLOBAL_MAINTENANCE_PROGRESS_KEY);+ const parsed = raw ? JSON.parse(raw) : {};+ return parsed && typeof parsed === 'object' ? parsed as GlobalMaintenanceProgress : {};+ } catch { return {}; }+}++/** The stamp gate: a phase result that means this pass did not finish its work. */+function phaseBlocksStamp(phase: PhaseResult): boolean {+ if (phase.status === 'fail') return true;+ if (phase.phase !== 'synthesize' && phase.phase !== 'patterns') return false;+ if (phase.details.reason === 'insufficient_cycle_budget') return true;+ if (phase.phase === 'patterns') {+ return typeof phase.details.child_outcome === 'string' && phase.details.child_outcome !== 'completed';+ }+ const synthesis = phase.details.synthesis as { non_completed_jobs?: number } | undefined;+ const triage = phase.details.triage as { deferred?: number } | undefined;+ return (synthesis?.non_completed_jobs ?? 0) > 0+ || (triage?.deferred ?? 0) > 0+ || (Array.isArray(phase.details.budget_deferred_transcripts) && phase.details.budget_deferred_transcripts.length > 0);+}/*** Brain-wide maintenance. Runs mixed + global phases ONCE per window instead* of repeating cross-source transcript/reflection reads in every source.* No source_id → uses the legacy global cycle lock; stamps autopilot.last_global_at- * on success so the dispatch gate backs off.+ * when a pass completes without a blocking phase so the dispatch gate backs off.*/export function makeAutopilotGlobalMaintenanceHandler(engine: BrainEngine): MinionHandler {return async (job) => {@@ -27,35 +81,137 @@ export function makeAutopilotGlobalMaintenanceHandler(engine: BrainEngine): Mini: MAINTENANCE_PHASES;const phases = (requested.length > 0 ? requested : MAINTENANCE_PHASES) as typeof MAINTENANCE_PHASES;- const report = await runCycle(engine, {- brainDir: repoPath,- pull: false, // brain-wide DB/maintenance work never git-pulls- signal: job.signal,- deadlineAtMs: job.deadlineAtMs, // #2781: phases budget sub-work from remaining time- // The maintenance lane is where synthesize/patterns actually run on- // multi-source brains (per-source payloads normalize down to the- // freshness phases) — without the owner id its private queues would be- // owner-less and recovery would degrade to lease-expiry only.- privateQueueOwnerJobId: job.id,- phases,- forceGlobalOrphans: true,- yieldBetweenPhases: async () => { await new Promise<void>((r) => setImmediate(r)); },- });+ const progress = await readGlobalMaintenanceProgress(engine);+ const save = async () => {+ try { await engine.setConfig(GLOBAL_MAINTENANCE_PROGRESS_KEY, JSON.stringify(progress)); }+ catch (e) { console.warn(`[autopilot-global-maintenance] failed to record progress: ${e instanceof Error ? e.message : String(e)}`); }+ };+ progress.durations ??= {};+ progress.timeouts ??= {};+ progress.skip_this_pass ??= [];+ const runToken = `${job.id}:${job.attempts_made ?? 0}`;+ const recordTimeout = (phase: string) => {+ const prev = progress.timeouts![phase];+ progress.timeouts![phase] = { count: (prev?.count ?? 0) + 1, last_at: new Date().toISOString() };+ if (!progress.skip_this_pass!.includes(phase)) progress.skip_this_pass!.push(phase);+ };+ const died = progress.running_phase;+ if (died && progress.running_job !== runToken) {+ recordTimeout(died);+ console.warn(`[autopilot-global-maintenance] phase ${died} was running when an earlier job died; skipping it for this pass. Run it alone with: gbrain dream --phase ${died}`);+ }+ const resumeAt = progress.next_phase ? phases.indexOf(progress.next_phase as never) : -1;+ const start = resumeAt >= 0 ? resumeAt : 0;+ if (start === 0) progress.pass_failed = false;++ const deadline = typeof job.deadlineAtMs === 'number' ? job.deadlineAtMs : null;+ const phaseDeadline = deadline !== null ? deadline - DEADLINE_RESERVE_MS : null;+ const reports: CycleReport[] = [];+ const ran: PhaseResult[] = [];+ let deferred: string[] = [];+ let stopReason: string | undefined;- if ((report.status === 'ok' || report.status === 'clean' || report.status === 'partial')- && !report.phases.some(phase => {- if (phase.status === 'fail') return true;- if (phase.phase !== 'synthesize' && phase.phase !== 'patterns') return false;- if (phase.details.reason === 'insufficient_cycle_budget') return true;- if (phase.phase === 'patterns') {- return typeof phase.details.child_outcome === 'string' && phase.details.child_outcome !== 'completed';+ for (let i = start; i < phases.length; i++) {+ const phase = phases[i]!;+ if (progress.skip_this_pass.includes(phase)) {+ progress.pass_failed = true;+ ran.push({ phase, status: 'skipped', duration_ms: 0, summary: `skipped: killed an earlier job; run gbrain dream --phase ${phase}`,+ details: { reason: 'timed_out_previous_job', recovery: `gbrain dream --phase ${phase}` } });+ continue;+ }+ const estimate = progress.durations[phase] ?? 0;+ if (i > start && phaseDeadline !== null && Date.now() + estimate > phaseDeadline) {+ deferred = phases.slice(i);+ stopReason = 'deadline';+ progress.next_phase = phase;+ break;+ }+ progress.running_phase = phase;+ progress.running_job = runToken;+ await save();+ let report: CycleReport;+ try {+ report = await runCycle(engine, {+ brainDir: repoPath,+ pull: false, // brain-wide DB/maintenance work never git-pulls+ signal: job.signal,+ deadlineAtMs: phaseDeadline, // #2781: phases budget sub-work from remaining time+ // The maintenance lane is where synthesize/patterns actually run on+ // multi-source brains (per-source payloads normalize down to the+ // freshness phases) — without the owner id its private queues would be+ // owner-less and recovery would degrade to lease-expiry only.+ privateQueueOwnerJobId: job.id,+ phases: [phase],+ forceGlobalOrphans: true,+ yieldBetweenPhases: async () => { await new Promise<void>((r) => setImmediate(r)); },+ });+ } catch (e) {+ progress.running_phase = undefined;+ progress.running_job = undefined;+ progress.next_phase = phase;+ progress.pass_failed = true;+ await save();+ throw e;+ }+ reports.push(report);+ progress.running_phase = undefined;+ progress.running_job = undefined;+ if (report.status === 'skipped' || report.reason === 'aborted' || report.reason === 'lock_stolen') {+ // A phase cut off by the job deadline would be cut off again next run.+ if (report.reason === 'aborted' && deadline !== null && Date.now() >= phaseDeadline!) {+ recordTimeout(phase);+ progress.pass_failed = true;}- const synthesis = phase.details.synthesis as { non_completed_jobs?: number } | undefined;- const triage = phase.details.triage as { deferred?: number } | undefined;- return (synthesis?.non_completed_jobs ?? 0) > 0- || (triage?.deferred ?? 0) > 0- || (Array.isArray(phase.details.budget_deferred_transcripts) && phase.details.budget_deferred_transcripts.length > 0);- })+ deferred = phases.slice(i);+ stopReason = report.reason ?? report.status;+ progress.next_phase = phase;+ break;+ }+ for (const result of report.phases) {+ ran.push(result);+ if (result.phase !== phase) continue;+ progress.durations[phase] = result.duration_ms;+ delete progress.timeouts[phase];+ if (phaseBlocksStamp(result)) progress.pass_failed = true;+ }+ }++ const passComplete = deferred.length === 0;+ if (passComplete) {+ progress.next_phase = undefined;+ progress.skip_this_pass = [];+ }+ await save();++ const totals = { ...(reports[0]?.totals ?? {}) } as CycleReport['totals'];+ for (const report of reports.slice(1)) {+ for (const [key, value] of Object.entries(report.totals)) {+ if (typeof value === 'number') (totals as Record<string, number>)[key] = ((totals as Record<string, number>)[key] ?? 0) + value;+ }+ }+ const last = reports[reports.length - 1];+ const statuses = reports.filter(r => r.status !== 'skipped').map(r => r.status);+ const status: CycleReport['status'] = statuses.length === 0+ ? (ran.some(p => p.details.reason === 'timed_out_previous_job') ? 'partial' : 'skipped')+ : deferred.length > 0 || ran.some(p => p.details.reason === 'timed_out_previous_job') ? 'partial'+ : statuses.every(st => st === 'failed') ? 'failed'+ : statuses.some(st => st === 'failed' || st === 'partial') ? 'partial'+ : statuses.some(st => st === 'ok') ? 'ok' : 'clean';+ const report: CycleReport & { deferred_phases?: string[]; resume_phase?: string } = {+ ...(last ?? { schema_version: '1', timestamp: new Date().toISOString(), brain_dir: repoPath }),+ duration_ms: reports.reduce((n, r) => n + r.duration_ms, 0),+ status,+ ...(stopReason ? { reason: stopReason } : {}),+ phases: ran,+ totals,+ ...(deferred.length ? { deferred_phases: deferred, resume_phase: progress.next_phase } : {}),+ } as CycleReport & { deferred_phases?: string[]; resume_phase?: string };+ if (deferred.length > 0 && stopReason === 'deadline') {+ console.warn(`[autopilot-global-maintenance] stopping before the job deadline; ${deferred.length} phase(s) resume at ${progress.next_phase} on the next run`);+ }++ if (passComplete && !progress.pass_failed && reports.length > 0+ && (status === 'ok' || status === 'clean' || status === 'partial')&& report.reason !== 'aborted' && report.reason !== 'lock_stolen') {try {await engine.setConfig(LAST_GLOBAL_AT_KEY, new Date().toISOString());diff --git a/test/autopilot-global-maintenance-resume-4578.test.ts b/test/autopilot-global-maintenance-resume-4578.test.tsnew file mode 100644index 0000000000..dce2f6573f--- /dev/null+++ b/test/autopilot-global-maintenance-resume-4578.test.ts@@ -0,0 +1,125 @@+/**+ * #4578: brain-wide maintenance on a large brain died at its fixed 30-minute+ * deadline and restarted every phase on each run, so late phases never ran.+ * The handler now stops starting phases the deadline would cut off, resumes+ * at the next phase on the following run, skips a phase that killed an+ * earlier job, and the deadline is configurable. Doctor names the phase and+ * the command that runs it without the job deadline.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdtempSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';+import { LAST_GLOBAL_AT_KEY } from '../src/core/cycle.ts';+import { MinionQueue } from '../src/core/minions/queue.ts';+import {+ GLOBAL_MAINTENANCE_PROGRESS_KEY,+ makeAutopilotGlobalMaintenanceHandler,+ readGlobalMaintenanceProgress,+} from '../src/core/minions/handlers/autopilot-global-maintenance.ts';+import { dispatchGlobalMaintenance, resolveGlobalMaintenanceTimeoutMs } from '../src/commands/autopilot-fanout.ts';+import { globalMaintenanceTimeoutsCheck } from '../src/commands/doctor/checks/global-maintenance-timeouts.ts';++let engine: PGLiteEngine;+let repoPath: string;+let schemaVersion: string;+const phases = ['orphans', 'purge'];++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ schemaVersion = (await engine.getConfig('version'))!;+ repoPath = mkdtempSync(join(tmpdir(), 'gbrain-global-resume-'));+}, 60_000);+afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => {+ await resetPgliteState(engine);+ await engine.setConfig('version', schemaVersion);+});++const run = (job: Record<string, unknown>) => makeAutopilotGlobalMaintenanceHandler(engine)(+ { id: 7001, attempts_made: 0, signal: undefined, deadlineAtMs: null, data: { phases, repoPath }, ...job } as never) as Promise<any>;++describe('autopilot-global-maintenance resumes across jobs (#4578)', () => {+ test('a phase the deadline would cut off is deferred to the next job, which resumes there and completes the pass', async () => {+ await engine.setConfig(GLOBAL_MAINTENANCE_PROGRESS_KEY, JSON.stringify({ durations: { purge: 20 * 60_000 } }));+ const first = await run({ deadlineAtMs: Date.now() + 5 * 60_000 });+ expect(first.report.phases.map((p: { phase: string }) => p.phase)).toEqual(['orphans']);+ expect(first.report.deferred_phases).toEqual(['purge']);+ expect(first.report.status).toBe('partial');+ expect(await engine.getConfig(LAST_GLOBAL_AT_KEY)).toBeNull();+ expect((await readGlobalMaintenanceProgress(engine)).next_phase).toBe('purge');++ const second = await run({ id: 7002 });+ expect(second.report.phases.map((p: { phase: string }) => p.phase)).toEqual(['purge']);+ expect(second.report.deferred_phases).toBeUndefined();+ expect(await engine.getConfig(LAST_GLOBAL_AT_KEY)).not.toBeNull();+ expect((await readGlobalMaintenanceProgress(engine)).next_phase).toBeUndefined();+ }, 60_000);++ test('a phase that was running when an earlier job died is skipped for the pass; later phases still run', async () => {+ await engine.setConfig(GLOBAL_MAINTENANCE_PROGRESS_KEY, JSON.stringify({ running_phase: 'orphans', running_job: '6999:0', next_phase: 'orphans' }));+ const result = await run({});+ expect(result.report.phases.find((p: { phase: string }) => p.phase === 'orphans'))+ .toMatchObject({ status: 'skipped', details: { reason: 'timed_out_previous_job', recovery: 'gbrain dream --phase orphans' } });+ expect(result.report.phases.find((p: { phase: string }) => p.phase === 'purge')?.status).not.toBe('skipped');+ expect(await engine.getConfig(LAST_GLOBAL_AT_KEY)).toBeNull();+ const progress = await readGlobalMaintenanceProgress(engine);+ expect(progress.timeouts?.orphans?.count).toBe(1);+ expect(progress.running_phase).toBeUndefined();+ }, 60_000);++ test('the job deadline follows env > config > the autopilot default', async () => {+ expect(await resolveGlobalMaintenanceTimeoutMs(engine, 1_800_000)).toBe(1_800_000);+ await engine.setConfig('autopilot.global_maintenance_timeout_ms', '7200000');+ expect(await resolveGlobalMaintenanceTimeoutMs(engine, 1_800_000)).toBe(7_200_000);+ await withEnv({ GBRAIN_GLOBAL_MAINTENANCE_TIMEOUT_MS: '5400000' }, async () => {+ expect(await resolveGlobalMaintenanceTimeoutMs(engine, 1_800_000)).toBe(5_400_000);+ });+ const added: Array<{ opts: { timeout_ms: number } }> = [];+ const queue = { add: async (_n: string, _d: unknown, opts: { timeout_ms: number }) => { added.push({ opts }); return { id: 1 }; } } as never;+ await dispatchGlobalMaintenance(engine, queue, { repoPath, slot: 's', timeoutMs: 1_800_000, jsonMode: true, emit: () => {} });+ expect(added[0]!.opts.timeout_ms).toBe(7_200_000);+ });+});++describe('global_maintenance_timeouts doctor check (#4578)', () => {+ async function deadJobs(n: number, error = 'timeout exceeded') {+ const queue = new MinionQueue(engine);+ for (let i = 0; i < n; i++) {+ const job = await queue.add('autopilot-global-maintenance', {}, { idempotency_key: `dead-${error}-${i}` });+ await engine.executeRaw(`UPDATE minion_jobs SET status = 'dead', error_text = $2, finished_at = now() + ($1 || ' seconds')::interval WHERE id = $3`,+ [String(i), error, job.id]);+ }+ }++ test('ok with no deaths; warns after three consecutive timeout deaths and names the phase and its command', async () => {+ expect((await globalMaintenanceTimeoutsCheck(engine)).status).toBe('ok');+ await deadJobs(2);+ expect((await globalMaintenanceTimeoutsCheck(engine)).status).toBe('ok');+ await deadJobs(1, 'timeout exceeded');+ await engine.setConfig(GLOBAL_MAINTENANCE_PROGRESS_KEY, JSON.stringify({ timeouts: { embed: { count: 3, last_at: '2026-10-01T00:00:00Z' } } }));+ const check = await globalMaintenanceTimeoutsCheck(engine);+ expect(check.status).toBe('warn');+ expect(check.details).toMatchObject({+ code: 'global_maintenance_timeouts',+ fix: { kind: 'run_command', argv: ['gbrain', 'dream', '--phase', 'embed'] },+ docs: 'docs/guides/troubleshooting.md#global-maintenance-timeouts',+ phases: [{ phase: 'embed', consecutive_deaths: 3 }],+ });+ expect(check.message).toContain('gbrain dream --phase embed');+ expect(check.message).toContain('autopilot.global_maintenance_timeout_ms');+ });++ test('a completed job after timeout deaths clears the warning', async () => {+ await deadJobs(3);+ expect((await globalMaintenanceTimeoutsCheck(engine)).status).toBe('warn');+ const job = await new MinionQueue(engine).add('autopilot-global-maintenance', {}, { idempotency_key: 'completed-after' });+ await engine.executeRaw(`UPDATE minion_jobs SET status = 'completed', finished_at = now() + interval '1 hour' WHERE id = $1`, [job.id]);+ expect((await globalMaintenanceTimeoutsCheck(engine)).status).toBe('ok');+ });+});diff --git a/test/dream-owner-id-threading.serial.test.ts b/test/dream-owner-id-threading.serial.test.tsindex 597cbfa648..d8f5ce5b40 100644--- a/test/dream-owner-id-threading.serial.test.ts+++ b/test/dream-owner-id-threading.serial.test.ts@@ -96,8 +96,9 @@ describe('privateQueueOwnerJobId === job.id threading', () => {signal: new AbortController().signal,});expect(result.status).toBe('ok');- expect(capturedOpts.length).toBe(1);- expect(capturedOpts[0].privateQueueOwnerJobId).toBe(43);+ // #4578: one runCycle call per maintenance phase; every call carries the owner id.+ expect(capturedOpts.length).toBe(realCycle.MAINTENANCE_PHASES.length);+ for (const opts of capturedOpts) expect(opts.privateQueueOwnerJobId).toBe(43);});test('the dream-phase wrapper (makePhaseHandler) threads its job id into runCycle', async () => {diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 95f3ecb7cd..9351395d32 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -875,6 +875,12 @@"name": "facts_health","status": "ok"},+ {+ "category": "ops",+ "message": "Brain-wide maintenance jobs are finishing within their deadline.",+ "name": "global_maintenance_timeouts",+ "status": "ok"+ },{"category": "ops","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 5e51eb5d56..e527be59ed 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -875,6 +875,12 @@"name": "facts_health","status": "ok"},+ {+ "category": "ops",+ "message": "Brain-wide maintenance jobs are finishing within their deadline.",+ "name": "global_maintenance_timeouts",+ "status": "ok"+ },{"category": "ops","details": {diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex b40fae8128..1c1561289f 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -489,6 +489,10 @@"category": "brain","name": "facts_health"},+ {+ "category": "ops",+ "name": "global_maintenance_timeouts"+ },{"category": "ops","name": "legacy_job_authority"