Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test: #6803 lane C deadline, capacity, default-budget and sync --status tests
garrytanfe9e55dec2bb
diff --git a/test/capacity-bounded-read-6803.test.ts b/test/capacity-bounded-read-6803.test.tsnew file mode 100644index 0000000000..4094f253c3--- /dev/null+++ b/test/capacity-bounded-read-6803.test.ts@@ -0,0 +1,121 @@+/**+ * #6803 C4: capacity reads with caller-bounded waits and an honest cache (both backends).+ *+ * - A status read or receipt that waits past its deadline gets `unknown› for that call only, while the+ * /metrics reader on the same shared fetch still gets the snapshot, and the cache stays good.+ * - A fetch that timed out (a cancelled statement) is never cached: the next caller fetches again.+ * - A pause that continues across a caller timeout or a timed-out fetch emits no false clear and no+ * second pause notice.+ */+import { afterAll, beforeAll, beforeEach, 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 { __resetCapacityNoticesForTests, cachedCapacitySnapshot, CAPACITY_SNAPSHOT_TTL_MS, capacityNotices,+ capacitySnapshotWithin } from '../src/core/persistence/capacity-snapshot.ts';+import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';+import { freshBrainFactory, requestFixture } from './helpers/persistence-request-fixture.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const databaseUrl = process.env.DATABASE_URL;+const setIds = (engine: BrainEngine, used: number) => engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ await tx.executeRaw("UPDATE persistence_counters SET lifetime_ids=$1 WHERE key LIKE 'principal:%'", [used]);+});+const codes = (notices: Array<{ code: string }>) => notices.map(n => n.code);++/** The engine with the snapshot's counter read delayed by `delayMs›, or failing once as a cancelled statement. */+function controlled(engine: BrainEngine) {+ const state = { delayMs: 0, cancelNext: false, fetches: 0 };+ const proxy = new Proxy(engine, {+ get(target, key) {+ if (key === 'executeRaw') {+ return async (sql: string, params?: unknown[], opts?: unknown) => {+ if (/FROM persistence_counters/.test(sql)) {+ state.fetches++;+ if (state.cancelNext) {+ state.cancelNext = false;+ throw Object.assign(new Error('canceling statement due to statement timeout'), { code: '57014' });+ }+ if (state.delayMs) await new Promise(r => setTimeout(r, state.delayMs));+ }+ return target.executeRaw(sql, params, opts as never);+ };+ }+ const value = Reflect.get(target, key, target);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ }) as BrainEngine;+ return { engine: proxy, state };+}++for (const kind of testBackends()) {+ describe(`#6803 bounded capacity reads (${kind})`, () => {+ let factory: Awaited<ReturnType<typeof freshBrainFactory>>;+ let scratch: string;+ beforeAll(async () => {+ scratch = mkdtempSync(join(tmpdir(), 'gbrain-6803-capacity-'));+ factory = await freshBrainFactory(kind, databaseUrl);+ }, 120_000);+ afterAll(async () => {+ await factory?.dispose();+ if (scratch) rmSync(scratch, { recursive: true, force: true });+ });+ beforeEach(() => __resetCapacityNoticesForTests());+ const check = (name: string, fn: (engine: BrainEngine) => Promise<void>) => test(name, async () => {+ const engine = await factory.fresh();+ await withEnv({ GBRAIN_HOME: scratch, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, () => fn(engine));+ }, 120_000);++ check('a read that waits past its deadline is unknown for that call only; /metrics gets the snapshot and the cache stays good', async engine => {+ await requestFixture(engine).then(r => r.admit('one'));+ await engine.setConfig('persistence.limits.principal_lifetime_ids', '1000');+ await setIds(engine, 900);+ const { engine: slow, state } = controlled(engine);+ state.delayMs = 800;+ const t0 = 4_000_000_000_000;+ const metrics = cachedCapacitySnapshot(slow, t0);+ const started = Date.now();+ const receipt = await capacitySnapshotWithin(slow, Date.now() + 100, t0 + 1);+ expect(receipt.status).toBe('unknown');+ expect(Date.now() - started).toBeLessThan(700);+ expect(await capacityNotices(slow, { throttle: true, now: t0 + 1, deadlineAt: Date.now() + 50 })).toEqual([]);+ const shared = await metrics;+ expect(shared.status).toBe('ok');+ expect(shared.low.map(row => row.resource)).toEqual(['lifetime_ids']);+ state.delayMs = 0;+ expect(await capacitySnapshotWithin(slow, Date.now() + 100, t0 + 2)).toBe(shared);+ expect(codes(await capacityNotices(slow, { throttle: true, now: t0 + 2, deadlineAt: Date.now() + 100 }))).toContain('write_capacity_low');+ expect(state.fetches).toBe(1);+ });++ check('a fetch that timed out is not cached: the next caller fetches again', async engine => {+ await requestFixture(engine).then(r => r.admit('one'));+ const { engine: flaky, state } = controlled(engine);+ const t0 = 4_100_000_000_000;+ state.cancelNext = true;+ expect((await cachedCapacitySnapshot(flaky, t0)).status).toBe('unknown');+ expect((await cachedCapacitySnapshot(flaky, t0 + 1)).status).toBe('ok');+ expect(state.fetches).toBe(2);+ });++ check('a pause that continues across a caller timeout or a timed-out fetch is neither cleared nor announced again', async engine => {+ await requestFixture(engine).then(r => r.admit('one'));+ await engine.setConfig('persistence.limits.principal_lifetime_ids', '1000');+ await engine.setConfig('persistence.capacity.warn_days', '0'); await engine.setConfig('persistence.capacity.fail_days', '0');+ await setIds(engine, 820);+ const { engine: slow, state } = controlled(engine);+ let now = 4_200_000_000_000;+ const step = () => (now += CAPACITY_SNAPSHOT_TTL_MS);+ expect(codes(await capacityNotices(slow, { throttle: false, now: step() }))).toEqual(['write_capacity_low', 'write_capacity_backpressure']);+ state.cancelNext = true;+ expect(await capacityNotices(slow, { throttle: false, now: step() })).toEqual([]);+ state.delayMs = 800;+ expect(await capacityNotices(slow, { throttle: false, now: step(), deadlineAt: Date.now() + 50 })).toEqual([]);+ state.delayMs = 0;+ expect(codes(await capacityNotices(slow, { throttle: false, now: step() }))).toEqual(['write_capacity_low']);+ });+ });+}diff --git a/test/doctor-default-budget-6803.test.ts b/test/doctor-default-budget-6803.test.tsnew file mode 100644index 0000000000..25a4777840--- /dev/null+++ b/test/doctor-default-budget-6803.test.ts@@ -0,0 +1,112 @@+/**+ * #6803 C5 (Decision 1): the non-interactive default budget of CLI `gbrain doctor --json›.+ *+ * - Applies only to plain CLI `--json› with stderr not a terminal; `--budget-ms›, `--tier›, `--fix›,+ * `--remediate› and `--remediation-plan› keep their own behavior.+ * - It starts with the check run (connect and migrations are not counted), and its stderr line prints then.+ * - `gbrain config set doctor.default_budget_ms 0› (file plane), read back through the pre-connect reader,+ * turns it off; `--budget-ms 0› turns it off for one run; `--tier ops› keeps its 4000 ms deadline.+ * - `doctor.entry_budget_ms› and `doctor.orphan_ratio.full_scan_max_pages› are accepted on the DB plane.+ * - Only the CLI doctor command applies it (MCP run_doctor and the remote paths never import it).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, relative } from 'node:path';+import { DEFAULT_BUDGET_MS, nonInteractiveDefaultBudget, readDefaultBudgetMs } from '../src/commands/doctor/default-budget.ts';+import { doctorRunSummary, parseBudgetMs, startDeferredDeadline, startDoctorDeadline } from '../src/commands/doctor/budget.ts';+import { KNOWN_CONFIG_KEYS, loadConfigFileOnly } from '../src/core/config.ts';+import { runCli } from './helpers/cli-spawn.ts';+import { withEnv } from './helpers/with-env.ts';++const NOTICE = '[gbrain doctor] non-interactive run';++describe('nonInteractiveDefaultBudget', () => {+ test('only plain --json with a non-terminal stderr gets the default', () => {+ expect(nonInteractiveDefaultBudget(['--json'], { stderrIsTty: false, configuredMs: DEFAULT_BUDGET_MS })).toBe(90_000);+ expect(nonInteractiveDefaultBudget(['--json', '--scope=brain', '--only', 'orphan_ratio'], { stderrIsTty: false, configuredMs: 5_000 })).toBe(5_000);+ expect(nonInteractiveDefaultBudget(['--json'], { stderrIsTty: true, configuredMs: DEFAULT_BUDGET_MS })).toBeNull();+ expect(nonInteractiveDefaultBudget([], { stderrIsTty: false, configuredMs: DEFAULT_BUDGET_MS })).toBeNull();+ for (const explicit of [['--budget-ms', '0'], ['--budget-ms=5000'], ['--tier', 'ops'], ['--tier=deep'], ['--fix'], ['--remediate'], ['--remediation-plan']]) {+ expect(nonInteractiveDefaultBudget(['--json', ...explicit], { stderrIsTty: false, configuredMs: DEFAULT_BUDGET_MS })).toBeNull();+ }+ expect(nonInteractiveDefaultBudget(['--json'], { stderrIsTty: false, configuredMs: 0 })).toBeNull();+ });++ test('the default starts with the check run, not before the connect', () => {+ const deadline = startDoctorDeadline(['--json'], 1_000);+ deadline.deferredBudgetMs = 5_000;+ expect(deadline.deadlineAt).toBeNull();+ expect(doctorRunSummary(['--json'], deadline)).toBeUndefined();+ startDeferredDeadline(deadline, 60_000);+ expect(deadline).toMatchObject({ startedAt: 60_000, budgetMs: 5_000, deadlineAt: 65_000, nonInteractiveDefault: true });+ expect(doctorRunSummary(['--json'], deadline)).toMatchObject({ tier: 'standard', budgetMs: 5_000 });+ });++ test('--budget-ms 0 is no overall budget for one run; a negative value is refused', () => {+ expect(parseBudgetMs(['--budget-ms', '0'], 'standard')).toBeNull();+ expect(startDoctorDeadline(['--budget-ms', '0'])).toMatchObject({ deadlineAt: null, explicit: true });+ expect(() => parseBudgetMs(['--budget-ms', '-5'], 'standard')).toThrow(/whole number of milliseconds/);+ });++ test('the doctor budget keys are known config keys', () => {+ for (const key of ['doctor.default_budget_ms', 'doctor.entry_budget_ms', 'doctor.orphan_ratio.full_scan_max_pages']) expect(KNOWN_CONFIG_KEYS).toContain(key);+ });++ test('only the CLI doctor command applies the default (MCP run_doctor and remote paths never import it)', () => {+ const root = join(import.meta.dir, '..', 'src');+ const files: string[] = [];+ const walk = (dir: string) => { for (const name of readdirSync(dir)) { const p = join(dir, name); if (statSync(p).isDirectory()) walk(p); else if (p.endsWith('.ts')) files.push(p); } };+ walk(root);+ const importers = files.filter((f) => /default-budget(\.ts)?['"]/.test(readFileSync(f, 'utf-8'))).map((f) => relative(root, f)).sort();+ expect(importers).toEqual(['cli/commands/doctor.ts', 'commands/config.ts']);+ });+});++describe('CLI doctor --json on PGLite (non-terminal stderr)', () => {+ let home: string;+ beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-6803-default-budget-'));+ const init = await runCli(['init', '--pglite', '--no-embedding', '--non-interactive'], { home, timeoutMs: 120_000 });+ expect(init.exitCode, init.stderr).toBe(0);+ }, 150_000);+ afterAll(() => rmSync(home, { recursive: true, force: true }));+ const doctor = async (extra: string[]) => {+ const run = await runCli(['doctor', '--json', '--scope=brain', ...extra], { home, timeoutMs: 120_000 });+ return { run, report: JSON.parse(run.stdout) as Record<string, unknown> };+ };++ test('a plain run is capped at 90000 ms and says so once on stderr', async () => {+ const { run, report } = await doctor([]);+ expect(run.stderr.split(NOTICE).length - 1).toBe(1);+ expect(run.stderr).toContain('90000 ms (doctor.default_budget_ms)');+ expect(run.stderr).toContain('--budget-ms 0');+ expect(report).toMatchObject({ tier: 'standard', budget_ms: 90_000 });+ expect(typeof report.complete).toBe('boolean');+ }, 150_000);++ test('--budget-ms 0 turns it off for one run; --tier ops keeps its 4000 ms deadline', async () => {+ const off = await doctor(['--budget-ms', '0']);+ expect(off.run.stderr).not.toContain(NOTICE);+ expect(off.report.budget_ms).toBeNull();+ const ops = await doctor(['--tier', 'ops']);+ expect(ops.run.stderr).not.toContain(NOTICE);+ expect(ops.report).toMatchObject({ tier: 'ops', budget_ms: 4_000 });+ }, 150_000);++ test('config set doctor.default_budget_ms 0 (file plane) turns it off, read back before connecting; unset restores it', async () => {+ const bad = await runCli(['config', 'set', 'doctor.default_budget_ms', '1.5'], { home });+ expect(bad.exitCode).not.toBe(0);+ const set = await runCli(['config', 'set', 'doctor.default_budget_ms', '0'], { home });+ expect(set.exitCode, set.stderr).toBe(0);+ await withEnv({ GBRAIN_HOME: home }, async () => { expect(readDefaultBudgetMs(loadConfigFileOnly())).toBe(0); });+ const { run, report } = await doctor([]);+ expect(run.stderr).not.toContain(NOTICE);+ expect(report.budget_ms).toBeUndefined();+ const unset = await runCli(['config', 'unset', 'doctor.default_budget_ms'], { home });+ expect(unset.exitCode, unset.stderr).toBe(0);+ await withEnv({ GBRAIN_HOME: home }, async () => { expect(readDefaultBudgetMs(loadConfigFileOnly())).toBe(DEFAULT_BUDGET_MS); });+ const entry = await runCli(['config', 'set', 'doctor.entry_budget_ms', '20000'], { home });+ expect(entry.exitCode, entry.stderr).toBe(0);+ }, 200_000);+});diff --git a/test/doctor-entry-deadline-6803.test.ts b/test/doctor-entry-deadline-6803.test.tsnew file mode 100644index 0000000000..9eec675c3c--- /dev/null+++ b/test/doctor-entry-deadline-6803.test.ts@@ -0,0 +1,269 @@+/**+ * #6803 C2/C3/C6: doctor reads that stay bounded (PGLite, and Postgres via testBackends;+ * test/e2e/doctor-entry-deadline-postgres.test.ts runs the Postgres arm, which the E2E backend+ * matrix runs again through transaction-mode PgBouncer).+ *+ * - The cheap incident checks (CHEAP_INCIDENT_CHECKS, keyed by check name) run before the first full scan.+ * - Under an overall deadline eaten by slow full scans, the cheap incident checks still report.+ * - Postgres: a two-statement entry over its 300 ms budget leaves no backend running 1 s later, its+ * post-expiry statement is refused, and a cancel the check caught still reports reason budget.+ * - Postgres: a locked config read does not outlive the run's deadline.+ * - Postgres: entry A running out of time mid-forecast never makes entry B report a counter-only ok, and+ * the run forecasts once.+ * - The frontmatter scan stops at its entry's deadline and reports what it read (partial), not unknown.+ * - --only X --budget-ms N gives X the whole N; the budget-unknown fix names --budget-ms above the time taken,+ * and running it completes the check (scaled down: 200 ms entry budget, 600 ms statements).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import postgres from '#postgres';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { buildChecks, type Check } from '../src/commands/doctor.ts';+import { CHEAP_INCIDENT_CHECKS, DOCTOR_CHECK_REGISTRY, runDoctorRegistry } from '../src/commands/doctor/registry.ts';+import { connectionGateEntry } from '../src/commands/doctor/checks/db-connection.ts';+import { frontmatterEntry } from '../src/commands/doctor/checks/content-quality.ts';+import { persistenceCapacityEntry } from '../src/commands/doctor/checks/ops-sections.ts';+import { startDoctorDeadline } from '../src/commands/doctor/budget.ts';+import type { DoctorContext, DoctorEntry } from '../src/commands/doctor/context.ts';+import { StatementDeadlineError, deadlineBoundEngine, withStatementDeadline } from '../src/core/statement-deadline.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const ENTRY_BUDGET = 'doctor.entry_budget_ms';+const noProgress = new Proxy({}, { get: () => () => undefined }) as DoctorContext['progress'];++function ctxFor(engine: BrainEngine, args: string[]): DoctorContext {+ return {+ engine, args, jsonOutput: true, fastMode: false, doFix: false, dryRun: false, scope: 'brain', orphanRatioSourceId: undefined,+ progress: noProgress, skillsDirResolution: { dir: null, source: 'none' }, skillsDir: null, autoFixReport: null, schemaVersion: 0,+ connectionFailed: false, only: null, tier: 'standard', deadline: startDoctorDeadline(args),+ };+}++/** The engine with executeRaw delayed for statements matching `slow›, and statements matching `count› counted. */+function instrumented(engine: BrainEngine, opts: { slow?: { match: RegExp; ms: number }; count?: RegExp } = {}): BrainEngine & { counted: number } {+ const state = { counted: 0 };+ return new Proxy(engine, {+ get(target, key) {+ if (key === 'counted') return state.counted;+ if (key === 'executeRaw') {+ return async (sql: string, params?: unknown[], o?: unknown) => {+ if (opts.count?.test(sql)) state.counted++;+ if (opts.slow?.match.test(sql)) await new Promise((r) => setTimeout(r, opts.slow!.ms));+ return target.executeRaw(sql, params, o as never);+ };+ }+ const value = Reflect.get(target, key, target);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ }) as BrainEngine & { counted: number };+}++const byName = (checks: Check[], name: string) => checks.find((c) => c.name === name);++/** A second connection holding ACCESS EXCLUSIVE on `table› for `holdMs›. */+async function lockTable(url: string, table: string, holdMs: number): Promise<{ release: () => Promise<void> }> {+ const locker = postgres(url, { max: 1, prepare: false });+ let locked!: () => void;+ const isLocked = new Promise<void>((resolve) => { locked = resolve; });+ const held = locker.begin(async (sql) => {+ await sql.unsafe(`LOCK TABLE ${table} IN ACCESS EXCLUSIVE MODE`);+ locked();+ await new Promise((r) => setTimeout(r, holdMs));+ });+ await isLocked;+ return { release: async () => { await held.catch(() => undefined); await locker.end(); } };+}++test('C2: every entry that emits a cheap incident check runs before the first full scan', () => {+ const gate = DOCTOR_CHECK_REGISTRY.indexOf(connectionGateEntry);+ const after = DOCTOR_CHECK_REGISTRY.slice(gate + 1);+ const cheap = (e: DoctorEntry) => e.emits.some((n) => CHEAP_INCIDENT_CHECKS.has(n));+ const firstScan = after.findIndex((e) => e.tier !== 'ops' && !cheap(e));+ expect(firstScan).toBeGreaterThan(0);+ expect(after.slice(firstScan).filter(cheap).map((e) => e.name)).toEqual([]);+ const emitted = new Set(DOCTOR_CHECK_REGISTRY.flatMap((e) => e.emits));+ expect([...CHEAP_INCIDENT_CHECKS].filter((n) => !emitted.has(n))).toEqual([]);+});++for (const kind of testBackends()) {+ describe(`#6803 doctor deadlines (${kind})`, () => {+ let engine: BrainEngine;+ let databaseUrl = '';+ let close: () => Promise<void> = async () => undefined;+ const scratch = mkdtempSync(join(tmpdir(), 'gbrain-6803-deadline-'));++ beforeAll(async () => {+ if (kind === 'pglite') {+ const pglite = new PGLiteEngine();+ await pglite.connect({});+ await pglite.initSchema();+ engine = pglite;+ close = () => pglite.disconnect();+ } else {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engine = pg.engine; databaseUrl = pg.databaseUrl; close = pg.close;+ }+ }, 120_000);+ afterAll(async () => {+ await close();+ rmSync(scratch, { recursive: true, force: true });+ });+ const withEntryBudget = async <T>(ms: number | null, run: () => Promise<T>): Promise<T> => {+ if (ms === null) await engine.executeRaw('DELETE FROM config WHERE key=$1', [ENTRY_BUDGET]);+ else await engine.setConfig(ENTRY_BUDGET, String(ms));+ try { return await run(); } finally { await engine.executeRaw('DELETE FROM config WHERE key=$1', [ENTRY_BUDGET]); }+ };++ test('under an overall deadline the slow full scans eat, the cheap incident checks still report', async () => {+ const slowScans = instrumented(engine, { slow: { match: /format_type|jsonb_typeof|pg_indexes|octet_length\(compiled_truth/i, ms: 3_000 } });+ const args = ['--json', '--scope=brain', '--budget-ms', '2500'];+ const checks = await buildChecks(slowScans, args, undefined, undefined, startDoctorDeadline(args));+ const lag = byName(checks, 'links_extraction_lag');+ expect(lag).toBeDefined();+ expect(lag!.details?.health, JSON.stringify(lag)).not.toBe('unknown');+ expect(byName(checks, 'persistence_capacity')?.details?.health).not.toBe('unknown');+ // The run did hit its deadline: some later check is unknown for the overall budget.+ expect(checks.some((c) => c.details?.reason === 'budget' && c.details?.limit === 'overall')).toBe(true);+ }, 60_000);++ test('--only X --budget-ms N gives X the whole N; the budget fix names a larger --budget-ms and running it completes the check', async () => {+ const slow = instrumented(engine, { slow: { match: /FROM persistence_counters/, ms: 600 } });+ await withEntryBudget(200, async () => {+ const capped = byName(await buildChecks(slow, ['--json', '--scope=brain', '--only', 'persistence_capacity']), 'persistence_capacity')!;+ expect(capped.details).toMatchObject({ health: 'unknown', reason: 'budget', limit: 'entry', budget_ms: 200 });+ const argv = capped.fix!.argv;+ const n = Number(argv[argv.indexOf('--budget-ms') + 1]);+ expect(argv.slice(0, 4)).toEqual(['gbrain', 'doctor', '--only', 'persistence_capacity']);+ expect(n).toBeGreaterThan(capped.elapsed_ms!);+ expect(capped.fix!.actor).toBe('agent');+ const rerunArgs = [...argv.slice(2), '--scope=brain'];+ const rerun = byName(await buildChecks(slow, rerunArgs, undefined, undefined, startDoctorDeadline(rerunArgs)), 'persistence_capacity')!;+ expect(rerun.details?.health, JSON.stringify(rerun)).not.toBe('unknown');+ expect(rerun.details?.reason).toBeUndefined();+ });+ }, 60_000);++ test('the frontmatter scan stops at its entry deadline and reports what it read', async () => {+ const root = join(scratch, 'fm-example');+ mkdirSync(root, { recursive: true });+ for (let i = 0; i < 20_000; i++) writeFileSync(join(root, `note-${i}.md`), `---\ntitle: Note ${i}\n---\n\nBody ${i}.\n`);+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2) ON CONFLICT (id) DO UPDATE SET local_path=EXCLUDED.local_path', ['fm-example', root]);+ try {+ await withEntryBudget(600, async () => {+ const started = Date.now();+ const checks = await runDoctorRegistry(ctxFor(engine, ['--json', '--scope=brain']), [connectionGateEntry, frontmatterEntry]);+ const fm = byName(checks, 'frontmatter_integrity')!;+ expect(fm.details?.health, JSON.stringify(fm)).not.toBe('unknown');+ expect(fm.message).toMatch(/partial|NOT SCANNED/i);+ expect(Date.now() - started).toBeLessThan(600 + 400);+ });+ } finally {+ await engine.executeRaw('DELETE FROM sources WHERE id=$1', ['fm-example']);+ }+ }, 120_000);++ if (kind === 'pglite') {+ test('PGLite: a statement after the deadline is refused before it runs; one already running finishes', async () => {+ const bound = deadlineBoundEngine(engine);+ const scope = { startedAt: Date.now(), deadlineAt: Date.now() + 50, expired: false };+ await withStatementDeadline(scope, async () => {+ expect(await bound.executeRaw('SELECT 1 AS one')).toEqual([{ one: 1 }]);+ await new Promise((r) => setTimeout(r, 80));+ await expect(bound.executeRaw('SELECT 1')).rejects.toBeInstanceOf(StatementDeadlineError);+ });+ expect(scope.expired).toBe(true);+ });+ return;+ }++ const activeMarked = async (marker: string) => (await engine.executeRaw<{ n: number }>(+ "SELECT count(*)::int AS n FROM pg_stat_activity WHERE pid <> pg_backend_pid() AND state <> 'idle' AND query LIKE '%' || $1 || '%'", [marker]))[0]!.n;++ test('Postgres: a two-statement entry over its 300 ms budget leaves no backend running and its second statement is refused', async () => {+ const seen: { caught?: unknown; second?: unknown; done?: boolean } = {};+ const entry: DoctorEntry = {+ name: 'two_statement_example', emits: ['two_statement_example'],+ run: async (ctx) => {+ try { await ctx.engine!.executeRaw("SELECT pg_sleep(5), 'gbrain-6803-' || 'two' AS marker /* gbrain-6803-two */"); } catch (error) { seen.caught = error; }+ try { await ctx.engine!.executeRaw('SELECT 1'); } catch (error) { seen.second = error; }+ seen.done = true;+ return [{ name: 'two_statement_example', status: 'ok', message: 'Looks clear (the check swallowed its own cancel).' }];+ },+ };+ await withEntryBudget(300, async () => {+ const started = Date.now();+ const checks = await runDoctorRegistry(ctxFor(engine, ['--json']), [connectionGateEntry, entry]);+ expect(Date.now() - started).toBeLessThan(1_500);+ expect(byName(checks, 'two_statement_example')!.details).toMatchObject({ health: 'unknown', reason: 'budget', limit: 'entry', budget_ms: 300 });+ await new Promise((r) => setTimeout(r, 1_000));+ expect(await activeMarked('gbrain-6803-two')).toBe(0);+ expect(seen.done).toBe(true);+ expect(String((seen.caught as Error)?.message)).toMatch(/statement timeout|canceling statement|abort/i);+ expect(seen.second).toBeInstanceOf(StatementDeadlineError);+ });+ }, 30_000);++ test('Postgres: a cancel the check catches still marks its scope expired, so the runner reports reason budget', async () => {+ const bound = deadlineBoundEngine(engine);+ const scope = { startedAt: Date.now(), deadlineAt: Date.now() + 300, expired: false };+ await withStatementDeadline(scope, async () => {+ await bound.executeRaw('SELECT pg_sleep(3)').catch(() => undefined);+ });+ expect(scope.expired).toBe(true);+ expect(Date.now() - scope.startedAt).toBeLessThan(1_500);+ }, 15_000);++ test('Postgres: a locked config read does not outlive the run deadline', async () => {+ const lock = await lockTable(databaseUrl, 'config', 6_000);+ try {+ const quick: DoctorEntry = { name: 'quick_example', emits: ['quick_example'], run: async () => [{ name: 'quick_example', status: 'ok', message: 'ok' }] };+ const started = Date.now();+ const checks = await runDoctorRegistry(ctxFor(engine, ['--json', '--budget-ms', '1500']), [connectionGateEntry, quick]);+ expect(Date.now() - started).toBeLessThan(2_500);+ expect(byName(checks, 'quick_example')).toBeDefined();+ await new Promise((r) => setTimeout(r, 1_000));+ const [{ n }] = await engine.executeRaw<{ n: number }>(+ "SELECT count(*)::int AS n FROM pg_stat_activity WHERE pid <> pg_backend_pid() AND wait_event_type = 'Lock' AND query LIKE 'SELECT value FROM config%'");+ expect(n).toBe(0);+ } finally {+ await lock.release();+ }+ }, 30_000);++ test('Postgres: entry A out of time mid-forecast never makes entry B report a counter-only ok, and the run forecasts once', async () => {+ const counting = instrumented(engine, { count: /FROM persistence_topology_changes/ });+ const lock = await lockTable(databaseUrl, 'persistence_requests', 1_500);+ try {+ const a = { ...persistenceCapacityEntry, name: 'capacity_a' };+ const b = { ...persistenceCapacityEntry, name: 'capacity_b' };+ const checks = await withEntryBudget(1_000, () => runDoctorRegistry(ctxFor(counting, ['--json']), [connectionGateEntry, a, b]));+ const [first, second] = checks.filter((c) => c.name === 'persistence_capacity');+ expect(first!.details).toMatchObject({ health: 'unknown', reason: 'budget' });+ for (const c of [first!, second!]) {+ const counterOnly = c.status === 'ok' && (c.details?.forecast as { health?: string } | undefined)?.health === 'unknown';+ expect(counterOnly, JSON.stringify(c)).toBe(false);+ }+ expect(second!.status === 'ok' ? (second!.details?.forecast as { rows?: unknown[] }).rows : second!.details?.health).toBeDefined();+ expect(counting.counted).toBe(1);+ } finally {+ await lock.release();+ }+ }, 30_000);++ test('Postgres: under an overall deadline that cancels the forecast, capacity is unknown (reason budget), never counter-only ok', async () => {+ const lock = await lockTable(databaseUrl, 'persistence_requests', 3_000);+ try {+ const args = ['--json', '--scope=brain', '--only', 'persistence_capacity', '--budget-ms', '1200'];+ const capacity = byName(await buildChecks(engine, args, undefined, undefined, startDoctorDeadline(args)), 'persistence_capacity')!;+ expect(capacity.status, JSON.stringify(capacity)).not.toBe('ok');+ expect(capacity.details).toMatchObject({ health: 'unknown', reason: 'budget' });+ } finally {+ await lock.release();+ }+ }, 30_000);+ });+}diff --git a/test/e2e/doctor-entry-deadline-postgres.test.ts b/test/e2e/doctor-entry-deadline-postgres.test.tsnew file mode 100644index 0000000000..f5591ee66e--- /dev/null+++ b/test/e2e/doctor-entry-deadline-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../doctor-entry-deadline-6803.test.ts'));diff --git a/test/sync-status-flag-6803.test.ts b/test/sync-status-flag-6803.test.tsnew file mode 100644index 0000000000..d92cc57bc8--- /dev/null+++ b/test/sync-status-flag-6803.test.ts@@ -0,0 +1,96 @@+/**+ * #6803 C1: `gbrain sync --status› is the status read, never a sync.+ *+ * Before, the strict flag validator accepted `--status› (sync's generated legal set is the union of its+ * modules' flags), nothing downstream read it, and `runSingleSourceSync› ran: a full sync under the+ * 3600 s watchdog that imported the source. Now one classifier (`syncOperatorVerb›) routes it to+ * `gbrain sync status› in the CLI preflight (no watchdog, no owner delegation) and in `runSyncInner›,+ * with one stderr hint. `--preview›, which no sync path reads, refuses `invalid_params›; `--dry-run› is+ * unchanged and still consumed by the direct parse and both owner delegation parsers.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+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';+import { parseSyncFlags } from '../src/commands/sync/args.ts';+import { syncOperatorVerb } from '../src/commands/sync/operator.ts';+import { parsePersistenceSyncArgs } from '../src/commands/sync-persistence-delegate.ts';+import { parseDelegatedSyncArgs } from '../src/commands/sync-delegate.ts';+import { runCli } from './helpers/cli-spawn.ts';++const HINT = 'sync --status is the status read';++describe('gbrain sync --status (real CLI)', () => {+ let home: string;+ let notes: string;+ const dbPath = () => join(home, '.gbrain', 'brain.pglite');+ const pageCount = async () => {+ const engine = new PGLiteEngine();+ await engine.connect({ database_path: dbPath() });+ try { return (await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages'))[0]!.n; } finally { await engine.disconnect(); }+ };++ beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-6803-sync-status-'));+ notes = join(home, 'notes');+ mkdirSync(notes, { recursive: true });+ for (const n of ['alpha', 'beta', 'gamma']) writeFileSync(join(notes, `${n}.md`), `---\ntitle: ${n}\n---\n\n# ${n}\n\nA note about acme-example.\n`);+ const init = await runCli(['init', '--pglite', '--no-embedding', '--non-interactive'], { home, timeoutMs: 120_000 });+ expect(init.exitCode, init.stderr).toBe(0);+ const add = await runCli(['sources', 'add', 'notes', '--path', notes, '--force'], { home, timeoutMs: 60_000 });+ expect(add.exitCode, add.stderr).toBe(0);+ }, 200_000);+ afterAll(() => rmSync(home, { recursive: true, force: true }));++ test('prints the sync status envelope and syncs nothing', async () => {+ const run = await runCli(['sync', '--status', '--source', 'notes', '--json'], { home, timeoutMs: 60_000 });+ expect(run.exitCode, run.stderr).toBe(0);+ const out = JSON.parse(run.stdout) as Record<string, unknown>;+ expect(out).not.toHaveProperty('sync_status');+ expect(out).toMatchObject({ source_id: 'notes', cursor: null });+ expect(out).toHaveProperty('holds');+ expect(run.stderr.split(HINT).length - 1).toBe(1);+ expect(run.stderr).not.toContain('[sync-watchdog]');+ expect(await pageCount()).toBe(0);+ }, 90_000);++ test('under a resident owner it gets exactly what `sync status` gets: no watchdog, no owner hand-off', async () => {+ const resident = new PGLiteEngine();+ await resident.connect({ database_path: dbPath() });+ try {+ const [plain, flag] = await Promise.all([+ runCli(['sync', 'status', '--source', 'notes', '--json'], { home, timeoutMs: 60_000 }),+ runCli(['sync', '--status', '--source', 'notes', '--json'], { home, timeoutMs: 60_000 }),+ ]);+ expect(flag.exitCode).toBe(plain.exitCode);+ expect(flag.stdout).toBe(plain.stdout);+ for (const marker of ['[sync-watchdog]', 'Delegating to the registered PGLite owner', 'owner-delegated', 'Delegating to the running serve']) {+ expect(flag.stderr).not.toContain(marker);+ }+ } finally {+ await resident.disconnect();+ }+ expect(await pageCount()).toBe(0);+ }, 120_000);++ test('--preview, which sync never reads, refuses with invalid_params and runs nothing', async () => {+ const run = await runCli(['sync', '--preview', '--source', 'notes', '--json'], { home, timeoutMs: 60_000 });+ expect(run.exitCode).not.toBe(0);+ expect(run.stdout + run.stderr).toContain('invalid_params');+ expect(run.stdout + run.stderr).toContain('does not read --preview');+ expect(run.stdout + run.stderr).toContain('--dry-run');+ expect(await pageCount()).toBe(0);+ }, 90_000);+});++test('--dry-run is still consumed by the direct parse and by both owner delegation parsers', async () => {+ expect(syncOperatorVerb(['--dry-run', '--source', 'notes'])).toBeNull();+ expect(syncOperatorVerb(['status', '--source', 'notes'])).toBe('status');+ expect(syncOperatorVerb(['--status', '--source', 'notes'])).toBe('status');+ expect(() => syncOperatorVerb(['--check'])).toThrow(/does not read --check/);+ expect(parseSyncFlags(['--dry-run']).dryRun).toBe(true);+ expect((await parsePersistenceSyncArgs(['--dry-run', '--source', 'notes'])).options.dryRun).toBe(true);+ const delegated = parseDelegatedSyncArgs(['--dry-run', '--source', 'notes']);+ expect(delegated.ok && delegated.options.dryRun).toBe(true);+});