Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(autopilot): compute the brain-health aggregate once per dispatch tick, bounded (#7236)

garrytan915551a5c57f
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.md
index 0887ef07a1..b17b85d282 100644
--- a/docs/architecture/key-files/commands-1.md
+++ b/docs/architecture/key-files/commands-1.md
@@ -23,6 +23,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers launchd/systemd/cron/container install and reload paths, the wrapper script with its env-file lane and exec guard, status and the self-upgrade channel. `runAutopilot` is a mode table (`AUTOPILOT_MODES`: --install, --uninstall, --status, --pause/--resume, --retry-global; first match wins) that otherwise lazily imports the daemon: `autopilot-daemon.ts` (`runAutopilotDaemon`: boot, lock, managed worker, shutdown and the tick loop over an explicit `AutopilotDaemonState`; steps `probeDatabaseOrReconnect`, `probeNoWorkerPeer`, `runInlineCycle`, `adaptiveInterval`), `autopilot-dispatch.ts` (`dispatchAutopilotTick`: freshness syncs, extract_atoms auto-drain, remediation plan, full-cycle fan-out or targeted submits; targeted submits go through `autopilotTargetedSteps` in `autopilot-remediation-policy.ts`, which drops manual-only steps) and `autopilot-probes.ts` (nightly quality and conversation-parser probes; the quality probe's `resolveNightlyProbeModelRoutesForDaemon` runs `refreshGatewayForJob`'s two gateway calls (inlined: importing `jobs.ts` would grant its flags to `autopilot` in the flag registry) and then reads the probe's model routes from the brain, only on a run past the 24h gate; both probes take their fixtures from `NIGHTLY_PROBE_FIXTURES`, the embedded assets, and the quality probe passes its cap source and `pricing.overrides` as `resolveBudgetPolicy`). No injectable single-tick function exists yet (TODOS: testable autopilot tick), so the wiring guards read these modules as source.
- `src/commands/autopilot-dispatch.ts` — one autopilot tick's submissions (`dispatchAutopilotTick`): freshness syncs, the extract_atoms auto-drain, the remediation plan, and full-cycle fan-out or targeted submits. After the brain-wide maintenance dispatch on the full-cycle branch it writes the stall verdict file (`recordGlobalMaintenanceStallStatus`, GBRA-130 C-6) that `autopilot --status` reads; a failed write is logged (`global_maintenance_verdict_failed` under `--json`) and leaves the previous verdict to expire. The auto-drain (`dispatchAutoDrain` → `submitAutoDrains`) runs on Postgres only, unless `autopilot.auto_drain.enabled` is `false`, and only when the active pack does not run extract_atoms in the routine cycle. It submits a bounded, protected `extract-atoms-drain` job per source with a backlog under a per-source UTC-day idempotency key, so a structural refusal costs at most one dead job per source per day. The daily cap (`autopilot.auto_drain.max_usd_per_day` / the per-attempt `cycle.extract_atoms.budget_usd` estimate) counts attempts, not jobs (`autoDrainUnitsToday`: a waiting job one, a retried job one per started attempt), and excludes a job whose only attempt dead-lettered with `structural_refusal:`. Checkout-backed and connector sources alternate for free slots, with the next kind persisted in `AUTO_DRAIN_NEXT_KIND_KEY` (`autopilot.auto_drain.next_kind`) across ticks and days; a source whose writer preflight would refuse (`atomDrainOwnerRefusal`) is skipped with a logged reason; connector sources need no `local_path` and submit no `repoPath`. Tests: `test/autopilot-auto-drain*.test.ts`, `test/e2e/autopilot-auto-drain-dispatch.test.ts`. #5028: the auto-drain no longer skips when the active pack declares extract_atoms (the daemon's per-source cycles run only SOURCE_FRESHNESS_PHASES, so the declaration never made the routine cycle drain it); extract_atoms runs stamp `sources.config.last_extract_atoms_at` (`stampExtractAtomsRun` in `src/core/cycle/extract-atoms-stamp.ts`, which also builds the doctor warning), and the `extract_atoms_backlog` doctor check's declared branch warns when a backlog source's stamp is missing or older than 48h even though cycles run. `autopilot.git_pull` (#6451, wave 15 P7.2): `automaticGitPullDisabled` in `core/persistence/automatic-sync-policy.ts` is read first by `automaticSyncPull`, so a non-truthy value queues every remote source's sync with `pull: false` before any persistence read; `dispatchFreshnessSyncs` prints one `git_pull: off` line (`git_pull_disabled` NDJSON event under `--json`) per tick while it is off. Pinned by `test/autopilot-git-pull-optout-6451.test.ts`. GBRA-133 PR 2a additions: [commit-notifier.md](commit-notifier.md#autopilot-and-the-jobs-worker).
+- `src/commands/autopilot-health.ts` — `readTickHealth` (#7236): one bounded health read per dispatch tick, shared with `adaptiveInterval`; a Postgres timeout logs `health_degraded` and returns null (no score). Tests: `test/autopilot-tick-health-7236.test.ts`.
- `src/commands/backup.ts` — trusted local `gbrain backup status|check`: status may reuse a recent warning; check forces a bounded remote readback sweep. Enabled missing/locked/degraded evidence does not return an all-clear. Quiet and disabled modes retain explicit zero-exit behavior. JSON separates configured repos from fresh verified recoverable repos and describes committed-file-only recovery. Remote MCP doctor never invokes this local Git path; see `docs/operations/backup-check.md` and `test/backup-cli.serial.test.ts`. `backup create|restore` failures render the agent-operator contract (`storage_error`, fix `gbrain doctor --json`) with the legacy `ok`/`reason`/`message`/`retryable` JSON keys; a message-less thrown value is described only by its bounded name/code/errno (`backupFailureMessage`), never `String(object)`.
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index e8d319d7d7..d3c09270d6 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -29,6 +29,7 @@ test/autopilot-pause-marker.test.ts pause marker fences minion job pickup 1 read
test/autopilot-self-upgrade.test.ts autopilot self-upgrade static-shape regressions 4 source-surface-helper
test/autopilot-shutdown-engine-close.test.ts autopilot.ts graceful engine shutdown (#1872) 6 source-surface-helper
test/autopilot-supervisor-wiring.test.ts autopilot.ts ↔ ChildWorkerSupervisor wiring 7 source-surface-helper
+test/autopilot-tick-health-7236.test.ts #7236 autopilot tick health read (${kind}) 5 source-surface-helper
test/backup-cli.serial.test.ts runBackupCli — PGLite lock fallback 3 readFileSync,source-surface-helper
test/backup-invalidation.serial.test.ts bootstrap repo — recordRepoInReceipt contract (source-text pin) 2 readFileSync
test/backup-private-path-text-5312.test.ts (file-level) 3 readFileSync
diff --git a/src/commands/autopilot-daemon.ts b/src/commands/autopilot-daemon.ts
index e431cedbc3..1b1e3d2a90 100644
--- a/src/commands/autopilot-daemon.ts
+++ b/src/commands/autopilot-daemon.ts
@@ -13,6 +13,8 @@ import { join } from 'path';
import { loadPreferences } from '../core/preferences.ts';
import { registerCleanup } from '../core/process-cleanup.ts';
import { dispatchAutopilotTick, sleepWatchingHeads } from './autopilot-dispatch.ts';
+import { readTickHealth } from './autopilot-health.ts';
+import type { BrainHealth } from '../core/types.ts';
import { writeAutopilotHeartbeat } from '../core/autopilot-heartbeat.ts';
import { runNightlyQualityProbeStep, runParserProbeStep } from './autopilot-probes.ts';
import { resolveChildCliInvocation } from '../core/minions/job-isolation.ts';
@@ -324,16 +326,16 @@ export async function runAutopilotDaemon(engine: BrainEngine, args: string[]): P
// (single SELECT). See the NO_WORKER_WARN_TICKS comment for caveats.
if (noWorker && useMinionsDispatch) await probeNoWorkerPeer(engine, state, baseInterval);
- const cycleOk = useMinionsDispatch
+ const tick = useMinionsDispatch
? await dispatchAutopilotTick(engine, state, { repoPath, baseInterval, jsonMode })
- : await runInlineCycle(engine, state, repoPath, shutdownAbort, jsonMode);
+ : { cycleOk: await runInlineCycle(engine, state, repoPath, shutdownAbort, jsonMode) };
if (configurationBlocked()) continue;
- // 4. Health check + adaptive interval (same for both paths)
- const interval = await adaptiveInterval(engine, baseInterval, cycleStart, jsonMode);
+ // 4. Adaptive interval; a dispatch tick hands over the health it routed on (#7236), the inline path reads it now.
+ const interval = await adaptiveInterval(engine, baseInterval, cycleStart, jsonMode, tick.health);
if (configurationBlocked()) continue;
- if (cycleOk) {
+ if (tick.cycleOk) {
state.consecutiveErrors = 0;
} else {
state.consecutiveErrors++;
@@ -652,18 +654,22 @@ async function runInlineCycle(
return cycleOk;
}
-/** 4. Health check + adaptive interval (same for both paths); returns the next interval in seconds. */
-async function adaptiveInterval(engine: BrainEngine, baseInterval: number, cycleStart: number, jsonMode: boolean): Promise<number> {
+/**
+ * 4. Adaptive interval; returns the next interval in seconds. Routes on `tickHealth` when the tick already read it
+ * (#7236), else reads it once; an unknown score (degraded read) keeps the base interval.
+ */
+export async function adaptiveInterval(engine: BrainEngine, baseInterval: number, cycleStart: number, jsonMode: boolean, tickHealth?: BrainHealth | null): Promise<number> {
let interval = baseInterval;
try {
- const health = await engine.getHealth();
- const score = (health as any).brain_score ?? 50;
- interval = score >= 90 ? baseInterval * 2
+ const health = tickHealth === undefined ? await readTickHealth(engine, jsonMode) : tickHealth;
+ const score = health?.brain_score ?? null;
+ interval = score === null ? baseInterval
+ : score >= 90 ? baseInterval * 2
: score < 70 ? Math.max(Math.floor(baseInterval / 2), 60)
: baseInterval;
const elapsed = ((Date.now() - cycleStart) / 1000).toFixed(0);
- const line = `[cycle] score=${score} elapsed=${elapsed}s next=${interval}s`;
+ const line = `[cycle] score=${score ?? 'unknown'} elapsed=${elapsed}s next=${interval}s`;
if (jsonMode) {
process.stderr.write(JSON.stringify({ event: 'cycle', brain_score: score, elapsed_s: Number(elapsed), next_s: interval }) + '\n');
} else {
diff --git a/src/commands/autopilot-dispatch.ts b/src/commands/autopilot-dispatch.ts
index abe2dd5254..8b918cd11f 100644
--- a/src/commands/autopilot-dispatch.ts
+++ b/src/commands/autopilot-dispatch.ts
@@ -5,6 +5,7 @@
* submits. Called by runAutopilotDaemon (src/commands/autopilot-daemon.ts).
*/
import type { BrainEngine } from '../core/engine.ts';
+import type { BrainHealth } from '../core/types.ts';
import type { MinionQueue } from '../core/minions/queue.ts';
import { loadAllSources, parseSourceConfig, sourceConfigHasRemoteUrl, sourceLocalPathSkipWarning, type SourceRow } from '../core/sources-load.ts';
import { isConnectorSourceKind } from '../core/persistence/connector-identity.ts';
@@ -22,17 +23,22 @@ import {
} from './autopilot-remediation-policy.ts';
import type { AutopilotDaemonState } from './autopilot-daemon.ts';
import { logError } from './autopilot.ts';
+import { readTickHealth } from './autopilot-health.ts';
import { readCheckoutHead } from '../core/checkout-head.ts';
import { SYNC_ON_COMMIT_KEY } from '../core/sync-config-keys.ts';
import { autopilotPaused } from '../core/autopilot-paths.ts';
-/** Returns cycleOk: false only when the dispatch itself threw. */
+/**
+ * cycleOk is false only when the dispatch itself threw. health is the snapshot the plan routed on (null: the bounded
+ * read timed out), for the daemon's adaptive interval (#7236); absent when the tick threw before reading it.
+ */
export async function dispatchAutopilotTick(
engine: BrainEngine,
state: AutopilotDaemonState,
{ repoPath, baseInterval, jsonMode }: { repoPath: string; baseInterval: number; jsonMode: boolean },
-): Promise<boolean> {
+): Promise<{ cycleOk: boolean; health?: BrainHealth | null }> {
let cycleOk = true;
+ let health: BrainHealth | null | undefined;
// v0.36+ brain-health-100 wave (T8): targeted-submit loop.
//
// Pre-fix: every tick submitted ONE autopilot-cycle job, full phase
@@ -68,7 +74,9 @@ export async function dispatchAutopilotTick(
await dispatchFreshnessSyncs(engine, queue, { baseInterval, slot, timeoutMs, jsonMode, freshnessHeads: state.freshnessHeads });
await dispatchAutoDrain(engine, queue, { timeoutMs, jsonMode });
- const { score, plan, estTotal } = await computeAutopilotPlan(engine, repoPath);
+ const autopilotPlan = await computeAutopilotPlan(engine, repoPath, jsonMode);
+ health = autopilotPlan.health;
+ const { score, plan, estTotal } = autopilotPlan;
// Track time since last full cycle for the 60-min floor.
const minutesSinceLastFull = (Date.now() - state.lastFullCycleAt) / 60000;
@@ -231,7 +239,7 @@ export async function dispatchAutopilotTick(
}
}
} catch (e) { logError('dispatch', e); cycleOk = false; }
- return cycleOk;
+ return { cycleOk, health };
}
const connectorNoticePrinted = new Set<string>();
@@ -702,11 +710,11 @@ export async function submitAutoDrains(
if (next !== pointer) await engine.setConfig(AUTO_DRAIN_NEXT_KIND_KEY, next);
}
-/** The remediation plan autopilot routes on (brain score + doctor/onboard recommendations). */
-async function computeAutopilotPlan(engine: BrainEngine, repoPath: string) {
+/** The remediation plan autopilot routes on (brain score + doctor/onboard recommendations); score null when health is degraded. */
+async function computeAutopilotPlan(engine: BrainEngine, repoPath: string, jsonMode: boolean) {
const { computeRecommendations, embeddingProviderConfigured, HOSTED_EMBED_KEY_CONFIG, chatApiKeyConfigured } = await import('../core/brain-score-recommendations.ts');
- // Cheap path: engine.getHealth() is a single SQL count query.
- const health = await engine.getHealth();
+ const health = await readTickHealth(engine, jsonMode);
+ if (!health) return { health, score: null, plan: [], estTotal: 0 };
const score = health.brain_score;
// v0.40.x: recipe-aware embedding-provider check shared with doctor.ts.
// Resolve the configured model (gateway → DB fallback), then pre-await
@@ -766,5 +774,5 @@ async function computeAutopilotPlan(engine: BrainEngine, repoPath: string) {
}
const plan = computeRecommendations(health, ctx, extraRemediations).filter((r) => r.status === 'remediable');
const estTotal = plan.reduce((s, r) => s + r.est_seconds, 0);
- return { score, plan, estTotal };
+ return { health, score, plan, estTotal };
}
diff --git a/src/commands/autopilot-health.ts b/src/commands/autopilot-health.ts
new file mode 100644
index 0000000000..21029a97b4
--- /dev/null
+++ b/src/commands/autopilot-health.ts
@@ -0,0 +1,44 @@
+/**
+ * #7236: the brain-health read one autopilot tick routes on.
+ *
+ * `engine.getHealth()` aggregates every content_chunks row (its `chunk_pages`
+ * CTE has no row filter), so on a large brain each call is a full scan. A
+ * Minions-dispatch tick reads it once, in `computeAutopilotPlan`, and hands the
+ * same snapshot to the daemon's adaptive interval instead of reading it again;
+ * the dispatch tick only enqueues jobs, so the brain the interval would have
+ * graded is the one the plan just graded. The inline path still reads it after
+ * its cycle, once.
+ *
+ * On Postgres the read runs in one transaction with a transaction-local
+ * `statement_timeout` (it holds through a transaction-mode pooler, the same
+ * bound `persistence/bounded-reads.ts` relies on), so every statement in it
+ * ends on the server at AUTOPILOT_HEALTH_TIMEOUT_MS. A read the server ends
+ * there (57014, or 55P03 from a shorter session lock_timeout) is reported as
+ * degraded and returns null: the tick then knows no score, so it neither
+ * sleeps as healthy nor doubles its interval, and the timeout is not counted
+ * as a failed cycle. Any other error still throws. PGLite has one in-process
+ * connection and no other session to wait on, so its read is unbounded.
+ */
+import type { BrainEngine } from '../core/engine.ts';
+import type { BrainHealth } from '../core/types.ts';
+import { isStatementTimeout } from '../core/persistence/bounded-reads.ts';
+
+export const AUTOPILOT_HEALTH_TIMEOUT_MS = 120_000;
+
+/** The tick's health snapshot, or null when the bounded read timed out (degraded; logged here). */
+export async function readTickHealth(engine: BrainEngine, jsonMode: boolean, timeoutMs = AUTOPILOT_HEALTH_TIMEOUT_MS): Promise<BrainHealth | null> {
+ try {
+ if (engine.kind !== 'postgres') return await engine.getHealth();
+ return await engine.transaction(async (tx) => {
+ await tx.executeRaw(`SET LOCAL statement_timeout = ${Math.max(1, Math.floor(timeoutMs))}`);
+ return tx.getHealth();
+ });
+ } catch (error) {
+ if (!isStatementTimeout(error)) throw error;
+ const reason = `the brain health aggregate did not finish within ${timeoutMs} ms (SQLSTATE ${error.code})`;
+ process.stderr.write((jsonMode
+ ? JSON.stringify({ event: 'health_degraded', reason, sqlstate: error.code, timeout_ms: timeoutMs })
+ : `[health] degraded: ${reason}; brain score unknown this tick`) + '\n');
+ return null;
+ }
+}
diff --git a/src/commands/autopilot-remediation-policy.ts b/src/commands/autopilot-remediation-policy.ts
index 652cceabbf..816cef8e52 100644
--- a/src/commands/autopilot-remediation-policy.ts
+++ b/src/commands/autopilot-remediation-policy.ts
@@ -6,7 +6,8 @@ export { isManualOnlyStep };
export const AUTOPILOT_FULL_CYCLE_FLOOR_MINUTES = 60;
export interface AutopilotRemediationPlanShape {
- score: number;
+ /** null: the tick's health read was degraded (#7236), so the score is unknown. */
+ score: number | null;
planLength: number;
estimatedSeconds: number;
minutesSinceLastFull: number;
@@ -37,15 +38,17 @@ export function shouldRunAutopilotFullCycle({
return minutesSinceLastFull >= AUTOPILOT_FULL_CYCLE_FLOOR_MINUTES
|| planLength > 3
|| estimatedSeconds >= 300
- || score < 70;
+ || (score !== null && score < 70);
}
+/** An unknown (null) score never sleeps as healthy. */
export function shouldSleepHealthyAutopilot(
- score: number,
+ score: number | null,
planLength: number,
minutesSinceLastFull: number,
): boolean {
- return score >= 95
+ return score !== null
+ && score >= 95
&& planLength === 0
&& minutesSinceLastFull < AUTOPILOT_FULL_CYCLE_FLOOR_MINUTES;
}
diff --git a/test/autopilot-tick-health-7236.test.ts b/test/autopilot-tick-health-7236.test.ts
new file mode 100644
index 0000000000..8b8314c2bd
--- /dev/null
+++ b/test/autopilot-tick-health-7236.test.ts
@@ -0,0 +1,170 @@
+/**
+ * #7236: one autopilot dispatch tick computed the unfiltered content_chunks
+ * health aggregate twice: `computeAutopilotPlan` (autopilot-dispatch.ts) and
+ * the daemon's `adaptiveInterval` (autopilot-daemon.ts) each called
+ * `engine.getHealth()`, and on a large brain each call is a full scan.
+ *
+ * Protects: a Minions-dispatch tick (the dispatch, then the adaptive interval,
+ * exactly as the daemon loop runs them) reads health once and the interval
+ * routes on the plan's snapshot; the read is bounded on Postgres by a
+ * transaction-local statement_timeout, and a read the server ends there is
+ * reported as degraded: the tick is not a failed cycle, does not sleep as
+ * healthy and does not double its interval.
+ * Fails when: a tick issues a second health aggregate, the interval ignores
+ * the tick's snapshot, a timed-out health read throws out of the tick or
+ * grades the brain healthy, or the Postgres read waits past its bound.
+ * PGLite always; Postgres through test/e2e/autopilot-tick-health-7236-postgres.test.ts.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { dispatchAutopilotTick } from '../src/commands/autopilot-dispatch.ts';
+import { shouldRunAutopilotFullCycle, shouldSleepHealthyAutopilot } from '../src/commands/autopilot-remediation-policy.ts';
+import * as daemon from '../src/commands/autopilot-daemon.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { surfaceFileSource } from './helpers/source-surface.ts';
+
+type Interval = (engine: BrainEngine, baseInterval: number, cycleStart: number, jsonMode: boolean, health?: unknown) => Promise<number>;
+const adaptiveInterval = (daemon as unknown as { adaptiveInterval: Interval }).adaptiveInterval;
+
+/** Captures stderr and stdout lines while `run` executes. */
+async function captured<T>(run: () => Promise<T>): Promise<{ value: T; lines: string[] }> {
+ const lines: string[] = [];
+ const write = process.stderr.write.bind(process.stderr);
+ const log = console.log;
+ (process.stderr as { write: unknown }).write = (chunk: unknown) => { lines.push(String(chunk)); return true; };
+ console.log = (...args: unknown[]) => { lines.push(args.map(String).join(' ')); };
+ try { return { value: await run(), lines }; } finally { (process.stderr as { write: unknown }).write = write; console.log = log; }
+}
+
+/** Counts every getHealth call on `engine` and on transaction engines derived from it (they inherit the own property). */
+function countHealthReads(engine: BrainEngine, fail?: () => Error): { reads: () => number; restore: () => void } {
+ let reads = 0;
+ const real = Object.getPrototypeOf(engine).getHealth as BrainEngine['getHealth'];
+ Object.defineProperty(engine, 'getHealth', {
+ configurable: true,
+ value: function (this: BrainEngine, ...args: Parameters<BrainEngine['getHealth']>) {
+ reads++;
+ if (fail) return Promise.reject(fail());
+ return real.apply(this, args);
+ },
+ });
+ return { reads: () => reads, restore: () => { delete (engine as unknown as Record<string, unknown>).getHealth; } };
+}
+
+/** One Minions-dispatch tick as the daemon loop runs it: the dispatch, then the adaptive interval on its result. */
+async function oneTick(engine: BrainEngine, baseInterval = 300) {
+ const state = { lastFullCycleAt: Date.now(), freshnessHeads: new Map<string, string>() } as never;
+ return captured(async () => {
+ const tick = await dispatchAutopilotTick(engine, state, { repoPath: '', baseInterval, jsonMode: true }) as unknown as { cycleOk: boolean; health?: unknown };
+ const interval = await adaptiveInterval(engine, baseInterval, Date.now(), true, tick.health);
+ return { tick, interval };
+ });
+}
+
+const statementTimeout = () => Object.assign(new Error('canceling statement due to statement timeout'), { code: '57014' });
+
+describe('#7236 routing on an unknown score', () => {
+ test('a degraded (null) score never sleeps as healthy and does not force the full cycle before the floor', () => {
+ expect(shouldSleepHealthyAutopilot(null, 0, 10)).toBe(false);
+ expect(shouldRunAutopilotFullCycle({ score: null, planLength: 0, estimatedSeconds: 0, minutesSinceLastFull: 10 })).toBe(false);
+ expect(shouldRunAutopilotFullCycle({ score: null, planLength: 0, estimatedSeconds: 0, minutesSinceLastFull: 60 })).toBe(true);
+ });
+});
+
+for (const kind of testBackends()) {
+ describe(`#7236 autopilot tick health read (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ let home: string;
+ beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-tick-health-'));
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else {
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ close = () => engine.disconnect();
+ }
+ await engine.putPage('notes/alpha-example', { type: 'note', title: 'Alpha example', compiled_truth: 'Alpha example body.' });
+ }, 120_000);
+ afterAll(async () => { await close?.(); rmSync(home, { recursive: true, force: true }); });
+
+ test('one dispatch tick computes the health aggregate once and the interval routes on that snapshot', async () => {
+ await withEnv({ GBRAIN_HOME: home, HOME: home }, async () => {
+ const spy = countHealthReads(engine);
+ try {
+ const { value, lines } = await oneTick(engine);
+ expect(spy.reads()).toBe(1);
+ expect(value.tick.cycleOk).toBe(true);
+ const cycle = lines.map(l => { try { return JSON.parse(l); } catch { return null; } }).find(e => e?.event === 'cycle');
+ expect(typeof cycle?.brain_score).toBe('number');
+ expect(cycle.brain_score).toBe((value.tick.health as { brain_score: number }).brain_score);
+ } finally { spy.restore(); }
+ });
+ }, 120_000);
+
+ test('a timed-out health aggregate reports degraded: no failed cycle, no healthy sleep, no doubled interval, still one read', async () => {
+ await withEnv({ GBRAIN_HOME: home, HOME: home }, async () => {
+ const spy = countHealthReads(engine, statementTimeout);
+ try {
+ const { value, lines } = await oneTick(engine, 300);
+ expect(spy.reads()).toBe(1);
+ const events = lines.map(l => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
+ expect(events.filter(e => e.event === 'health_degraded').map(e => e.sqlstate)).toEqual(['57014']);
+ expect(value.tick.cycleOk).toBe(true);
+ expect(value.tick.health).toBeNull();
+ expect(value.interval).toBe(300);
+ expect(events.some(e => e.event === 'skip_healthy')).toBe(false);
+ expect(events.find(e => e.event === 'cycle')?.brain_score).toBeNull();
+ } finally { spy.restore(); }
+ });
+ }, 120_000);
+
+ test('a health read error other than a timeout still fails the cycle', async () => {
+ await withEnv({ GBRAIN_HOME: home, HOME: home }, async () => {
+ const spy = countHealthReads(engine, () => Object.assign(new Error('relation does not exist'), { code: '42P01' }));
+ try {
+ const { value } = await oneTick(engine, 300);
+ expect(value.tick.cycleOk).toBe(false);
+ } finally { spy.restore(); }
+ });
+ }, 120_000);
+
+ if (kind === 'postgres') {
+ test('the Postgres health read ends on the server at its bound and reports degraded', async () => {
+ const { readTickHealth } = await import('../src/commands/autopilot-health.ts');
+ let release!: () => void;
+ const held = new Promise<void>(resolve => { release = resolve; });
+ let locked!: () => void;
+ const isLocked = new Promise<void>(resolve => { locked = resolve; });
+ const holder = engine.transaction(async (tx) => {
+ await tx.executeRaw('LOCK TABLE content_chunks IN ACCESS EXCLUSIVE MODE');
+ locked();
+ await held;
+ });
+ try {
+ await isLocked;
+ const startedAt = Date.now();
+ const { value, lines } = await captured(() => readTickHealth(engine, true, 300));
+ const elapsed = Date.now() - startedAt;
+ expect(value).toBeNull();
+ expect(elapsed).toBeLessThan(10_000);
+ const degraded = lines.map(l => { try { return JSON.parse(l); } catch { return null; } }).find(e => e?.event === 'health_degraded');
+ expect(['57014', '55P03']).toContain(degraded?.sqlstate);
+ expect(degraded?.timeout_ms).toBe(300);
+ } finally { release(); await holder; }
+ const fresh = await readTickHealth(engine, true, 30_000);
+ expect(fresh?.page_count).toBe(1);
+ }, 120_000);
+ }
+
+ test('the daemon loop hands the dispatch tick\'s health to the adaptive interval', () => {
+ const src = surfaceFileSource('autopilot', 'src/commands/autopilot-daemon.ts');
+ expect(src.includes('adaptiveInterval(engine, baseInterval, cycleStart, jsonMode, tick.health)')).toBe(true);
+ });
+ });
+}
diff --git a/test/e2e/autopilot-tick-health-7236-postgres.test.ts b/test/e2e/autopilot-tick-health-7236-postgres.test.ts
new file mode 100644
index 0000000000..f81ecce6d5
--- /dev/null
+++ b/test/e2e/autopilot-tick-health-7236-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../autopilot-tick-health-7236.test.ts'));