Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

scale: assert the F4d operational ceilings through the real CLI

garrytanfb17de37d920
diff --git a/TODOS.md b/TODOS.md
index 47d9c605e6..4a2f25a16d 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -89,18 +89,16 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md` (Deferred list). Contract: `docs/pro
**What:** proven on PGLite, Postgres and PgBouncer fixtures only. **Fix:** run the preview and apply on a managed brain with real history and record the filled and unrecorded counts. **Effort:** S. **Priority:** P2 (Foundations 2).
- [ ] **P2 — `--json` refusals from CLI-only ops print to stderr only.**
**What:** `gbrain attribution --json` (and other CLI ops through the shared framework) write refusals to stderr, not as a JSON object on stdout. **Effort:** S. **Priority:** P2 (Foundations 2).
-- [ ] **P2 — PGLite `sources refresh` while `gbrain serve` owns the database.**
- **What:** the refresh needs the writer lock; with a resident serve on PGLite it waits or refuses. **Fix:** delegate the refresh over the local persistence IPC socket. **Effort:** M. **Priority:** P2 (Foundations 2).
-- [ ] **P3 — The consumer's idle probe ignores the refresh effect fence.**
- **What:** the resident consumer's idle tick does not consult an active refresh's fence before probing. Harmless today (the probe writes nothing). **Effort:** S. **Priority:** P3 (Foundations 2).
+- [x] **P2 — PGLite `sources refresh` while `gbrain serve` owns the database.** **Completed: Foundations 2** — the refresh runs inside the resident owner through the `writer_refresh` administration operation (`src/commands/sources-refresh-delegate.ts`).
+- [x] **P3 — The consumer's idle probe ignores the refresh effect fence.** **Completed: Foundations 2** — the idle probe applies `refreshFenceClear` to effects like the claims do.
- [ ] **P2 — Drop the JSONB grant authority for legacy tokens.**
**What:** migrated tokens still mirror `permissions` JSON for older binaries, and admin-dashboard-created tokens are still born on the JSONB shape. **Fix:** after one release window, read only the unified columns and have the dashboard mint through `insertUnifiedToken`. **Effort:** M. **Priority:** P2 (Foundations 2).
- [ ] **P2 — `--sources none` for OAuth clients.**
**What:** refused for clients in F3 (no behavior change); needs per-client takes holders. **Effort:** M. **Priority:** P2 (Foundations 2).
-- [ ] **P2 — Seat follow-ups (#4618).**
- **What:** Codex hooks' trust hash changes when a seat is added; the harness Codex note should say so; OpenClaw's heartbeat does not report a seat write failure; a pattern page's `seat` is never removed when its sessions age out. **Effort:** M. **Priority:** P2 (Foundations 2).
-- [ ] **P2 — Large-brain ceilings in the 50k nightly.**
- **What:** the progress-aware sync deadline, 20k-file `sources add`, the loud embed budget stop and the serve boot window are pinned by unit and CLI tests, not yet asserted by the 50k scale-tier run; delegated syncs (serve-owned) are not yet progress-aware. **Effort:** M. **Priority:** P2 (Foundations 2).
+- [x] **P2 — Seat follow-ups (#4618).** **Completed: Foundations 2** — the OpenClaw context-engine heartbeat reports seat reasons (write failure, conflict, invalid label) with their hints, and a pattern page drops a seat its reflections no longer share. The Codex trust-hash item closed with no code: the Codex SessionEnd command never carries a seat (`buildCodexSessionEndCommand` takes only the gbrain binary; `--seat` prints a note to set `GBRAIN_SEAT` instead), so adding a seat cannot change its trust hash.
+- [x] **P2 — Large-brain ceilings in the scale tier.** **Completed: Foundations 2** — every scale run asserts the F4d ceilings through the real CLI (`scripts/scale/f4d.ts`: progress-aware sync deadline, loud embed budget stop and serve boot window at every tier, the 20,000-file `sources add` at 20k and up), so the 50k tier carries them once `trend.ts` unlocks it; delegated syncs keep the progress-aware deadline.
+- [ ] **P3 — `findOrphans` recomputes the full orphan set per call.**
+ **What:** `find_orphans` pages its rows in TypeScript after computing every orphan, so each page of a large result costs a full scan (the scale verifier reads `total_orphans` and one maximal page instead of paging). **Fix:** page in SQL with `ORDER BY source_id, slug LIMIT/OFFSET` and a separate count. **Effort:** S. **Priority:** P3.
- [ ] **P3 — Keyword search scoped to one source: 18.2 to 22.1 ms at 10k PGLite pages.**
**What:** the five-run ranges overlap (17.4-19.4 vs 18.7-25.0 ms), so this may be noise; the scale tier's calibrated budget will show a trend. **Effort:** S. **Priority:** P3 (Foundations 2).
- [ ] **P3 — Enforce the scale tier's ceilings and calibrated budgets.**
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 638d34f94b..a473068001 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -290,9 +290,22 @@ writes the vectors onto every chunk so the vector arm runs keylessly through
each with a known-answer check: `get_health`, `list_pages`, local and MCP-path
`search`, a source-scoped grant search, hybrid `query` with an injected
vector, `traverse_graph`, `get_backlinks` and `find_orphans`, plus a
-cold-process first query and two concurrent receipt-bearing `put_page`s. It
+cold-process first query and two concurrent receipt-bearing `put_page`s.
+`find_orphans` is checked with one call at the op's maximum page size: its
+rows must hold every fixture island and match `total_orphans`. It
captures every statement each op sends and replays the reads under
-`EXPLAIN ANALYZE` for the planner check. The report leads with the headline
+`EXPLAIN ANALYZE` for the planner check. With the brain closed, it then runs
+the large-brain operational ceilings through the real CLI
+(`scripts/scale/f4d.ts`), each an enforced data check with its measurement in
+the report's `f4d` section: a `gbrain sync` of a fresh source (1,000 files at 10k and up) past a 1 s
+progress-aware deadline completes (`f4d_sync_deadline`); `gbrain embed
+--stale` against a local stub embedding endpoint stops at its time budget with
+exit 11, the remaining count and the resume command (`f4d_embed_budget_stop`;
+nothing leaves the machine); `gbrain serve` answers initialize and a search
+without hitting its boot deadline (`f4d_serve_boot`); and at 20,000 pages and
+up, `gbrain sources add` registers a 20,000-file checkout on a fresh managed
+brain (`f4d_sources_add_20k`). Each phase logs its start and end, so a run
+stopped by a job timeout shows where it was. The report leads with the headline
metric, MCP search p50 at the run's size as shipped (no manual ANALYZE).
Exit codes: 0 when every enforced gate passes, or always without `--enforce`;
@@ -313,8 +326,9 @@ nightly runs; a reviewer then sets the repo variable
`GBRAIN_SCALE_ENFORCE_CEILINGS=1`. The same script picks the nightly sizes.
Reproduce any report with the command it prints. The fixture's determinism
is pinned by `test/scripts/scale-fixture.test.ts`, the gate policy by
-`test/scripts/scale-gates.test.ts` and `scale-trend.test.ts`, and a 40-page
-enforced run by `test/scripts/scale-harness.slow.test.ts`.
+`test/scripts/scale-gates.test.ts` and `scale-trend.test.ts`, the
+`find_orphans` known answer by `test/scripts/scale-orphans-verifier.test.ts`,
+and a 40-page enforced run by `test/scripts/scale-harness.slow.test.ts`.
### Authoring gate
diff --git a/scripts/scale/f4d.ts b/scripts/scale/f4d.ts
new file mode 100644
index 0000000000..d5ee0620e4
--- /dev/null
+++ b/scripts/scale/f4d.ts
@@ -0,0 +1,201 @@
+/**
+ * Large-brain operational assertions (Foundations 1 F4d) for the scale tier.
+ * Each runs the real CLI against the scale run's brain (or, for `sources
+ * add`, a fresh managed brain) after the timed ops, and lands in the report as
+ * an enforced data check plus its measurement:
+ *
+ * f4d_sync_deadline `gbrain sync` of a fresh source (1,000 files at 10k and up)
+ * past a 1 s progress-aware deadline keeps importing and completes.
+ * f4d_embed_budget_stop `gbrain embed --stale` stopped by its time budget exits 11
+ * with the remaining count and the resume command (a local
+ * stub embedding endpoint; no provider call leaves the machine).
+ * f4d_serve_boot `gbrain serve` on the brain answers initialize and a search
+ * inside its boot window and does not exit on the boot deadline.
+ * f4d_sources_add_20k `gbrain sources add` registers a 20,000-file checkout on a
+ * fresh managed brain (tiers of 20,000 pages and up only).
+ */
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { DataCheck } from './gates.ts';
+
+/** Files in the sync-deadline checkout: one tenth of the brain, between 100 and 1,000 (1,000 at the 10k and 20k tiers). */
+export const f4dSyncFiles = (pages: number) => Math.min(1000, Math.max(100, Math.floor(pages / 10)));
+export const F4D_ADD_FILES = 20_000;
+export const F4D_ADD_MIN_PAGES = 20_000;
+const EMBED_BUDGET_MS = 1500;
+const EMBED_STUB_DELAY_MS = 200;
+
+export interface F4dContext {
+ repo: string;
+ home: string;
+ pages: number;
+ dim: number;
+ probeToken: string;
+ /** The config a fresh managed brain for the 20k-file add should use (a new PGLite path or a new Postgres database). */
+ freshManagedBrain: () => Promise<{ initArgs: string[]; cleanup: () => Promise<void> }>;
+}
+
+interface Run { code: number; stdout: string; stderr: string; ms: number }
+
+async function cli(ctx: F4dContext, args: string[], env: Record<string, string | undefined> = {}, home = ctx.home): Promise<Run> {
+ const started = performance.now();
+ const child = Bun.spawn([process.execPath, join(ctx.repo, 'src/cli.ts'), ...args],
+ { env: { ...process.env, GBRAIN_HOME: home, ...env }, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });
+ const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);
+ return { code, stdout, stderr, ms: Math.round(performance.now() - started) };
+}
+
+function gitCheckout(root: string, files: number, prefix: string): void {
+ for (let i = 0; i < files; i++) {
+ const dir = join(root, 'notes', `batch-${String(Math.floor(i / 500)).padStart(3, '0')}`);
+ if (i % 500 === 0) mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, `${prefix}-${String(i).padStart(6, '0')}.md`), `---\ntitle: ${prefix} ${i}\ntype: note\n---\n\nOperational ceiling note ${i}.\n`);
+ }
+ const git = (args: string[]) => execFileSync('git', ['-c', '[email protected]', '-c', 'user.name=scale', ...args], { cwd: root, stdio: 'ignore' });
+ git(['init', '--quiet']);
+ git(['add', '-A']);
+ git(['commit', '--quiet', '-m', 'f4d fixture']);
+}
+
+const tail = (run: Run) => `exit ${run.code}; stdout: ${run.stdout.slice(-600)} stderr: ${run.stderr.slice(-600)}`;
+const lastJson = (text: string) => {
+ const line = text.trim().split('\n').reverse().find(l => l.startsWith('{'));
+ try { return line ? JSON.parse(line) as Record<string, unknown> : undefined; } catch { return undefined; }
+};
+
+async function syncDeadline(ctx: F4dContext): Promise<{ check: DataCheck; measured: Record<string, unknown> }> {
+ const root = join(ctx.home, 'f4d-sync');
+ const files = f4dSyncFiles(ctx.pages);
+ gitCheckout(root, files, 'sync');
+ const add = await cli(ctx, ['sources', 'add', 'f4d-sync', '--path', root]);
+ if (add.code !== 0) return { check: { check: 'f4d_sync_deadline', status: 'fail', detail: `sources add failed: ${tail(add)}` }, measured: {} };
+ const sync = await cli(ctx, ['sync', '--source', 'f4d-sync', '--no-pull', '--no-embed', '--json'],
+ { GBRAIN_SYNC_MAX_RUNTIME_SECONDS: '1', GBRAIN_SYNC_STALL_ABORT_SECONDS: '300' });
+ const body = lastJson(sync.stdout);
+ const imported = Number(body?.added ?? 0);
+ const extended = sync.stderr.includes('still progressing');
+ const problem = sync.code !== 0 ? `sync exited before finishing: ${tail(sync)}`
+ : imported !== files ? `sync imported ${imported} of ${files} files`
+ : !extended && sync.ms > 2000 ? 'sync outlasted its 1 s deadline without the progress-aware extension notice' : null;
+ return { check: { check: 'f4d_sync_deadline', status: problem ? 'fail' : 'pass', ...(problem ? { detail: problem } : {}) },
+ measured: { files, deadline_s: 1, wall_ms: sync.ms, imported, extended } };
+}
+
+async function embedBudgetStop(ctx: F4dContext): Promise<{ check: DataCheck; measured: Record<string, unknown> }> {
+ const vector = Array.from({ length: ctx.dim }, (_, i) => (i === 0 ? 1 : 0));
+ const server = Bun.serve({ port: 0, hostname: '127.0.0.1', async fetch(request) {
+ const url = new URL(request.url);
+ if (url.pathname.endsWith('/models')) return Response.json({ object: 'list', data: [{ id: 'bge-m3', object: 'model' }] });
+ if (!url.pathname.endsWith('/embeddings')) return new Response('not found', { status: 404 });
+ const body = await request.json() as { input: string | string[] };
+ const inputs = Array.isArray(body.input) ? body.input : [body.input];
+ await Bun.sleep(EMBED_STUB_DELAY_MS);
+ return Response.json({ object: 'list', model: 'bge-m3', usage: { prompt_tokens: inputs.length, total_tokens: inputs.length },
+ data: inputs.map((_, index) => ({ object: 'embedding', index, embedding: vector })) });
+ } });
+ const configPath = join(ctx.home, '.gbrain', 'config.json');
+ const original = readFileSync(configPath, 'utf8');
+ try {
+ const { embedding_disabled: _off, ...base } = JSON.parse(original) as Record<string, unknown>;
+ writeFileSync(configPath, JSON.stringify({ ...base, embedding_model: 'ollama:bge-m3', embedding_dimensions: ctx.dim }, null, 2) + '\n');
+ const embed = await cli(ctx, ['embed', '--stale', '--batch-size', '50', '--yes'], {
+ OLLAMA_BASE_URL: `http://127.0.0.1:${server.port}/v1`, GBRAIN_EMBED_TIME_BUDGET_MS: String(EMBED_BUDGET_MS), GBRAIN_EMBED_CONCURRENCY: '1',
+ });
+ const verdict = `${embed.stdout}\n${embed.stderr}`.split('\n').find(l => l.includes('reason: time_budget')) ?? '';
+ const left = Number(/with (\d+) stale chunk\(s\) left/.exec(verdict)?.[1] ?? NaN);
+ const problem = embed.code !== 11 ? `embed exited ${embed.code}, expected the budget-stop status 11: ${tail(embed)}`
+ : !(left > 0) ? `the budget-stop verdict does not name the remaining stale chunks: ${verdict || tail(embed)}`
+ : !verdict.includes('gbrain embed --stale --catch-up') ? `the budget-stop verdict does not name the resume command: ${verdict}` : null;
+ return { check: { check: 'f4d_embed_budget_stop', status: problem ? 'fail' : 'pass', ...(problem ? { detail: problem } : {}) },
+ measured: { budget_ms: EMBED_BUDGET_MS, wall_ms: embed.ms, exit_code: embed.code, remaining_stale: Number.isFinite(left) ? left : null } };
+ } finally {
+ writeFileSync(configPath, original);
+ server.stop(true);
+ }
+}
+
+async function serveBoot(ctx: F4dContext): Promise<{ check: DataCheck; measured: Record<string, unknown> }> {
+ const started = performance.now();
+ const child = Bun.spawn([process.execPath, join(ctx.repo, 'src/cli.ts'), 'serve'],
+ { env: { ...process.env, GBRAIN_HOME: ctx.home }, stdin: 'pipe', stdout: 'pipe', stderr: 'pipe' });
+ let stdout = '', stderr = '';
+ const decoder = new TextDecoder();
+ const pump = async (stream: ReadableStream<Uint8Array>, append: (s: string) => void) => { for await (const chunk of stream) append(decoder.decode(chunk)); };
+ const pumps = [pump(child.stdout as ReadableStream<Uint8Array>, s => { stdout += s; }), pump(child.stderr as ReadableStream<Uint8Array>, s => { stderr += s; })];
+ const send = (message: unknown) => (child.stdin as { write(s: string): unknown }).write(JSON.stringify(message) + '\n');
+ const answered = async (id: number, limitMs: number) => {
+ const deadline = performance.now() + limitMs;
+ while (performance.now() < deadline) {
+ const line = stdout.split('\n').find(l => { try { return JSON.parse(l).id === id; } catch { return false; } });
+ if (line) return { ms: Math.round(performance.now() - started), body: JSON.parse(line) as Record<string, unknown> };
+ if (child.exitCode !== null) return null;
+ await Bun.sleep(25);
+ }
+ return null;
+ };
+ try {
+ send({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'scale-f4d', version: '1' } } });
+ const init = await answered(1, 180_000);
+ send({ jsonrpc: '2.0', method: 'notifications/initialized' });
+ send({ jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'search', arguments: { query: ctx.probeToken, limit: 5 } } });
+ const search = await answered(2, 180_000);
+ const timedOut = stderr.includes('boot did not complete');
+ const problem = timedOut ? `serve exited on its boot deadline: ${stderr.slice(-800)}`
+ : !init ? `serve never answered initialize (exit ${child.exitCode}): ${stderr.slice(-800)}`
+ : !search || (search.body as { error?: unknown }).error ? `serve did not answer a search after boot: ${JSON.stringify(search?.body ?? null).slice(0, 400)} ${stderr.slice(-400)}`
+ : child.exitCode !== null ? `serve exited ${child.exitCode} after answering` : null;
+ return { check: { check: 'f4d_serve_boot', status: problem ? 'fail' : 'pass', ...(problem ? { detail: problem } : {}) },
+ measured: { initialize_ms: init?.ms ?? null, first_search_ms: search?.ms ?? null } };
+ } finally {
+ child.kill('SIGTERM');
+ const killer = setTimeout(() => child.kill('SIGKILL'), 30_000);
+ await child.exited;
+ clearTimeout(killer);
+ await Promise.allSettled(pumps);
+ }
+}
+
+async function sourcesAdd20k(ctx: F4dContext): Promise<{ check: DataCheck; measured: Record<string, unknown> }> {
+ const home = join(ctx.home, 'f4d-managed');
+ const root = join(home, 'checkout');
+ mkdirSync(root, { recursive: true });
+ const brain = await ctx.freshManagedBrain();
+ try {
+ const init = await cli(ctx, ['init', ...brain.initArgs, '--no-embedding'], { DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, home);
+ if (init.code !== 0) return { check: { check: 'f4d_sources_add_20k', status: 'fail', detail: `init of the managed brain failed: ${tail(init)}` }, measured: {} };
+ const t = performance.now();
+ gitCheckout(root, F4D_ADD_FILES, 'add');
+ const checkoutMs = Math.round(performance.now() - t);
+ const add = await cli(ctx, ['sources', 'add', 'big', '--path', root], {}, home);
+ const body = (() => { try { return JSON.parse(add.stdout.slice(add.stdout.indexOf('{'))) as Record<string, unknown>; } catch { return undefined; } })();
+ const problem = add.stderr.includes('request_too_large') ? `sources add hit request_too_large: ${tail(add)}`
+ : add.code !== 0 ? `sources add failed: ${tail(add)}`
+ : body?.source_id !== 'big' || body.state !== 'committed' ? `sources add did not commit the source: ${add.stdout.slice(-600)}` : null;
+ return { check: { check: 'f4d_sources_add_20k', status: problem ? 'fail' : 'pass', ...(problem ? { detail: problem } : {}) },
+ measured: { files: F4D_ADD_FILES, checkout_ms: checkoutMs, add_ms: add.ms } };
+ } finally {
+ await brain.cleanup();
+ }
+}
+
+/** Run every F4d assertion that applies at this tier; the scale brain must be closed (PGLite has one owner). */
+export async function runF4dChecks(ctx: F4dContext): Promise<{ checks: DataCheck[]; measured: Record<string, Record<string, unknown>> }> {
+ const checks: DataCheck[] = [];
+ const measured: Record<string, Record<string, unknown>> = {};
+ const steps: Array<[string, (c: F4dContext) => Promise<{ check: DataCheck; measured: Record<string, unknown> }>]> = [
+ ['sync_deadline', syncDeadline], ['embed_budget_stop', embedBudgetStop], ['serve_boot', serveBoot],
+ ...(ctx.pages >= F4D_ADD_MIN_PAGES ? [['sources_add_20k', sourcesAdd20k] as [string, typeof syncDeadline]] : []),
+ ];
+ for (const [name, step] of steps) {
+ try {
+ const result = await step(ctx);
+ checks.push(result.check);
+ measured[name] = result.measured;
+ } catch (error) {
+ checks.push({ check: `f4d_${name}`, status: 'fail', detail: `the assertion crashed: ${error instanceof Error ? error.message : String(error)}` });
+ }
+ }
+ if (ctx.pages < F4D_ADD_MIN_PAGES) measured.sources_add_20k = { skipped: `runs at ${F4D_ADD_MIN_PAGES} pages and up` };
+ return { checks, measured };
+}
diff --git a/scripts/scale/run.ts b/scripts/scale/run.ts
index 82b79e67dc..95752da7b3 100644
--- a/scripts/scale/run.ts
+++ b/scripts/scale/run.ts
@@ -30,6 +30,7 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { corpusMarkdownFiles, generateScaleFixture, SCALE_SOURCES, scaleVector, writeScaleCorpus, type ScaleFixture } from './fixture.ts';
+import { runF4dChecks } from './f4d.ts';
import {
BUDGET_MULTIPLIER, evaluateScaleGates, FIND_ORPHANS_PARAMS, HEADLINE_OP, HOT_TABLES, PLANNER_HEALTH_ENFORCED, PLANNER_STATS_MIN_ROWS, orphansProblem, reproduceCommand, resultHits, verdictLines,
type DataCheck, type GatePolicy, type OpPlan, type OpResult, type PlanStatement, type ScaleReport,
@@ -107,19 +108,23 @@ async function closeEngine(engine: Engine): Promise<void> {
await engine.disconnect();
}
-async function createFreshPostgres(): Promise<void> {
+async function freshPostgresDatabase(suffix = ''): Promise<{ url: string; drop: () => Promise<void> }> {
const { default: postgres } = await import('#postgres');
const admin = postgres(adminUrl!, { max: 1, onnotice: () => {} });
- const name = `gbrain_scale_${process.pid}_${Date.now()}`;
+ const name = `gbrain_scale_${process.pid}_${Date.now()}${suffix}`;
await admin.unsafe(`CREATE DATABASE ${name}`);
await admin.end();
const url = new URL(adminUrl!);
url.pathname = `/${name}`;
- databaseUrl = url.toString();
- dropDatabase = async () => {
+ return { url: url.toString(), drop: async () => {
const drop = postgres(adminUrl!, { max: 1, onnotice: () => {} });
try { await drop.unsafe(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`); } finally { await drop.end(); }
- };
+ } };
+}
+async function createFreshPostgres(): Promise<void> {
+ const fresh = await freshPostgresDatabase();
+ databaseUrl = fresh.url;
+ dropDatabase = fresh.drop;
}
/** Record every statement the engine sends while `fn` runs (postgres.js debug hook; PGLite query wrapper). */
@@ -474,6 +479,18 @@ async function main(): Promise<FullReport> {
phases.budgets = Math.round(performance.now() - budgetsStart);
await closeEngine(engine);
+ // F4d operational ceilings through the real CLI (the brain is closed: PGLite has one owner).
+ const f4d = await timed('f4d', async () => {
+ const result = await runF4dChecks({ repo: REPO, home, pages: fixture.pages.length, dim, probeToken: probe.token,
+ freshManagedBrain: async () => {
+ if (engineKind === 'pglite') return { initArgs: ['--pglite', '--path', join(home, 'f4d-managed', 'brain.pglite')], cleanup: async () => {} };
+ const fresh = await freshPostgresDatabase('_f4d');
+ return { initArgs: ['--non-interactive', '--url', fresh.url], cleanup: fresh.drop };
+ } });
+ data.push(...result.checks);
+ return result.measured;
+ });
+
const budgets = existsSync(BUDGETS_FILE) ? (JSON.parse(readFileSync(BUDGETS_FILE, 'utf8')) as { budgets?: Record<string, Record<string, number>> }).budgets ?? {} : {};
const budgetKey = `${engineKind}:${pagesArg}`;
const headline = ops.find(o => o.op === HEADLINE_OP)!;
@@ -491,7 +508,7 @@ async function main(): Promise<FullReport> {
extract,
planner: { hot_table_stat_rows: statRows, hot_table_rows: tableRows, probed_after: probedAfter,
tables_without_stats: HOT_TABLES.filter(t => tableRows[t]! > PLANNER_STATS_MIN_ROWS && statRows[t] === 0) },
- ops, data, cold_query: cold, vector_dim: dim, phases_ms: phases,
+ ops, data, f4d, cold_query: cold, vector_dim: dim, phases_ms: phases,
...(budgets[budgetKey] ? { budgets_ms: budgets[budgetKey] } : {}),
};
}
@@ -520,6 +537,7 @@ try {
console.log(`[scale] ${r.known_answer === 'pass' ? 'PASS' : 'FAIL'} ${r.op}: p50 ${r.p50_ms} ms${r.plan?.worst_loops ? `, worst nested-loop inner loops ${r.plan.worst_loops.inner_loops}` : ''}${r.detail ? ` (${r.detail})` : ''}`);
}
for (const d of report.data) console.log(`[scale] ${d.status === 'pass' ? 'PASS' : 'FAIL'} ${d.check}${d.detail ? ` (${d.detail})` : ''}`);
+ for (const [name, measured] of Object.entries(report.f4d)) console.log(`[scale] F4D ${name}: ${JSON.stringify(measured)}`);
console.log(`[scale] phases (ms): ${Object.entries(report.phases_ms).map(([k, v]) => `${k}=${v}`).join(' ')}`);
for (const line of verdictLines(report, verdict, policy)) console.log(line);
console.log(`[scale] report: ${out}${explain ? ` (EXPLAIN for failures: ${out.replace(/\.json$/, '')}.explain.txt)` : ''}; reproduce with: ${full.reproduce}`);
diff --git a/test/scripts/scale-harness.slow.test.ts b/test/scripts/scale-harness.slow.test.ts
index 6aede41524..208b8390a8 100644
--- a/test/scripts/scale-harness.slow.test.ts
+++ b/test/scripts/scale-harness.slow.test.ts
@@ -35,6 +35,10 @@ test('a 40-page enforced PGLite run passes every enforced gate and writes a head
expect(Object.keys(report.planner.hot_table_rows).sort()).toEqual(Object.keys(report.planner.hot_table_stat_rows).sort());
expect(report.planner.hot_table_rows.pages).toBeGreaterThan(0);
expect(report.policy.planner_health).toBe('enforced');
+ // F4d operational ceilings run through the real CLI at every tier; the 20k-file add only from 20k pages.
+ expect(report.data.map((d: { check: string }) => d.check)).toEqual(expect.arrayContaining(['f4d_sync_deadline', 'f4d_embed_budget_stop', 'f4d_serve_boot']));
+ expect(report.f4d.embed_budget_stop.exit_code).toBe(11);
+ expect(report.f4d.sources_add_20k).toEqual({ skipped: 'runs at 20000 pages and up' });
expect(report.ops.map((o: { op: string }) => o.op)).toEqual(expect.arrayContaining([
'query (hybrid, injected vector)', 'search (MCP path, source-scoped grant)', 'cold-process first query (MCP path)', 'concurrent put_page x2 (receipts)']));
} finally {