Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(#7188): a failed phase marks its job phase_failed and no longer backs off the source
garrytanf1d4fcdff1dc
diff --git a/docs/architecture/key-files/core-minions-2.md b/docs/architecture/key-files/core-minions-2.mdindex add0ca1a99..671f9df4a1 100644--- a/docs/architecture/key-files/core-minions-2.md+++ b/docs/architecture/key-files/core-minions-2.md@@ -41,7 +41,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/minions/worker-registry.ts` — live worker registry backing niceness observability. Each running `gbrain jobs work` self-registers `worker-<pid>.json` under `gbrainPath('workers')` (brain-isolated via `GBRAIN_HOME`; entries tagged with `currentBrainId()` so multiple DBs under one home don't cross-report). `registerWorker(info)` is best-effort (never blocks the worker) and returns a cleanup fn the caller wires to BOTH the shutdown `finally` AND `process.on('exit')` (the unhealthy `process.exit(1)` bypasses the awaited finally). `readWorkers(getNice?)` enumerates the dir, drops confirmed-dead pids (`classifyLiveness`: ESRCH = dead/prune, EPERM = alive/keep), applies a pid-reuse start-time guard (zone-free `ps -o etime=` parsed by `parseEtimeToMs`, start = now - elapsed; rejects a pid that started >5s after the entry was written), and re-measures each live worker's niceness now. Reports the worker's REAL pid, sidestepping the tini-wrapper-pid problem. Only a missing directory (ENOENT) reads as no workers; any other listing failure throws `WorkerRegistryUnreadableError` (errno + path, read with `workerRegistryReadFailure`), and every liveness consumer reports unknown instead of zero: doctor `queue_health` (`worker_alive: null`, no start-a-worker fix) and `wedged_queue`, `legacy_job_authority` (`live_workers: null`), `jobs supervisor status` (`workers: null`), the submit-time `probeQueueState` (`worker_alive` omitted, liveness-unknown warning), the `migrate-embeddings` writer census (`workers: null`) and the readiness worker probe (`probe_failed`); each carries `worker_registry_unreadable`, `worker_registry_errno` and `worker_registry_path`. Pinned by `test/worker-registry.serial.test.ts`.- `src/core/minions/no-worker.ts` — queue honesty (agent-first operator wave E5). `queueWorkerAlive(queue, read?)` (a live registered worker serves the queue on this host; undefined when the registry is unreadable), `runWaitingJobsFix(engineKind, queue)` (PGLite: `gbrain jobs work [--queue Q]`, a foreground drain, `requires_exclusive`; Postgres: `gbrain jobs supervisor start`), `noWorkerNotice(...)` (code `no_worker`, kind `degraded`). Consumers: CLI `jobs submit` on PGLite refuses without `--follow` unless `--queue-only` (`src/commands/jobs/submit.ts`); `gbrain jobs work` on PGLite drains via `drainPgliteQueue` (`src/commands/jobs/work.ts`) and exits; MCP `submit_job` / `get_job_stats` emit the notice (`src/core/ops/jobs.ts`, PGLite fix wrapped by readiness `exclusiveFix` behind a running serve); `deriveWedgeSignal(wedge, {workerAlive})` returns `no_worker` and never calls that case wedged (`jobs stats`, `get_job_stats`); doctor `queue_health` counts PGLite waiting rows (`src/commands/doctor/checks/queue-jobs.ts`). Pinned by `test/queue-no-worker.test.ts`.-- `src/core/minions/worker.ts` — MinionWorker class (handler registry, lock renewal, graceful shutdown, timeout safety net). The `ready` event follows final startup checks; listener failure stops startup before claims or timers. The renewal adapter latches typed configuration faults before the generic retry tick consumes them, including deadline verification. Configuration shutdown stops claims, tracks actual executions separately from scheduling slots, and releases only confirmed stopped work through `MinionQueue.releaseConfigurationJob` within one bounded shutdown envelope. The active/token-fenced release returns `released`, `no_op` or `unconfirmed`, leaves attempt/stall counters unchanged, and delays released work for 30 seconds; an unconfirmed stop or DB write falls back to lease expiry. Outstanding claims register their token before the post-claim configuration check so late claims cannot launch handlers. Aborted jobs call `failJob` with reason (`timeout`/`cancel`/`lock-lost`/`shutdown`); `shutdownAbort` (instance field) fires on SIGTERM/SIGINT and propagates to `ctx.shutdownSignal` (shell handler listens; non-shell handlers don't). Per-job timeout fires `abort.abort(new Error('timeout'))` then a 30s grace-then-evict safety net force-evicts the job from `inFlight` and marks it dead if the handler ignores the abort signal (the generic abort listener fires for ANY abort reason). The `launchJob` lock-renewal block is a thin sync wrapper around the pure `runLockRenewalTick` from `src/core/minions/lock-renewal-tick.ts` (NEVER `setInterval(async () => await renewLock(...))` — that shape surfaces an unhandledRejection during PgBouncer rotation). Guarantees: (1) `cancelled` flag captured in the timer closure stops in-flight IIFEs writing misleading audit events after the job ended; (2) re-entrancy guard `tickInFlight` (skips counted as `overlapSkips` telemetry) + per-call `Promise.race` timeout with best-effort AbortSignal cancellation; (3) verify-before-evict: eviction requires a fenced-false (certain loss) or the `hardEvictMs` backstop — never bare local arithmetic; the per-job lease (`job.lock_duration_ms ?? opts.lockDuration`) drives the renewal state, and the cadence clamps to `min(lease/2, 60s)`; (4) explicit `.catch()` on the stored `executeJob(...).finally(...)` promise closes the second unhandledRejection vector; (5) exported `INFRASTRUCTURE_ABORT_REASONS = new Set(['lock-renewal-failed', 'lock-lost'])` so executeJob's catch skips `failJob` for these (PgBouncer blips don't dead-letter healthy jobs; the stall detector reclaims); worker configuration shutdown is not in this set — it is gated separately by the typed `configurationError` latch; (6) inFlight generation-safety — force-evict and the handler's finally delete the inFlight entry ONLY when it still carries their own lockToken (the token is the generation; an evicted execution's late delete cannot remove a same-worker re-claim's entry); (7) eviction observability — the worker keeps a `perf_hooks.monitorEventLoopDelay` histogram (reset on every successful renewal, sampled ns→ms at eviction) plus raw loadavg, and both the abort and grace-evict log lines carry cause / since-last-success / tick-lateness / overlap-skips / load / event-loop-delay from the stashed `abortMeta`. CI guard `scripts/check-worker-lock-renewal-shape.sh` (in `bun run verify`) asserts the bug pattern stays absent AND `launchJob` keeps calling `runLockRenewalTick`. Engine-ownership invariant: `start()` does NOT call `engine.disconnect()` on shutdown — the CLI handler in `src/commands/jobs.ts case 'work'` owns engine lifecycle via try/finally with loud error logging. RSS watchdog uses non-file-backed pages on Linux: exported `parseRssFromProcStatus(status)` (pure parser; field-presence regex so `RssAnon: 0 + RssShmem: 512` parses correctly) and `getAccurateRss(readStatus?)` (reads `/proc/self/status` for `RssAnon + RssShmem`, falls back to `process.memoryUsage().rss` on macOS / restricted containers / kernel <4.5); the default `getRss` in `WorkerOpts` is `getAccurateRss`. `checkMemoryLimit` tracks peak RSS, fires an 80%-of-cap soft-warn (once per crossing, carrying peak + in-flight job kinds), and on exceed sets `_rssWatchdogTriggered=true` (exposed via `get rssWatchdogTriggered()`) so `jobs work`'s finally can `process.exit(WORKER_EXIT_RSS_WATCHDOG)` after disconnect (drain self-identifying instead of an opaque code-0 exit). The poll loop wraps `claim` in try/catch: on a retryable conn error it reconnects ONCE and continues to the next tick rather than blind-retrying (a retry after `UPDATE...RETURNING` committed but the socket died would double-claim). `LockRenewalDeps` is wired with `reconnect` when the engine supports it. The self-health DB-liveness probe runs EVEN under a supervisor (`GBRAIN_SUPERVISED=1`): the outer guard is `if (this.opts.healthCheckInterval > 0)` and only the STALL-detection block is wrapped in `if (!isSupervisedChild)` — so a supervised worker whose own pool dies self-exits `unhealthy(db_dead)` after `dbFailExitAfter` probes (the supervisor watches a different connection and can't see this worker's dead pool), while the supervisor's progress watchdog owns forward-progress. Pinned by the `test/worker-lock-renewal.test.ts` hermetic suite, `test/audit/lock-renewal-audit.test.ts`, `test/scripts/check-worker-lock-renewal-shape.test.ts`, `test/worker-shutdown-disconnect.test.ts` (asserts `disconnectSpy).not.toHaveBeenCalled()`), `test/worker-rss.test.ts` (11), `test/worker-supervised-db-probe.test.ts` (3). Per-job process isolation: `MinionWorkerOpts.jobIsolation` (`inline`|`process`) + `childCliInvocation`/`childTiniPath` swap `handler(context)` for `runJobInChild(...)` in executeJob — every reporting branch (completeJob, failJob, lease release, infra no-burn) is reused on the child outcome; when isolated the parent-side context is not built at all. Three extra no-burn child classes in the catch: `ChildSpawnInfraError` + `ChildWorkerShutdownError` (released, no attempt burned) and `ChildNotClaimedError` (the child proved the claim was already gone — reclaimed/cancelled before the handler ran — so nothing is recorded against it). The health probe delegates to `runDbProbe` (db-probe.ts) with a cancellation signal on every probe and emits a `verdict` (`pool_starved`/`server_unreachable`/`unknown`/`client_misconfigured`); typed configuration faults block immediately instead of burning the transient DB failure threshold. `getHandler(name)` is the read-only registry accessor run-child uses. Inline handlers run under `runWithJobSpend`; an isolated spend-authorized job passes `spendAuthorized` to the child runner's capability gate. #5062: `requestShutdown()` is the signal entry point (the `jobs work` signal owner calls it for SIGHUP/broken pipe too); a handler that ends because of the shutdown signal hands its claim back (`worker-shutdown.ts`: token-fenced, no attempt burned, `error_text = 'worker_shutdown: <handler error>'`); any handler error during shutdown is presumed shutdown-induced (`endedByShutdown` in `worker-shutdown.ts`) except `UnrecoverableError`, which dead-letters with its original text (W9F Decision 7; in-process and, for a child whose stop is confirmed, isolated; `test/worker-shutdown-error-matrix.test.ts`), and claims still running after the 30s drain are handed back the same way with `drainForced` set, which `jobs work` turns into exit `WORKER_EXIT_DRAIN_FORCED` (17). The RSS watchdog's `gracefulShutdown(reason)` aborts every `inFlight` job and records the reason; a claim whose `UPDATE … RETURNING` committed before the shutdown but whose result had not reached the poll loop is not in `inFlight` yet, so `launchJob` aborts it with the recorded reason as soon as it registers it, and the job takes the abort path instead of running unaborted through the drain (forced case in `test/worker-shutdown-error-matrix.test.ts`, which holds the claim result until the watchdog has fired). Each `inFlight` entry carries `shared` (another job ran beside it, or it registered after the drain began); the catch hands a watchdog-aborted shared job to `settleWatchdogAbort` (back to `waiting` uncharged, marked to run alone), so only a job that ran alone is charged `aborted: watchdog`, and it is marked too. A worker running a marked job claims nothing else, and a worker with jobs in flight claims no marked job. GBRA-133 2a.4: the idle poll wait (nothing claimed, nothing in flight) goes through `idleWaiter` (`src/core/minions/idle-wait.ts`), which the sync-queue wake ends early; `claimStarted()` runs right before each claim, and `stop()` and `requestShutdown()` end the wait at once. Before recording a handler's return, the worker reads it with `jobResultOutcome`: a reported failure ends the job through `failJob(..., 'failed', 0, result)`, and a partial result completes with `job_outcome: 'partial'` added.-- `src/core/minions/job-outcome.ts` — `jobResultOutcome(result)` (#7188): `failed` for a phase with status `fail` (the reason names the phase, code and message) or a top-level or nested `report` status of `failed` / `blocked_by_failures`; `partial` for `partial: true` or status `partial`; `clean` otherwise, a `skipped` result included. Pinned by `test/minions-job-outcome-7188.test.ts`.+- `src/core/minions/worker.ts` — MinionWorker class (handler registry, lock renewal, graceful shutdown, timeout safety net). The `ready` event follows final startup checks; listener failure stops startup before claims or timers. The renewal adapter latches typed configuration faults before the generic retry tick consumes them, including deadline verification. Configuration shutdown stops claims, tracks actual executions separately from scheduling slots, and releases only confirmed stopped work through `MinionQueue.releaseConfigurationJob` within one bounded shutdown envelope. The active/token-fenced release returns `released`, `no_op` or `unconfirmed`, leaves attempt/stall counters unchanged, and delays released work for 30 seconds; an unconfirmed stop or DB write falls back to lease expiry. Outstanding claims register their token before the post-claim configuration check so late claims cannot launch handlers. Aborted jobs call `failJob` with reason (`timeout`/`cancel`/`lock-lost`/`shutdown`); `shutdownAbort` (instance field) fires on SIGTERM/SIGINT and propagates to `ctx.shutdownSignal` (shell handler listens; non-shell handlers don't). Per-job timeout fires `abort.abort(new Error('timeout'))` then a 30s grace-then-evict safety net force-evicts the job from `inFlight` and marks it dead if the handler ignores the abort signal (the generic abort listener fires for ANY abort reason). The `launchJob` lock-renewal block is a thin sync wrapper around the pure `runLockRenewalTick` from `src/core/minions/lock-renewal-tick.ts` (NEVER `setInterval(async () => await renewLock(...))` — that shape surfaces an unhandledRejection during PgBouncer rotation). Guarantees: (1) `cancelled` flag captured in the timer closure stops in-flight IIFEs writing misleading audit events after the job ended; (2) re-entrancy guard `tickInFlight` (skips counted as `overlapSkips` telemetry) + per-call `Promise.race` timeout with best-effort AbortSignal cancellation; (3) verify-before-evict: eviction requires a fenced-false (certain loss) or the `hardEvictMs` backstop — never bare local arithmetic; the per-job lease (`job.lock_duration_ms ?? opts.lockDuration`) drives the renewal state, and the cadence clamps to `min(lease/2, 60s)`; (4) explicit `.catch()` on the stored `executeJob(...).finally(...)` promise closes the second unhandledRejection vector; (5) exported `INFRASTRUCTURE_ABORT_REASONS = new Set(['lock-renewal-failed', 'lock-lost'])` so executeJob's catch skips `failJob` for these (PgBouncer blips don't dead-letter healthy jobs; the stall detector reclaims); worker configuration shutdown is not in this set — it is gated separately by the typed `configurationError` latch; (6) inFlight generation-safety — force-evict and the handler's finally delete the inFlight entry ONLY when it still carries their own lockToken (the token is the generation; an evicted execution's late delete cannot remove a same-worker re-claim's entry); (7) eviction observability — the worker keeps a `perf_hooks.monitorEventLoopDelay` histogram (reset on every successful renewal, sampled ns→ms at eviction) plus raw loadavg, and both the abort and grace-evict log lines carry cause / since-last-success / tick-lateness / overlap-skips / load / event-loop-delay from the stashed `abortMeta`. CI guard `scripts/check-worker-lock-renewal-shape.sh` (in `bun run verify`) asserts the bug pattern stays absent AND `launchJob` keeps calling `runLockRenewalTick`. Engine-ownership invariant: `start()` does NOT call `engine.disconnect()` on shutdown — the CLI handler in `src/commands/jobs.ts case 'work'` owns engine lifecycle via try/finally with loud error logging. RSS watchdog uses non-file-backed pages on Linux: exported `parseRssFromProcStatus(status)` (pure parser; field-presence regex so `RssAnon: 0 + RssShmem: 512` parses correctly) and `getAccurateRss(readStatus?)` (reads `/proc/self/status` for `RssAnon + RssShmem`, falls back to `process.memoryUsage().rss` on macOS / restricted containers / kernel <4.5); the default `getRss` in `WorkerOpts` is `getAccurateRss`. `checkMemoryLimit` tracks peak RSS, fires an 80%-of-cap soft-warn (once per crossing, carrying peak + in-flight job kinds), and on exceed sets `_rssWatchdogTriggered=true` (exposed via `get rssWatchdogTriggered()`) so `jobs work`'s finally can `process.exit(WORKER_EXIT_RSS_WATCHDOG)` after disconnect (drain self-identifying instead of an opaque code-0 exit). The poll loop wraps `claim` in try/catch: on a retryable conn error it reconnects ONCE and continues to the next tick rather than blind-retrying (a retry after `UPDATE...RETURNING` committed but the socket died would double-claim). `LockRenewalDeps` is wired with `reconnect` when the engine supports it. The self-health DB-liveness probe runs EVEN under a supervisor (`GBRAIN_SUPERVISED=1`): the outer guard is `if (this.opts.healthCheckInterval > 0)` and only the STALL-detection block is wrapped in `if (!isSupervisedChild)` — so a supervised worker whose own pool dies self-exits `unhealthy(db_dead)` after `dbFailExitAfter` probes (the supervisor watches a different connection and can't see this worker's dead pool), while the supervisor's progress watchdog owns forward-progress. Pinned by the `test/worker-lock-renewal.test.ts` hermetic suite, `test/audit/lock-renewal-audit.test.ts`, `test/scripts/check-worker-lock-renewal-shape.test.ts`, `test/worker-shutdown-disconnect.test.ts` (asserts `disconnectSpy).not.toHaveBeenCalled()`), `test/worker-rss.test.ts` (11), `test/worker-supervised-db-probe.test.ts` (3). Per-job process isolation: `MinionWorkerOpts.jobIsolation` (`inline`|`process`) + `childCliInvocation`/`childTiniPath` swap `handler(context)` for `runJobInChild(...)` in executeJob — every reporting branch (completeJob, failJob, lease release, infra no-burn) is reused on the child outcome; when isolated the parent-side context is not built at all. Three extra no-burn child classes in the catch: `ChildSpawnInfraError` + `ChildWorkerShutdownError` (released, no attempt burned) and `ChildNotClaimedError` (the child proved the claim was already gone — reclaimed/cancelled before the handler ran — so nothing is recorded against it). The health probe delegates to `runDbProbe` (db-probe.ts) with a cancellation signal on every probe and emits a `verdict` (`pool_starved`/`server_unreachable`/`unknown`/`client_misconfigured`); typed configuration faults block immediately instead of burning the transient DB failure threshold. `getHandler(name)` is the read-only registry accessor run-child uses. Inline handlers run under `runWithJobSpend`; an isolated spend-authorized job passes `spendAuthorized` to the child runner's capability gate. #5062: `requestShutdown()` is the signal entry point (the `jobs work` signal owner calls it for SIGHUP/broken pipe too); a handler that ends because of the shutdown signal hands its claim back (`worker-shutdown.ts`: token-fenced, no attempt burned, `error_text = 'worker_shutdown: <handler error>'`); any handler error during shutdown is presumed shutdown-induced (`endedByShutdown` in `worker-shutdown.ts`) except `UnrecoverableError`, which dead-letters with its original text (W9F Decision 7; in-process and, for a child whose stop is confirmed, isolated; `test/worker-shutdown-error-matrix.test.ts`), and claims still running after the 30s drain are handed back the same way with `drainForced` set, which `jobs work` turns into exit `WORKER_EXIT_DRAIN_FORCED` (17). The RSS watchdog's `gracefulShutdown(reason)` aborts every `inFlight` job and records the reason; a claim whose `UPDATE … RETURNING` committed before the shutdown but whose result had not reached the poll loop is not in `inFlight` yet, so `launchJob` aborts it with the recorded reason as soon as it registers it, and the job takes the abort path instead of running unaborted through the drain (forced case in `test/worker-shutdown-error-matrix.test.ts`, which holds the claim result until the watchdog has fired). Each `inFlight` entry carries `shared` (another job ran beside it, or it registered after the drain began); the catch hands a watchdog-aborted shared job to `settleWatchdogAbort` (back to `waiting` uncharged, marked to run alone), so only a job that ran alone is charged `aborted: watchdog`, and it is marked too. A worker running a marked job claims nothing else, and a worker with jobs in flight claims no marked job. GBRA-133 2a.4: the idle poll wait (nothing claimed, nothing in flight) goes through `idleWaiter` (`src/core/minions/idle-wait.ts`), which the sync-queue wake ends early; `claimStarted()` runs right before each claim, and `stop()` and `requestShutdown()` end the wait at once. Before recording a handler's return, the worker reads it with `jobResultOutcome`: a reported failure ends the job through `failJob(..., 'failed', 0, result)` and a partial one completes, each storing `jobOutcomeResult`.+- `src/core/minions/job-outcome.ts` — `jobResultOutcome(result)` (#7188): `failed` for a phase with status `fail` (the reason names the phase, code and message) or a top-level or nested `report` status of `failed` / `blocked_by_failures`; `partial` for `partial: true` or status `partial`; `clean` otherwise, a `skipped` result included. `jobOutcomeResult` adds the stored markers: `job_outcome: 'phase_failed'` with `failed_phase`, `'failed'`, or `'partial'`; the autopilot source failure cooldown (`readRecentSourceFailures` in `src/commands/autopilot-fanout.ts`) skips `phase_failed` jobs. Pinned by `test/minions-job-outcome-7188.test.ts` and `test/autopilot-failure-cooldown.test.ts`.- `src/core/minions/watchdog-attribution.ts` — RSS watchdog attribution (GBRA-130 A-30). The watchdog measures the whole worker process, so a drain with several jobs in flight cannot name the job that grew: `settleWatchdogAbort` requeues each such job token-fenced with no attempt burned (`error_text` `WATCHDOG_DRAIN_RELEASE`) and appends `WATCHDOG_SUSPECT_MARK` once to its `stacktrace`, the job's durable history; a job that ran alone is marked and its caller charges it. An isolated child whose stop is unconfirmed, or any error during the release, leaves the claim to the stall sweep. `unmarkedJobSql` is the claim filter. `requeueCoRunnerStalls` requeues, marked and with no stall counted, the stalled claims of a worker that held other expired claims (lock tokens share the `<worker id>:` prefix, or a co-runner was already requeued with `worker_stalled_with_co_runners: <worker id>`); a marked or lone job's stall counts as before, so a kernel OOM kill gets the same attribution. Doctor's watchdog-kill counts (`error_text = 'aborted: watchdog'` on dead/failed rows) therefore count only jobs charged for a solo trip. Pinned by `test/pathological/a30-watchdog-attribution.test.ts` (both engines) and `test/worker-shutdown-error-matrix.test.ts`.diff --git a/src/commands/autopilot-fanout.ts b/src/commands/autopilot-fanout.tsindex e7d490bd40..bcc8b289d3 100644--- a/src/commands/autopilot-fanout.ts+++ b/src/commands/autopilot-fanout.ts@@ -293,6 +293,10 @@ export async function resolveFailureCooldownOpts(engine: BrainEngine): Promise<C* the exact failures that drive the storm. Engine-parity-safe via executeRaw* (one query, both engines); cutoff is precomputed in JS to avoid INTERVAL* portability concerns. codex #6: rows with a null source_id are excluded.+ * #7188: a cycle that ran but had a failed phase ends `failed` with+ * `job_outcome: 'phase_failed'` and does not count: only a whole-cycle failure+ * (a thrown handler, a timeout or stall, `blocked_by_failures`) backs a source off,+ * so one failing phase never stops the source's sync.*/export async function readRecentSourceFailures(engine: BrainEngine,@@ -310,6 +314,7 @@ export async function readRecentSourceFailures(FROM minion_jobsWHERE name = 'autopilot-cycle'AND status IN ('dead','failed')+ AND (result->>'job_outcome' IS NULL OR result->>'job_outcome' <> 'phase_failed')AND data->>'source_id' IS NOT NULLAND finished_at IS NOT NULLAND finished_at > $1`;diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 326f56aeea..f1a5585fb8 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1029,9 +1029,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.330.0', text: 'Classic `gbrain sync --full` no longer deletes pages it cannot prove were removed (#7130): when Git cannot list the history that shows their files were committed (a dangling ref fails `git log --all`), it keeps every stale page with a warning, where before it skipped the never-committed check and deleted them all. With readable history it deletes as before.' },{ since: '0.60.330.0', text: 'The autopilot purge phase and the `purge` job no longer hard-delete a page that a managed sync soft-deleted unless another live page of the same source has identical content (#7130). Each sync deletion now leaves a durable record (op_checkpoints `sync-delete-tombstone`; a tombstone from before this release is recognized by its uncompacted `managed_sync_delete` receipt, and one whose receipt was compacted is not). Held pages are reported as `sync_delete_unreviewed` in the phase\'s `purged_pages_blocked` and counted in `held`, and the phase reports warn. `gbrain pages purge-deleted` still purges them after consent: its dry run reports `sync_unreviewed` and its consent text names how many of the set are sync deletions with no live twin and that a purged page can only come back from a backup. The purge phase\'s recovery window (pages and orphan clone temp dirs), and the `purge` job\'s default, now follow `purge.retention_hours` instead of a fixed 72 hours. It can only lengthen the window (default and minimum 72, so a 72-hour restore promise always holds); `gbrain config set` refuses a smaller value.' },{ since: '0.60.330.0', text: 'New doctor check `uncommitted_sync_deletions` and explicit-only repair kind `gbrain repair uncommitted-deletions --source <id>` (#7130): on each managed source\'s owner host, doctor warns about soft-deleted pages a sync removed although Git never held their recorded file (`.gitignore` excludes it, or no commit holds it and it is not on the disk), bounded to 20,000 tombstones per source and 2,000 Git evidence reads per run. The repair previews each page (slug, recorded path, deletion time, evidence, whether a sync deleted it) with a hash; `--apply --expect <hash> --yes` restores exactly that set, each page live and database-only (detached: it forgets its recorded file and no file is written), so the next sync keeps it. Pages another writer deleted join only with `--include-ambiguous`; a sync deletion is recognized by its record or receipt for the page\'s current tombstone. A preview reads one bounded window, newest page id first, and `--after <page-id>` (named in the preview\'s `next_after` and in the doctor message) continues past it. It refuses off the owner host (`not_owner_host`) and a changed plan (`preview_changed`); without `--yes` a non-interactive run exits 3 and changes nothing. Pages already purged cannot be restored by this command; only a backup (pg_dump, or `gbrain backup create`) can bring them back. It never runs on upgrade or automatically.' },- { since: 'TBD', text: 'On Postgres, gbrain opens its transactions READ WRITE and runs an autocommit statement refused as read-only (SQLSTATE 25006) once more inside a READ WRITE transaction, so a server connection whose default is read-only (a session-level SET another client left on a transaction-mode pooler connection, or a role or database default) no longer stops sync, page writes, leases or the jobs queue. A refusal that persists (a read-only server) is now `connection_inherited_read_only` in the write receipt, `gbrain sync status` (systemic, needs the database operator) and the CLI and MCP error envelope, instead of `storage_error` or `internal_error`. Deliberately read-only transactions (graduation, export, sync pass reads) stay read-only.' },- { since: 'TBD', text: 'The worker stall detector no longer stops when a drain lease holder died without deleting its `gbrain-drain-lease` row: dead-lettering that row broke a table constraint and aborted every sweep, so every job left `active` with an expired lock stayed there. The sweep now deletes a holder row whose holder stopped renewing it (logged as dropped holder rows) and reclaims stranded jobs as before, and the wall-clock timeout sweep skips holder rows, which it used to fail on during any drain longer than its threshold.' },- { since: 'TBD', text: 'A Minions job whose handler result reports a failed phase or a `failed` / `blocked_by_failures` status now ends `failed` (no retry), its error naming the phase, code and message and its result kept, instead of `completed`; under `on_child_fail: fail_parent` it fails its parent, and a failed `autopilot-cycle` job counts toward the source failure cooldown. A result that reports unfinished work without a failure (`status: partial` or `partial: true`) still completes, with `job_outcome: "partial"` added to the result. Skips and clean results are unchanged.' },+ { since: '0.60.330.0', text: 'On Postgres, gbrain opens its transactions READ WRITE and runs an autocommit statement refused as read-only (SQLSTATE 25006) once more inside a READ WRITE transaction, so a server connection whose default is read-only (a session-level SET another client left on a transaction-mode pooler connection, or a role or database default) no longer stops sync, page writes, leases or the jobs queue. A refusal that persists (a read-only server) is now `connection_inherited_read_only` in the write receipt, `gbrain sync status` (systemic, needs the database operator) and the CLI and MCP error envelope, instead of `storage_error` or `internal_error`. Deliberately read-only transactions (graduation, export, sync pass reads) stay read-only.' },+ { since: '0.60.330.0', text: 'The worker stall detector no longer stops when a drain lease holder died without deleting its `gbrain-drain-lease` row: dead-lettering that row broke a table constraint and aborted every sweep, so every job left `active` with an expired lock stayed there. The sweep now deletes a holder row whose holder stopped renewing it (logged as dropped holder rows) and reclaims stranded jobs as before, and the wall-clock timeout sweep skips holder rows, which it used to fail on during any drain longer than its threshold.' },+ { since: '0.60.330.0', text: 'A Minions job whose handler result reports a failed phase or a `failed` / `blocked_by_failures` status now ends `failed` (no retry) instead of `completed`: its error names the phase, code and message, and its result is kept with `job_outcome` set (`phase_failed` plus `failed_phase` for a failed phase, `failed` otherwise); under `on_child_fail: fail_parent` it fails its parent. An `autopilot-cycle` job that ended `phase_failed` does not count toward the source failure cooldown, so one failing phase never backs off a source (or stops its sync); a thrown handler, a timeout or stall, and `blocked_by_failures` still do. A result that reports unfinished work without a failure (`status: partial` or `partial: true`) still completes, with `job_outcome: "partial"` added. Skips and clean results are unchanged.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/minions/job-outcome.ts b/src/core/minions/job-outcome.tsindex 2b317f2d6c..4837078f81 100644--- a/src/core/minions/job-outcome.ts+++ b/src/core/minions/job-outcome.ts@@ -1,36 +1,45 @@/*** #7188: what a handler's returned result says about its job, read by the worker before it records the job's end.*- * `failed`: the result reports a failure, as a top-level `status` of `failed` or `blocked_by_failures` (also on a nested- * cycle `report`) or a phase of that report with status `fail` (the first such phase names the reason, with its code).- * `partial`: unfinished work and no failure (`partial: true` or `status: 'partial'`: phases deferred to the next pass, a- * drain that stopped at its deadline with a follow-up queued, a source another drainer holds). `clean`: everything else,- * a deliberate skip included.+ * `failed`: the result reports a failure: a top-level (or nested cycle `report`) status of `blocked_by_failures`+ * or `failed`, or a phase of that report with status `fail` (the first such phase names the reason, with its code,+ * and is returned as `phase`). `partial`: unfinished work and no failure (`partial: true` or `status: 'partial'`:+ * phases deferred to the next pass, a drain that stopped at its deadline with a follow-up queued, a source another+ * drainer holds). `clean`: everything else, a deliberate skip included.*- * The worker ends a `failed` result as a terminal `failed` job whose error names the reason, keeping the result;- * a `partial` one completes with `job_outcome: 'partial'` on its result, since the queue has no partial status and- * deferred work that resumes on its own is not a failure.+ * The worker ends a `failed` result as a terminal `failed` job whose error names the reason and stores+ * `jobOutcomeResult`: `job_outcome: 'phase_failed'` with `failed_phase` when a phase failed (the autopilot source+ * cooldown skips those, so one failing phase does not back off a source's sync), `job_outcome: 'failed'` otherwise. A+ * `partial` one completes with `job_outcome: 'partial'`, since the queue has no partial status.*/-export interface JobOutcome { outcome: 'clean' | 'partial' | 'failed'; reason?: string }+export interface JobOutcome { outcome: 'clean' | 'partial' | 'failed'; reason?: string; phase?: string }type Rec = Record<string, unknown>;const rec = (value: unknown): Rec | null => value !== null && typeof value === 'object' && !Array.isArray(value) ? value as Rec : null;-const FAILED_STATUSES = new Set(['failed', 'blocked_by_failures']);+const statusReason = (status: string, report: Rec) => `result status ${status}${typeof report.reason === 'string' ? ` (${report.reason})` : ''}`;export function jobResultOutcome(result: unknown): JobOutcome {const top = rec(result);if (!top || top.skipped === true) return { outcome: 'clean' };const report = rec(top.report) ?? top;+ if (top.status === 'blocked_by_failures' || report.status === 'blocked_by_failures') return { outcome: 'failed', reason: statusReason('blocked_by_failures', report) };const phases = Array.isArray(report.phases) ? report.phases.map(rec).filter((p): p is Rec => p !== null) : [];const failedPhase = phases.find(p => p.status === 'fail');if (failedPhase) {const error = rec(failedPhase.error);const code = failedPhase.code ?? error?.code;const detail = error?.message ?? failedPhase.summary;- return { outcome: 'failed', reason: `phase ${String(failedPhase.phase)} failed${code ? ` (${String(code)})` : ''}${detail ? `: ${String(detail)}` : ''}` };+ const phase = String(failedPhase.phase);+ return { outcome: 'failed', phase, reason: `phase ${phase} failed${code ? ` (${String(code)})` : ''}${detail ? `: ${String(detail)}` : ''}` };}- const status = [top.status, report.status].find(s => typeof s === 'string' && FAILED_STATUSES.has(s));- if (status) return { outcome: 'failed', reason: `result status ${String(status)}${typeof report.reason === 'string' ? ` (${report.reason})` : ''}` };+ if (top.status === 'failed' || report.status === 'failed') return { outcome: 'failed', reason: statusReason('failed', report) };if (top.partial === true || top.status === 'partial' || report.status === 'partial') return { outcome: 'partial' };return { outcome: 'clean' };}++/** The result the worker stores for an outcome: the handler's result with the `job_outcome` markers above. */+export function jobOutcomeResult(result: Rec | undefined, verdict: JobOutcome): Rec | undefined {+ if (verdict.outcome === 'clean') return result;+ if (verdict.outcome === 'partial') return { ...result, job_outcome: 'partial' };+ return { ...result, job_outcome: verdict.phase ? 'phase_failed' : 'failed', ...(verdict.phase ? { failed_phase: verdict.phase } : {}) };+}diff --git a/src/core/minions/worker.ts b/src/core/minions/worker.tsindex 3872dfcebc..9d1879c309 100644--- a/src/core/minions/worker.ts+++ b/src/core/minions/worker.ts@@ -89,7 +89,7 @@ import { evaluateQuietHours, type QuietHoursConfig } from './quiet-hours.ts';import { endedByShutdown, releaseUndrainedClaims, settleShutdownInterruptedJob } from './worker-shutdown.ts';import { isWatchdogSuspect, settleWatchdogAbort } from './watchdog-attribution.ts';import { IdleWaiter } from './idle-wait.ts';-import { jobResultOutcome } from './job-outcome.ts';+import { jobOutcomeResult, jobResultOutcome } from './job-outcome.ts';import { readFileSync } from 'fs';/**@@ -1564,8 +1564,8 @@ export class MinionWorker extends EventEmitter {const verdict = jobResultOutcome(stored);// Complete the job (token-fenced); a result that reports a failure (#7188) ends it failed instead.const completed = verdict.outcome === 'failed'- ? await this.queue.failJob(job.id, lockToken, verdict.reason!, 'failed', 0, stored)- : await this.queue.completeJob(job.id, lockToken, verdict.outcome === 'partial' ? { ...stored, job_outcome: 'partial' } : stored);+ ? await this.queue.failJob(job.id, lockToken, verdict.reason!, 'failed', 0, jobOutcomeResult(stored, verdict))+ : await this.queue.completeJob(job.id, lockToken, jobOutcomeResult(stored, verdict));const execution = this.executions.get(lockToken);if (execution) execution.stopped = true;diff --git a/test/autopilot-failure-cooldown.test.ts b/test/autopilot-failure-cooldown.test.tsindex edcb93e9c7..386bbc643c 100644--- a/test/autopilot-failure-cooldown.test.ts+++ b/test/autopilot-failure-cooldown.test.ts@@ -24,6 +24,10 @@ import {type CooldownOpts,} from '../src/commands/autopilot-fanout.ts';import type { SourceRow } from '../src/core/engine.ts';+import { MinionQueue } from '../src/core/minions/queue.ts';+import { MinionWorker } from '../src/core/minions/worker.ts';+import type { MinionJob } from '../src/core/minions/types.ts';+import { waitFor } from './helpers/wait-for.ts';const OPTS: CooldownOpts = { baseMin: 10, capMin: 120 };@@ -149,3 +153,64 @@ describe('readRecentSourceFailures + isSourceInCooldown (PGLite)', () => {expect(opts.baseMin).toBe(0);});});++describe('#7188: a cycle with one failed phase does not back off its source', () => {+ let engine: PGLiteEngine;+ let queue: MinionQueue;+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ queue = new MinionQueue(engine);+ }, 30000);+ afterAll(async () => { await engine.disconnect(); });+ async function freshSource(): Promise<void> {+ await engine.executeRaw('DELETE FROM minion_jobs');+ await engine.executeRaw(`DELETE FROM sources WHERE id = 'repo-phase'`);+ await engine.executeRaw(`INSERT INTO sources (id, name, config, created_at) VALUES ('repo-phase', 'r', '{}'::jsonb, now())`, []);+ }+ beforeEach(freshSource);++ const cycleWithFailedPhase = {+ partial: true, status: 'partial',+ report: { status: 'partial', phases: [{ phase: 'sync', status: 'ok' }, { phase: 'extract', status: 'fail', summary: 'extract failed' }] },+ };++ /** Run `cycles` autopilot-cycle jobs for repo-phase through a worker whose handler does `handler`. */+ async function runCycles(cycles: number, handler: () => Promise<Record<string, unknown>>): Promise<MinionJob[]> {+ const jobs: MinionJob[] = [];+ for (let i = 0; i < cycles; i++) jobs.push(await queue.add('autopilot-cycle', { source_id: 'repo-phase' }, { max_attempts: 1 }));+ const worker = new MinionWorker(engine, { pollInterval: 25 });+ worker.register('autopilot-cycle', handler);+ const running = worker.start();+ try {+ await waitFor(async () => {+ const rows = await Promise.all(jobs.map(j => queue.getJob(j.id)));+ return rows.every(r => r && ['completed', 'failed', 'dead'].includes(r.status));+ }, { timeoutMs: 15_000, label: 'cycles terminal' });+ } finally {+ worker.stop();+ await running;+ }+ return (await Promise.all(jobs.map(j => queue.getJob(j.id)))) as MinionJob[];+ }++ test('N cycles each ending failed on one phase leave the source dispatchable', async () => {+ const jobs = await runCycles(4, async () => cycleWithFailedPhase);+ for (const job of jobs) {+ expect(job.status).toBe('failed');+ expect(job.result).toMatchObject({ job_outcome: 'phase_failed', failed_phase: 'extract' });+ }+ expect((await readRecentSourceFailures(engine, { sinceMin: 120 })).has('repo-phase')).toBe(false);+ expect(await isSourceInCooldown(engine, 'repo-phase')).toBe(false);+ });++ test('a whole-cycle failure still backs the source off: a thrown handler, or blocked_by_failures', async () => {+ await runCycles(1, async () => { throw new Error('cycle crashed'); });+ expect(await isSourceInCooldown(engine, 'repo-phase')).toBe(true);+ await freshSource();+ const [blocked] = await runCycles(1, async () => ({ status: 'blocked_by_failures', reason: 'held_files' }));+ expect(blocked.result).toMatchObject({ job_outcome: 'failed' });+ expect(await isSourceInCooldown(engine, 'repo-phase')).toBe(true);+ });+});diff --git a/test/minions-job-outcome-7188.test.ts b/test/minions-job-outcome-7188.test.tsindex 210736663a..f0bfb2154d 100644--- a/test/minions-job-outcome-7188.test.ts+++ b/test/minions-job-outcome-7188.test.ts@@ -1,6 +1,7 @@/*** #7188: a job whose handler result reports a failed phase, a failed or blocked status, or unfinished work no longer- * ends a plain `completed`. A failure ends `failed` with the phase and reason (result kept); unfinished work+ * ends a plain `completed`. A failure ends `failed` with the phase and reason (result kept, marked `job_outcome`+ * `phase_failed` with `failed_phase`, or `failed`); unfinished work* completes with `job_outcome: 'partial'` on its result (the queue has no partial status); a clean result or a* deliberate skip completes as before.*/@@ -20,7 +21,7 @@ const cycleResult = (phases: unknown[], status: string) => ({ partial: status !=describe('#7188 jobResultOutcome', () => {test('a failed phase fails the job and names the phase, code and message', () => {expect(jobResultOutcome(cycleResult([{ phase: 'lint', status: 'ok' }, failedSyncPhase], 'partial'))).toEqual({- outcome: 'failed', reason: 'phase sync failed (25006): cannot execute INSERT in a read-only transaction',+ outcome: 'failed', phase: 'sync', reason: 'phase sync failed (25006): cannot execute INSERT in a read-only transaction',});});@@ -73,7 +74,7 @@ describe('#7188 worker records the outcome', () => {expect(job.status).toBe('failed');expect(job.attempts_made).toBe(1);expect(job.error_text).toBe('phase sync failed (25006): cannot execute INSERT in a read-only transaction');- expect(job.result).toEqual(result);+ expect(job.result).toEqual({ ...result, job_outcome: 'phase_failed', failed_phase: 'sync' });expect(job.finished_at).not.toBeNull();});