Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(minions): an unreadable worker registry reads as unknown liveness, never zero workers (#6933)
time-attack32b8a69e3d24
diff --git a/docs/architecture/key-files/core-minions-2.md b/docs/architecture/key-files/core-minions-2.mdindex 88a4718ddb..6735eecfcf 100644--- a/docs/architecture/key-files/core-minions-2.md+++ b/docs/architecture/key-files/core-minions-2.md@@ -34,7 +34,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/minions/worker-exit-codes.ts` — single source of truth for reserved worker process exit codes, shared by the worker (sets them) and supervisor/CLI (classify them). Exports `WORKER_EXIT_RSS_WATCHDOG = 12` and `WORKER_EXIT_CONFIGURATION = 16`; the latter blocks the owning supervisor before generic crash accounting and requires repair plus explicit restart. The RSS watchdog drain must be self-identifying: a code-0 exit is indistinguishable from a healthy queue-drain, so a `code===0 → clean_exit` classifier would never count it and a respawn loop would stay invisible. A distinct code makes the drain `likely_cause=rss_watchdog`. Code 12 is deliberately outside {0 clean, 1 runtime_error} and the 128+N signal range. Also reserves the `jobs run-child` codes: 13 usage/PGLite, 14 not-claimed/token-mismatch, 15 result-write-failed (result-file presence, not the exit code, classifies the normal path).-- `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. Pinned by `test/worker-registry.serial.test.ts`.+- `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.diff --git a/src/commands/doctor/checks/legacy-job-authority.ts b/src/commands/doctor/checks/legacy-job-authority.tsindex 6e4c0f9e49..72f96d6a39 100644--- a/src/commands/doctor/checks/legacy-job-authority.ts+++ b/src/commands/doctor/checks/legacy-job-authority.ts@@ -109,10 +109,21 @@ async function runLegacyJobAuthority(ctx: DoctorContext): Promise<Check[]> {const engine = connectedEngine(ctx);const { status, message, details } = await legacyJobAuthorityCheck(engine);const spend = await readQueuedSpend(engine).catch(() => null);- const workers = spend?.long_waiting ? (await import('../../../core/minions/worker-registry.ts')).readWorkers().length : 0;+ // null: the worker registry is unreadable, so the live-worker count is unknown (never zero).+ let workers: number | null = 0;+ let registryFailure: { errno: string; path: string | null } | null = null;+ if (spend?.long_waiting) {+ const registry = await import('../../../core/minions/worker-registry.ts');+ try {+ workers = registry.readWorkers().length;+ } catch (e) {+ workers = null;+ registryFailure = registry.workerRegistryReadFailure(e);+ }+ }const census = spend && Object.keys(spend.by_basis).length? ` Queued paid jobs by spend basis: ${Object.entries(spend.by_basis).map(([b, n]) => `${b} ${n}`).join(', ')}.` : '';- if (status === 'ok' && spend?.long_waiting && workers > 0) {+ if (status === 'ok' && spend?.long_waiting && workers !== null && workers > 0) {checks.push({ name: 'legacy_job_authority', status: 'warn', details: { ...details, queued_spend: spend, live_workers: workers },message: `${spend.long_waiting} spend-authorized job(s) (${spend.long_waiting_ids.join(', ')}) have waited over 10 minutes while ${workers} worker(s) run: `+ `an un-upgraded worker may be fenced off; un-upgraded workers stop claiming at a fenced row. Upgrade gbrain on every worker host and restart the workers (gbrain jobs supervisor stop, then gbrain jobs supervisor start, or your service manager).${census}`,@@ -120,7 +131,9 @@ async function runLegacyJobAuthority(ctx: DoctorContext): Promise<Check[]> {why: 'Shows the waiting rows and their spend records; fenced rows run once every worker runs the upgraded binary.' } });return checks;}- checks.push({ name: 'legacy_job_authority', status, message: `${message}${census}`, details: spend ? { ...details, queued_spend: spend } : details });+ const unknownWorkers = registryFailure+ ? { live_workers: null, worker_registry_unreadable: true, worker_registry_errno: registryFailure.errno, worker_registry_path: registryFailure.path } : {};+ checks.push({ name: 'legacy_job_authority', status, message: `${message}${census}`, details: spend ? { ...details, queued_spend: spend, ...unknownWorkers } : details });return checks;}diff --git a/src/commands/doctor/checks/queue-jobs.ts b/src/commands/doctor/checks/queue-jobs.tsindex 67c9b99f2a..5221a0764b 100644--- a/src/commands/doctor/checks/queue-jobs.ts+++ b/src/commands/doctor/checks/queue-jobs.ts@@ -126,11 +126,16 @@ export async function computeQueueHealthCheck(// Read the live-worker registry unconditionally (was: only when old// embed-backfill rows existed) — the structured `details.worker_alive`- // below needs it on every run. Cheap: one directory enumeration.- const workers = opts.readWorkers- ? opts.readWorkers()- : (await import('../../../core/minions/worker-registry.ts')).readWorkers();- const liveWorkerQueues = new Set(workers.map((w) => w.queue));+ // below needs it on every run. Cheap: one directory enumeration. An+ // unreadable registry is unknown liveness (null), never "no worker".+ const registry = await import('../../../core/minions/worker-registry.ts');+ let liveWorkerQueues: Set<string> | null = null;+ let registryFailure: { errno: string; path: string | null } | null = null;+ try {+ liveWorkerQueues = new Set((opts.readWorkers ?? registry.readWorkers)().map((w) => w.queue));+ } catch (e) {+ registryFailure = registry.workerRegistryReadFailure(e);+ }// Minions-visibility wave: structured details so machine callers stop// parsing prose. depth = total waiting jobs; oldest_age_seconds = age of@@ -164,7 +169,8 @@ export async function computeQueueHealthCheck(},null,),- worker_alive: waitingByQueue.every((r) => liveWorkerQueues.has(r.queue)),+ worker_alive: liveWorkerQueues === null ? null : waitingByQueue.every((r) => liveWorkerQueues.has(r.queue)),+ ...(registryFailure ? { worker_registry_unreadable: true, worker_registry_errno: registryFailure.errno, worker_registry_path: registryFailure.path } : {}),};const problems: string[] = [];@@ -187,8 +193,16 @@ export async function computeQueueHealthCheck();}for (const row of oldWaitingRows) {- if (liveWorkerQueues.has(row.queue)) continue;+ if (liveWorkerQueues?.has(row.queue)) continue;const hours = Math.max(1, Math.round(Number(row.oldest_age_seconds ?? 0) / 3600));+ if (registryFailure) {+ problems.push(+ `${row.depth} ${row.name} job(s) have waited on queue '${row.queue}' for up to ${hours}h; ` ++ `the worker registry is unreadable (${registryFailure.errno}${registryFailure.path ? ` at ${registryFailure.path}` : ''}), ` ++ `so worker liveness is unknown. Check that directory's permissions, then run \`gbrain jobs supervisor status\`.`+ );+ continue;+ }problems.push(`${row.depth} ${row.name} job(s) have waited on queue '${row.queue}' for up to ${hours}h ` +`and no live worker is registered for that queue. ` +@@ -289,7 +303,9 @@ export async function computeQueueHealthCheck(details,};}- const noWorkerQueue = oldWaitingRows.find(r => !liveWorkerQueues.has(r.queue))?.queue;+ const noWorkerQueue = liveWorkerQueues === null+ ? undefined+ : oldWaitingRows.find(r => !liveWorkerQueues.has(r.queue))?.queue;return {name: 'queue_health',status: 'warn',@@ -407,26 +423,22 @@ export async function computeWedgedQueueCheck(// operator toward restarting a worker that was never there — a queue// with no worker needs `start`, not `stop && start`.let liveWorkers: Array<{ queue: string }> = [];- let registryReadable = true;+ let registryFailure: { errno: string; path: string | null } | null = null;+ const registry = await import('../../../core/minions/worker-registry.ts');try {- // Lazy import mirrors computeQueueHealthCheck's own registry access- // above — the registry module stays off this file's eager import- // graph and only loads once a wedge actually needs the signal.- const getLiveWorkers = opts.readWorkers- ?? (await import('../../../core/minions/worker-registry.ts')).readWorkers;- liveWorkers = getLiveWorkers();- } catch {+ liveWorkers = (opts.readWorkers ?? registry.readWorkers)();+ } catch (e) {// A registry read error must not turn this check green (the queue is// demonstrably wedged) — but it also must not fabricate a liveness// verdict either way. Fall through to the liveness-unknown wording.- registryReadable = false;+ registryFailure = registry.workerRegistryReadFailure(e);}- if (!registryReadable) {+ if (registryFailure) {return {name: 'wedged_queue',status: 'fail',message:- `Wedged queue(s) — worker registry unreadable, worker liveness unknown: ` ++ `Wedged queue(s) — worker registry unreadable (${registryFailure.errno}${registryFailure.path ? ` at ${registryFailure.path}` : ''}), worker liveness unknown: ` +`${wedged.map((w) => w.label).join('; ')}. ` +`If a worker is running for the queue, restart it: ` +'`gbrain jobs supervisor stop && gbrain jobs supervisor start [--queue <name>]`; ' +@@ -434,6 +446,8 @@ export async function computeWedgedQueueCheck(details: {wedged_queues: wedged.length,worker_registry_unreadable: true,+ worker_registry_errno: registryFailure.errno,+ worker_registry_path: registryFailure.path,threshold_minutes: thresholdMin,},};diff --git a/src/commands/jobs/supervisor.ts b/src/commands/jobs/supervisor.tsindex 6cdbafc54f..368616c0b4 100644--- a/src/commands/jobs/supervisor.ts+++ b/src/commands/jobs/supervisor.ts@@ -180,7 +180,7 @@ async function showSupervisorStatus(): Promise<void> {const { readSupervisorEvents, summarizeCrashes } = await import('../../core/minions/handlers/supervisor-audit.ts');const { readSupervisorPid } = await import('../../core/minions/supervisor-pid.ts');- const { readWorkers } = await import('../../core/minions/worker-registry.ts');+ const { readWorkers, workerRegistryReadFailure } = await import('../../core/minions/worker-registry.ts');const pidStatus = readSupervisorPid(pidFile);const supervisorPid = pidStatus.pid;@@ -224,12 +224,19 @@ async function showSupervisorStatus(const maxCrashesEvent = events.filter(e => e.event === 'max_crashes_exceeded').pop() ?? null;// Niceness (issue #1815): measure live workers + the supervisor itself.- const workers = readWorkers().map(w => ({- pid: w.pid,- queue: w.queue,- nice_requested: w.nice_requested,- nice: w.nice_now,- }));+ // workers is null when the registry is unreadable: liveness unknown, not zero.+ let workers: Array<{ pid: number; queue: string; nice_requested: number | null; nice: number | null }> | null = null;+ let workerRegistryError: { errno: string; path: string | null } | null = null;+ try {+ workers = readWorkers().map(w => ({+ pid: w.pid,+ queue: w.queue,+ nice_requested: w.nice_requested,+ nice: w.nice_now,+ }));+ } catch (e) {+ workerRegistryError = workerRegistryReadFailure(e);+ }const supervisorNice = pidfileRunning && supervisorPid !== null? getEffectiveNiceness(supervisorPid): null;@@ -263,6 +270,7 @@ async function showSupervisorStatus(max_crashes_exceeded: !!maxCrashesEvent,nice: supervisorNice,workers,+ ...(workerRegistryError ? { worker_registry_unreadable: true, worker_registry_errno: workerRegistryError.errno, worker_registry_path: workerRegistryError.path } : {}),};if (jsonMode) {@@ -282,7 +290,10 @@ async function showSupervisorStatus(console.log(` Crashes (24h): ${summary.total} (runtime=${summary.by_cause.runtime_error} oom=${summary.by_cause.oom_or_external_kill} unknown=${summary.by_cause.unknown} legacy=${summary.by_cause.legacy})`);console.log(` Clean exits (24h): ${summary.clean_exits}`);if (supervisorNice !== null) console.log(` Nice (supervisor): ${formatNice(supervisorNice)}`);- for (const w of workers) {+ if (workerRegistryError) {+ console.log(` Workers: unknown (worker registry unreadable: ${workerRegistryError.errno}${workerRegistryError.path ? ` at ${workerRegistryError.path}` : ''})`);+ }+ for (const w of workers ?? []) {const req = w.nice_requested !== null && w.nice !== null && w.nice_requested !== w.nice? ` (requested ${formatNice(w.nice_requested)})` : '';console.log(` Worker pid ${w.pid} [${w.queue}]: nice ${w.nice !== null ? formatNice(w.nice) : '?'}${req}`);diff --git a/src/commands/migrate-embeddings.ts b/src/commands/migrate-embeddings.tsindex 36e0693266..e07ac2e254 100644--- a/src/commands/migrate-embeddings.ts+++ b/src/commands/migrate-embeddings.ts@@ -197,8 +197,9 @@ function renderPlan(ctx: MigrationPlanContext): string {if (plan.resuming) {lines.push(' Resuming: a prior migration to this target was interrupted; continuing it.');}- if (concurrentWriters.workers > 0 || concurrentWriters.embedJobs > 0) {- lines.push(` WARNING: ${concurrentWriters.workers} live minion worker(s) and ${concurrentWriters.embedJobs} waiting/running`);+ if (concurrentWriters.workers !== 0 || concurrentWriters.embedJobs > 0) {+ const workerCount = concurrentWriters.workers === null ? 'an unknown number of (worker registry unreadable)' : String(concurrentWriters.workers);+ lines.push(` WARNING: ${workerCount} live minion worker(s) and ${concurrentWriters.embedJobs} waiting/running`);lines.push(' embed job(s) detected. Generic embed/cycle jobs do not take the migration');lines.push(' locks — stop the worker (or let the queue drain) first, or their writes');lines.push(' will be counted stale by the final census and re-embedded.');@@ -441,8 +442,8 @@ export interface MigrationPlanContext {rerankerPlan: RerankerPlan;/** Which brain/DB this run is actually pointed at (wrong-brain visibility). */identity: { engine: string; target: string };- /** Quiesce-lite: live embed writers that are NOT under the migration locks. */- concurrentWriters: { workers: number; embedJobs: number };+ /** Quiesce-lite: live embed writers that are NOT under the migration locks; workers is null when the worker registry is unreadable. */+ concurrentWriters: { workers: number | null; embedJobs: number };/** Non-default search_embedding_column, if configured (read-path caveat). */customSearchColumn: string | null;}@@ -551,10 +552,12 @@ export async function planMigrationFlow(// Quiesce-lite census (round-1 C2 / round-2 #3): embed writers outside the// migration locks. Report, don't block — the completion census is the// correctness backstop; this is the operator's "stop the worker first" cue.- let concurrentWriters = { workers: 0, embedJobs: 0 };+ let concurrentWriters: { workers: number | null; embedJobs: number } = { workers: 0, embedJobs: 0 };try {const { readWorkers } = await import('../core/minions/worker-registry.ts');- const workers = readWorkers().length;+ // An unreadable registry is an unknown worker count (null), and must not also drop the embed-job count below.+ let workers: number | null = null;+ try { workers = readWorkers().length; } catch { /* registry unreadable: worker count unknown */ }const rows = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM minion_jobsWHERE status IN ('waiting', 'running')diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 8b9f942345..b49dcce091 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -909,6 +909,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.307.0', text: 'The `advisor` MCP operation now judges the cached backup verdict the way the doctor does: a remote readback older than one hour, a future-dated cache or a degraded compute reports the `backup_coverage_aggregate` warning instead of no finding. It still reads the cache only and names reason counts, never source ids.' },{ since: '0.60.307.0', text: '`gbrain advisor` (and the `advisor` MCP operation) reports a database read that fails inside the `usage-shape` or `stalled-jobs` check as `collector_failed:<check>` and exits 1, instead of returning no findings for that check and possibly reporting a healthy brain. A brain with no pages, and an older brain without `minion_jobs`, `sources` or `sources.last_sync_at`, still report nothing for those checks.' },{ since: '0.60.307.0', text: '`gbrain search tune --apply` now writes before it reports: `--json` lists in `applied` and `revert_commands` only the changes that landed, adds per-item `results` (`applied`, `unsupported`, `failed`, `outcome_unknown`, `not_attempted`), `not_applied` and `apply_error`, and the text output marks a failed or unrecognized change with ✗ instead of ✓. The batch stops at the first write that does not land and the command exits non-zero; changes that already landed stay in place with their revert commands.' },+ { since: '0.60.307.0', text: 'A worker registry directory that exists but cannot be listed (permission denied, or a file where the directory should be) now reads as unknown worker liveness instead of no workers. Doctor `queue_health` reports `worker_alive: null` with a liveness-unknown message and no start-a-worker fix, `legacy_job_authority` reports `live_workers: null`, `gbrain jobs supervisor status --json` reports `workers: null`, a submitted job\'s `queue_state` omits `worker_alive` and warns that liveness is unknown, `gbrain jobs stats` reports a wedge instead of `no_worker`, and the `migrate-embeddings` plan warns about an unknown worker count. Each names the errno and path in `worker_registry_errno` and `worker_registry_path`. A missing registry directory still means no workers.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/minions/supervisor.ts b/src/core/minions/supervisor.tsindex 718c0bbd78..f7221690b4 100644--- a/src/core/minions/supervisor.ts+++ b/src/core/minions/supervisor.ts@@ -47,7 +47,7 @@ import { dirname, resolve } from 'path';import { hostname } from 'os';import type { BrainEngine } from '../engine.ts';import { tryAcquireDbLock, waitForDbLockTakeover, inspectLock, isLockHolderLive, type DbLockHandle } from '../db-lock.ts';-import { currentBrainId, readWorkers } from './worker-registry.ts';+import { currentBrainId, readWorkers, workerRegistryReadFailure } from './worker-registry.ts';import { autopilotOperatorPauseMarkerPath, autopilotPaused } from '../autopilot-paths.ts';import { registerSignalOwner, triggerCleanupAndExit } from '../process-cleanup.ts';import { resolveEnvNumber } from '../env-number.ts';@@ -335,7 +335,7 @@ export interface QueueSubmitState {depth?: number;/** Age of the oldest waiting job on the queue, or null when depth is 0. */oldest_waiting_age_seconds?: number | null;- /** A supervisor DB lock is live, a registered worker serves the queue, or a live-lock active job proves one exists. */+ /** A supervisor DB lock is live, a registered worker serves the queue, or a live-lock active job proves one exists. Absent when the worker registry is unreadable and nothing else proves a worker (liveness unknown). */worker_alive?: boolean;/** The autopilot pause marker is present — nothing will start until it clears. */paused?: boolean;@@ -427,14 +427,14 @@ async function probeQueueStateInner(} catch {// Pre-migration brains lack the locks table — registry/active signals stand.}- let registeredWorker = false;+ // An unreadable registry leaves the other signals standing, but their absence is then unknown liveness, not "no worker".+ let registeredWorker = false, registryErrno: string | null = null;try {registeredWorker = readWorkers().some((w) => w.queue === queue);- } catch {- // Registry dir unreadable — remaining signals stand.- }+ } catch (e) { registryErrno = workerRegistryReadFailure(e).errno; }const workerAlive = supervisorLive || registeredWorker || sig.activeHealthy > 0;+ const livenessUnknown = !workerAlive && registryErrno !== null;const paused = autopilotPaused();// Same operator knob the doctor's queue_health depth check reads.@@ -445,11 +445,8 @@ async function probeQueueStateInner(? 'system paused by the operator (gbrain autopilot resume clears it) — job will not start until the pause clears': 'system paused for migration — job will not start until the pause clears');}- if (!workerAlive) {- warnings.push(- `no live worker detected for queue '${queue}' — job will wait until one starts (gbrain jobs work --queue ${queue})`,- );- }+ if (livenessUnknown) warnings.push(`worker liveness unknown for queue '${queue}': the worker registry is unreadable (${registryErrno}); check gbrain jobs supervisor status`);+ else if (!workerAlive) warnings.push(`no live worker detected for queue '${queue}' — job will wait until one starts (gbrain jobs work --queue ${queue})`);if (sig.waiting > threshold) {warnings.push(`waiting depth ${sig.waiting} exceeds GBRAIN_QUEUE_WAITING_THRESHOLD (${threshold})`);}@@ -457,7 +454,7 @@ async function probeQueueStateInner(const state: QueueSubmitState = {depth: sig.waiting,oldest_waiting_age_seconds: oldestAge,- worker_alive: workerAlive,+ ...(livenessUnknown ? {} : { worker_alive: workerAlive }),};if (paused) state.paused = true;if (warnings.length > 0) state.warning = warnings.join('; ');diff --git a/src/core/minions/worker-registry.ts b/src/core/minions/worker-registry.tsindex 50121b5da3..cd14402112 100644--- a/src/core/minions/worker-registry.ts+++ b/src/core/minions/worker-registry.ts@@ -51,6 +51,28 @@ export interface LiveWorker extends WorkerRegistryEntry {nice_now: number | null;}+/**+ * The registry directory exists but cannot be listed (EACCES on it or a+ * parent, ENOTDIR, ...). Worker liveness is unknown: callers report it as+ * unknown with this errno and path, never as zero workers.+ */+export class WorkerRegistryUnreadableError extends Error {+ readonly path: string;+ readonly errno: string;+ constructor(path: string, errno: string, cause: unknown) {+ super(`worker registry unreadable (${errno}): ${path}`, { cause });+ this.name = 'WorkerRegistryUnreadableError';+ this.path = path;+ this.errno = errno;+ }+}++/** The safe evidence of a failed registry read: errno and path, or the error class name for anything else. */+export function workerRegistryReadFailure(err: unknown): { errno: string; path: string | null } {+ if (err instanceof WorkerRegistryUnreadableError) return { errno: err.errno, path: err.path };+ return { errno: err instanceof Error ? err.name : 'unknown', path: null };+}+/** Directory holding one file per live worker. Brain-isolated via GBRAIN_HOME. */export function workerRegistryDir(): string {return gbrainPath('workers');@@ -206,24 +228,27 @@ const PID_REUSE_TOLERANCE_MS = 5000;* confirmed-dead entries (pruning their files), filters by brain id, applies the* PID-reuse guard, and re-measures each live worker's niceness now.*+ * Only a missing registry directory (ENOENT) is an empty registry; any other+ * listing failure throws WorkerRegistryUnreadableError (existsSync() answers+ * false for an unsearchable parent too, so it is not used as the gate).* `getNice` is injectable for tests.*/export function readWorkers(getNice: (pid: number) => number | null = (pid) => getEffectiveNiceness(pid),): LiveWorker[] {const dir = workerRegistryDir();- if (!existsSync(dir)) return [];-- const brainId = currentBrainId();- const live: LiveWorker[] = [];-let files: string[];try {files = readdirSync(dir).filter((f) => f.startsWith('worker-') && f.endsWith('.json'));- } catch {- return [];+ } catch (e) {+ const errno = (e as NodeJS.ErrnoException)?.code;+ if (errno === 'ENOENT') return [];+ throw new WorkerRegistryUnreadableError(dir, errno ?? 'unknown', e);}+ const brainId = currentBrainId();+ const live: LiveWorker[] = [];+for (const f of files) {const full = join(dir, f);let entry: WorkerRegistryEntry;diff --git a/test/doctor-queue-divergence.test.ts b/test/doctor-queue-divergence.test.tsindex b22edb8fd7..610df9f24a 100644--- a/test/doctor-queue-divergence.test.ts+++ b/test/doctor-queue-divergence.test.ts@@ -116,6 +116,35 @@ describe('queue_health — healthy queue stays quiet', () => {});});+describe('queue_health — unreadable worker registry', () => {+ it('reports liveness unknown instead of erroring or advising a worker start', async () => {+ await seed('default', 'embed-backfill', 'waiting', { createdAtSql: "now() - interval '3 hours'" });+ const check = await computeQueueHealthCheck(pgLike, {+ readWorkers: () => { throw new Error('EACCES: permission denied'); },+ });+ expect(check.status).toBe('warn');+ expect(check.details?.worker_alive).toBeNull();+ expect(check.message).toContain('worker liveness is unknown');+ expect(check.message).not.toContain('no live worker is registered');+ expect(check.fix).toBeUndefined();+ });++ it('carries the registry errno and path in details and the message', async () => {+ await seed('default', 'embed-backfill', 'waiting', { createdAtSql: "now() - interval '3 hours'" });+ const { WorkerRegistryUnreadableError } = await import('../src/core/minions/worker-registry.ts');+ const check = await computeQueueHealthCheck(pgLike, {+ readWorkers: () => { throw new WorkerRegistryUnreadableError('/home/alice-example/.gbrain/workers', 'EACCES', null); },+ });+ expect(check.details).toMatchObject({+ worker_alive: null,+ worker_registry_unreadable: true,+ worker_registry_errno: 'EACCES',+ worker_registry_path: '/home/alice-example/.gbrain/workers',+ });+ expect(check.message).toContain('unreadable (EACCES at /home/alice-example/.gbrain/workers)');+ });+});+describe('malformed_path_pages discovery check (buildChecks seam)', () => {it('warns naming the count + slug when a page is backed by a bracketed filename', async () => {await base.executeRaw(diff --git a/test/doctor-queued-spend.test.ts b/test/doctor-queued-spend.test.tsindex 9509443d7d..6c9610e28a 100644--- a/test/doctor-queued-spend.test.ts+++ b/test/doctor-queued-spend.test.ts@@ -5,7 +5,7 @@* run under the legacy default cap.*/import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';-import { mkdtempSync, rmSync } from 'node:fs';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';@@ -58,6 +58,18 @@ describe('queued spend in doctor', () => {} finally { await withEnv({ GBRAIN_HOME: home }, () => unregister()); }});+ test('an unreadable worker registry reports live_workers unknown instead of failing the check', async () => {+ const job = await queue.add('enrich', { sourceId: 'default' }, {}, { spendAuthorization: spend() });+ await engine.executeRaw(`UPDATE minion_jobs SET updated_at = now() - interval '20 minutes' WHERE id = $1`, [job.id]);+ const brokenHome = mkdtempSync(join(tmpdir(), 'gbrain-doctor-queued-spend-unreadable-'));+ try {+ mkdirSync(join(brokenHome, '.gbrain'), { recursive: true });+ writeFileSync(join(brokenHome, '.gbrain', 'workers'), 'not a directory');+ const [check] = await (withEnv({ GBRAIN_HOME: brokenHome }, () => legacyJobAuthorityEntry.run({ engine } as never)) as Promise<Array<Record<string, any>>>);+ expect(check).toMatchObject({ status: 'ok', details: { queued_spend: { long_waiting_ids: [job.id] }, live_workers: null, worker_registry_unreadable: true, worker_registry_errno: 'ENOTDIR' } });+ } finally { rmSync(brokenHome, { recursive: true, force: true }); }+ });+test('no banner line without legacy rows', async () => {await queue.add('enrich', { sourceId: 'default' }, {}, { spendAuthorization: spend() });expect(await legacyDefaultSpendBannerNote(engine)).toBeNull();diff --git a/test/doctor-wedged-queue.test.ts b/test/doctor-wedged-queue.test.tsindex afa36b604c..94faa6bfc6 100644--- a/test/doctor-wedged-queue.test.ts+++ b/test/doctor-wedged-queue.test.ts@@ -126,6 +126,8 @@ describe('issue #1801 fix #3 — computeWedgedQueueCheck', () => {expect(check.message).not.toContain('worker alive but not claiming work');expect(check.message).not.toContain('No worker subscribed');expect(check.details?.worker_registry_unreadable).toBe(true);+ expect(check.details?.worker_registry_errno).toBe('Error');+ expect(check.details?.worker_registry_path).toBeNull();});it('mixed stuck + no-worker queues → both messages, details count each subset', async () => {diff --git a/test/jobs-supervisor-offline-status.test.ts b/test/jobs-supervisor-offline-status.test.tsindex 5c1d2bee85..90f03584ab 100644--- a/test/jobs-supervisor-offline-status.test.ts+++ b/test/jobs-supervisor-offline-status.test.ts@@ -51,4 +51,31 @@ describe('supervisor status without a database connection', () => {rmSync(home, { recursive: true, force: true });}});++ test('an unreadable worker registry reports workers unknown instead of aborting status', async () => {+ const home = mkdtempSync(join(tmpdir(), 'supervisor-status-registry-unreadable-'));+ try {+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({+ engine: 'postgres',+ database_url: 'postgresql://127.0.0.1:1/gbrain_test',+ }));+ writeFileSync(join(home, '.gbrain', 'workers'), 'not a directory');+ const pidFile = join(home, 'supervisor.pid');+ writeFileSync(pidFile, `${process.pid}\n`);+ const result = await runCli(['jobs', 'supervisor', 'status', '--pid-file', pidFile, '--json'], {+ home,+ timeoutMs: 10_000,+ env: { GBRAIN_AUDIT_DIR: join(home, 'audit') },+ });+ expect(result.exitCode).toBe(0);+ const status = JSON.parse(result.stdout);+ expect(status.running).toBe(true);+ expect(status.workers).toBeNull();+ expect(status.worker_registry_unreadable).toBe(true);+ expect(status.worker_registry_errno).toBe('ENOTDIR');+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ });});diff --git a/test/migrate-embeddings-hardening.serial.test.ts b/test/migrate-embeddings-hardening.serial.test.tsindex 83ed33ce34..a984d2624a 100644--- a/test/migrate-embeddings-hardening.serial.test.ts+++ b/test/migrate-embeddings-hardening.serial.test.ts@@ -1097,3 +1097,22 @@ describe('empty-brain migration (plan pin 15)', () => {}}, 120000);});++describe('concurrent-writer census', () => {+ test('an unreadable worker registry does not also drop the embed-job count', async () => {+ const registry = join(tmpHome, '.gbrain', 'workers');+ rmSync(registry, { recursive: true, force: true });+ writeFileSync(registry, 'not a directory');+ await engine.executeRaw(+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, created_at, updated_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'embed-backfill', 'default', 'waiting', now(), now())`,+ );+ try {+ const ctx = await planMigrationFlow(engine, { to: 'openai:text-embedding-3-small', dim: TO_DIMS });+ expect(ctx.concurrentWriters).toEqual({ workers: null, embedJobs: 1 });+ } finally {+ await engine.executeRaw(`DELETE FROM minion_jobs WHERE name = 'embed-backfill'`);+ rmSync(registry, { force: true });+ }+ }, 120000);+});diff --git a/test/submit-queue-state.test.ts b/test/submit-queue-state.test.tsindex 4c10c9867b..dfa30b7731 100644--- a/test/submit-queue-state.test.ts+++ b/test/submit-queue-state.test.ts@@ -71,6 +71,21 @@ describe('probeQueueState — dead/degraded lane signals', () => {});});+ it('unreadable worker registry: worker_alive omitted (unknown) and the warning names the errno, never "no live worker"', async () => {+ await seedJob({ createdAtSql: "now() - interval '2 hours'" });+ const home = emptyHome();+ mkdirSync(`${home}/.gbrain`, { recursive: true });+ writeFileSync(`${home}/.gbrain/workers`, 'not a directory');+ await withEnv({ GBRAIN_HOME: home }, async () => {+ const state = await probeQueueState(engine, 'default', ['embed']);+ expect(state.probe_failed).toBeUndefined();+ expect('worker_alive' in state).toBe(false);+ expect(state.warning).toContain("worker liveness unknown for queue 'default'");+ expect(state.warning).toContain('ENOTDIR');+ expect(state.warning).not.toContain('no live worker detected');+ });+ });+it('a live-lock active job counts as worker evidence (worker_alive true, no worker warning)', async () => {await seedJob({ status: 'active', lockUntilSql: "now() + interval '5 minutes'" });await withEnv({ GBRAIN_HOME: emptyHome() }, async () => {diff --git a/test/worker-registry.serial.test.ts b/test/worker-registry.serial.test.tsindex 061fbba382..eaff94acd6 100644--- a/test/worker-registry.serial.test.ts+++ b/test/worker-registry.serial.test.ts@@ -157,3 +157,53 @@ describe('pruning + guards', () => {expect(readWorkers(() => 5).length).toBe(0);});});++describe('unreadable registry is unknown, not empty', () => {+ // queueWorkerAlive, wedged_queue and remediation all keep a liveness-unknown+ // path for a throwing read; readWorkers must actually throw to reach it.+ test('a missing registry dir reads as empty and no-worker', async () => {+ const { readWorkers, workerRegistryDir } = await reg();+ const { queueWorkerAlive } = await import('../src/core/minions/no-worker.ts');+ expect(existsSync(workerRegistryDir())).toBe(false);+ expect(readWorkers(() => null)).toEqual([]);+ expect(queueWorkerAlive('default')).toBe(false);+ });++ test('a registry path that cannot be listed (ENOTDIR) throws; liveness is unknown, so no no_worker advice', async () => {+ const { readWorkers, workerRegistryDir } = await reg();+ const { queueWorkerAlive } = await import('../src/core/minions/no-worker.ts');+ const { deriveWedgeSignal } = await import('../src/core/minions/queue.ts');+ require('fs').mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(workerRegistryDir(), 'not a directory');+ expect(() => readWorkers(() => null)).toThrow(/ENOTDIR/);+ const { WorkerRegistryUnreadableError, workerRegistryReadFailure } = await reg();+ let caught: unknown;+ try { readWorkers(() => null); } catch (e) { caught = e; }+ expect(caught).toBeInstanceOf(WorkerRegistryUnreadableError);+ expect(workerRegistryReadFailure(caught)).toEqual({ errno: 'ENOTDIR', path: workerRegistryDir() });+ expect(queueWorkerAlive('default')).toBeUndefined();+ const signal = deriveWedgeSignal(+ { queue: 'default', active_healthy: 0, waiting: 3, minutes_since_completion: null },+ { workerAlive: queueWorkerAlive('default') },+ );+ expect(signal.no_worker).toBe(false);+ expect(signal.wedged).toBe(true);+ });++ test.skipIf(process.platform === 'win32' || process.getuid?.() === 0)(+ 'an unsearchable parent (EACCES) throws instead of reading as absent',+ async () => {+ const { readWorkers } = await reg();+ const { queueWorkerAlive } = await import('../src/core/minions/no-worker.ts');+ const parent = join(home, '.gbrain');+ require('fs').mkdirSync(join(parent, 'workers'), { recursive: true });+ require('fs').chmodSync(parent, 0o000);+ try {+ expect(() => readWorkers(() => null)).toThrow(/EACCES/);+ expect(queueWorkerAlive('default')).toBeUndefined();+ } finally {+ require('fs').chmodSync(parent, 0o700);+ }+ },+ );+});