feat(research): run durable backtests in a bounded worker pool

This commit is contained in:
Boki 2026-10-24 17:41:00 -04:00
parent bbf0dd4453
commit 26b97265c6
15 changed files with 1730 additions and 129 deletions

View file

@ -0,0 +1,430 @@
/** Disposable PG/Redis + actual one-shot Rust workers. No financial simulator or timing pass/fail threshold. */
import { execFileSync } from 'node:child_process';
import { createHash, randomUUID } from 'node:crypto';
import { readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { cpus, freemem, platform, release, totalmem } from 'node:os';
import { resolve } from 'node:path';
import { defined } from '@stock-bot/invariants';
import type { CanonicalRunResult } from '@stock-bot/stock-config/canonical-research';
import { readCanonicalBuildIdentity } from '../apps/stock/orchestrator/src/backtest/canonical-build';
import type { ResearchConcurrency } from '../apps/stock/orchestrator/src/backtest/ResearchBacktestPool';
import { canonicalReproductionHash } from '../apps/stock/web-api/src/services/reproduction-comparison';
import { nativeReplayFixture } from '../test/fixtures/native-replay';
import {
admittedTrialIds,
researchPoolFixture,
untilResearch,
} from '../test/fixtures/research-pool';
export function percentile(samples: readonly number[], quantile: number) {
if (
!samples.length ||
samples.some(value => !Number.isFinite(value) || value < 0) ||
quantile <= 0 ||
quantile > 1
) {
throw new Error('Invalid latency samples');
}
const sorted = [...samples].sort((a, b) => a - b);
return defined(
sorted[Math.max(0, Math.ceil(quantile * sorted.length) - 1)],
'Missing percentile'
);
}
export function efficiency(serialMs: number, parallelMs: number, slots: ResearchConcurrency) {
if (serialMs <= 0 || parallelMs <= 0 || !Number.isFinite(serialMs + parallelMs)) {
throw new Error('Invalid batch duration');
}
return serialMs / (slots * parallelMs);
}
export function verifyHashParity(
expected: readonly string[] | undefined,
actual: readonly string[]
) {
if (
!actual.length ||
actual.some(hash => !/^[a-f0-9]{64}$/.test(hash)) ||
(expected &&
(expected.length !== actual.length || expected.some((hash, index) => hash !== actual[index])))
) {
throw new Error('Per-candidate economic hash parity failed');
}
}
export function sampleProcessTree(root = process.pid) {
const pending = [root],
seen = new Set<number>(),
processes: { pid: number; rssBytes: number }[] = [];
while (pending.length) {
const pid = defined(pending.pop(), 'Missing sampled process');
if (seen.has(pid)) {
continue;
}
seen.add(pid);
try {
const match = /^VmRSS:\s+(\d+)\s+kB$/m.exec(readFileSync(`/proc/${pid}/status`, 'utf8'));
if (match) {
processes.push({ pid, rssBytes: Number(match[1]) * 1024 });
}
for (const tid of readdirSync(`/proc/${pid}/task`)) {
try {
for (const child of readFileSync(`/proc/${pid}/task/${tid}/children`, 'utf8')
.trim()
.split(/\s+/)) {
if (Number(child) > 0) {
pending.push(Number(child));
}
}
} catch {
/* Threads can exit while sampling. */
}
}
} catch {
/* Children can exit while sampling. */
}
}
return { rssBytes: processes.reduce((sum, child) => sum + child.rssBytes, 0), processes };
}
export async function measurePool(options: { output?: string; smoke?: boolean }) {
const startedAt = new Date().toISOString(),
start = performance.now();
const bars = options.smoke ? 100 : 10000,
repetitions = options.smoke ? 1 : 5;
const grid = options.smoke
? { fastPeriod: [2, 3], slowPeriod: [12, 16] }
: { fastPeriod: [2, 3, 4, 5, 6, 7], slowPeriod: [12, 16, 20, 24] };
const report: Record<string, unknown> = {
version: 'research-pool-measurement/v1',
status: 'running',
startedAt,
smoke: options.smoke ?? false,
workload: {
assetsPerTrial: 1,
barsPerTrial: bars,
candidates: grid.fastPeriod.length * grid.slowPeriod.length,
grid,
seed: 42,
repetitions,
slots: [1, 2, 4],
},
host: {
platform: platform(),
release: release(),
cpuModel: cpus()[0]?.model,
logicalCpus: cpus().length,
totalMemoryBytes: totalmem(),
freeMemoryBytesAtStart: freemem(),
runtime: Bun.version,
pid: process.pid,
},
definitions: {
throughput:
'Successful trials / (first submission request start to last durable completion event). Includes admission, SQL/Redis dispatch, data loading, native one-shot startup, replay, and result commit.',
serviceLatency:
'Claim transaction resolved to durable completion event, measured in one parent monotonic clock.',
endToEndLatency:
'First submission request start to each durable completion event; shared batch admission start, including queue wait.',
queueWait:
'Submission response resolved to claim transaction resolved; dispatcher starts after admission.',
aggregation:
'Validated result reads, canonical economic hashes and row inspection measured separately after completion.',
rss: '100ms procfs sum of benchmark driver and all descendants; approximate sampled peak, shared pages counted per process, short peaks can be missed. External PostgreSQL/Redis RSS excluded.',
cold: 'Initial fixture/catalog packaging, SQL migration/dataset retention, and first one-trial native run reported separately. OS/DB page caches are not flushed.',
warm: 'Same retained SQL dataset and executable build reused; every trial still forks a fresh native process. No resident worker/dataset cache.',
dispatcher:
'Unmodified production batch20, interval5000ms, republish30000ms, maxAttempts3. One BullMQ worker with concurrency1/2/4.',
claims:
'Single asset independent retained builtin strategies only; synthetic deterministic price history, not market alpha evidence or candidate sandbox throughput.',
},
};
const persist = () => {
if (options.output) {
writeFileSync(resolve(options.output), JSON.stringify(report, null, 2) + '\n');
}
};
persist();
let fixture: Awaited<ReturnType<typeof researchPoolFixture>> | undefined;
const samples: unknown[] = [];
report.samples = samples;
let failure: unknown;
try {
const sourceFiles = [
'apps/stock/orchestrator/src/backtest/ResearchBacktestPool.ts',
'apps/stock/orchestrator/src/container.ts',
'apps/stock/orchestrator/src/backtest/BacktestRunner.ts',
'apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts',
'apps/stock/web-api/src/services/BacktestDispatcher.ts',
'scripts/benchmark-research-pool.ts',
'test/fixtures/research-pool.ts',
];
report.source = {
revision: execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim(),
dirty: execFileSync('git', ['status', '--porcelain'], { encoding: 'utf8' }).trim().length > 0,
files: Object.fromEntries(
sourceFiles.map(path => [
path,
createHash('sha256').update(readFileSync(path)).digest('hex'),
])
),
};
report.build = await readCanonicalBuildIdentity();
const dataset = nativeReplayFixture(bars).dataset;
fixture = await researchPoolFixture(dataset);
const f = fixture;
report.dataset = dataset.manifest;
report.setupMs = performance.now() - start;
let baseline: string[] | undefined;
async function batch(slots: ResearchConcurrency, repetition: number, cold = false) {
const workers = f.createWorkers(slots);
await workers.queue.getBullQueue().waitUntilReady();
const input = {
backtestId: f.draft.id,
name: 'Paired bounded pool workload',
grid: cold ? { fastPeriod: [2], slowPeriod: [12] } : grid,
};
const previewStart = performance.now();
const preview = await f.experiments.preview(input);
const previewMs = performance.now() - previewStart;
const claims = new Map<string, number>(),
completed = new Map<string, number>();
workers.repositories.forEach(repository => {
const claim = repository.startCanonical.bind(repository);
repository.startCanonical = async request => {
const result = await claim(request);
claims.set(result.runId, performance.now());
return result;
};
});
workers.runtime.on('complete', (result: CanonicalRunResult) => {
completed.set(result.runId, performance.now());
});
const rss: {
elapsedMs: number;
rssBytes: number;
processes: { pid: number; rssBytes: number }[];
}[] = [];
const batchStart = performance.now();
const sample = () =>
rss.push({ elapsedMs: performance.now() - batchStart, ...sampleProcessTree() });
sample();
const timer = setInterval(sample, 100);
try {
const experiment = await f.experiments.submit(
{ ...input, previewHash: preview.previewHash },
{ principal: 'operator', key: randomUUID() }
);
const admittedAt = performance.now();
const ids = admittedTrialIds(experiment);
workers.dispatcher.start();
const rows = await f.wait(ids, 180000);
if (rows.every(row => row.status === 'completed')) {
await untilResearch(async () => completed.size === ids.length, 5000);
}
sample();
const observations = rows.map(row => ({
runId: row.id,
candidateIndex: row.trial_index,
trialKey: row.trial_key,
status: row.status,
attemptNumber: row.attempt_number,
error: row.error,
resultCount: row.result_count,
createdAt: row.created_at,
startedAt: row.started_at,
completedAt: row.completed_at,
claimElapsedMs: claims.has(row.id)
? defined(claims.get(row.id), 'Missing claim timestamp') - batchStart
: null,
commitElapsedMs: completed.has(row.id)
? defined(completed.get(row.id), 'Missing completion timestamp') - batchStart
: null,
}));
if (
rows.some(
row => row.status !== 'completed' || row.attempt_number !== 1 || row.result_count !== 1
) ||
completed.size !== ids.length ||
claims.size !== ids.length
) {
samples.push({
slots,
repetition,
cold,
observations,
rss,
error: 'Incomplete, failed, retried, or unobserved trial',
});
throw new Error('Every measured trial must complete exactly once');
}
const elapsedMs = Math.max(...completed.values()) - batchStart;
const aggregateStart = performance.now(),
hashes: string[] = [];
for (const id of ids) {
const result = await f.api.getRunResults(id);
if (!result || !('kind' in result) || result.kind !== 'canonical-result/v1') {
throw new Error('Missing validated canonical result');
}
hashes.push(canonicalReproductionHash(result));
}
if (!cold) {
verifyHashParity(baseline, hashes);
baseline ??= hashes;
}
const aggregationMs = performance.now() - aggregateStart;
const service = ids.map(
id =>
defined(completed.get(id), 'Missing completion timestamp') -
defined(claims.get(id), 'Missing claim timestamp')
);
const endToEnd = ids.map(
id => defined(completed.get(id), 'Missing completion timestamp') - batchStart
);
const queueWait = ids.map(
id => defined(claims.get(id), 'Missing claim timestamp') - admittedAt
);
const measurement = {
slots,
repetition,
cold,
experimentId: experiment.id,
previewHash: preview.previewHash,
parameters: experiment.preview.candidates.map(candidate => candidate.parameters),
previewMs,
admissionMs: admittedAt - batchStart,
elapsedMs,
trialsPerSecond: (ids.length * 1000) / elapsedMs,
aggregationMs,
hashes,
serviceMs: {
p50: percentile(service, 0.5),
p95: percentile(service, 0.95),
raw: service,
},
endToEndMs: {
p50: percentile(endToEnd, 0.5),
p95: percentile(endToEnd, 0.95),
raw: endToEnd,
},
queueWaitMs: {
p50: percentile(queueWait, 0.5),
p95: percentile(queueWait, 0.95),
raw: queueWait,
},
peakAggregateRssBytes: Math.max(...rss.map(sample => sample.rssBytes)),
rss,
observations,
};
console.error(
`pool slots=${slots} repetition=${repetition} cold=${cold} trials=${ids.length} ms=${elapsedMs.toFixed(1)} trials/s=${measurement.trialsPerSecond.toFixed(3)}`
);
return measurement;
} finally {
clearInterval(timer);
await workers.stop();
}
}
report.firstNativeTrial = await batch(1, -1, true);
persist();
const batches: Awaited<ReturnType<typeof batch>>[] = [];
for (let repetition = 0; repetition < repetitions; repetition++) {
const order: ResearchConcurrency[] =
repetition % 3 === 0 ? [1, 2, 4] : repetition % 3 === 1 ? [2, 4, 1] : [4, 1, 2];
for (const slots of order) {
const sample = await batch(slots, repetition);
batches.push(sample);
samples.push(sample);
persist();
}
}
report.summary = [1, 2, 4].map(slots => {
const selected = batches.filter(batch => batch.slots === slots);
return {
slots,
medianTrialsPerSecond: percentile(
selected.map(batch => batch.trialsPerSecond),
0.5
),
medianBatchMs: percentile(
selected.map(batch => batch.elapsedMs),
0.5
),
pairedEfficiency: selected.map(batch => ({
repetition: batch.repetition,
value: efficiency(
defined(
batches.find(serial => serial.repetition === batch.repetition && serial.slots === 1),
'Missing paired serial batch'
).elapsedMs,
batch.elapsedMs,
batch.slots
),
})),
peakAggregateRssBytes: Math.max(...selected.map(batch => batch.peakAggregateRssBytes)),
serviceP95Ms: percentile(
selected.flatMap(batch => batch.serviceMs.raw),
0.95
),
endToEndP95Ms: percentile(
selected.flatMap(batch => batch.endToEndMs.raw),
0.95
),
};
});
report.status = 'passed';
} catch (error) {
report.status = 'failed';
report.error = error instanceof Error ? error.message : String(error);
failure = error;
} finally {
try {
await fixture?.close();
} catch (error) {
report.status = 'failed';
report.cleanupError = String(error);
failure =
failure === undefined
? error
: new AggregateError([failure, error], 'Measurement and cleanup failed');
} finally {
report.finishedAt = new Date().toISOString();
report.totalMs = performance.now() - start;
persist();
}
}
if (failure !== undefined) {
throw failure;
}
return report;
}
export function parsePoolArguments(args: string[]): { output?: string; smoke: boolean } {
let measure = false,
smoke = false,
output: string | undefined;
for (let i = 0; i < args.length; i++) {
const argument = args[i];
if (argument === '--measure' && !measure) {
measure = true;
} else if (argument === '--smoke' && !smoke) {
smoke = true;
} else if (
argument === '--output' &&
output === undefined &&
args[i + 1] &&
!args[i + 1]?.startsWith('--')
) {
output = args[++i];
} else {
throw new Error('Invalid pool benchmark arguments');
}
}
if (!measure) {
throw new Error('Pass --measure to run disposable PostgreSQL/Redis/native measurements');
}
return { output, smoke };
}
if (import.meta.main) {
console.log(
JSON.stringify(await measurePool(parsePoolArguments(process.argv.slice(2))), null, 2)
);
}

View file

@ -0,0 +1,62 @@
import { describe, expect, test } from 'bun:test';
import {
efficiency,
parsePoolArguments,
percentile,
sampleProcessTree,
verifyHashParity,
} from '../benchmark-research-pool';
describe('bounded pool measurement integrity', () => {
test('nearest-rank tails preserve zero and reject incomplete/nonfinite samples', () => {
expect(percentile([0, 4, 2, 1, 3], 0.5)).toBe(2);
expect(
percentile(
Array.from({ length: 24 }, (_, i) => i),
0.95
)
).toBe(22);
for (const values of [[], [NaN], [Infinity], [-1]]) {
expect(() => percentile(values, 0.95)).toThrow();
}
});
test('paired efficiency uses full serial duration divided by slots times parallel duration', () => {
expect(efficiency(100, 60, 2)).toBeCloseTo(0.83333333);
expect(efficiency(100, 100, 1)).toBe(1);
expect(efficiency(100, 120, 4)).toBeCloseTo(0.20833333);
expect(() => efficiency(100, 0, 2)).toThrow();
});
test('parity is per candidate index, never sorted by result or completion order', () => {
const a = 'a'.repeat(64),
b = 'b'.repeat(64);
verifyHashParity(undefined, [a, b]);
verifyHashParity([a, b], [a, b]);
for (const hashes of [[b, a], [a], [], [a, 'invalid']]) {
expect(() => verifyHashParity([a, b], hashes)).toThrow();
}
});
test('measurement execution is explicit and malformed options cannot silently run', () => {
expect(parsePoolArguments(['--measure', '--smoke', '--output', '/tmp/report.json'])).toEqual({
smoke: true,
output: '/tmp/report.json',
});
for (const args of [
[],
['--smoke'],
['unknown', '--measure'],
['--measure', '--output'],
['--measure', '--output', '--smoke'],
['--measure', '--measure'],
]) {
expect(() => parsePoolArguments(args)).toThrow();
}
});
test('RSS includes the actual driver and records process identities', () => {
const sample = sampleProcessTree();
expect(sample.processes.some(processInfo => processInfo.pid === process.pid)).toBe(true);
expect(sample.rssBytes).toBeGreaterThan(0);
expect(sample.rssBytes).toBe(
sample.processes.reduce((total, processInfo) => total + processInfo.rssBytes, 0)
);
});
});