Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(scale): report-only scale harness skeleton, bun run test:scale -- --pages N (O-CEO-16, O-DX-12)

garrytand79edb4b6887
diff --git a/docs/TESTING.md b/docs/TESTING.md
index f466558198..b6ce4b9bfe 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -267,6 +267,27 @@ E2E schedule does not shorten a PR critical path dominated by persistence.
Report matched executed timings separately from dry-run partition estimates,
including setup, queueing and retries; never count skip-only output as coverage.
+### Scale tier
+
+`bun run test:scale -- --pages 2000 [--seed 1] [--out <file.json>]` is the
+contributor scale loop (`scripts/scale/run.ts`). It generates a deterministic
+two-source brain from the seed (`scripts/scale/fixture.ts`; links, timeline
+bullets, partly overlapping bodies, island pages; no embeddings), imports it
+into a fresh in-memory PGLite brain under a temporary `GBRAIN_HOME`, runs
+`extract all --source db`, and writes a JSON report plus a summary: import
+rate (last 10% vs first 10% per-page cost), planner health (hot tables with
+statistics, the worst Nested Loop count in the backlink plan), and p50 over
+five runs after a warmup for `get_health`, `list_pages`, local and MCP-path
+`search`, `traverse_graph` depth 3, `get_backlinks` and `find_orphans`, each
+with a known-answer check. It is report-only: it exits 0 whatever the numbers
+say (a harness crash exits 1) and no CI job runs it yet. The gate shape,
+cadence and enforcement are defined once, by O-CEO-16 and O-ENG-16 in the
+fix-wave-8 plan: rate, planner-health and known-answer checks become enforced
+in the F4 scale tier, and interactive ceilings stay report-only until five
+consecutive nightly runs are stable. Reproduce a report with its printed seed
+and page count. The fixture's determinism is pinned by
+`test/scripts/scale-fixture.test.ts`.
+
### Authoring gate
Before adding a test, answer four questions in the PR description or the test
diff --git a/llms-full.txt b/llms-full.txt
index 53d90d6a17..9ca6c90b1b 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -4203,6 +4203,7 @@ names — reasons may be added, never renamed or removed). All 16:
| `db_missing` | 3D000 — the named database does not exist |
| `schema_missing` | 42P01/42703 — pending migrations (`gbrain apply-migrations --yes`; excluded from the db-repair marker on the MCP mid-operation path, where it usually means code skew) |
| `pgvector_missing` | the vector extension is absent — auto tier creates it |
+| `storage_corrupt` | XX001/XX002, or an XX000 such as `unexpected chunk number … for toast value` or `tuple concurrently deleted` — stored data is damaged; db-repair stops at manual and names the first step, `gbrain repair orphan-children` (preview, includes the torn-TOAST probe; [orphan children](guides/repair.md#orphan-children)) |
| `unknown` | unclassified — redacted error + `gbrain doctor` |
The classifier lives in `src/core/pg-access-classify.ts`; remediation copy has
@@ -8762,6 +8763,7 @@ should also check `results[].complete`.
| `orphan-bindings` | `orphan_persistence_bindings` | Deletes persistence source bindings whose source was removed, or that belong to an earlier incarnation of a source re-added under the same id. Releases before this one left the binding behind on `gbrain sources remove` and `gbrain sources purge`, so the re-added source read as claimed and every `gbrain sync --source <id>` failed with `writer_coordinator_required`. Bookkeeping only: no journal admission, no page or file changes, and it runs brain-wide (`--source` does not narrow it). See [orphan bindings](#orphan-bindings). | A binding that a queued, running or recovering write request of the same source incarnation still references. |
| `embedding-effects` | `stale_embedding_effects` | Settles stale queued and failed embedding effects of committed writes, which block receipt compaction and activation: `reconciled` when current vectors pass the effect verifier, `superseded` when the page was deleted or a newer revision owns its own effect, `retry_queued` for the owner (paid; a used-up retry allowance gets one new bounded cycle per explicit apply). See [stale queued embedding effects](#stale-queued-embedding-effects). | `blocked` effects, counted by reason (`owner_unavailable`, `embedding_disabled`, `embedding_unconfigured`, `projection_pending`, `no_replacement_obligation`). |
| `safe-chunks` | `safe_index_pending` (also `contextual_retrieval_coverage`, `details.unsealed_pages`) | Rebuilds the chunks of markdown and code pages indexed before the safe-chunk fence, which remote and MCP search withhold. It rebuilds projections only: no page write, no new page version and no request ID. Vectors whose embedding input did not change are kept; the rest are embedded unless you pass `--no-embed` or no embedding model is configured. | `code_without_source_path`: code pages with no recorded file to re-chunk. `unsupported_page_kind`: other page kinds, such as images. Their importer re-seals them. |
+| `orphan-children` | `child_table_orphans` (also a `storage_corrupt` error) | Explicit-only. Deletes rows of page child tables (chunks, versions, tags, takes, raw data, timeline, links) whose page row no longer exists, and clears dangling `links.origin_page_id` and `files.page_id` references, each in one statement that rechecks the orphan condition. See [orphan children](#orphan-children). | `torn_pages`: page rows whose stored body cannot be read (torn TOAST). The preview names them; the repair never changes them. |
| `contextual-mode` | `contextual_retrieval_coverage` (pages with no recorded mode) | Stamps the contextual retrieval mode on markdown pages imported without one (for example by a large `--no-embed` sync or a connector source before this release), exactly as a fresh import of the page would: the page, source and brain settings decide, and the per-chunk synopsis tier lands at the free title tier. It rebuilds projections only: no page write, no new page version and no request ID. A page whose stored vectors already match the stamped convention keeps them and queues no re-embedding; a page whose embedding input changes has only those vectors cleared and is re-embedded once, unless you pass `--no-embed`. | `unsealed_projection`: pages whose chunks lag their text; `gbrain embed --stale` or `safe-chunks` seals them first, and the next run stamps them. `embed_skip`: pages marked to skip embedding keep their stored vectors and are not stamped. |
gbrain repair google-file-modes --apply # explicit-only: runs only when named
gbrain repair --all --apply # every automatic kind in order
@@ -8957,6 +8959,40 @@ Do not delete binding rows by hand: the repair rechecks, in the same
statement, that the binding is still orphaned and that no pending write
request uses it.
+### Orphan children
+
+**Say to your agent:** *"gbrain fails with `unexpected chunk number` or
+`tuple concurrently deleted`, or doctor warns `child_table_orphans`. Fix it."*
+
+These errors (SQLSTATE XX000) mean stored data is damaged, usually after a
+crash or a full disk. Child rows can outlive their page row, and a page body
+can be torn, so every command that reads it fails. Preview first; it changes
+nothing:
+
+```bash
+gbrain repair orphan-children # orphan child rows per table, plus torn_pages
+gbrain repair orphan-children --apply # deletes the orphan rows, clears dangling references
+gbrain doctor # child_table_orphans is ok
+```
+
+The preview also reads every page body and lists the rows it cannot read
+(`torn_pages`, with page id, source and slug). The repair never changes those
+rows. Recover them from a backup, or create a fresh brain and sync it again
+from its source files. Until then, a write that names the revision of a page
+the upgrade could not backfill is refused with `revision_backfill_pending`;
+`gbrain apply-migrations --yes` resumes that backfill and prints its progress.
+
+### Timeline history scan coverage
+
+Doctor's `timeline_history` check classifies at most 2,000 pages or 10
+seconds of work per run. On a larger brain each run continues where the last
+one stopped (the cursor is kept in the config row
+`doctor.timeline_history.scan:<sources>`), so a few consecutive `gbrain doctor`
+runs finish a full pass and report exact counts. While the next pass is in
+progress, a clean finished pass keeps the check `ok` until a newer timeline row
+is written. A run that has neither says `scan incomplete` and is a lower bound;
+`gbrain repair timeline` (preview) counts the whole brain in one go.
+
### Stale atoms
`gbrain repair stale-atoms` (explicit-only, #5770) retires atoms that drifted
@@ -9592,6 +9628,7 @@ a receipt can report has a row here.
| `writer_pool_capacity` | `writer_pool_capacity` | The canonical owner has no free publication slot right now; the write stays queued. | Wait and poll the receipt (`gbrain write-request <id>`). If it persists, check `gbrain sources writer status <source>`. |
| `revision_required` | `revision_required` | The operation must be bound to a revision you reviewed (for example `--if-version` or `expected_revision`), and none was given. | Preview first, then repeat with the revision the preview printed. |
| `revision_conflict` | `revision_conflict` | The page changed after the revision this write was bound to. Nothing was overwritten. | Re-read the page, merge your change, and save with the new revision. |
+| `revision_backfill_pending` | `revision_backfill_pending` | The page was written before page revisions existed (an upgrade from below schema v150) and the resumable revision backfill has not reached it, so it has no revision to bind to. Its revision reads as `backfill_pending`, never a UUID. Nothing was written. | Resume the backfill with `gbrain apply-migrations --yes` (it prints its progress). If it reports rows it could not update, run `gbrain repair orphan-children` to preview orphaned child rows and torn page bodies ([orphan children](repair.md#orphan-children)). |
| `idempotency_conflict` | `idempotency_conflict` | The `request_id` was already used for a different target, content or protocol. | Use a new `request_id` for a different write; reuse an ID only to replay the same write. |
| `write_pending` | `write_pending` | The write was accepted but has not committed yet, or its acknowledgment was lost. It keeps its request ID. | Poll `gbrain write-request <id>`, or repeat the same command with the same options to resume. |
| `storage_error` | `storage_error` | The write did not commit for a reason with no more specific code. | Inspect the durable request with `gbrain write-request <id>` on the source host and follow its message. |
diff --git a/package.json b/package.json
index 8596f78620..b198796263 100644
--- a/package.json
+++ b/package.json
@@ -84,6 +84,7 @@
"test:compile-smoke": "GBRAIN_SELFUPDATE_COMPILE_SMOKE=1 bun test test/binary-self-update-compiled.serial.test.ts",
"test:e2e": "bash scripts/run-e2e.sh",
"test:slow": "bash scripts/run-slow-tests.sh",
+ "test:scale": "bun scripts/scale/run.ts",
"test:heavy": "bash scripts/run-heavy.sh",
"test:profile": "bash scripts/profile-tests.sh",
"test:serial": "bash scripts/run-serial-tests.sh",
diff --git a/scripts/scale/fixture.ts b/scripts/scale/fixture.ts
new file mode 100644
index 0000000000..ef323ac62d
--- /dev/null
+++ b/scripts/scale/fixture.ts
@@ -0,0 +1,78 @@
+/**
+ * Deterministic synthetic brain for the report-only scale harness
+ * (`bun run test:scale`, docs/TESTING.md "Scale tier"). Same seed and page
+ * count always produce the same pages, links and known answers, so a report
+ * can be reproduced from its printed seed. No embeddings, no provider calls.
+ *
+ * Two sources: `default` and `scale-b`. About a third of `scale-b` bodies copy
+ * a `default` body (partly overlapping corpora). Each page links to three
+ * pages of its own source, carries two dated timeline bullets and a unique
+ * search token. A few island pages have no links in or out (known orphans).
+ */
+
+export interface ScalePage { sourceId: string; slug: string; content: string; token: string; links: string[] }
+export interface ScaleFixture {
+ seed: number;
+ pages: ScalePage[];
+ /** Island pages: no inbound or outbound links. */
+ islands: string[];
+ /** A `default` page with outbound links, for traversal and backlink queries. */
+ hub: string;
+}
+
+export const SCALE_SOURCES = ['default', 'scale-b'] as const;
+const WORDS = ['ledger', 'harbor', 'quartz', 'meadow', 'signal', 'lantern', 'orbit', 'canvas', 'summit', 'thicket', 'ember', 'falcon',
+ 'garnet', 'hollow', 'island', 'juniper', 'kestrel', 'linden', 'marble', 'nectar', 'oracle', 'pepper', 'quiver', 'russet'];
+
+function mulberry32(seed: number): () => number {
+ let a = seed >>> 0;
+ return () => {
+ a = (a + 0x6d2b79f5) >>> 0;
+ let t = a;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+function kindFor(i: number): 'people' | 'companies' | 'notes' {
+ const r = i % 10;
+ return r < 2 ? 'people' : r < 3 ? 'companies' : 'notes';
+}
+
+export function generateScaleFixture(opts: { pages: number; seed: number }): ScaleFixture {
+ if (!Number.isInteger(opts.pages) || opts.pages < 20) throw new Error('scale fixture needs at least 20 pages');
+ const rand = mulberry32(opts.seed);
+ const pick = <T,>(items: readonly T[]) => items[Math.floor(rand() * items.length)]!;
+ const perSource = [Math.ceil(opts.pages / 2), Math.floor(opts.pages / 2)];
+ const slugsBySource = SCALE_SOURCES.map((_, s) => Array.from({ length: perSource[s]! }, (_, i) => `${kindFor(i)}/scale-${s}-${i}`));
+ const islandEvery = 97;
+ const isIsland = (i: number) => i % islandEvery === islandEvery - 1;
+ const pages: ScalePage[] = [];
+ const defaultBodies: string[] = [];
+ for (const [s, sourceId] of SCALE_SOURCES.entries()) {
+ const slugs = slugsBySource[s]!;
+ const linkable = slugs.filter((_, i) => !isIsland(i));
+ for (const [i, slug] of slugs.entries()) {
+ const token = `scaletok${s}x${i}`;
+ const links = isIsland(i) ? [] : Array.from({ length: 3 }, () => pick(linkable)).filter(target => target !== slug);
+ const reuse = s === 1 && i % 3 === 0 && defaultBodies.length > 0;
+ const prose = reuse ? defaultBodies[i % defaultBodies.length]!
+ : Array.from({ length: 3 }, () => Array.from({ length: 24 }, () => pick(WORDS)).join(' ') + '.').join('\n\n');
+ if (s === 0) defaultBodies.push(prose);
+ const month = String(1 + Math.floor(rand() * 12)).padStart(2, '0');
+ const day = String(1 + Math.floor(rand() * 28)).padStart(2, '0');
+ const content = [
+ '---', `title: Scale ${s} ${i}`, `type: ${kindFor(i) === 'people' ? 'person' : kindFor(i) === 'companies' ? 'company' : 'note'}`, '---',
+ `# Scale ${s} ${i}`, '', `${prose} Marker ${token}.`, '',
+ ...links.map(target => `See [[${target}]].`), '',
+ '## Timeline', '', `- **2025-${month}-${day}** | Scale event ${i} recorded`, `- **2026-${month}-${day}** | Scale follow-up ${i}`, '',
+ ].join('\n');
+ pages.push({ sourceId, slug, content, token, links });
+ }
+ }
+ const islands = pages.filter(p => p.sourceId === 'default' && p.links.length === 0
+ && !pages.some(other => other.sourceId === 'default' && other.links.includes(p.slug))).map(p => p.slug);
+ const hub = pages.find(p => p.sourceId === 'default' && p.links.length === 3)!.slug;
+ return { seed: opts.seed, pages, islands, hub };
+}
diff --git a/scripts/scale/run.ts b/scripts/scale/run.ts
new file mode 100644
index 0000000000..31495d043f
--- /dev/null
+++ b/scripts/scale/run.ts
@@ -0,0 +1,153 @@
+#!/usr/bin/env bun
+/**
+ * Report-only scale harness (fix wave 8 skeleton of the F4 scale tier).
+ *
+ * bun run test:scale -- --pages 2000 [--seed 1] [--out <file.json>]
+ *
+ * Generates the deterministic fixture (scripts/scale/fixture.ts), imports it
+ * into a fresh in-memory PGLite brain under a temporary GBRAIN_HOME (never
+ * ~/.gbrain), and reports: import rate (last 10% vs first 10% per-page cost),
+ * planner health (statistics on the hot tables after import, no Nested Loop
+ * with loops above 10x pages in the backlink plan), and p50 timings over five
+ * runs after a warmup for the key operations, each with a known-answer check.
+ * Gate shape and cadence: O-CEO-16 / O-ENG-16 in docs/TESTING.md "Scale tier".
+ *
+ * REPORT-ONLY: exits 0 whatever the numbers or checks say; a crash exits 1.
+ */
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join, resolve } from 'node:path';
+import { generateScaleFixture, SCALE_SOURCES } from './fixture.ts';
+
+interface OpReport { op: string; p50_ms: number; runs_ms: number[]; known_answer: 'pass' | 'fail'; detail?: string }
+
+function flag(name: string, fallback: string): string {
+ const i = process.argv.indexOf(name);
+ return i >= 0 && process.argv[i + 1] ? process.argv[i + 1]! : fallback;
+}
+
+const pagesArg = Number(flag('--pages', '2000'));
+const seed = Number(flag('--seed', '1'));
+if (!Number.isInteger(pagesArg) || pagesArg < 20 || !Number.isInteger(seed)) {
+ console.error('Usage: bun run test:scale -- --pages <N >= 20> [--seed <int>] [--out <file.json>]');
+ process.exit(2);
+}
+const out = resolve(flag('--out', join('.context', 'scale', `report-pglite-${pagesArg}-seed${seed}.json`)));
+const home = mkdtempSync(join(tmpdir(), 'gbrain-scale-'));
+process.env.GBRAIN_HOME = home;
+delete process.env.DATABASE_URL;
+delete process.env.GBRAIN_DATABASE_URL;
+
+const { PGLiteEngine } = await import('../../src/core/pglite-engine.ts');
+const { importFromContent } = await import('../../src/core/import-file.ts');
+const { operations } = await import('../../src/core/operations.ts');
+const { runExtract } = await import('../../src/commands/extract.ts');
+
+const median = (xs: number[]) => [...xs].sort((a, b) => a - b)[Math.floor(xs.length / 2)]!;
+
+async function main() {
+ console.log(`[scale] seed=${seed} pages=${pagesArg} engine=pglite (report-only)`);
+ const fixture = generateScaleFixture({ pages: pagesArg, seed });
+ const engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ for (const sourceId of SCALE_SOURCES) {
+ if (sourceId !== 'default') await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT DO NOTHING', [sourceId]);
+ }
+
+ const perPage: number[] = [];
+ const importStart = performance.now();
+ for (const page of fixture.pages) {
+ const t = performance.now();
+ 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 importMs = performance.now() - importStart;
+ const extractStart = performance.now();
+ await runExtract(engine, ['all', '--source', 'db', '--json']);
+ const extractMs = performance.now() - extractStart;
+ const tenth = Math.max(1, Math.floor(perPage.length / 10));
+ const avg = (xs: number[]) => xs.reduce((a, b) => a + b, 0) / xs.length;
+ const rateRatio = avg(perPage.slice(-tenth)) / avg(perPage.slice(0, tenth));
+
+ const hotTables = ['pages', 'links', 'content_chunks', 'timeline_entries', 'facts', 'takes'];
+ const stats: Record<string, number> = {};
+ for (const table of hotTables) {
+ stats[table] = Number((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pg_stats WHERE tablename = $1', [table]))[0]?.n ?? 0);
+ }
+ const [{ id: hubId }] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE slug = $1 AND source_id = 'default'", [fixture.hub]);
+ const [plan] = await engine.executeRaw<{ 'QUERY PLAN': unknown }>(
+ `EXPLAIN (ANALYZE, FORMAT JSON) SELECT p.slug FROM links l JOIN pages p ON p.id = l.from_page_id WHERE l.to_page_id = $1`, [hubId]);
+ let worstLoops = 0;
+ const walk = (node: Record<string, unknown>) => {
+ if (node['Node Type'] === 'Nested Loop') worstLoops = Math.max(worstLoops, Number(node['Actual Loops'] ?? 0));
+ for (const child of (node.Plans as Array<Record<string, unknown>> | undefined) ?? []) walk(child);
+ };
+ for (const root of (plan!['QUERY PLAN'] as Array<{ Plan: Record<string, unknown> }>)) walk(root.Plan);
+
+ const local = { engine, config: {}, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false, sourceId: 'default' } as never;
+ const remote = { ...(local as object), remote: true, auth: { token: 't', clientId: 'scale', scopes: ['read'], allowedSources: [...SCALE_SOURCES] } } as never;
+ const op = (name: string) => operations.find(o => o.name === name)!;
+ const probe = fixture.pages[Math.floor(fixture.pages.length / 3)]!;
+ const hub = fixture.pages.find(p => p.slug === fixture.hub && p.sourceId === 'default')!;
+ const checks: Array<{ op: string; run: () => Promise<unknown>; verify: (result: unknown) => string | null }> = [
+ { op: 'get_health', run: () => op('get_health').handler(local, {}),
+ verify: r => Number((r as { page_count?: number }).page_count) === fixture.pages.length ? null : `page_count ${(r as { page_count?: number }).page_count} != ${fixture.pages.length}` },
+ { op: 'list_pages', run: () => op('list_pages').handler(local, { limit: 50 }),
+ verify: r => (r as unknown[]).length === 50 ? null : `${(r as unknown[]).length} rows, expected 50` },
+ { op: 'search (keyword, local)', run: () => op('search').handler(local, { query: probe.token, limit: 10, source_id: probe.sourceId }),
+ verify: r => JSON.stringify(r).includes(probe.slug) ? null : `${probe.slug} not returned for ${probe.token}` },
+ { op: 'search (MCP path, remote)', run: () => op('search').handler(remote, { query: probe.token, limit: 10 }),
+ verify: r => JSON.stringify(r).includes(probe.slug) ? null : `${probe.slug} not returned for ${probe.token}` },
+ { op: 'traverse_graph depth 3', run: () => op('traverse_graph').handler(local, { slug: fixture.hub, depth: 3 }),
+ verify: r => hub.links.every(target => JSON.stringify(r).includes(target)) ? null : 'a direct link target of the hub is missing' },
+ { op: 'get_backlinks', run: () => op('get_backlinks').handler(local, { slug: hub.links[0] }),
+ verify: r => JSON.stringify(r).includes(fixture.hub) ? null : `${fixture.hub} missing from backlinks of ${hub.links[0]}` },
+ { op: 'find_orphans', run: () => op('find_orphans').handler(local, {}),
+ verify: r => fixture.islands.every(slug => JSON.stringify(r).includes(slug)) ? null : 'an island page is missing from find_orphans' },
+ ];
+ const ops: OpReport[] = [];
+ for (const check of checks) {
+ let result: unknown;
+ let error: string | undefined;
+ const runs: number[] = [];
+ for (let i = 0; i < 6; i++) {
+ const t = performance.now();
+ try { result = await check.run(); } catch (e) { error = e instanceof Error ? e.message : String(e); }
+ if (i > 0) runs.push(performance.now() - t);
+ }
+ const detail = error ?? check.verify(result) ?? undefined;
+ ops.push({ op: check.op, p50_ms: Math.round(median(runs) * 10) / 10, runs_ms: runs.map(r => Math.round(r)), known_answer: detail ? 'fail' : 'pass', ...(detail ? { detail } : {}) });
+ }
+ await engine.disconnect();
+
+ const report = {
+ harness: 'gbrain-scale', mode: 'report-only', engine: 'pglite', seed, pages: fixture.pages.length, sources: SCALE_SOURCES,
+ runtime: { bun: Bun.version, platform: process.platform, arch: process.arch },
+ extract_db_ms: Math.round(extractMs),
+ import: { total_ms: Math.round(importMs), per_page_ms_first10: Math.round(avg(perPage.slice(0, tenth)) * 10) / 10,
+ per_page_ms_last10: Math.round(avg(perPage.slice(-tenth)) * 10) / 10, rate_ratio: Math.round(rateRatio * 100) / 100, gate_rate_ratio_max: 1.5 },
+ planner: { hot_table_stat_rows: stats, tables_without_stats: hotTables.filter(t => stats[t] === 0),
+ backlink_plan_worst_nested_loops: worstLoops, gate_loops_max: 10 * fixture.pages.length },
+ ops,
+ todo: ['injected query vectors (vector arm)', 'facts/takes population', 'source-scoped grant query', 'cold-process first query',
+ 'concurrent receipt-bearing writers', 'Postgres engine', '10k/20k/50k tiers and CI seed upload'],
+ };
+ mkdirSync(dirname(out), { recursive: true });
+ writeFileSync(out, JSON.stringify(report, null, 2) + '\n');
+ console.log(`[scale] extract --source db ${report.extract_db_ms} ms`);
+ console.log(`[scale] import ${report.import.total_ms} ms; per-page first10 ${report.import.per_page_ms_first10} ms, last10 ${report.import.per_page_ms_last10} ms, ratio ${report.import.rate_ratio} (gate <= 1.5)`);
+ console.log(`[scale] planner: tables without stats: ${report.planner.tables_without_stats.join(', ') || 'none'}; backlink plan worst nested-loop loops ${worstLoops} (gate <= ${report.planner.gate_loops_max})`);
+ for (const r of ops) console.log(`[scale] ${r.known_answer === 'pass' ? 'PASS' : 'FAIL'} ${r.op}: p50 ${r.p50_ms} ms${r.detail ? ` (${r.detail})` : ''}`);
+ console.log(`[scale] report: ${out} (report-only; exit 0 regardless of results; reproduce with --seed ${seed} --pages ${pagesArg})`);
+}
+
+try {
+ await main();
+} catch (error) {
+ console.error(`[scale] harness crashed: ${error instanceof Error ? error.stack ?? error.message : String(error)}`);
+ process.exitCode = 1;
+} finally {
+ rmSync(home, { recursive: true, force: true });
+}
diff --git a/test/scripts/scale-fixture.test.ts b/test/scripts/scale-fixture.test.ts
new file mode 100644
index 0000000000..e69c460349
--- /dev/null
+++ b/test/scripts/scale-fixture.test.ts
@@ -0,0 +1,32 @@
+/**
+ * The report-only scale harness (`bun run test:scale`) is reproducible only if
+ * its fixture is: the same seed and page count must give byte-identical pages,
+ * and the known answers the harness asserts must hold in the fixture itself.
+ */
+import { expect, test } from 'bun:test';
+import { generateScaleFixture } from '../../scripts/scale/fixture.ts';
+
+test('same seed and size give an identical fixture; another seed differs', () => {
+ const a = generateScaleFixture({ pages: 300, seed: 7 });
+ const b = generateScaleFixture({ pages: 300, seed: 7 });
+ expect(JSON.stringify(a)).toBe(JSON.stringify(b));
+ expect(JSON.stringify(generateScaleFixture({ pages: 300, seed: 8 }).pages)).not.toBe(JSON.stringify(a.pages));
+});
+
+test('fixture shape: page count, two sources, unique tokens, links stay in their source, islands and hub hold', () => {
+ const f = generateScaleFixture({ pages: 301, seed: 1 });
+ expect(f.pages.length).toBe(301);
+ expect(f.pages.filter(p => p.sourceId === 'default').length).toBe(151);
+ expect(new Set(f.pages.map(p => p.token)).size).toBe(301);
+ for (const p of f.pages) {
+ expect(p.content).toContain(p.token);
+ const own = new Set(f.pages.filter(q => q.sourceId === p.sourceId).map(q => q.slug));
+ for (const target of p.links) expect(own.has(target)).toBe(true);
+ }
+ expect(f.islands.length).toBeGreaterThan(0);
+ for (const island of f.islands) {
+ expect(f.pages.some(p => p.sourceId === 'default' && p.links.includes(island))).toBe(false);
+ }
+ expect(f.pages.find(p => p.slug === f.hub && p.sourceId === 'default')!.links.length).toBe(3);
+ expect(() => generateScaleFixture({ pages: 5, seed: 1 })).toThrow();
+});