Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
scale: out-of-process phase watchdog, per-batch vectors progress, two-engine promotion rule
garrytan9f01f5f7bc9c
diff --git a/.github/workflows/scale-tier.yml b/.github/workflows/scale-tier.ymlindex fe9492ace9..220eafa245 100644--- a/.github/workflows/scale-tier.yml+++ b/.github/workflows/scale-tier.yml@@ -5,9 +5,9 @@ name: Scale tier## When it runs (one rule):# - pull requests that touch the paths below, or carry the `scale-tier` label: 10k;-# - nightly: 10k + 20k until the import-rate gate has passed at 20k on five-# consecutive nights, then 50k (scripts/scale/trend.ts decides from the last-# five nightly reports);+# - nightly: 10k + 20k until the import-rate gate has passed at 20k on both+# engines on five consecutive nights, then 50k (scripts/scale/trend.ts+# decides from the last five nightly reports);# - workflow_dispatch: the size you pass.## Enforced: import rate, known answers, no-op re-import, no duplicates across@@ -127,9 +127,10 @@ jobs:engine: [pglite, postgres]pages: ${{ fromJSON(needs.plan.outputs.pages) }}runs-on: ubicloud-standard-8-ubuntu-2404- # Backstop only: the harness phase timers fail first, naming the phase- # (10k <= 20 min, 50k <= 100 min per engine).- timeout-minutes: ${{ matrix.pages > 20000 && 130 || 50 }}+ # Backstop only: the harness's out-of-process phase watchdog+ # (scripts/scale/watchdog.ts, 1.5x the phase ceilings: 10k ~30 min,+ # 20k ~60 min) kills a stalled phase first and names it.+ timeout-minutes: ${{ matrix.pages >= 20000 && 130 || 50 }}services:postgres:# An empty image skips the service on the PGLite cell.@@ -180,7 +181,12 @@ jobs:REPORT: .context/scale/report-${{ matrix.engine }}-${{ matrix.pages }}-seed1.jsonrun: |if [ ! -f "$REPORT" ]; then- echo "No report: the harness crashed before writing one; see the step log." >> "$GITHUB_STEP_SUMMARY"+ WATCHDOG="${REPORT%.json}.watchdog.txt"+ if [ -f "$WATCHDOG" ]; then+ { echo "### Phase watchdog killed the harness"; echo '```'; cat "$WATCHDOG"; echo '```'; } >> "$GITHUB_STEP_SUMMARY"+ else+ echo "No report: the harness crashed before writing one; see the step log." >> "$GITHUB_STEP_SUMMARY"+ fiexit 0fijq -r '"### " + .headline.metric + ": " + (.headline.p50_ms|tostring) + " ms (" + .engine + ")",diff --git a/scripts/scale/run.ts b/scripts/scale/run.tsindex 82b79e67dc..714ac15593 100644--- a/scripts/scale/run.ts+++ b/scripts/scale/run.ts@@ -21,9 +21,14 @@* cold-process first query, two concurrent receipt-bearing writers, a no-op* re-import and cross-source duplicates. scripts/scale/gates.ts decides.*+ * The harness runs as a child of an out-of-process phase watchdog+ * (scripts/scale/watchdog.ts) that kills a phase stalled past 1.5x its gate+ * ceiling and names it; the vectors phase prints one progress line per batch.+ ** Exit codes: 0 all enforced gates pass, or a report-only run (no --enforce);* 1 an enforced gate failed (each failure names the gate, the op and its- * EXPLAIN); 2 usage error; 3 the harness itself crashed (not a verdict).+ * EXPLAIN) or the watchdog killed a stalled phase (diagnostic in+ * <out>.watchdog.txt); 2 usage error; 3 the harness itself crashed (not a verdict).* The JSON report (and a .explain.txt for failures) lands in --out.*/import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';@@ -64,7 +69,32 @@ if (engineKind === 'postgres' && !adminUrl) {+ 'e.g. DATABASE_URL=postgresql://<user>:<password>@localhost:5432/gbrain_test.');}const out = resolve(flag('--out', join('.context', 'scale', `report-${engineKind}-${pagesArg}-seed${seed}.json`)));++// The harness runs as a child of an out-of-process phase watchdog (scripts/scale/watchdog.ts).+if (process.env.GBRAIN_SCALE_SUPERVISED !== '1') {+ const { superviseScaleRun, watchdogLimitsMs } = await import('./watchdog.ts');+ let limits;+ try { limits = watchdogLimitsMs(pagesArg); } catch (e) { usage(e instanceof Error ? e.message : String(e)); }+ const dropDatabase = async (name: string) => {+ const { default: postgres } = await import('#postgres');+ const admin = postgres(adminUrl!, { max: 1, onnotice: () => {} });+ try { await admin.unsafe(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`); } finally { await admin.end(); }+ };+ process.exit(await superviseScaleRun({+ command: [process.execPath, ...process.argv.slice(1)],+ pages: pagesArg,+ limits,+ reproduce: `bun run test:scale -- ${process.argv.slice(2).join(' ')}`,+ dropDatabase: engineKind === 'postgres' ? dropDatabase : undefined,+ onDiagnostic: text => {+ mkdirSync(dirname(out), { recursive: true });+ writeFileSync(out.replace(/\.json$/, '') + '.watchdog.txt', text + '\n');+ },+ }));+}+const home = mkdtempSync(join(tmpdir(), 'gbrain-scale-'));+console.log(`[scale] brain home: ${home}`);const corpusDir = resolve(flag('--corpus-dir', join(home, 'corpus')));const policy: GatePolicy = { enforce, enforcePlanner: PLANNER_HEALTH_ENFORCED, enforceCeilings: process.env.GBRAIN_SCALE_ENFORCE_CEILINGS === '1' };@@ -113,6 +143,7 @@ async function createFreshPostgres(): Promise<void> {const name = `gbrain_scale_${process.pid}_${Date.now()}`;await admin.unsafe(`CREATE DATABASE ${name}`);await admin.end();+ console.log(`[scale] scale database: ${name}`);const url = new URL(adminUrl!);url.pathname = `/${name}`;databaseUrl = url.toString();@@ -304,11 +335,17 @@ async function main(): Promise<FullReport> {if (!Number.isInteger(d)) throw new Error(`content_chunks.embedding is ${col?.t ?? 'missing'}; expected vector(N)`);const ids = new Map((await engine.executeRaw<{ id: number; source_id: string; slug: string }>('SELECT id, source_id, slug FROM pages')).map(r => [`${r.source_id}:${r.slug}`, r.id]));+ const batches = Math.ceil(fixture.pages.length / 500);+ const vectorsStart = performance.now();for (let i = 0; i < fixture.pages.length; i += 500) {const batch = fixture.pages.slice(i, i + 500);+ const t = performance.now();await engine.executeRaw('UPDATE content_chunks c SET embedding = u.vec::vector FROM unnest($1::int[], $2::text[]) AS u(page_id, vec) WHERE c.page_id = u.page_id',[batch.map(p => ids.get(`${p.sourceId}:${p.slug}`)!), batch.map(p => `[${Array.from(scaleVector(p.index, d)).join(',')}]`)]);+ const rss = Math.round(process.memoryUsage.rss() / 1048576);+ console.log(`[scale] vectors batch ${i / 500 + 1}/${batches}: ${batch.length} pages in ${Math.round(performance.now() - t)} ms `+ + `(${i + batch.length}/${fixture.pages.length} pages, ${Math.round(performance.now() - vectorsStart)} ms total, dim ${d}, rss ${rss} MiB)`);}return d;});diff --git a/scripts/scale/trend.ts b/scripts/scale/trend.tsindex 49bfa30a4e..5db15d101c 100644--- a/scripts/scale/trend.ts+++ b/scripts/scale/trend.ts@@ -16,7 +16,8 @@* per metric. Enforcement then flips with the repo variable* GBRAIN_SCALE_ENFORCE_CEILINGS=1, a reviewed human step.* 2. Which sizes run tonight (the one cadence rule)? 10k + 20k nightly until- * the import-rate gate has passed at 20k on five consecutive nights, then+ * the import-rate gate has passed at 20k on both engines on five+ * consecutive nights (a missing 20k report counts as not passed), then* 50k nightly (sticky: once the latest night ran 50k it stays there).** Exit 0 whatever the verdict (it is advice; the workflow reads --json);@@ -31,6 +32,8 @@ export const STABLE_RUNS = 5;export const CV_MAX = 0.15;export const DEFAULT_TIERS = [10_000, 20_000];export const PROMOTED_TIERS = [50_000];+/** Promotion needs a 20k report from every engine: a cell that never wrote one (killed, cancelled) blocks it. */+export const ENGINES = ['pglite', 'postgres'];export interface TrendReport {engine: string;@@ -88,7 +91,8 @@ export function nightlyTiers(runs: TrendRun[]): { tiers: number[]; reason: strinconst window = runs.slice(0, STABLE_RUNS);const ratePassedAt20k = (run: TrendRun) => {const at20k = run.reports.filter(r => r.pages === 20_000);- return at20k.length > 0 && at20k.every(r => r.gates?.find(g => g.gate === 'import_rate')?.status === 'pass');+ return ENGINES.every(engine => at20k.some(r => r.engine === engine))+ && at20k.every(r => r.gates?.find(g => g.gate === 'import_rate')?.status === 'pass');};if (window.length === STABLE_RUNS && window.every(ratePassedAt20k)) {return { tiers: PROMOTED_TIERS, reason: `the import-rate gate passed at 20k on the last ${STABLE_RUNS} nights` };diff --git a/scripts/scale/watchdog.ts b/scripts/scale/watchdog.tsnew file mode 100644index 0000000000..0df14b2695--- /dev/null+++ b/scripts/scale/watchdog.ts@@ -0,0 +1,138 @@+/**+ * Out-of-process phase watchdog for the scale harness (A6/X5; ENG-2, DX-13).+ *+ * scripts/scale/run.ts re-runs itself as a child under this supervisor. A+ * PGLite statement runs synchronously inside WASM on the child's main thread,+ * so an in-process timer cannot fire during a stall; the parent reads the+ * child's `[scale] phase <name> start` lines, times each watched phase, and+ * SIGKILLs the child's process group at the limit. The diagnostic names the+ * phase, elapsed vs limit, the last progress line, the X5 TODO and the+ * override variable, then the supervisor removes the child's brain home and+ * scale database (the killed child cannot run its own cleanup).+ *+ * Watched phases and the child phases they cover:+ * import corpus, schema, import_files, extract, vectors (the gate's import window)+ * extract extract+ * vectors vectors+ * budgets ops, reimport, cold_query, writers (the gate's budgets window)+ * Limits are 1.5x the gate ceilings (scripts/scale/gates.ts phaseLimitsMs), so+ * the gate stays the verdict and the watchdog only ends hangs. Override one+ * with GBRAIN_SCALE_PHASE_LIMIT_MS_<PHASE> (e.g. ..._VECTORS=3600000) for a+ * local investigation.+ */+import { spawn } from 'node:child_process';+import { rmSync } from 'node:fs';+import { phaseLimitsMs } from './gates.ts';++export type WatchedPhase = 'import' | 'extract' | 'vectors' | 'budgets';+export const WATCHED_PHASES: WatchedPhase[] = ['import', 'extract', 'vectors', 'budgets'];+const COVERS: Record<string, WatchedPhase[]> = {+ corpus: ['import'], schema: ['import'], import_files: ['import'],+ extract: ['import', 'extract'], vectors: ['import', 'vectors'],+ ops: ['budgets'], reimport: ['budgets'], cold_query: ['budgets'], writers: ['budgets'],+};+export const WATCHDOG_GRACE = 1.5;+export const X5_TODO = 'TODOS.md "PGLite bulk-embedding cliff at ~20k chunks" (X5)';+export const HOME_LINE = '[scale] brain home: ';+export const DATABASE_LINE = '[scale] scale database: ';++export const overrideVariable = (phase: WatchedPhase) => `GBRAIN_SCALE_PHASE_LIMIT_MS_${phase.toUpperCase()}`;++export function watchdogLimitsMs(pages: number, env: Record<string, string | undefined> = process.env): Record<WatchedPhase, number> {+ const gate = phaseLimitsMs(pages);+ const limits: Record<WatchedPhase, number> = {+ import: gate.import * WATCHDOG_GRACE,+ extract: gate.import * 0.5 * WATCHDOG_GRACE,+ vectors: gate.import * 0.25 * WATCHDOG_GRACE,+ budgets: gate.budgets * WATCHDOG_GRACE,+ };+ for (const phase of WATCHED_PHASES) {+ const raw = env[overrideVariable(phase)];+ if (raw === undefined || raw === '') continue;+ const ms = Number(raw);+ if (!Number.isFinite(ms) || ms <= 0) throw new Error(`${overrideVariable(phase)} must be a positive number of milliseconds, got '${raw}'.`);+ limits[phase] = ms;+ }+ return limits;+}++export function watchdogDiagnostic(phase: WatchedPhase, elapsedMs: number, limitMs: number, lastLine: string, reproduce: string): string {+ return [+ `[scale] FAIL phase watchdog: ${phase} ran ${Math.round(elapsedMs / 1000)} s, limit ${Math.round(limitMs / 1000)} s; the harness was killed (exit 1).`,+ `[scale] last progress line: ${lastLine || '(none)'}`,+ `[scale] Why: a phase past its watchdog limit (${WATCHDOG_GRACE}x its gate ceiling unless overridden) is a stall, and an in-process timer cannot fire while PGLite blocks the main thread.`,+ `[scale] Known issue: ${X5_TODO} tracks the PGLite vectors stall at 20k pages.`,+ `[scale] Fix: profile the named phase; to let it run longer locally, set ${overrideVariable(phase)}=<ms> and rerun: ${reproduce}`,+ ].join('\n');+}++export interface SuperviseOptions {+ command: string[];+ pages: number;+ reproduce: string;+ env?: Record<string, string | undefined>;+ limits?: Record<WatchedPhase, number>;+ /** Drops the child's scale database after a kill; run.ts passes a Postgres admin connection. */+ dropDatabase?: (name: string) => Promise<void>;+ onDiagnostic?: (text: string) => void;+}++/** Run the harness child under the watchdog; resolves to the exit code to use. */+export async function superviseScaleRun(opts: SuperviseOptions): Promise<number> {+ const limits = opts.limits ?? watchdogLimitsMs(opts.pages, opts.env);+ const child = spawn(opts.command[0]!, opts.command.slice(1), {+ env: { ...(opts.env ?? process.env), GBRAIN_SCALE_SUPERVISED: '1' },+ stdio: ['ignore', 'pipe', 'pipe'],+ detached: true,+ });+ const started = new Map<WatchedPhase, number>();+ let lastLine = '';+ let home: string | undefined;+ let database: string | undefined;+ let fired: string | undefined;++ const consume = (stream: NodeJS.ReadableStream, sink: NodeJS.WriteStream) => {+ let buffered = '';+ stream.on('data', (chunk: Buffer) => {+ sink.write(chunk);+ buffered += chunk.toString();+ const lines = buffered.split(/\r?\n/);+ buffered = lines.pop() ?? '';+ for (const raw of lines) {+ const line = raw.trim();+ if (!line) continue;+ lastLine = line.slice(0, 500);+ if (line.startsWith(HOME_LINE)) home = line.slice(HOME_LINE.length);+ if (line.startsWith(DATABASE_LINE)) database = line.slice(DATABASE_LINE.length);+ const phase = /^\[scale\] phase (\w+) start$/.exec(line)?.[1];+ const now = performance.now();+ for (const p of WATCHED_PHASES) if (started.has(p) && !(COVERS[phase ?? '']?.includes(p) ?? true)) started.delete(p);+ for (const p of COVERS[phase ?? ''] ?? []) if (!started.has(p)) started.set(p, now);+ }+ });+ };+ consume(child.stdout!, process.stdout);+ consume(child.stderr!, process.stderr);++ const exited = new Promise<number>(resolve => child.on('exit', (code, signal) => resolve(code ?? (signal ? 1 : 3))));+ const timer = setInterval(() => {+ if (fired) return;+ const now = performance.now();+ for (const [phase, since] of started) {+ if (now - since <= limits[phase]) continue;+ fired = watchdogDiagnostic(phase, now - since, limits[phase], lastLine, opts.reproduce);+ try { process.kill(-child.pid!, 'SIGKILL'); } catch { child.kill('SIGKILL'); }+ return;+ }+ }, 250);+ const code = await exited;+ clearInterval(timer);+ if (!fired) return code;+ console.log(fired);+ opts.onDiagnostic?.(fired);+ if (home) rmSync(home, { recursive: true, force: true });+ if (database && opts.dropDatabase) {+ await opts.dropDatabase(database).catch(e => console.log(`[scale] could not drop ${database}: ${e instanceof Error ? e.message : String(e)}; drop it by hand with DROP DATABASE ${database} WITH (FORCE)`));+ }+ return 1;+}diff --git a/test/scripts/scale-trend.test.ts b/test/scripts/scale-trend.test.tsindex 90deee26dc..d9e5fd499f 100644--- a/test/scripts/scale-trend.test.ts+++ b/test/scripts/scale-trend.test.ts@@ -44,3 +44,8 @@ test('nightly sizes: 10k + 20k until the 20k rate gate passes five nights in a rexpect(nightlyTiers(oneFailed)).toMatchObject({ tiers: [10_000, 20_000], reason: expect.stringContaining('4 of the last 5') });expect(nightlyTiers(runs(1, () => [report('pglite', 50_000, 1, 1)])).tiers).toEqual([50_000]);});++test('a 20k cell with no report (killed or cancelled) blocks promotion to 50k', () => {+ const pgliteMissing = runs(5, () => [report('postgres', 20_000, 1, 1)]);+ expect(nightlyTiers(pgliteMissing)).toMatchObject({ tiers: [10_000, 20_000], reason: expect.stringContaining('0 of the last 5') });+});diff --git a/test/scripts/scale-watchdog.test.ts b/test/scripts/scale-watchdog.test.tsnew file mode 100644index 0000000000..b23dad1d92--- /dev/null+++ b/test/scripts/scale-watchdog.test.ts@@ -0,0 +1,96 @@+/**+ * scripts/scale/watchdog.ts: the out-of-process phase watchdog ends a phase+ * whose main thread is blocked synchronously (as a PGLite WASM statement+ * blocks it) and names the phase, elapsed vs limit, the last progress line,+ * the X5 TODO and the override variable.+ */+import { describe, expect, test } from 'bun:test';+import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { superviseScaleRun, watchdogLimitsMs, type WatchedPhase } from '../../scripts/scale/watchdog.ts';++const HOUR = 3_600_000;+const limits = (vectors: number): Record<WatchedPhase, number> => ({ import: HOUR, extract: HOUR, vectors, budgets: HOUR });++function fixture(body: string): { dir: string; script: string } {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-scale-watchdog-'));+ const script = join(dir, 'child.ts');+ writeFileSync(script, body);+ return { dir, script };+}++describe('scale phase watchdog', () => {+ test('a phase blocking the main thread synchronously fails by name within limit + grace, and its home and process group are cleaned up', async () => {+ const { dir, script } = fixture(`+ import { spawn } from 'node:child_process';+ import { mkdirSync } from 'node:fs';+ const home = ${JSON.stringify(join(tmpdir(), 'unused'))}.replace('unused', 'gbrain-scale-watchdog-home-' + process.pid);+ mkdirSync(home, { recursive: true });+ const grandchild = spawn('sleep', ['60'], { stdio: 'ignore' });+ console.log('[scale] brain home: ' + home);+ console.log('[scale] grandchild: ' + grandchild.pid);+ console.log('[scale] phase vectors start');+ console.log('[scale] vectors batch 3/40: 500 pages in 12 ms');+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0);+ `);+ const lines: string[] = [];+ const write = process.stdout.write.bind(process.stdout);+ process.stdout.write = ((chunk: string | Uint8Array) => { lines.push(String(chunk)); return true; }) as typeof process.stdout.write;+ let code: number;+ let diagnostic = '';+ const t = performance.now();+ try {+ code = await superviseScaleRun({+ command: [process.execPath, script], pages: 20_000, limits: limits(1500), reproduce: 'bun run test:scale -- --pages 20000',+ onDiagnostic: text => { diagnostic = text; },+ });+ } finally {+ process.stdout.write = write;+ }+ const elapsed = performance.now() - t;+ try {+ expect(code).toBe(1);+ expect(elapsed).toBeLessThan(1500 + 3000);+ expect(diagnostic).toContain('FAIL phase watchdog: vectors ran');+ expect(diagnostic).toContain('limit 2 s');+ expect(diagnostic).toContain('last progress line: [scale] vectors batch 3/40: 500 pages in 12 ms');+ expect(diagnostic).toContain('PGLite bulk-embedding cliff at ~20k chunks" (X5)');+ expect(diagnostic).toContain('GBRAIN_SCALE_PHASE_LIMIT_MS_VECTORS=<ms>');+ expect(diagnostic).toContain('bun run test:scale -- --pages 20000');+ const output = lines.join('');+ const home = /\[scale\] brain home: (.+)/.exec(output)![1]!;+ expect(existsSync(home)).toBe(false);+ const grandchild = Number(/\[scale\] grandchild: (\d+)/.exec(output)![1]);+ await Bun.sleep(100);+ expect(() => process.kill(grandchild, 0)).toThrow();+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('a phase that finishes inside its limit passes the child exit code through and leaves its home alone', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-scale-watchdog-keep-'));+ const { dir, script } = fixture(`+ console.log('[scale] brain home: ${home}');+ console.log('[scale] phase vectors start');+ console.log('[scale] phase vectors done in 1 ms');+ console.log('[scale] phase ops start');+ process.exit(7);+ `);+ try {+ expect(await superviseScaleRun({ command: [process.execPath, script], pages: 20_000, limits: limits(60_000), reproduce: 'r' })).toBe(7);+ expect(existsSync(home)).toBe(true);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ rmSync(home, { recursive: true, force: true });+ }+ });++ test('limits are 1.5x the gate ceilings, and the override variable replaces one phase', () => {+ const at20k = watchdogLimitsMs(20_000, {});+ expect(at20k).toEqual({ import: 45 * 60_000, extract: 22.5 * 60_000, vectors: 11.25 * 60_000, budgets: 15 * 60_000 });+ expect(watchdogLimitsMs(20_000, { GBRAIN_SCALE_PHASE_LIMIT_MS_VECTORS: '5000' }).vectors).toBe(5000);+ expect(() => watchdogLimitsMs(20_000, { GBRAIN_SCALE_PHASE_LIMIT_MS_EXTRACT: 'soon' })).toThrow('GBRAIN_SCALE_PHASE_LIMIT_MS_EXTRACT must be a positive number');+ });+});