Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(weights): miner prunes against tracked files in every mode, independent of --run order (#8103, #8096)
garrytan9893ef293b10
diff --git a/scripts/mine-shard-weights.ts b/scripts/mine-shard-weights.tsindex fb9476998d..0d2fba4a06 100644--- a/scripts/mine-shard-weights.ts+++ b/scripts/mine-shard-weights.ts@@ -4,11 +4,14 @@* Serial: per-file runner PASS records, seconds (not buffered log timestamps).* E2E: per-file Bun summaries, milliseconds. Partial selections merge old weights;* explicit full-profile runs replace them after source-corpus validation.- * Several --run values give each file its median over those runs: one run's+ * Several --run values, in any order, give each file its median over those runs: one run's* timings carry that run's runner speeds (whole runs differ by 0.75-1.3x and* two-shard jobs within one run by 0.7-1.7x), so a lone fast run under-predicts* every shard.+ * Every mode drops entries for files git no longer tracks, so a deleted or+ * renamed test leaves the map whatever the runs measured.* Refresh after large test additions or sustained shard imbalance.+ * Seam: GBRAIN_MINE_ROOT (the checkout whose tracked files bound the map).*/import { spawnSync } from "node:child_process";import { readFileSync, writeFileSync, renameSync, rmSync, existsSync, mkdtempSync, mkdirSync } from "node:fs";@@ -18,7 +21,7 @@ import { createHash } from "node:crypto";import { fileURLToPath } from "node:url";import { loadWeights } from "./sharding.ts";-const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");+const ROOT = process.env.GBRAIN_MINE_ROOT ?? resolve(dirname(fileURLToPath(import.meta.url)), "..");export type Lane = "unit" | "serial" | "e2e";type E2EProfile = "selected" | "full";const OUTPUTS = { unit: "test-weights", serial: "serial-weights", e2e: "e2e-weights" };@@ -256,7 +259,7 @@ async function main(): Promise<void> {for (let i = 0; i < argv.length; i++) {const arg = argv[i]!;if (arg === "--help" || arg === "-h") {- console.log("usage: bun run weights:mine [--lane unit|serial|e2e] [--e2e-profile selected|full] [--run ID [--run ID ...] | --from-file PATH | <stdin>] [--out PATH]\nseveral --run values (newest first) give each file its median over those runs\nfull E2E requires --lane e2e, exactly one --run and a matching source checkout");+ console.log("usage: bun run weights:mine [--lane unit|serial|e2e] [--e2e-profile selected|full] [--run ID [--run ID ...] | --from-file PATH | <stdin>] [--out PATH]\nseveral --run values (any order) give each file its median over those runs; files git no longer tracks are dropped\nfull E2E requires --lane e2e, exactly one --run and a matching source checkout");return;}if (!["--lane", "--e2e-profile", "--run", "--run-id", "--from-file", "--out"].includes(arg) || !argv[i + 1] || argv[i + 1]!.startsWith("--")) throw new Error(`unknown/incomplete option: ${arg}`);@@ -313,11 +316,11 @@ async function main(): Promise<void> {// complete GitHub unit/serial/full-E2E run replaces the full map; selected E2E always// merges because its executed corpus depends on the diff.const mergeExisting = !full && (!run || lane === "e2e");- // A complete newest run (the first --run) names the current files, so one only older runs measured was deleted or- // renamed since. A merging run's corpus is partial, so every run's median stands.- const median = medianWeights(mined.map(m => m.measured));- const measured = mergeExisting ? median : new Map([...median].filter(([file]) => mined[0]!.measured.has(file)));- const weights = mergeExisting && existsSync(out) ? loadWeights(out) : new Map<string, number>();+ // An older run, or the existing map a partial source merges into, can name a file deleted or renamed since;+ // the checkout's tracked files decide what stays, whatever the --run order.+ const tracked = new Set(git(["ls-files"]).split("\n"));+ const measured = new Map([...medianWeights(mined.map(m => m.measured))].filter(([file]) => tracked.has(file)));+ const weights = new Map([...(mergeExisting && existsSync(out) ? loadWeights(out) : [])].filter(([file]) => tracked.has(file)));for (const [file, duration] of measured) weights.set(file, duration);const metadata = { lane, unit: lane === "serial" ? "seconds" : "milliseconds", run: run ?? null, commit, source: run ? "github" : input ? "file" : "stdin",...(mined.length > 1 ? { runs, commits: mined.map(m => m.commit) } : {}), measuredFiles: measured.size, totalFiles: weights.size, mergeExisting,diff --git a/test/scripts/mine-shard-weights.test.ts b/test/scripts/mine-shard-weights.test.tsindex 1d4cb93375..b81d3365e2 100644--- a/test/scripts/mine-shard-weights.test.ts+++ b/test/scripts/mine-shard-weights.test.ts@@ -5,7 +5,7 @@import { describe, expect, it } from "bun:test";import { chmodSync, mkdirSync, mkdtempSync, writeFileSync, readFileSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';-import { join } from 'node:path';+import { dirname, join } from 'node:path';import { spawnSync } from 'node:child_process';import {computeWeights,@@ -16,6 +16,18 @@ import {sourceE2ECorpus,} from "../../scripts/mine-shard-weights.ts";+/** A checkout tracking `files`, the set the miner bounds its output by (GBRAIN_MINE_ROOT). */+function trackedCheckout(dir: string, files: string[]): NodeJS.ProcessEnv {+ const root = join(dir, 'checkout');+ mkdirSync(root, { recursive: true });+ for (const file of files) {+ mkdirSync(dirname(join(root, file)), { recursive: true });+ writeFileSync(join(root, file), '');+ }+ for (const args of [['init', '-q'], ['add', '-A']]) expect(spawnSync('git', args, { cwd: root, encoding: 'utf8' }).status).toBe(0);+ return { ...process.env, GBRAIN_MINE_ROOT: root };+}+const SAMPLE = `test (1)\tUNKNOWN STEP\t2026-05-25T11:26:40.000000Z ##[group]test/alpha.test.ts:test (1)\tUNKNOWN STEP\t2026-05-25T11:26:41.000000Z (pass) some test [1.00ms]test (1)\tUNKNOWN STEP\t2026-05-25T11:26:43.500000Z ##[group]test/beta.test.ts:@@ -270,13 +282,14 @@ it('a failed CLI refresh leaves the existing output untouched', () => {try {const out = join(dir, 'weights');const input = join(dir, 'truncated.log');+ const env = trackedCheckout(dir, ['keep', ...['alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta'].map(name => `test/${name}.test.ts`)]);writeFileSync(out, '{"keep":123}\n');writeFileSync(input, SAMPLE);- const failed = spawnSync(process.execPath, [join(import.meta.dir, '../../scripts/mine-shard-weights.ts'), '--from-file', input, '--out', out], { encoding: 'utf8' });+ const failed = spawnSync(process.execPath, [join(import.meta.dir, '../../scripts/mine-shard-weights.ts'), '--from-file', input, '--out', out], { env, encoding: 'utf8' });expect(failed.status).not.toBe(0);expect(readFileSync(out, 'utf8')).toBe('{"keep":123}\n');writeFileSync(input, SAMPLE + 'test (1)\tstep\t2026-05-25T11:26:56.000Z 0 fail\ntest (1)\tstep\t2026-05-25T11:26:57.000Z Ran 4 tests across 4 files. [17s]\ntest (2)\tstep\t2026-05-25T11:26:56.000Z 0 fail\ntest (2)\tstep\t2026-05-25T11:26:58.000Z Ran 2 tests across 2 files. [16s]\n');- const passed = spawnSync(process.execPath, [join(import.meta.dir, '../../scripts/mine-shard-weights.ts'), '--from-file', input, '--out', out], { encoding: 'utf8' });+ const passed = spawnSync(process.execPath, [join(import.meta.dir, '../../scripts/mine-shard-weights.ts'), '--from-file', input, '--out', out], { env, encoding: 'utf8' });expect(passed.status, passed.stderr).toBe(0);const weights = JSON.parse(readFileSync(out, 'utf8'));expect(weights['test/delta.test.ts']).toBe(7000);@@ -293,15 +306,16 @@ it('partial serial artifacts preserve unobserved files; malformed durations cannconst input = join(dir, 'serial.log');const line = (text: string) => `serial-tests (1)\tstep\t2026-05-25T11:26:50.000Z ${text}\n`;const raw = line('[serial-tests] PASS 7s test/a.serial.test.ts (1pass)') + line('[serial-tests] all 1 file(s) passed in 7s (pool=4)');+ const env = trackedCheckout(dir, ['test/a.serial.test.ts', 'test/unobserved.serial.test.ts']);writeFileSync(out, '{"test/unobserved.serial.test.ts":42}\n');writeFileSync(input, raw);const args = [join(import.meta.dir, '../../scripts/mine-shard-weights.ts'), '--lane', 'serial', '--from-file', input, '--out', out];- expect(spawnSync(process.execPath, args, { encoding: 'utf8' }).status).toBe(0);+ expect(spawnSync(process.execPath, args, { env, encoding: 'utf8' }).status).toBe(0);expect(JSON.parse(readFileSync(out, 'utf8'))).toEqual({ 'test/a.serial.test.ts': 7, 'test/unobserved.serial.test.ts': 42 });expect(JSON.parse(readFileSync(meta, 'utf8'))).toMatchObject({ measuredFiles: 1, totalFiles: 2, mergeExisting: true });const saved = [readFileSync(out, 'utf8'), readFileSync(meta, 'utf8')];writeFileSync(input, raw.replace('PASS 7s', 'PASS 1..2s'));- expect(spawnSync(process.execPath, args, { encoding: 'utf8' }).status).not.toBe(0);+ expect(spawnSync(process.execPath, args, { env, encoding: 'utf8' }).status).not.toBe(0);expect([readFileSync(out, 'utf8'), readFileSync(meta, 'utf8')]).toEqual(saved);} finally { rmSync(dir, { recursive: true, force: true }); }});@@ -331,7 +345,7 @@ it('GitHub refresh verifies every eligible job before replacing the complete lanwriteFileSync(out, '{"test/old.test.ts":42}\n');writeFileSync(meta, '{"existing":true}\n');const args = [join(import.meta.dir, '../../scripts/mine-shard-weights.ts'), '--run', '123', '--out', out];- const env = { ...process.env, PATH: `${bin}:${process.env.PATH}`, FIXTURE_GH_INFO: info, FIXTURE_GH_ARTIFACTS: artifacts };+ const env = { ...trackedCheckout(dir, ['test/one.test.ts', 'test/two.test.ts']), PATH: `${bin}:${process.env.PATH}`, FIXTURE_GH_INFO: info, FIXTURE_GH_ARTIFACTS: artifacts };for (const partial of [null, line('test (2)', '##[gbrain-capture-start]') + line('test (2)', 'snapshot setup started') + line('test (2)', '##[gbrain-capture-complete] exit=0')]) {artifact(2, partial);expect(spawnSync(process.execPath, args, { env, encoding: 'utf8' }).status).not.toBe(0);@@ -373,7 +387,7 @@ it('GitHub serial refresh reads each job log by id instead of the whole-run log'const line = (text: string) => `${job}\tUNKNOWN STEP\t2026-10-10T06:00:01.000Z ${text}\n`;writeFileSync(log, line('[serial-tests] PASS 4s test/a.serial.test.ts (1pass)') + line('[serial-tests] all 1 file(s) passed in 4s (pool=4)'));const args = [join(import.meta.dir, '../../scripts/mine-shard-weights.ts'), '--lane', 'serial', '--run', '123', '--out', out];- const env = { ...process.env, PATH: `${bin}:${process.env.PATH}`, FIXTURE_GH_INFO: info, FIXTURE_GH_LOG: log };+ const env = { ...trackedCheckout(dir, ['test/a.serial.test.ts']), PATH: `${bin}:${process.env.PATH}`, FIXTURE_GH_INFO: info, FIXTURE_GH_LOG: log };writeFileSync(info, JSON.stringify({ conclusion: 'success', headSha: 'fixture-commit', jobs: [{ name: job, conclusion: 'success' }] }));expect(spawnSync(process.execPath, args, { env, encoding: 'utf8' }).stderr).toContain('serial: missing job identity');writeFileSync(info, JSON.stringify({ conclusion: 'success', headSha: 'fixture-commit', jobs: [{ name: job, conclusion: 'success', databaseId: 77 }] }));@@ -462,7 +476,7 @@ it('GitHub refresh mines every shard of a packed unit job (test.yml runs two perwriteFileSync(info, JSON.stringify({ conclusion: 'success', headSha: 'fixture-commit', jobs: [{ name: 'test (1, 2)', conclusion: 'success' }, { name: 'test (3, 4)', conclusion: 'success' }] }));writeFileSync(out, '{"test/old.test.ts":42}\n');const args = [join(import.meta.dir, '../../scripts/mine-shard-weights.ts'), '--run', '123', '--out', out];- const env = { ...process.env, PATH: `${bin}:${process.env.PATH}`, FIXTURE_GH_INFO: info, FIXTURE_GH_ARTIFACTS: artifacts };+ const env = { ...trackedCheckout(dir, ['test/one.test.ts', 'test/two.test.ts', 'test/three.test.ts', 'test/four.test.ts']), PATH: `${bin}:${process.env.PATH}`, FIXTURE_GH_INFO: info, FIXTURE_GH_ARTIFACTS: artifacts };expect(spawnSync(process.execPath, args, { env, encoding: 'utf8' }).status).not.toBe(0);expect(readFileSync(out, 'utf8')).toBe('{"test/old.test.ts":42}\n');writeFileSync(join(artifacts, 'timings-unit-2.log'), complete('test (2)', 'test/two.test.ts'));@@ -495,12 +509,12 @@ it('a refresh from several GitHub runs takes each file\'s median, so one fast or};run('101', 'commit-a', [['test/one.test.ts', 1000], ['test/two.test.ts', 9000], ['test/new.test.ts', 500]]);run('102', 'commit-b', [['test/one.test.ts', 2000], ['test/two.test.ts', 6000]]);- // test/gone.test.ts was deleted before the newest run (101), so it must not stay in the weights.+ // test/gone.test.ts was deleted after run 103 (git no longer tracks it), so it must not stay in the weights.run('103', 'commit-c', [['test/one.test.ts', 4000], ['test/two.test.ts', 3000], ['test/gone.test.ts', 700]]);run('104', 'commit-d', [['test/one.test.ts', 1], ['test/two.test.ts', 1]], 'failure');const out = join(dir, 'weights.json');const meta = join(dir, 'weights.metadata.json');- const env = { ...process.env, PATH: `${bin}:${process.env.PATH}`, FIXTURE_GH: fixtures };+ const env = { ...trackedCheckout(dir, ['test/one.test.ts', 'test/two.test.ts', 'test/new.test.ts']), PATH: `${bin}:${process.env.PATH}`, FIXTURE_GH: fixtures };const mine = (...args: string[]) => spawnSync(process.execPath, [join(import.meta.dir, '../../scripts/mine-shard-weights.ts'), ...args, '--out', out], { env, encoding: 'utf8' });writeFileSync(out, '{"test/old.test.ts":42}\n');writeFileSync(meta, '{"prior":true}\n');@@ -515,6 +529,10 @@ it('a refresh from several GitHub runs takes each file\'s median, so one fast orlane: 'unit', run: '101', commit: 'commit-a', runs: ['101', '102', '103'], commits: ['commit-a', 'commit-b', 'commit-c'],measuredFiles: 3, totalFiles: 3, mergeExisting: false,});+ // Oldest first gives the same map: the tracked files decide what stays, not which run came first.+ const oldestFirst = mine('--run', '103', '--run', '102', '--run', '101');+ expect(oldestFirst.status, oldestFirst.stderr).toBe(0);+ expect(JSON.parse(readFileSync(out, 'utf8'))).toEqual({ 'test/new.test.ts': 500, 'test/one.test.ts': 2000, 'test/two.test.ts': 6000 });} finally { rmSync(dir, { recursive: true, force: true }); }});@@ -538,12 +556,28 @@ it('selected E2E from several runs keeps the median of a file only an older runconst out = join(dir, 'e2e-weights.json');writeFileSync(out, '{"test/e2e/beta.test.ts":42}\n');const result = spawnSync(process.execPath, [join(import.meta.dir, '../../scripts/mine-shard-weights.ts'), '--lane', 'e2e', '--run', '201', '--run', '202', '--out', out],- { env: { ...process.env, PATH: bin + ':' + process.env.PATH, FIXTURE_GH: fixtures }, encoding: 'utf8' });+ { env: { ...trackedCheckout(dir, ['test/e2e/alpha.test.ts', 'test/e2e/beta.test.ts']), PATH: bin + ':' + process.env.PATH, FIXTURE_GH: fixtures }, encoding: 'utf8' });expect(result.status, result.stderr).toBe(0);expect(JSON.parse(readFileSync(out, 'utf8'))).toEqual({ 'test/e2e/alpha.test.ts': 2000, 'test/e2e/beta.test.ts': 800 });} finally { rmSync(dir, { recursive: true, force: true }); }});+it('a merging source drops the existing entry of a test file git no longer tracks (#8103)', () => {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-mine-merge-prune-'));+ try {+ const out = join(dir, 'weights.json');+ const input = join(dir, 'serial.log');+ const line = (text: string) => `serial-tests (1)\tstep\t2026-05-25T11:26:50.000Z ${text}\n`;+ writeFileSync(input, line('[serial-tests] PASS 7s test/a.serial.test.ts (1pass)') + line('[serial-tests] all 1 file(s) passed in 7s (pool=4)'));+ writeFileSync(out, '{"test/a.serial.test.ts":3,"test/deleted.serial.test.ts":9,"test/unobserved.serial.test.ts":42}\n');+ const env = trackedCheckout(dir, ['test/a.serial.test.ts', 'test/unobserved.serial.test.ts']);+ const result = spawnSync(process.execPath, [join(import.meta.dir, '../../scripts/mine-shard-weights.ts'), '--lane', 'serial', '--from-file', input, '--out', out], { env, encoding: 'utf8' });+ expect(result.status, result.stderr).toBe(0);+ expect(JSON.parse(readFileSync(out, 'utf8'))).toEqual({ 'test/a.serial.test.ts': 7, 'test/unobserved.serial.test.ts': 42 });+ expect(JSON.parse(readFileSync(join(dir, 'weights.metadata.json'), 'utf8'))).toMatchObject({ measuredFiles: 1, totalFiles: 2, mergeExisting: true });+ } finally { rmSync(dir, { recursive: true, force: true }); }+});+describe('medianWeights', () => {it('takes each file\'s median over the runs that measured it, averaging the middle two of an even count', () => {const runs = [new Map([['a', 1], ['b', 10]]), new Map([['a', 9], ['b', 30], ['c', 7]]), new Map([['a', 3]]), new Map([['a', 5], ['b', 20]])];