Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(scale): enforce planner health and the budgets phase timer since F4b; probe hot-table stats after the first timed op, only tables above 500 rows

garrytana704696c08d6
diff --git a/.github/workflows/scale-tier.yml b/.github/workflows/scale-tier.yml
index 575ad8f102..167c58c60b 100644
--- a/.github/workflows/scale-tier.yml
+++ b/.github/workflows/scale-tier.yml
@@ -10,10 +10,10 @@ name: Scale tier
# five nightly reports);
# - workflow_dispatch: the size you pass.
#
-# Enforced from day one: import rate, known answers, no-op re-import, no
-# duplicates across sources, the import phase timer. Planner health and the
-# budgets phase timer are report-only until F4b (PLANNER_HEALTH_ENFORCED in
-# scripts/scale/gates.ts). Interactive ceilings
+# Enforced: import rate, known answers, no-op re-import, no duplicates across
+# sources, the import phase timer, planner health (probed after the first
+# timed op, hot tables above 500 rows) and the budgets phase timer
+# (PLANNER_HEALTH_ENFORCED in scripts/scale/gates.ts). Interactive ceilings
# and calibrated budgets stay report-only until `bun scripts/scale/trend.ts`
# prints "ceilings stable" and a reviewer sets the repo variable
# GBRAIN_SCALE_ENFORCE_CEILINGS=1.
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 2746d3de19..85ac56027a 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -300,9 +300,12 @@ Exit codes: 0 when every enforced gate passes, or always without `--enforce`;
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).
Enforced under `--enforce`: import rate, known answers, no-op re-import,
-no duplicates across sources, the import phase timer. The stats-dependent
-gates, planner health and the budgets phase timer, are report-only until F4b
-lands (`PLANNER_HEALTH_ENFORCED` in `scripts/scale/gates.ts`).
+no duplicates across sources, the import phase timer, and the stats-dependent
+gates (`PLANNER_HEALTH_ENFORCED` in `scripts/scale/gates.ts`): the Nested Loop
+inner-loop gate on the key plans, the budgets phase timer, and planner stats.
+Planner stats are probed after the first timed op, because F4b analyzes on the
+first planner-sensitive read, and only hot tables above 500 rows must have
+`pg_stats` rows.
Interactive ceilings and calibrated budgets (`scripts/scale/budgets.json`,
written by `--calibrate`) stay report-only until
`bun scripts/scale/trend.ts` prints "ceilings stable" over the last five
diff --git a/scripts/scale/gates.ts b/scripts/scale/gates.ts
index c91b007266..a07263037e 100644
--- a/scripts/scale/gates.ts
+++ b/scripts/scale/gates.ts
@@ -15,16 +15,18 @@
* variable GBRAIN_SCALE_ENFORCE_CEILINGS=1.
*/
+import { PLANNER_STATS_MIN_PENDING } from '../../src/core/planner-stats.ts';
+
/**
* The one switch for the stats-dependent gates: planner health (hot-table
- * statistics after import, Nested Loop inner loops in the key plans) and the
- * budgets phase timer, whose time un-analyzed plans dominate (12 s get_health,
- * 40 s source-scoped search at 10k PGLite pages). Report-only until F4b
- * (planner-stats ANALYZE during import, after GBRA-39's ad7252a) lands:
- * before it, PGLite has no statistics after an import and this gate would
- * fail every run. Flip to true in the commit that merges F4b.
+ * statistics after the first read, Nested Loop inner loops in the key plans)
+ * and the budgets phase timer, whose time un-analyzed plans dominate. On since
+ * F4b (row-delta ANALYZE during import and on the first planner-sensitive
+ * read): at 10k PGLite pages its key plans run 42-52 inner loops against a
+ * 100k gate and the budgets phase 25 s against 300 s. Set false to make them
+ * report-only again.
*/
-export const PLANNER_HEALTH_ENFORCED = false;
+export const PLANNER_HEALTH_ENFORCED = true;
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. */
@@ -32,6 +34,12 @@ export const RATE_MIN_PAGES = 1000;
export const TOTAL_VS_HALF_MAX = 2.5;
export const LOOPS_PER_PAGE_MAX = 10;
export const HOT_TABLES = ['pages', 'links', 'content_chunks', 'timeline_entries', 'facts', 'takes'] as const;
+/**
+ * The planner-stats gate checks only hot tables holding more than this many rows: F4b analyzes a
+ * table once its pending row count passes max(500, 10% of its rows), so a smaller table may
+ * correctly have no statistics yet.
+ */
+export const PLANNER_STATS_MIN_ROWS = PLANNER_STATS_MIN_PENDING;
/** The plans the planner-health gate inspects (every captured read statement of these ops). */
export const KEY_PLAN_OPS = ['get_backlinks', 'search (MCP path, remote)', 'get_health', 'find_orphans'] as const;
export const HEADLINE_OP = 'search (MCP path, remote)';
@@ -68,7 +76,11 @@ export interface ScaleReport {
seed: number;
import_mode: 'cli' | 'content';
import: { rate_ratio: number; total_vs_half: number; per_page_ms_first10: number; per_page_ms_last10: number };
- planner: { hot_table_stat_rows: Record<string, number> };
+ /**
+ * 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.
+ */
+ planner: { hot_table_stat_rows: Record<string, number>; hot_table_rows: Record<string, number>; probed_after: string };
ops: OpResult[];
data: DataCheck[];
phases_ms: Record<string, number>;
@@ -107,11 +119,13 @@ export function evaluateScaleGates(report: ScaleReport, policy: GatePolicy): Gat
+ `total import time is ${total_vs_half}x the time at the halfway mark (gate <= ${TOTAL_VS_HALF_MAX}). `
+ `A rising per-page cost means import slows as the brain grows, usually stale planner statistics during import. Reproduce: ${repro}`);
- const missing = HOT_TABLES.filter(t => !(report.planner.hot_table_stat_rows[t]! > 0));
+ const { hot_table_stat_rows: statRows, hot_table_rows: tableRows, probed_after: probedAfter } = report.planner;
+ const missing = HOT_TABLES.filter(t => tableRows[t]! > PLANNER_STATS_MIN_ROWS && !(statRows[t]! > 0));
add('planner_stats', missing.length === 0, policy.enforcePlanner,
- missing.length === 0 ? 'planner stats: every hot table has pg_stats rows after import'
- : `planner stats: no pg_stats rows after import for ${missing.join(', ')}; the planner is guessing row counts on these tables. `
- + `Shipped import must leave statistics behind (F4b). Reproduce: ${repro}`);
+ missing.length === 0 ? `planner stats: every hot table above ${PLANNER_STATS_MIN_ROWS} rows has pg_stats rows after ${probedAfter}`
+ : `planner stats: no pg_stats rows after ${probedAfter} for ${missing.map(t => `${t} (${tableRows[t]} rows)`).join(', ')}; `
+ + 'the planner is guessing row counts on these tables. Import and the first planner-sensitive read must leave statistics behind (F4b); '
+ + `check \`gbrain doctor\` planner_stats_stale and run \`gbrain repair planner-stats --apply\` to confirm. Reproduce: ${repro}`);
const loopsLimit = LOOPS_PER_PAGE_MAX * report.pages;
for (const name of KEY_PLAN_OPS) {
@@ -174,7 +188,7 @@ export function verdictLines(report: ScaleReport, verdict: GateVerdict, policy:
} else if (verdict.failures.length > 0) {
lines.push(`[scale] ${verdict.failures.length} enforced gate(s) failed; exit 1. Fix the named op or phase, then rerun: ${reproduceCommand(report)}`);
} else {
- lines.push(`[scale] all enforced gates passed (planner health and the budgets phase timer ${policy.enforcePlanner ? 'enforced' : 'report-only until F4b'}, `
+ lines.push(`[scale] all enforced gates passed (planner health and the budgets phase timer ${policy.enforcePlanner ? 'enforced' : 'report-only (PLANNER_HEALTH_ENFORCED=false)'}, `
+ `ceilings ${policy.enforceCeilings ? 'enforced' : 'report-only until GBRAIN_SCALE_ENFORCE_CEILINGS=1'}).`);
}
return lines;
diff --git a/scripts/scale/run.ts b/scripts/scale/run.ts
index 77c2611fbc..e79131362a 100644
--- a/scripts/scale/run.ts
+++ b/scripts/scale/run.ts
@@ -15,8 +15,8 @@
* per source, timing each file from its progress events; `--import-mode
* content` keeps the per-page `importFromContent` loop. Then it extracts
* links, timeline, facts and takes, writes deterministic vectors onto every
- * chunk, and measures: import rate, planner health (pg_stats on hot tables,
- * Nested Loop inner loops in the captured plans of the key ops), p50 over
+ * chunk, and measures: import rate, planner health (pg_stats on hot tables
+ * above 500 rows, read after the first timed op; Nested Loop inner loops in the captured plans of the key ops), p50 over
* five runs after a warmup for each op with a known-answer check, a
* cold-process first query, two concurrent receipt-bearing writers, a no-op
* re-import and cross-source duplicates. scripts/scale/gates.ts decides.
@@ -31,7 +31,7 @@ import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { generateScaleFixture, SCALE_SOURCES, scaleVector, writeScaleCorpus, type ScaleFixture } from './fixture.ts';
import {
- BUDGET_MULTIPLIER, evaluateScaleGates, HEADLINE_OP, HOT_TABLES, PLANNER_HEALTH_ENFORCED, reproduceCommand, resultHits, verdictLines,
+ BUDGET_MULTIPLIER, evaluateScaleGates, HEADLINE_OP, HOT_TABLES, PLANNER_HEALTH_ENFORCED, PLANNER_STATS_MIN_ROWS, reproduceCommand, resultHits, verdictLines,
type DataCheck, type GatePolicy, type OpPlan, type OpResult, type PlanStatement, type ScaleReport,
} from './gates.ts';
@@ -280,11 +280,6 @@ async function main(): Promise<FullReport> {
});
console.log(`[scale] extracted links/timeline, ${extract.factsInserted} facts, ${extract.takesUpserted} takes in ${phases.extract} ms`);
- // Planner health is read here: after import and extraction, before anything else touches statistics.
- const statRows: Record<string, number> = {};
- for (const table of HOT_TABLES) {
- statRows[table] = Number((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pg_stats WHERE tablename = $1', [table]))[0]?.n ?? 0);
- }
// Deterministic vectors on every chunk, so the vector arm runs keylessly through queryEmbedFn.
const dim = await timed('vectors', async () => {
@@ -358,6 +353,9 @@ async function main(): Promise<FullReport> {
verify: r => fixture.islands.every(slug => resultHits(r).some(h => h.slug === slug)) ? null : 'an island page is missing from find_orphans' },
];
const ops: OpResult[] = [];
+ const statRows: Record<string, number> = {};
+ const tableRows: Record<string, number> = {};
+ let probedAfter = '';
await timed('ops', async () => {
for (const check of checks) {
let result: unknown;
@@ -379,6 +377,16 @@ async function main(): Promise<FullReport> {
}
const detail = error ?? check.verify(result) ?? undefined;
ops.push({ op: check.op, p50_ms: round1(median(runs)), runs_ms: runs.map(r => Math.round(r)), known_answer: detail ? 'fail' : 'pass', ...(detail ? { detail } : {}), ...(plan ? { plan } : {}) });
+ // Planner health is read after the first timed op, not right after import: F4b analyzes on the first planner-sensitive read by design.
+ if (!probedAfter) {
+ probedAfter = check.op;
+ for (const table of HOT_TABLES) {
+ const [row] = await engine.executeRaw<{ stats: number; n: number }>(
+ `SELECT (SELECT count(*) FROM pg_stats WHERE tablename = $1)::int AS stats, (SELECT count(*) FROM ${table})::int AS n`, [table]);
+ statRows[table] = Number(row?.stats ?? 0);
+ tableRows[table] = Number(row?.n ?? 0);
+ }
+ }
}
});
@@ -459,14 +467,15 @@ async function main(): Promise<FullReport> {
harness: 'gbrain-scale', mode: enforce ? 'enforce' : 'report-only', engine: engineKind, seed, pages: fixture.pages.length,
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 (F4b pending)', ceilings: policy.enforceCeilings ? 'enforced' : 'report-only' },
+ 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,
},
extract,
- planner: { hot_table_stat_rows: statRows, tables_without_stats: HOT_TABLES.filter(t => statRows[t] === 0) },
+ 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,
...(budgets[budgetKey] ? { budgets_ms: budgets[budgetKey] } : {}),
};
@@ -491,7 +500,7 @@ try {
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)`);
- console.log(`[scale] planner: tables without stats: ${report.planner.tables_without_stats.join(', ') || 'none'}`);
+ 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/test/scripts/scale-gates.test.ts b/test/scripts/scale-gates.test.ts
index e05204b1c9..3e62511a3b 100644
--- a/test/scripts/scale-gates.test.ts
+++ b/test/scripts/scale-gates.test.ts
@@ -7,7 +7,7 @@
*/
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, resultHits, verdictLines,
+ 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,
} from '../../scripts/scale/gates.ts';
@@ -20,7 +20,7 @@ function passingReport(): ScaleReport {
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 },
- planner: { hot_table_stat_rows: Object.fromEntries(HOT_TABLES.map(t => [t, 3])) },
+ 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' }],
phases_ms: { import: 60_000, budgets: 30_000 },
@@ -131,11 +131,24 @@ describe('scale gates under --enforce', () => {
const on = evaluateScaleGates(report, { ...ENFORCE, enforcePlanner: true });
expect(on.exitCode).toBe(1);
expect(on.failures.map(f => f.gate)).toEqual(['planner_stats', 'planner_loops:get_health']);
- expect(on.failures[0]!.message).toContain('no pg_stats rows after import for links');
+ expect(on.failures[0]!.message).toContain('no pg_stats rows after get_health for links (10000 rows)');
expect(on.failures[1]!.explain).toContain('Seq Scan on links (loops=100001)');
expect(KEY_PLAN_OPS).toContain('get_health');
});
+ test('planner health is enforced since F4b and checks only hot tables above the row threshold', () => {
+ expect(PLANNER_HEALTH_ENFORCED).toBe(true);
+ const small = passingReport();
+ small.planner.hot_table_stat_rows.takes = 0;
+ small.planner.hot_table_rows.takes = PLANNER_STATS_MIN_ROWS;
+ expect(evaluateScaleGates(small, ENFORCE)).toMatchObject({ exitCode: 0, failures: [] });
+ small.planner.hot_table_rows.takes = PLANNER_STATS_MIN_ROWS + 1;
+ const verdict = evaluateScaleGates(small, ENFORCE);
+ expect(verdict.failures.map(f => f.gate)).toEqual(['planner_stats']);
+ expect(verdict.failures[0]!.message).toContain(`no pg_stats rows after get_health for takes (${PLANNER_STATS_MIN_ROWS + 1} rows)`);
+ expect(verdict.failures[0]!.message).toContain('gbrain repair planner-stats --apply');
+ });
+
test('without --enforce every run exits 0 and says how many gates would fail', () => {
const report = passingReport();
report.ops[0] = { ...report.ops[0]!, known_answer: 'fail', detail: 'page_count 1 != 10000' };
diff --git a/test/scripts/scale-harness.slow.test.ts b/test/scripts/scale-harness.slow.test.ts
index eb8dac5dc4..6aede41524 100644
--- a/test/scripts/scale-harness.slow.test.ts
+++ b/test/scripts/scale-harness.slow.test.ts
@@ -30,6 +30,11 @@ test('a 40-page enforced PGLite run passes every enforced gate and writes a head
expect(report.headline.metric).toBe('MCP search p50 at 40 brain pages, as shipped (no manual ANALYZE)');
expect(report.ops.filter((o: { known_answer: string }) => o.known_answer !== 'pass')).toEqual([]);
expect(report.data.every((d: { status: string }) => d.status === 'pass')).toBe(true);
+ // Planner health is probed after the first timed op (F4b analyzes on the first planner-sensitive read), with each table's row count.
+ expect(report.planner.probed_after).toBe(report.ops[0].op);
+ 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');
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 {