Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(scale): judge PGLite import rate on main-thread CPU time, not wall time

time-attack0f32b8d44968
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 420525a58b..6b6e7e0bfc 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -291,7 +291,9 @@ O-CEO-9) in the Foundations 1 plan; `scripts/scale/gates.ts` and
`.github/workflows/scale-tier.yml` implement it. This section says how to run it.
How to run it, what it measures, exit codes, the watchdog and the large-brain
-ceilings: [scripts/scale/README.md](../scripts/scale/README.md).
+ceilings: [scripts/scale/README.md](../scripts/scale/README.md). The import-rate
+gate times PGLite by the import process's CPU time and Postgres by wall time;
+the README says why.
### Authoring gate
diff --git a/docs/progress-events.md b/docs/progress-events.md
index dd0e008adf..df05d87158 100644
--- a/docs/progress-events.md
+++ b/docs/progress-events.md
@@ -87,12 +87,17 @@ won't emit more often than `minIntervalMs` (default 1000) and
`minItems` (default `max(10, ceil(total/100))`).
```json
-{"event":"tick","phase":"orphans.scan","done":15000,"total":52000,"pct":28.8,"elapsed_ms":4200,"eta_ms":10300,"ts":"..."}
+{"event":"tick","phase":"orphans.scan","done":15000,"total":52000,"pct":28.8,"elapsed_ms":4200,"cpu_ms":3900,"eta_ms":10300,"ts":"..."}
```
Fields:
- `done` — items completed in this phase.
+- `cpu_ms` — CPU time (user + system) the emitting process's main thread has
+ used since the phase started. Unlike `elapsed_ms` it excludes time the host
+ gave the CPU to other work, and it excludes work on runtime helper threads
+ (garbage collection, JIT) and in other processes (a Postgres server, a
+ provider). The scale tier's import-rate gate times PGLite imports with it.
- `total` — total items, if known. Omitted when the scan doesn't have a
total up front (e.g. a streaming iterator).
- `pct` — `done/total * 100`, one decimal. Omitted when `total` is unknown.
diff --git a/scripts/scale/README.md b/scripts/scale/README.md
index 2ad83c0e80..ed26c48222 100644
--- a/scripts/scale/README.md
+++ b/scripts/scale/README.md
@@ -41,6 +41,18 @@ Exit codes: 0 when every enforced gate passes, or always without `--enforce`;
1 when an enforced gate fails (each failure names the gate and op and prints
its EXPLAIN; the JSON report and a `.explain.txt` land next to `--out`);
2 on a usage error; 3 when the harness itself crashed (not a verdict).
+The import-rate gate compares the last 10% of pages' per-page cost with the
+first 10% (<= 1.5x) and the total import with the time at the halfway mark
+(<= 2.5x). The report and its JSON `import` section carry both bases for every
+engine: wall time (`elapsed_ms`) and the import process's main-thread CPU time
+(`cpu_ms`, user + system, from each progress tick; in-process timing under
+`--import-mode content`). PGLite is judged on CPU time: the database runs
+synchronously on the import's main thread, so that CPU time holds all of its
+work (and not the runtime's GC and JIT helper threads), while wall time
+also counts time a shared CI host gives the CPU to other tenants, which once
+failed a run with no code change. Postgres is judged on wall time, because the
+server's work never shows up in the import process's CPU time.
+
Enforced under `--enforce`: import rate, known answers, no-op re-import,
no duplicates across sources, the import phase timer, and the stats-dependent
gates (`PLANNER_HEALTH_ENFORCED` in `scripts/scale/gates.ts`): the Nested Loop
diff --git a/scripts/scale/gates.ts b/scripts/scale/gates.ts
index 22068a0286..8668000224 100644
--- a/scripts/scale/gates.ts
+++ b/scripts/scale/gates.ts
@@ -33,6 +33,57 @@ export const RATE_RATIO_MAX = 1.5;
/** Below this size per-process warmup dominates the per-page cost, so the rate gate is reported but not enforced. */
export const RATE_MIN_PAGES = 1000;
export const TOTAL_VS_HALF_MAX = 2.5;
+
+/** One timing basis of the import: per-page cost of the first and last 10%, and total vs the halfway mark. */
+export interface RateMeasure {
+ per_page_ms_first10: number;
+ per_page_ms_last10: number;
+ rate_ratio: number;
+ total_ms: number;
+ ms_at_half: number;
+ total_vs_half: number;
+}
+
+/**
+ * Per-file wall and CPU milliseconds from `gbrain import --progress-json --progress-interval 0`
+ * stderr: one `import.files` tick per file, each with cumulative `elapsed_ms` and `cpu_ms`.
+ * A file without a tick, or a tick without a field, yields NaN for the caller to reject.
+ */
+export function importProgressPerFile(stderr: string): { wallMs: number[]; cpuMs: number[] } {
+ const wall: number[] = [];
+ const cpu: number[] = [];
+ for (const line of stderr.split('\n')) {
+ if (!line.startsWith('{')) continue;
+ const event = JSON.parse(line) as { event?: string; phase?: string; done?: number; elapsed_ms?: number; cpu_ms?: number };
+ if (event.event !== 'tick' || event.phase !== 'import.files' || typeof event.done !== 'number') continue;
+ wall[event.done - 1] = event.elapsed_ms ?? Number.NaN;
+ cpu[event.done - 1] = event.cpu_ms ?? Number.NaN;
+ }
+ const perFile = (cumulative: number[]) => Array.from(cumulative, (ms, i) => (ms ?? Number.NaN) - (i > 0 ? cumulative[i - 1] ?? Number.NaN : 0));
+ return { wallMs: perFile(wall), cpuMs: perFile(cpu) };
+}
+
+export function rateMeasure(perPageMs: number[]): RateMeasure {
+ const sum = (xs: number[]) => xs.reduce((a, b) => a + b, 0);
+ const tenth = Math.max(1, Math.floor(perPageMs.length / 10));
+ const first = sum(perPageMs.slice(0, tenth)) / tenth;
+ const last = sum(perPageMs.slice(-tenth)) / tenth;
+ const half = sum(perPageMs.slice(0, Math.floor(perPageMs.length / 2)));
+ const total = sum(perPageMs);
+ const round = (n: number, places: number) => Math.round(n * 10 ** places) / 10 ** places;
+ return { per_page_ms_first10: round(first, 1), per_page_ms_last10: round(last, 1), rate_ratio: round(last / first, 2),
+ total_ms: Math.round(total), ms_at_half: Math.round(half), total_vs_half: round(total / half, 2) };
+}
+
+/**
+ * The timing basis the import-rate gate judges. PGLite runs on the import process's main thread, so
+ * that thread's CPU time holds all the import's work and none of the time a shared host takes the CPU away, which
+ * inflates wall time on CI runners. Postgres does its work in the server, outside that process's
+ * CPU time, so it keeps wall time.
+ */
+export function importRateBasis(engine: ScaleReport['engine']): 'cpu' | 'wall' {
+ return engine === 'pglite' ? 'cpu' : 'wall';
+}
export const LOOPS_PER_PAGE_MAX = 10;
export const HOT_TABLES = ['pages', 'links', 'content_chunks', 'timeline_entries', 'facts', 'takes'] as const;
/**
@@ -76,7 +127,8 @@ export interface ScaleReport {
pages: number;
seed: number;
import_mode: 'cli' | 'content';
- import: { rate_ratio: number; total_vs_half: number; per_page_ms_first10: number; per_page_ms_last10: number };
+ /** Both timing bases, reported for every engine; `importRateBasis` picks the one the gate judges. */
+ import: { wall: RateMeasure; cpu: RateMeasure };
/**
* Read after the first timed op (`probed_after`), not right after import: F4b analyzes on the
* first planner-sensitive read by design. `hot_table_rows` is each table's row count.
@@ -116,10 +168,13 @@ export function evaluateScaleGates(report: ScaleReport, policy: GatePolicy): Gat
const add = (gate: string, ok: boolean, enforced: boolean, message: string, explain?: string) =>
results.push({ gate, status: ok ? 'pass' : 'fail', enforced, message, ...(explain && !ok ? { explain } : {}) });
- const { rate_ratio, total_vs_half, per_page_ms_first10, per_page_ms_last10 } = report.import;
+ const basis = importRateBasis(report.engine);
+ const other = basis === 'cpu' ? 'wall' : 'cpu';
+ const { rate_ratio, total_vs_half, per_page_ms_first10, per_page_ms_last10 } = report.import[basis];
add('import_rate', rate_ratio <= RATE_RATIO_MAX && total_vs_half <= TOTAL_VS_HALF_MAX, report.pages >= RATE_MIN_PAGES,
- `import rate: last 10% per-page cost ${per_page_ms_last10} ms is ${rate_ratio}x the first 10% (${per_page_ms_first10} ms; gate <= ${RATE_RATIO_MAX}); `
+ `import rate (${basis} time): last 10% per-page cost ${per_page_ms_last10} ms is ${rate_ratio}x the first 10% (${per_page_ms_first10} ms; gate <= ${RATE_RATIO_MAX}); `
+ `total import time is ${total_vs_half}x the time at the halfway mark (gate <= ${TOTAL_VS_HALF_MAX}). `
+ + `Not judged on ${report.engine}: ${other} time ratio ${report.import[other].rate_ratio}, total/half ${report.import[other].total_vs_half}. `
+ `A rising per-page cost means import slows as the brain grows, usually stale planner statistics during import. Reproduce: ${repro}`);
const { hot_table_stat_rows: statRows, hot_table_rows: tableRows, probed_after: probedAfter } = report.planner;
diff --git a/scripts/scale/run.ts b/scripts/scale/run.ts
index d834b6c5c5..61fbd6000d 100644
--- a/scripts/scale/run.ts
+++ b/scripts/scale/run.ts
@@ -37,7 +37,8 @@ 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,
+ BUDGET_MULTIPLIER, evaluateScaleGates, FIND_ORPHANS_PARAMS, HEADLINE_OP, HOT_TABLES, importProgressPerFile, importRateBasis, PLANNER_HEALTH_ENFORCED, PLANNER_STATS_MIN_ROWS,
+ orphansProblem, RATE_RATIO_MAX, rateMeasure, reproduceCommand, resultHits, TOTAL_VS_HALF_MAX, verdictLines,
type DataCheck, type GatePolicy, type OpPlan, type OpResult, type PlanStatement, type ScaleReport,
} from './gates.ts';
@@ -118,7 +119,6 @@ const { disposePersistenceConsumer } = await import('../../src/core/persistence/
type Engine = Awaited<ReturnType<typeof createEngine>>;
const median = (xs: number[]) => [...xs].sort((a, b) => a - b)[Math.floor(xs.length / 2)]!;
-const avg = (xs: number[]) => xs.reduce((a, b) => a + b, 0) / xs.length;
const round1 = (n: number) => Math.round(n * 10) / 10;
const silent = { info() {}, warn() {}, error() {} };
@@ -212,7 +212,7 @@ async function writeConfig(): Promise<void> {
writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ ...engineConfig(), embedding_disabled: true }, null, 2) + '\n');
}
-interface CliImport { perFileMs: number[]; result: Record<string, unknown>; wallMs: number }
+interface CliImport { perFileMs: number[]; perFileCpuMs: number[]; result: Record<string, unknown>; wallMs: number }
/** Run the real `gbrain import` for one source; per-file cost comes from its JSON progress ticks (one per file at interval 0). */
async function cliImport(sourceId: string): Promise<CliImport> {
const sourceDir = join(corpusDir, sourceId);
@@ -236,18 +236,13 @@ async function cliImport(sourceId: string): Promise<CliImport> {
+ 'Its file listing skipped the rest (a .gitignore or hidden-path rule of an enclosing repository is the usual cause). '
+ `Fix: check \`git -C ${sourceDir} check-ignore -v .\`, or pass a --corpus-dir outside any repository.`);
}
- const elapsed: number[] = [];
- for (const line of stderr.split('\n')) {
- if (!line.startsWith('{')) continue;
- const event = JSON.parse(line) as { event?: string; phase?: string; done?: number; elapsed_ms?: number };
- if (event.event === 'tick' && event.phase === 'import.files' && typeof event.done === 'number') elapsed[event.done - 1] = event.elapsed_ms ?? 0;
+ const { wallMs: perFileMs, cpuMs: perFileCpuMs } = importProgressPerFile(stderr);
+ const usable = perFileMs.filter((ms, i) => Number.isFinite(ms) && Number.isFinite(perFileCpuMs[i])).length;
+ if (perFileMs.length !== totalFiles || usable !== totalFiles) {
+ throw new Error(`gbrain import of source ${sourceId} emitted ${usable} usable per-file progress ticks for `
+ + `${totalFiles} files; the rate gate needs one tick per file with elapsed_ms and cpu_ms (--progress-json --progress-interval 0).`);
}
- const perFileMs = Array.from(elapsed, (ms, i) => ms - (i > 0 ? elapsed[i - 1] ?? Number.NaN : 0));
- if (perFileMs.length !== Number(JSON.parse(lastJson).total_files) || perFileMs.some(ms => !Number.isFinite(ms))) {
- throw new Error(`gbrain import of source ${sourceId} emitted ${perFileMs.filter(Number.isFinite).length} usable per-file progress ticks for `
- + `${String(JSON.parse(lastJson).total_files)} files; the rate gate needs one tick per file (--progress-json --progress-interval 0).`);
- }
- return { perFileMs, result: JSON.parse(lastJson) as Record<string, unknown>, wallMs };
+ return { perFileMs, perFileCpuMs, result: JSON.parse(lastJson) as Record<string, unknown>, wallMs };
}
async function brainSnapshot(engine: Engine): Promise<Record<string, string>> {
@@ -263,7 +258,6 @@ async function brainSnapshot(engine: Engine): Promise<Record<string, string>> {
interface FullReport extends ScaleReport {
headline: { metric: string; p50_ms: number };
- import: ScaleReport['import'] & { files_ms: number; ms_at_half: number };
planner: ScaleReport['planner'] & { tables_without_stats: string[] };
[key: string]: unknown;
}
@@ -295,6 +289,7 @@ async function main(): Promise<FullReport> {
// Import.
let perPage: number[] = [];
+ let perPageCpu: number[] = [];
await timed('import_files', async () => {
if (importMode === 'cli') {
await closeEngine(engine);
@@ -305,21 +300,23 @@ async function main(): Promise<FullReport> {
throw new Error(`gbrain import of source ${sourceId} imported ${String(run.result.imported)}/${expected} with ${String(run.result.errors)} errors: ${JSON.stringify(run.result).slice(0, 2000)}`);
}
perPage = perPage.concat(run.perFileMs);
+ perPageCpu = perPageCpu.concat(run.perFileCpuMs);
console.log(`[scale] gbrain import --source ${sourceId}: ${expected} files in ${Math.round(run.wallMs)} ms wall`);
}
engine = await openEngine();
} else {
for (const page of fixture.pages) {
const t = performance.now();
+ const cpu = process.threadCpuUsage();
const result = await importFromContent(engine, page.slug, page.content, { sourceId: page.sourceId, noEmbed: true });
if (result.status === 'error') throw new Error(`import failed for ${page.sourceId}:${page.slug}: ${result.error}`);
perPage.push(performance.now() - t);
+ const used = process.threadCpuUsage(cpu);
+ perPageCpu.push((used.user + used.system) / 1000);
}
}
});
- const tenth = Math.max(1, Math.floor(perPage.length / 10));
- const half = perPage.slice(0, Math.floor(perPage.length / 2)).reduce((a, b) => a + b, 0);
- const filesMs = perPage.reduce((a, b) => a + b, 0);
+ const importRate = { wall: rateMeasure(perPage), cpu: rateMeasure(perPageCpu) };
// Derived data, as a cycle would: links + timeline, facts and takes fences.
const extract = await timed('extract', async () => {
@@ -537,11 +534,7 @@ async function main(): Promise<FullReport> {
import_mode: importMode, sources: SCALE_SOURCES,
runtime: { bun: Bun.version, platform: process.platform, arch: process.arch, cpus: navigator.hardwareConcurrency },
policy: { planner_health: policy.enforcePlanner ? 'enforced' : 'report-only (PLANNER_HEALTH_ENFORCED=false)', ceilings: policy.enforceCeilings ? 'enforced' : 'report-only' },
- import: {
- files_ms: Math.round(filesMs), per_page_ms_first10: round1(avg(perPage.slice(0, tenth))), per_page_ms_last10: round1(avg(perPage.slice(-tenth))),
- rate_ratio: Math.round((avg(perPage.slice(-tenth)) / avg(perPage.slice(0, tenth))) * 100) / 100,
- ms_at_half: Math.round(half), total_vs_half: Math.round((filesMs / half) * 100) / 100,
- },
+ import: importRate,
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) },
@@ -567,8 +560,11 @@ try {
console.log(`[scale] calibrated budgets (${BUDGET_MULTIPLIER}x p50) for ${report.engine}:${report.pages} written to ${BUDGETS_FILE}`);
}
console.log(`[scale] HEADLINE ${report.headline.metric}: ${report.headline.p50_ms} ms`);
- const imp = report.import;
- console.log(`[scale] import (${report.import_mode}) files ${imp.files_ms} ms; per-page first10 ${imp.per_page_ms_first10} ms, last10 ${imp.per_page_ms_last10} ms, ratio ${imp.rate_ratio} (gate <= 1.5); total/half ${imp.total_vs_half} (gate <= 2.5)`);
+ const gatedBasis = importRateBasis(report.engine);
+ for (const basis of ['cpu', 'wall'] as const) {
+ const imp = report.import[basis];
+ console.log(`[scale] import (${report.import_mode}, ${basis} time${basis === gatedBasis ? ', gated' : ', reported'}) files ${imp.total_ms} ms; per-page first10 ${imp.per_page_ms_first10} ms, last10 ${imp.per_page_ms_last10} ms, ratio ${imp.rate_ratio} (gate <= ${RATE_RATIO_MAX}); total/half ${imp.total_vs_half} (gate <= ${TOTAL_VS_HALF_MAX})`);
+ }
console.log(`[scale] planner (after ${report.planner.probed_after}): tables above ${PLANNER_STATS_MIN_ROWS} rows without stats: ${report.planner.tables_without_stats.join(', ') || 'none'}`);
for (const r of report.ops) {
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})` : ''}`);
diff --git a/src/core/progress.ts b/src/core/progress.ts
index f87e4cee5e..95596dbf11 100644
--- a/src/core/progress.ts
+++ b/src/core/progress.ts
@@ -13,7 +13,7 @@
*
* JSON event schema (stable from v0.15.2, additive only):
* {"event":"start","phase":"<snake.dot.path>","total"?:N,"ts":"<iso>"}
- * {"event":"tick","phase":"...","done":N,"total"?:N,"pct"?:F,"elapsed_ms":N,"eta_ms"?:N,"ts":"..."}
+ * {"event":"tick","phase":"...","done":N,"total"?:N,"pct"?:F,"elapsed_ms":N,"cpu_ms":N,"eta_ms"?:N,"ts":"..."}
* {"event":"heartbeat","phase":"...","note":"<str>","elapsed_ms":N,"ts":"..."}
* {"event":"finish","phase":"...","done"?:N,"total"?:N,"elapsed_ms":N,"ts":"..."}
* {"event":"abort","phase":"...","reason":"<SIGINT|SIGTERM>","elapsed_ms":N,"ts":"..."}
@@ -168,6 +168,7 @@ interface PhaseState {
total?: number;
done: number;
startedAt: number;
+ cpuAtStart: NodeJS.CpuUsage;
lastEmitMs: number;
lastDoneEmitted: number;
heartbeatTimer?: ReturnType<typeof setInterval>;
@@ -257,6 +258,7 @@ class Reporter implements ReporterInternal {
total,
done: 0,
startedAt: now,
+ cpuAtStart: process.threadCpuUsage(),
lastEmitMs: now,
lastDoneEmitted: 0,
live: null,
@@ -305,11 +307,13 @@ class Reporter implements ReporterInternal {
const elapsedMs = now - s.startedAt;
if (this.renderMode === 'json') {
+ const cpu = process.threadCpuUsage(s.cpuAtStart);
const obj: Record<string, unknown> = {
event: 'tick',
phase: s.phase,
done: s.done,
elapsed_ms: elapsedMs,
+ cpu_ms: Math.round((cpu.user + cpu.system) / 1000),
ts: nowIso(),
};
if (typeof s.total === 'number' && s.total > 0) {
diff --git a/test/progress.test.ts b/test/progress.test.ts
index 0e73649bb6..189a542f0f 100644
--- a/test/progress.test.ts
+++ b/test/progress.test.ts
@@ -145,9 +145,27 @@ describe('progress reporter', () => {
expect(events[1]).toMatchObject({ event: 'tick', phase: 'doctor.jsonb_integrity', done: 1, total: 4 });
expect(events[1].pct).toBe(25);
expect(typeof events[1].elapsed_ms).toBe('number');
+ expect(typeof events[1].cpu_ms).toBe('number');
expect(events[events.length - 1]).toMatchObject({ event: 'finish', phase: 'doctor.jsonb_integrity' });
});
+ test('json tick cpu_ms counts CPU work since the phase started, not time spent waiting', async () => {
+ const { stream, read } = sink(false);
+ const p = createProgress({ mode: 'json', stream, minIntervalMs: 0, minItems: 1 });
+ p.start('import.files', 3);
+ const cpuMs = () => { const u = process.threadCpuUsage(); return (u.user + u.system) / 1000; };
+ const spinUntil = cpuMs() + 60;
+ while (cpuMs() < spinUntil) { /* burn 60 ms of CPU */ }
+ p.tick(1);
+ await new Promise(resolve => setTimeout(resolve, 200));
+ p.tick(1);
+ p.finish();
+ const [, worked, waited] = parseJsonl(read()) as Array<{ cpu_ms: number; elapsed_ms: number }>;
+ expect(worked.cpu_ms).toBeGreaterThanOrEqual(60);
+ expect(waited.elapsed_ms - worked.elapsed_ms).toBeGreaterThanOrEqual(190);
+ expect(waited.cpu_ms - worked.cpu_ms).toBeLessThan(100);
+ });
+
test('quiet mode emits nothing', () => {
const { stream, read } = sink(false);
const p = createProgress({ mode: 'quiet', stream });
diff --git a/test/scripts/scale-gates.test.ts b/test/scripts/scale-gates.test.ts
index 5be3b9ed23..1702af3a2c 100644
--- a/test/scripts/scale-gates.test.ts
+++ b/test/scripts/scale-gates.test.ts
@@ -7,19 +7,20 @@
*/
import { describe, expect, test } from 'bun:test';
import {
- CEILINGS_MS, evaluateScaleGates, RATE_MIN_PAGES, HEADLINE_OP, HOT_TABLES, KEY_PLAN_OPS, phaseLimitsMs, PLANNER_HEALTH_ENFORCED, PLANNER_STATS_MIN_ROWS, resultHits, verdictLines,
- type GatePolicy, type ScaleReport,
+ CEILINGS_MS, evaluateScaleGates, importProgressPerFile, RATE_MIN_PAGES, HEADLINE_OP, HOT_TABLES, KEY_PLAN_OPS, phaseLimitsMs, PLANNER_HEALTH_ENFORCED, PLANNER_STATS_MIN_ROWS,
+ rateMeasure, resultHits, verdictLines, type GatePolicy, type RateMeasure, type ScaleReport,
} from '../../scripts/scale/gates.ts';
const ENFORCE: GatePolicy = { enforce: true, enforcePlanner: PLANNER_HEALTH_ENFORCED, enforceCeilings: false };
const PLAN = { sql: 'SELECT 1', execution_ms: 1, inner_loops: 3, text: 'Result (actual rows=1 loops=1)' };
+const STEADY: RateMeasure = { rate_ratio: 1.1, total_vs_half: 2.1, per_page_ms_first10: 10, per_page_ms_last10: 11, total_ms: 105_000, ms_at_half: 50_000 };
function passingReport(): ScaleReport {
const ops = ['get_health', 'list_pages', HEADLINE_OP, 'get_backlinks', 'find_orphans', 'query (hybrid, injected vector)']
.map(op => ({ op, p50_ms: 10, runs_ms: [10, 10, 10, 10, 10], known_answer: 'pass' as const, plan: { statements: 1, slowest: PLAN, worst_loops: PLAN } }));
return {
engine: 'pglite', pages: 10_000, seed: 1, import_mode: 'cli',
- import: { rate_ratio: 1.1, total_vs_half: 2.1, per_page_ms_first10: 10, per_page_ms_last10: 11 },
+ import: { wall: { ...STEADY }, cpu: { ...STEADY } },
planner: { hot_table_stat_rows: Object.fromEntries(HOT_TABLES.map(t => [t, 3])), hot_table_rows: Object.fromEntries(HOT_TABLES.map(t => [t, 10_000])), probed_after: 'get_health' },
ops,
data: [{ check: 'noop_reimport_writes_nothing', status: 'pass' }],
@@ -101,15 +102,66 @@ describe('scale gates under --enforce', () => {
test('import rate fails on either ratio: last-10% cost, or total vs the halfway mark', () => {
const slowTail = passingReport();
- slowTail.import = { ...slowTail.import, rate_ratio: 2.3, per_page_ms_last10: 23 };
+ slowTail.import.cpu = { ...STEADY, rate_ratio: 2.3, per_page_ms_last10: 23 };
expect(evaluateScaleGates(slowTail, ENFORCE).failures.map(f => f.gate)).toEqual(['import_rate']);
const slowHalf = passingReport();
- slowHalf.import = { ...slowHalf.import, total_vs_half: 2.6 };
+ slowHalf.import.cpu = { ...STEADY, total_vs_half: 2.6 };
expect(evaluateScaleGates(slowHalf, ENFORCE).failures.map(f => f.gate)).toEqual(['import_rate']);
const tiny = { ...slowHalf, pages: RATE_MIN_PAGES - 1 };
expect(evaluateScaleGates(tiny, ENFORCE)).toMatchObject({ exitCode: 0, reportOnlyBreaches: [expect.objectContaining({ gate: 'import_rate' })] });
});
+ // A shared CI host that takes the CPU away mid-import inflates wall time but not the import
+ // process's CPU time; a brain whose per-page work really grows raises both.
+ describe('import rate from the progress stream', () => {
+ const PAGES = 10_000;
+ function progressStream(perPage: (i: number) => { wall: number; cpu: number }): string {
+ let wall = 0;
+ let cpu = 0;
+ const lines = ['{"event":"start","phase":"import.files","total":10000,"ts":"t"}', 'a non-JSON warning line'];
+ for (let i = 0; i < PAGES; i++) {
+ const page = perPage(i);
+ wall += page.wall;
+ cpu += page.cpu;
+ lines.push(JSON.stringify({ event: 'tick', phase: 'import.files', done: i + 1, total: PAGES, elapsed_ms: wall, cpu_ms: cpu, ts: 't' }));
+ }
+ return lines.join('\n');
+ }
+ function importRateGate(engine: ScaleReport['engine'], stderr: string) {
+ const { wallMs, cpuMs } = importProgressPerFile(stderr);
+ const report = { ...passingReport(), engine, import: { wall: rateMeasure(wallMs), cpu: rateMeasure(cpuMs) } };
+ return evaluateScaleGates(report, ENFORCE).results.find(r => r.gate === 'import_rate')!;
+ }
+ const lastTenth = (i: number) => i >= PAGES * 0.9;
+
+ test('wall time spiking while CPU time stays flat passes on PGLite and still fails on Postgres', () => {
+ const stolen = progressStream(i => ({ wall: lastTenth(i) ? 13 : 5, cpu: 5 }));
+ const pglite = importRateGate('pglite', stolen);
+ expect(pglite.status).toBe('pass');
+ expect(pglite.message).toContain('import rate (cpu time): last 10% per-page cost 5 ms is 1x the first 10%');
+ expect(pglite.message).toContain('Not judged on pglite: wall time ratio 2.6');
+ const postgres = importRateGate('postgres', stolen);
+ expect(postgres.status).toBe('fail');
+ expect(postgres.message).toContain('import rate (wall time): last 10% per-page cost 13 ms is 2.6x the first 10%');
+ });
+
+ test('CPU time rising with the brain fails on both engines', () => {
+ const growing = progressStream(i => ({ wall: lastTenth(i) ? 13 : 5, cpu: lastTenth(i) ? 12 : 5 }));
+ expect(importRateGate('pglite', growing)).toMatchObject({ status: 'fail', enforced: true });
+ expect(importRateGate('postgres', growing)).toMatchObject({ status: 'fail', enforced: true });
+ });
+
+ test('a tick without cpu_ms, or a missing tick, leaves NaN for the harness to reject', () => {
+ const stream = progressStream(() => ({ wall: 5, cpu: 5 })).split('\n');
+ stream[5] = stream[5]!.replace(/,"cpu_ms":\d+/, '');
+ stream.splice(9, 1);
+ const { wallMs, cpuMs } = importProgressPerFile(stream.join('\n'));
+ expect(wallMs).toHaveLength(PAGES);
+ expect(Number.isNaN(cpuMs[3]!) && Number.isNaN(cpuMs[4]!)).toBe(true);
+ expect(wallMs.filter(ms => !Number.isFinite(ms))).toHaveLength(2);
+ });
+ });
+
test('a failed data check (no-op re-import wrote rows) exits 1 naming the check', () => {
const report = passingReport();
report.data = [{ check: 'noop_reimport_writes_nothing', status: 'fail', detail: 're-importing the unchanged corpus imported 3 page(s)' }];