Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(doctor): background doctor-refresh queues behind sync and cycles, stops at a 10 min budget, and can be turned off (#7263)

garrytan46f5b6b99614
diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.md
index c85b5a5c63..26f0cd4850 100644
--- a/docs/architecture/key-files/commands-2-continued.md
+++ b/docs/architecture/key-files/commands-2-continued.md
@@ -33,7 +33,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/doctor/checks/image-embedding-coverage.ts` — `image_embedding_coverage` (#6529, brain category, after `image_assets`). Counts live image pages (`page_kind = 'image'`), those with no `embedding_image` chunk, those with a NULL `source_path`, and the `managed_image_sync_unsupported` holds per source, and reads `isMultimodalEnabled()`. Ok when the brain has no image pages, when every image page has an image vector and a `source_path` and nothing is held, or when multimodal embedding is off (the counts are then informational: image search is not expected to work). On a multimodal install it warns with the counts (text coverage counts those pages as embedded while image search does not see them) and names `gbrain embed --stale --images` and `gbrain sync --no-pull --source <id>` for the holds. Read-only; no paid call. Test: `test/doctor-image-embedding-coverage.test.ts`.
- `src/commands/doctor/checks/provider-consent.ts` — `provider_consent` (OPS, engine-free filesystem lane right after `embedding_key_source`; not in `doctorReportRemote`): the provider-use decision `gbrain setup` recorded for this install (`localSetupRecords` in `src/core/setup/local-receipts.ts`). A decline (any live receipt; opt-outs win) is `ok` + info `disabled_by_choice`, "skipped by consent", naming the provider key variables present (names only) and carrying `providerConsentFix`: `gbrain setup <harness> --providers` (+ `--name`/`--scope project`), actor `user`, consent `paid`+`egress`, so `next: tell_user_to_run`. Accepted is plain `ok`; no receipt is info `not_applicable`. The same fix rides `embedding_provider`'s `--probe` skip (`checks/embedding-health.ts`), and `probe-consent.ts` authorizes nothing when a decline is recorded. Reads files only; sends nothing. Pinned by `test/doctor-provider-consent.serial.test.ts` (request counter: zero outbound under a decline, controls prove discovery and the probe are seen otherwise).
- `src/commands/doctor/budget.ts` + `checks/ops-sections.ts` + `checks/orphan-estimate.ts` — doctor tiers and budgets (#6696 B1). `parseDoctorTier` (`--tier ops|quick|standard|deep`, a bad value is `invalid_params`), `parseBudgetMs` (`--budget-ms`, default 4000 under ops, 10000 under quick, none otherwise) and `startDoctorDeadline` build the `DoctorDeadline` the CLI starts before connecting. `runDoctorRegistry` runs the entries tagged `tier: 'ops'` (persistence capacity, terminal failures, managed sync movement, persistence compaction, serve build drift, schema-pack consistency, embedding state) right after the connection lane; under `--tier ops` it runs only those (each `executeRaw` gets the absolute `deadlineAt`, so `SET LOCAL statement_timeout` is the time left after the pool wait: `postgres-engine/bounded-statement.ts`), reports an entry marked `opsPglite: 'not_applicable'` as an `ok` info row on PGLite, and stays complete. Every other tier bounds each entry by `doctor.entry_budget_ms` (default 15000). An entry past its budget, an unknown reported after the overall deadline, or a connect the deadline ended becomes `budgetUnknownCheck` (warn, `details.health: 'unknown'`, `reason: 'budget'`, `exact: false`, a rerun-alone fix), never a clear result; every check carries `elapsed_ms`, and the report adds `tier`/`complete`/`unknown_sections`/`elapsed_ms`/`budget_ms` only when `--tier` or `--budget-ms` was given (`doctorRunSummary`). `doctorHealth(ctx)` memoizes `getHealth` for one run. `orphan_ratio` estimates from a `TABLESAMPLE SYSTEM` sample above `doctor.orphan_ratio.full_scan_max_pages` (default 50000) unless `--tier deep`. Capacity (`persistence_capacity`, PR A's forecast) and compaction freshness (`persistence_compaction`) run as ops entries in `checks/ops-sections.ts`. #6803 (Part 5): on every tier each entry runs inside its own `StatementDeadline` (`src/core/statement-deadline.ts`: an AsyncLocalStorage scope plus `deadlineBoundEngine`, one stable Proxy per real engine that refuses any engine call past the deadline, carries the deadline to the server on Postgres `executeRaw`, and marks the scope expired on a cancel even when the check catches it; `engineCacheKey` maps the wrapper to the real engine for engine-keyed caches; PGLite gets only the pre-statement refusal). The budget-config read is one bounded statement (2 s, default kept). `CHEAP_INCIDENT_CHECKS` (by check name: persistence capacity, managed sync movement, `text_projection_readiness`, `partial_embedding`, `links_extraction_lag`, now its own entry) run right after the ops sections, before any full scan. `scanDeadline` clips the frontmatter walk and the fence census to the entry deadline less 250 ms, so they report partial results. `--only` with an explicit `--budget-ms` gives the selected entries the whole overall budget; `budgetUnknownCheck` names the limiting budget (`details.limit`: `entry` or `overall`) and fixes with `--only <check> --budget-ms N` (N ten times that budget; actor agent while N fits `AGENT_TOOL_LIMIT_MS` less 10 s, else actor user). `--budget-ms 0` is no overall budget. `default-budget.ts`: a plain non-interactive CLI `doctor --json` (stderr not a TTY; no `--budget-ms`, `--tier`, `--fix`, `--remediate` or `--remediation-plan`) caps its check run at `doctor.default_budget_ms` (file plane, default 90000, 0 off), started by `startDeferredDeadline` when the registry starts (connect and migrations are outside it), with one stderr line; the report then carries the tier fields. `capacity-memo.ts` `doctorCapacityForecast`: one forecast per run (shared by `persistence_capacity` and `persistence_request_growth`) read under the run's overall deadline and dropped from the memo on a deadline failure, which makes the waiting check unknown instead of a counter-only verdict. `persistence_session_timeouts` reads `SHOW statement_timeout` outside the entry deadline. Tests: `test/doctor-tier-6696.test.ts`, `test/doctor-day-zero.test.ts` (`--tier ops`), `test/e2e/doctor-ops-tier-postgres.test.ts`, `test/doctor-entry-deadline-6803.test.ts` (plus `test/e2e/doctor-entry-deadline-postgres.test.ts`, in the PgBouncer matrix), `test/doctor-default-budget-6803.test.ts`; bench `scripts/bench/doctor-scale.ts`.
-- `src/commands/doctor/last-known.ts` — the quick tier's last known results (#7142). `--tier quick` (budget.ts: `QUICK_BUDGET_MS_DEFAULT` 10000, connect included; `entryRunsAt` orders ops ⊂ quick ⊂ standard ⊂ deep; `cheapTier` gives it the ops tier's round-trip connection check and counter-mode embedding state) runs the ops entries plus the entries tagged `tier: 'quick'` (schema version, the stub-guard entry with `sync_failures`, queue health, partial embeddings). `lastKnownMode` turns the store on only for a brain-wide local CLI run (`buildChecks(..., { lastKnown: 'cli' })` from `runDoctor`) or the refresh job, never under `--only`, `--source`, a remote scope, `--fix` or `--tier ops`. `runDoctorRegistry` records each entry's outcome (`done`, `expired` when it ran out of budget or emitted a budget unknown, `not_run` when the tier skipped a standard entry); `withLastKnown` writes the finished entries of a standard or deep run to `op_checkpoints` (op `doctor-last-known`, fingerprint = entry name, `completed_keys[0]` = `{ checks, measured_at, elapsed_ms }`, one bounded statement, best-effort) and `applyLastKnown` replaces an unfinished entry's checks with its last known ones when they are at most `LAST_KNOWN_MAX_AGE_MS` (24 h) old: same status, message prefixed `Last known, N ago (...)`, `details.last_known` `{ measured_at, age_ms, reason: not_in_tier | budget }`. The rest are named in one `doctor_last_known` warning (`details.health: 'unknown'`, `unknown_checks`), which `tierFields` expands into `unknown_sections`; served checks go to `last_known_sections` and make the report incomplete. An entry with no result younger than `REFRESH_AFTER_MS` (1 h) queues one `doctor-refresh` job on Postgres (idempotency key per hour, `maxWaiting: 1`); the handler (`runDoctorRefresh`, registered in `commands/jobs.ts`) runs `doctorRefreshRegistry()` (the connection lane plus every standard entry after the connection gate; filesystem entries are recorded only by CLI runs) with `REFRESH_ENTRY_BUDGET_MS` (600000) per entry and queues nothing itself. Tests: `test/doctor-quick-tier-7142.test.ts` (+ `test/e2e/doctor-quick-tier-7142-postgres.test.ts`).
+- `src/commands/doctor/last-known.ts` — the quick tier's last known results (#7142). `--tier quick` (budget.ts: `QUICK_BUDGET_MS_DEFAULT` 10000, connect included; `entryRunsAt` orders ops ⊂ quick ⊂ standard ⊂ deep; `cheapTier` gives it the ops tier's round-trip connection check and counter-mode embedding state) runs the ops entries plus the entries tagged `tier: 'quick'` (schema version, the stub-guard entry with `sync_failures`, queue health, partial embeddings). `lastKnownMode` turns the store on only for a brain-wide local CLI run (`buildChecks(..., { lastKnown: 'cli' })` from `runDoctor`) or the refresh job, never under `--only`, `--source`, a remote scope, `--fix` or `--tier ops`. `runDoctorRegistry` records each entry's outcome (`done`, `expired` when it ran out of budget or emitted a budget unknown, `not_run` when the tier skipped a standard entry); `withLastKnown` writes the finished entries of a standard or deep run to `op_checkpoints` (op `doctor-last-known`, fingerprint = entry name, `completed_keys[0]` = `{ checks, measured_at, elapsed_ms }`, one bounded statement, best-effort) and `applyLastKnown` replaces an unfinished entry's checks with its last known ones when they are at most `LAST_KNOWN_MAX_AGE_MS` (24 h) old: same status, message prefixed `Last known, N ago (...)`, `details.last_known` `{ measured_at, age_ms, reason: not_in_tier | budget }`. The rest are named in one `doctor_last_known` warning (`details.health: 'unknown'`, `unknown_checks`), which `tierFields` expands into `unknown_sections`; served checks go to `last_known_sections` and make the report incomplete. An entry with no result younger than `REFRESH_AFTER_MS` (1 h) queues one `doctor-refresh` job on Postgres (idempotency key per hour, `maxWaiting: 1`, priority 10 so sync, the autopilot cycles, global maintenance, embed backfill and loops extract claim first, `timeout_ms` 15 min; none when DB config `doctor.background_refresh` is `false`, #7263); the handler (`runDoctorRefresh`, registered in `commands/jobs.ts`) runs `doctorRefreshRegistry()` (the connection lane plus every standard entry after the connection gate; filesystem entries are recorded only by CLI runs) with `REFRESH_ENTRY_BUDGET_MS` (600000) per entry inside the overall `REFRESH_BUDGET_MS` (10 min, passed as `--budget-ms`: past it no entry starts and the running one is cut, so the job completes with what it measured and the rest waits for the next slot) and queues nothing itself. `doctor-refresh` is in `DEFAULT_LONG_JOB_NAMES` (`minions/lanes.ts`). Tests: `test/doctor-refresh-7263.test.ts`. Tests: `test/doctor-quick-tier-7142.test.ts` (+ `test/e2e/doctor-quick-tier-7142-postgres.test.ts`).
- `src/commands/doctor/brain-health-bands.ts` + `remote-tier.ts` + `ops-snapshot.ts`, `src/core/doctor-remote-tier.ts`, `src/core/persistence/capacity-view.ts` — the ops tier for agents and remote clients (#6696 B2). `readCapacityView` (for `/admin/api/ops`) reads the counter rows, `capacityDiagnostics`, the light `readCapacityForecast` (null when unreadable: days unknown) and `readLastCompaction`; the bands read `cachedCapacitySnapshot`; `capacityVerify()` is the verify of every capacity fix (`gbrain doctor --only persistence_capacity --json` plus MCP `get_brain_health`). `readBrainHealthBands` backs the read-scope `get_brain_health` op: capacity band and days band, write failures and active blockers as count bands for the caller's readable sources, no slugs or exact counters, cached 60 s per engine and scope. `runRemoteDoctorTier` backs `run_doctor`'s `tier: "ops"` / `only` (admin). `runScopedRemoteDoctor` is the thin client's `gbrain doctor --tier ops` / `--only <registry check>`: it reads `tools/list` and uses `run_doctor` with the parameters, else the bands (`BAND_CHECKS`), else refuses `doctor_tier_unavailable`; it never runs the full remote report in their place. `cachedOpsSnapshot` serves `/admin/api/ops` from one ops run a minute. Tests: `test/doctor-ops-remote-6696.test.ts`.
- `src/commands/doctor/checks/rename-identity-downgrades.ts` — `rename_identity_downgrades` (#6729): warn while a downgraded rename record is open (`sync-identity-downgrades.ts`), naming up to 5 pairs with their facts and links; fix = the first pair's `gbrain repair rename-identity` apply (destructive, `ask_user`, `preview_argv`, `plan_hash`; `--close` on a managed brain), so unbound classic Postgres pairs get an actionable fix too; `gbrain restore <old-slug> --source-id <id> --force` is named as the alternative in its text only where `restore_available !== false`, and `restore_unavailable_sources` lists the rest.
diff --git a/src/commands/doctor/last-known.ts b/src/commands/doctor/last-known.ts
index dba9c9bd6b..7d9b556aa2 100644
--- a/src/commands/doctor/last-known.ts
+++ b/src/commands/doctor/last-known.ts
@@ -28,7 +28,16 @@ export const REFRESH_AFTER_MS = 60 * 60_000;
/** The background refresh job and its per-check budget (the time a slow check needs on a large brain, not 15 s). */
export const REFRESH_JOB = 'doctor-refresh';
export const REFRESH_ENTRY_BUDGET_MS = 600_000;
-const REFRESH_TIMEOUT_MS = 2 * 60 * 60_000;
+/**
+ * #7263: the whole refresh's budget, well under its hourly slot. Past it no further check starts (the one running is cut
+ * at it), what finished is recorded and the rest stays unknown for the next slot; the job still completes.
+ */
+export const REFRESH_BUDGET_MS = 10 * 60_000;
+const REFRESH_TIMEOUT_MS = 15 * 60_000;
+/** #7263: behind sync (-10, 0, continuations 5), the autopilot cycles and global maintenance (0), embed backfill and loops extract (5). */
+const REFRESH_PRIORITY = 10;
+/** #7263: `false` turns the background refresh off (DB plane; default on). */
+export const BACKGROUND_REFRESH_KEY = 'doctor.background_refresh';
/** Bound of the cache read and write (they run outside every entry's deadline). */
const IO_BOUND_MS = 3_000;
@@ -131,12 +140,13 @@ export function unmeasuredCheck(stale: readonly EntryOutcome[], cache: ReadonlyM
};
}
-/** Queue one background refresh (deduplicated per hour); null when it cannot be queued. */
+/** Queue one background refresh (deduplicated per hour); null when it cannot be queued or `doctor.background_refresh` is false. */
export async function queueRefresh(engine: BrainEngine, now = Date.now()): Promise<{ id: number } | null> {
try {
+ if ((await bounded(engine.getConfig(BACKGROUND_REFRESH_KEY)))?.trim().toLowerCase() === 'false') return null;
const { MinionQueue } = await import('../../core/minions/queue.ts');
const slot = new Date(now).toISOString().slice(0, 13);
- const job = await bounded(new MinionQueue(engine).add(REFRESH_JOB, {}, { queue: 'default', idempotency_key: `${REFRESH_JOB}:${slot}`, max_attempts: 1, timeout_ms: REFRESH_TIMEOUT_MS, maxWaiting: 1 }));
+ const job = await bounded(new MinionQueue(engine).add(REFRESH_JOB, {}, { queue: 'default', idempotency_key: `${REFRESH_JOB}:${slot}`, max_attempts: 1, timeout_ms: REFRESH_TIMEOUT_MS, priority: REFRESH_PRIORITY, maxWaiting: 1 }));
return { id: Number(job.id) };
} catch {
return null;
@@ -150,13 +160,13 @@ export function lastKnownMode(ctx: Pick<DoctorContext, 'only' | 'sourceIds' | 'o
}
/**
- * The `doctor-refresh` job: every standard-tier database check, each with REFRESH_ENTRY_BUDGET_MS, recorded as last
- * known results. Read-only apart from that record; it never queues another refresh.
+ * The `doctor-refresh` job: every standard-tier database check, each with REFRESH_ENTRY_BUDGET_MS and all of them within
+ * `budgetMs`, recorded as last known results. Read-only apart from that record; it never queues another refresh.
*/
-export async function runDoctorRefresh(engine: BrainEngine): Promise<{ recorded: number; unfinished: string[]; elapsed_ms: number }> {
+export async function runDoctorRefresh(engine: BrainEngine, budgetMs = REFRESH_BUDGET_MS): Promise<{ recorded: number; unfinished: string[]; elapsed_ms: number }> {
const started = Date.now();
const { buildChecks } = await import('../doctor.ts');
- const checks = await buildChecks(engine, ['--json', '--tier', 'standard', '--scope=brain'], undefined, undefined, undefined, { lastKnown: 'refresh', entryBudgetOverrideMs: REFRESH_ENTRY_BUDGET_MS, refreshOnly: true });
+ const checks = await buildChecks(engine, ['--json', '--tier', 'standard', '--scope=brain', '--budget-ms', String(budgetMs)], undefined, undefined, undefined, { lastKnown: 'refresh', entryBudgetOverrideMs: REFRESH_ENTRY_BUDGET_MS, refreshOnly: true });
const unfinished = [...new Set(checks.filter(c => c.details?.health === 'unknown' && c.details.reason === 'budget').map(c => c.name))];
return { recorded: checks.length - unfinished.length, unfinished, elapsed_ms: Date.now() - started };
}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 83ed377eeb..ea10f65aad 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1058,7 +1058,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.341.0', text: 'Nothing derived from a private page is stored wider than the page. Facts extracted from a `visibility: private` page are private even when `facts.default_visibility` is world (before, a fact with no fence page was then returned to remote callers by recall and the entity card), and a page marked private only by `access: private|restricted|confidential` or `confidentiality: confidential|secret|private|restricted` counts as private for its facts, chronicle events, timeline rows and remember saves. `remember` without a `visibility` now saves private when its target page is private or `facts.default_visibility` is explicitly private; otherwise the default stays world. Google Calendar events marked private or confidential sync as `visibility: private` pages, and a connector re-render keeps a page\'s private label. Remote page reads honor the privacy aliases only after `gbrain config set visibility.honor_aliases true`.' },
{ since: '0.60.341.0', text: 'Doctor `derived_visibility` also reports pages that carry a privacy alias but no `visibility`, chronicle events of a private origin, and world facts held in or extracted from a private page (fact ids a remote caller can read today are listed). `gbrain repair visibility` previews all of them and, with `--apply` only, makes them private; nothing runs on upgrade.' },
// Minions usability PR 2 (#7242): the maintainer's Oct 20, 2026 ask to make minions more usable. `since` is stamped at the merge slot.
- { since: 'TBD', text: 'A `gbrain jobs work` worker running two or more jobs at once (the supervisor and autopilot default is 2) now keeps one slot free of long jobs: autopilot-cycle, autopilot-global-maintenance, embed-backfill, connector-sync and extract run in at most concurrency minus one slots, so short jobs such as facts-absorb no longer wait behind them. Long jobs can take longer to start when one is already running. `gbrain config set minions.short_job_reserved_slots 0` restores the old behavior; `minions.long_job_names` adds job names to the long set.' },
+ { since: 'TBD', text: 'A `gbrain jobs work` worker running two or more jobs at once (the supervisor and autopilot default is 2) now keeps one slot free of long jobs: autopilot-cycle, autopilot-global-maintenance, embed-backfill, connector-sync, extract and doctor-refresh run in at most concurrency minus one slots, so short jobs such as facts-absorb no longer wait behind them. Long jobs can take longer to start when one is already running. `gbrain config set minions.short_job_reserved_slots 0` restores the old behavior; `minions.long_job_names` adds job names to the long set.' },
+ // #7263 (a background doctor refresh held a one-job worker for up to 2 h).
+ { since: 'TBD', text: 'The background `doctor-refresh` job now queues behind sync, the autopilot cycles, global maintenance, embed backfill and loops extract (priority 10), and measures for at most 10 minutes: past that it starts no further check, records what it finished and completes, and the rest stays unknown until the next hourly refresh. Its timeout drops from 2 hours to 15 minutes. `gbrain config set doctor.background_refresh false` stops doctor from queueing it.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/config.ts b/src/core/config.ts
index 26e68e440f..b66cf6e105 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1799,7 +1799,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'shared_skills.inventory.max_files', 'shared_skills.inventory.max_total_bytes', 'shared_skills.inventory.max_file_bytes', 'shared_skills.inventory.max_entries', 'shared_skills.migration.enabled', // #6466: false declines the 0.53.0 migration (commands/migrations/opt-out.ts)
'persistence.write_wait_ms', // #5232: file plane, persistence/write-wait.ts
'migrate.graduation', // file plane, src/commands/migrate-graduation.ts (engine graduation opt-out)
- 'doctor.default_budget_ms', 'doctor.entry_budget_ms', 'doctor.orphan_ratio.full_scan_max_pages', // #6803: file plane (commands/doctor/default-budget.ts); DB plane (doctor/budget.ts, checks/orphan-estimate.ts)
+ 'doctor.default_budget_ms', 'doctor.entry_budget_ms', 'doctor.orphan_ratio.full_scan_max_pages', 'doctor.background_refresh', // #6803: file plane (commands/doctor/default-budget.ts); DB plane (doctor/budget.ts, checks/orphan-estimate.ts)
'consent.preapprove.paid.max_usd_per_run', 'consent.preapprove.persistent_install', // A4: file plane, core/consent.ts
// F4b: PGLite row-delta ANALYZE (src/core/planner-stats.ts); F4a: get_health memo TTL (src/core/health-memo.ts, 0 disables).
'planner.auto_analyze', 'planner.first_read_budget_ms', 'import.analyze_every_pages', 'health.cache_ttl_ms',
diff --git a/src/core/minions/lanes.ts b/src/core/minions/lanes.ts
index f6dd6efcb8..e8bcc6986d 100644
--- a/src/core/minions/lanes.ts
+++ b/src/core/minions/lanes.ts
@@ -10,12 +10,14 @@
* `excludeNames` to `MinionQueue.claim` once that budget is used.
*
* DEFAULT_LONG_JOB_NAMES holds only single-flight, brain-wide passes with a
- * 30-minute budget in handler-timeouts.ts:
+ * 30-minute budget in handler-timeouts.ts, plus doctor-refresh:
* - autopilot-cycle, autopilot-global-maintenance: the per-source and
* brain-wide maintenance passes that motivated the issue.
* - embed-backfill: a brain-wide embedding backfill.
* - connector-sync: a full account sync for a chat connector.
* - extract: a brain-wide `extract --stale` sweep or remediation pass.
+ * - doctor-refresh: the background measure of every standard doctor check
+ * (#7263; its own overall budget in commands/doctor/last-known.ts).
* Per-page jobs (facts-absorb, chronicle_extract, contextual_reindex_per_chunk)
* are deliberately absent: they arrive in large fan-outs, so limiting them to
* one slot would cut their throughput. subagent jobs are absent too: callers
@@ -30,6 +32,7 @@ export const DEFAULT_LONG_JOB_NAMES: readonly string[] = [
'embed-backfill',
'connector-sync',
'extract',
+ 'doctor-refresh',
];
export const DEFAULT_SHORT_JOB_RESERVED_SLOTS = 1;
diff --git a/test/doctor-refresh-7263.test.ts b/test/doctor-refresh-7263.test.ts
new file mode 100644
index 0000000000..2e392884d5
--- /dev/null
+++ b/test/doctor-refresh-7263.test.ts
@@ -0,0 +1,112 @@
+/**
+ * #7263: the background doctor-refresh job must not hold a one-slot worker. It queues behind sync, the autopilot
+ * cycles, global maintenance and loops extract (a numerically higher priority), stops starting checks at an overall
+ * budget well under its hourly slot and still completes, recording what it measured, and an operator can turn it off.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { MinionWorker } from '../src/core/minions/worker.ts';
+import { DEFAULT_LONG_JOB_NAMES } from '../src/core/minions/lanes.ts';
+import { LAST_KNOWN_OP, REFRESH_BUDGET_MS, REFRESH_JOB, queueRefresh, runDoctorRefresh } from '../src/commands/doctor/last-known.ts';
+import { waitFor } from './helpers/wait-for.ts';
+
+let engine: PGLiteEngine;
+let queue: MinionQueue;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ queue = new MinionQueue(engine);
+}, 60_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM minion_jobs');
+ await engine.executeRaw('DELETE FROM op_checkpoints WHERE op = $1', [LAST_KNOWN_OP]);
+ await engine.executeRaw("DELETE FROM config WHERE key = 'doctor.background_refresh'");
+});
+
+async function claimOrder(): Promise<number[]> {
+ const rows = await engine.executeRaw<{ id: number }>('SELECT id FROM minion_jobs WHERE started_at IS NOT NULL ORDER BY started_at, id');
+ return rows.map(r => Number(r.id));
+}
+
+/** An engine whose every SQL statement takes 100 ms, so each doctor entry is slow and the full refresh takes far longer than its budget. */
+function slowEngine(inner: PGLiteEngine): PGLiteEngine {
+ return new Proxy(inner, {
+ get(target, prop, receiver) {
+ const value = Reflect.get(target, prop, receiver);
+ if (typeof value !== 'function') return value;
+ if (prop === 'executeRaw' || prop === 'executeRawDirect') {
+ return async (...args: unknown[]) => { await new Promise(r => setTimeout(r, 100)); return value.apply(target, args); };
+ }
+ return value.bind(target);
+ },
+ });
+}
+
+describe('doctor-refresh on a one-slot worker (#7263)', () => {
+ test('a sync queued after a refresh is claimed first, and the refresh runs once the slot is free', async () => {
+ const refresh = await queueRefresh(engine);
+ expect(refresh).not.toBeNull();
+ const sync = await queue.add('sync', { sourceId: 'source-a' });
+ const worker = new MinionWorker(engine, { concurrency: 1, pollInterval: 20, healthCheckInterval: 0, stalledInterval: 60_000 });
+ worker.register(REFRESH_JOB, async () => ({ ok: true }));
+ worker.register('sync', async () => ({ ok: true }));
+ const running = worker.start();
+ try {
+ await waitFor(async () => (await queue.getJob(refresh!.id))?.status === 'completed', { timeoutMs: 10_000, label: 'refresh completed' });
+ } finally {
+ worker.stop();
+ await running;
+ }
+ expect(await claimOrder()).toEqual([sync.id, refresh!.id]);
+ }, 30_000);
+
+ test('the refresh queues behind sync, the autopilot cycles, global maintenance and loops extract, with a timeout over its budget', async () => {
+ const job = (await queue.getJob((await queueRefresh(engine))!.id))!;
+ expect(job.priority).toBeGreaterThan(5);
+ expect(job.timeout_ms).toBeGreaterThan(REFRESH_BUDGET_MS);
+ expect(job.timeout_ms).toBeLessThanOrEqual(30 * 60_000);
+ expect(REFRESH_BUDGET_MS).toBeLessThanOrEqual(10 * 60_000);
+ });
+
+ test('a two-slot worker treats the refresh as a long job', () => {
+ expect(DEFAULT_LONG_JOB_NAMES).toContain(REFRESH_JOB);
+ });
+
+ test('doctor.background_refresh false queues nothing', async () => {
+ await engine.setConfig('doctor.background_refresh', 'false');
+ expect(await queueRefresh(engine)).toBeNull();
+ expect(await engine.executeRaw('SELECT id FROM minion_jobs WHERE name = $1', [REFRESH_JOB])).toHaveLength(0);
+ });
+});
+
+describe('doctor-refresh overall budget (#7263)', () => {
+ test('a refresh whose entries are slow stops at its budget, records what it measured and completes', async () => {
+ const budgetMs = 3_000;
+ const job = await queue.add(REFRESH_JOB, {}, { queue: 'default', max_attempts: 1 });
+ const worker = new MinionWorker(engine, { concurrency: 1, pollInterval: 20, healthCheckInterval: 0, stalledInterval: 60_000 });
+ worker.register(REFRESH_JOB, async () => runDoctorRefresh(slowEngine(engine), budgetMs));
+ const running = worker.start();
+ try {
+ await waitFor(async () => ['completed', 'failed', 'dead'].includes((await queue.getJob(job.id))?.status ?? ''), { timeoutMs: 30_000, label: 'refresh settled' });
+ } finally {
+ worker.stop();
+ await running;
+ }
+ const done = (await queue.getJob(job.id))!;
+ expect(done.status).toBe('completed');
+ const result = done.result as { recorded: number; unfinished: string[]; elapsed_ms: number };
+ expect(result.unfinished.length).toBeGreaterThan(0);
+ expect(result.recorded).toBeGreaterThan(0);
+ expect(result.elapsed_ms).toBeLessThan(budgetMs + 5_000);
+ const [{ n }] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM op_checkpoints WHERE op = $1', [LAST_KNOWN_OP]);
+ expect(n).toBeGreaterThan(0);
+ }, 60_000);
+});
diff --git a/test/minions-lanes.test.ts b/test/minions-lanes.test.ts
index 6de40678eb..342abb8332 100644
--- a/test/minions-lanes.test.ts
+++ b/test/minions-lanes.test.ts
@@ -109,10 +109,12 @@ describe('resolveLanePolicy', () => {
});
describe('defaults', () => {
- test('every built-in long job has a 30-minute-or-longer handler budget', () => {
+ test('every built-in long job has a 30-minute-or-longer handler budget, except doctor-refresh with its own overall budget', () => {
for (const name of DEFAULT_LONG_JOB_NAMES) {
+ if (name === 'doctor-refresh') continue;
expect(HANDLER_DEFAULT_TIMEOUT_MS[name]).toBeGreaterThanOrEqual(30 * 60 * 1000);
}
+ expect(DEFAULT_LONG_JOB_NAMES).toContain('doctor-refresh');
expect(DEFAULT_LONG_JOB_NAMES).toContain('autopilot-cycle');
expect(DEFAULT_LONG_JOB_NAMES).toContain('autopilot-global-maintenance');
expect(DEFAULT_LONG_JOB_NAMES).not.toContain('facts-absorb');