stock-bot/scripts/test/benchmark-research.test.ts

356 lines
13 KiB
TypeScript

import { describe, expect, test } from 'bun:test';
import { createHash } from 'node:crypto';
import { chmodSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { prepareDataset } from '../../apps/stock/orchestrator/src/data/historical-dataset';
import {
economicHash,
identity,
parameters,
researchFixture,
unavailable,
verifyRepeats,
} from '../benchmark-research';
function runGit(cwd: string, args: string[]): void {
const result = Bun.spawnSync(['git', ...args], {
cwd,
stdout: 'pipe',
stderr: 'pipe',
env: {
...process.env,
GIT_CONFIG_NOSYSTEM: '1',
GIT_CONFIG_GLOBAL: '/dev/null',
},
});
if (result.exitCode !== 0) {
throw new Error(`git ${args.join(' ')} failed: ${result.stderr.toString()}`);
}
}
function withTempGitRepo<T>(fn: (repoDir: string, protectForCleanup: (path: string) => void) => T): T {
const repoDir = mkdtempSync(join(tmpdir(), 'stock-bot-benchmark-identity-'));
const chmodPaths: string[] = [];
const protectForCleanup = (path: string) => {
chmodPaths.push(path);
};
try {
runGit(repoDir, ['init']);
const emptyExcludesPath = join(repoDir, '.git', 'info', 'exclude');
writeFileSync(emptyExcludesPath, '');
runGit(repoDir, ['config', 'core.excludesFile', emptyExcludesPath]);
writeFileSync(join(repoDir, 'tracked.txt'), 'tracked-v1\n');
runGit(repoDir, ['add', 'tracked.txt']);
runGit(repoDir, [
'-c',
'user.name=Test User',
'-c',
'user.email=test@example.com',
'commit',
'-m',
'initial',
]);
return fn(repoDir, protectForCleanup);
} finally {
for (const path of chmodPaths) {
try {
chmodSync(path, 0o600);
} catch {
// Ignore if file was removed during the test.
}
}
rmSync(repoDir, { recursive: true, force: true });
}
}
function fsError(code: string, path: string): NodeJS.ErrnoException {
const error = new Error(`${code}: ${path}`) as NodeJS.ErrnoException;
error.code = code;
return error;
}
function sha256(data: Uint8Array | string): string {
return createHash('sha256').update(data).digest('hex');
}
function expectedSourceSha256(entries: [string, string][]): string {
const hash = createHash('sha256');
for (const [path, entry] of [...entries].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
hash.update(JSON.stringify([path, entry]));
}
return hash.digest('hex');
}
describe('existing-path research benchmark', () => {
test('fixture is seeded, ordered, hash-verified and detached by real dataset preparation', async () => {
for (const assets of [1, 10]) {
const source = researchFixture(80 * assets, assets);
const dataset = await prepareDataset(source);
expect(dataset).not.toBe(source);
expect(Object.isFrozen(dataset.bars)).toBe(true);
expect(dataset.manifest.hash).toBe(researchFixture(80 * assets, assets).manifest.hash);
expect(dataset.manifest.hash).not.toBe(
researchFixture(80 * assets, assets, 43).manifest.hash
);
expect(dataset.manifest.barCount).toBe(80 * assets);
expect(new Set(dataset.bars.map(b => b.symbol)).size).toBe(assets);
expect(await prepareDataset(dataset)).toBe(dataset);
}
expect(() => researchFixture(81, 10)).toThrow('divisible');
expect(() => researchFixture(80, 0)).toThrow('assets');
expect(() => researchFixture(80, 1, NaN)).toThrow('seed');
});
test('economic hash ignores only run metadata, map order and unordered position summaries', () => {
const a = {
backtestId: 'first',
completedAt: 'now',
executionTime: 1,
metrics: { cash: 99, commission: 1 },
positions: [
{ symbol: 'B', quantity: 2 },
{ symbol: 'A', quantity: 1 },
],
trades: [
{ id: 'first', price: 5 },
{ id: 'second', price: 6 },
],
equity: [100, 99],
ohlcData: { B: [2, 3], A: [1, 4] },
};
const b = {
...a,
backtestId: 'second',
completedAt: 'later',
executionTime: 99,
metrics: { commission: 1, cash: 99 },
positions: [...a.positions].reverse(),
ohlcData: { A: [1, 4], B: [2, 3] },
};
expect(economicHash(a)).toBe(economicHash(b));
expect(economicHash(a)).not.toBe(economicHash({ ...b, trades: [...b.trades].reverse() }));
expect(economicHash(a)).not.toBe(economicHash({ ...b, equity: [...b.equity].reverse() }));
expect(economicHash(a)).not.toBe(economicHash({ ...b, metrics: { commission: 2, cash: 98 } }));
expect(economicHash(a)).not.toBe(economicHash({ ...b, newEconomicField: 1 }));
expect(a.positions[0]!.symbol).toBe('B');
});
test('comparison rejects changed data, policy or economics instead of accepting faster results', () => {
const sample = {
datasetHash: 'dataset',
policyHash: 'policy',
trials: [{ strategyParameters: parameters[0]!, economicHash: 'economic' }],
};
expect(() => verifyRepeats([sample, structuredClone(sample)])).not.toThrow();
expect(() => verifyRepeats([sample, { ...sample, datasetHash: 'changed' }])).toThrow(
'Dataset/policy'
);
expect(() => verifyRepeats([sample, { ...sample, policyHash: 'changed' }])).toThrow(
'Dataset/policy'
);
expect(() =>
verifyRepeats([
sample,
{ ...sample, trials: [{ ...sample.trials[0]!, economicHash: 'changed' }] },
])
).toThrow('Economic mismatch');
expect(() => verifyRepeats([])).toThrow('Missing');
expect(
Object.values(unavailable).every(reason => typeof reason === 'string' && reason.length > 0)
).toBe(true);
});
test('tiny native self-test records honest phases and pinned identities without timing thresholds', async () => {
const worker = Bun.spawn([process.execPath, 'scripts/benchmark-research.ts', '--self-test'], {
cwd: new URL('../..', import.meta.url).pathname,
stdout: 'pipe',
stderr: 'pipe',
});
const [stdout, stderr, exit] = await Promise.all([
new Response(worker.stdout).text(),
new Response(worker.stderr).text(),
worker.exited,
]);
expect(exit, stderr).toBe(0);
const report = JSON.parse(stdout);
expect(report.mode).toBe('self-test');
expect(report.source.commit).toMatch(/^[a-f0-9]{40}$/);
for (const hash of [
report.source.contentSha256,
report.native.sha256,
report.runtime.executableSha256,
report.runtime.lockSha256,
report.runtime.cargoLockSha256,
report.host.sha256,
report.seed.sha256,
]) {
expect(hash).toMatch(/^[a-f0-9]{64}$/);
}
expect(typeof report.source.dirty).toBe('boolean');
expect(report.runtime.bun).toBe(Bun.version);
expect(report.native.path).toContain('/apps/stock/engine/dist/engine.node');
expect(report.native.buildProfile).toMatch(/^(debug|release|unverified)$/);
expect(report.unavailable).toEqual(unavailable);
expect(report.measurements.map((m: any) => m.workload.assets)).toEqual([1, 10]);
for (const measurement of report.measurements) {
expect(measurement.repeatedEconomicHashesMatch).toBe(true);
expect(measurement.samples).toHaveLength(2);
verifyRepeats(measurement.samples);
for (const sample of measurement.samples) {
expect(sample.trials).toHaveLength(6);
expect(sample.datasetHash).toMatch(/^[a-f0-9]{64}$/);
expect(sample.policyHash).toMatch(/^[a-f0-9]{64}$/);
expect(sample.processWallMs).toBeGreaterThan(0);
expect(sample.phasesMs).toHaveProperty('addonImportMs');
expect(sample.phasesMs).toHaveProperty('datasetPreparationMs');
for (const trial of sample.trials) {
expect(trial.fills).toBeGreaterThan(0);
expect(trial.resultBytes).toBeGreaterThan(0);
expect(trial.rssBytes).toBeGreaterThan(0);
expect(trial.timingsMs).toHaveProperty('nativeLoadMs');
expect(trial.timingsMs).toHaveProperty('nativeRunMs');
expect(trial.timingsMs).toHaveProperty('resultParseMs');
expect(trial.economicHash).toMatch(/^[a-f0-9]{64}$/);
}
}
}
});
test('identity hashes unreadable untracked files deterministically while throwing on tracked or non-permission errors', () => {
withTempGitRepo(repoDir => {
const untrackedPath = join(repoDir, '.bash_profile');
const trackedPath = join(repoDir, 'tracked.txt');
writeFileSync(untrackedPath, 'placeholder\n');
for (const code of ['EACCES', 'EPERM'] as const) {
const readSourceFile = (path: string) => {
if (path === untrackedPath) {
throw fsError(code, path);
}
return readFileSync(path);
};
const first = identity({ sourceRoot: repoDir, readSourceFile });
const second = identity({ sourceRoot: repoDir, readSourceFile });
expect(Object.keys(first)).toEqual(['source', 'native', 'runtime', 'host']);
expect(first.source.contentSha256).toBe(second.source.contentSha256);
expect(first.source.contentSha256).toBe(
expectedSourceSha256([
['.bash_profile', 'unreadable'],
['tracked.txt', sha256(readFileSync(trackedPath))],
])
);
expect(first.source.files).toBe(2);
expect(first.source.dirty).toBe(true);
expect(first.source.scope).toContain('unreadable');
// Changing a readable file changes contentSha256.
writeFileSync(trackedPath, `tracked-${code}\n`);
const afterReadableEdit = identity({ sourceRoot: repoDir, readSourceFile });
expect(afterReadableEdit.source.contentSha256).not.toBe(first.source.contentSha256);
// Tracked files still throw EACCES / EPERM.
expect(() =>
identity({
sourceRoot: repoDir,
readSourceFile: path => {
if (path === trackedPath) {
throw fsError(code, path);
}
return readFileSync(path);
},
})
).toThrow(code);
}
// Non-permission errors on untracked files still throw.
expect(() =>
identity({
sourceRoot: repoDir,
readSourceFile: path => {
if (path === untrackedPath) {
throw fsError('EIO', path);
}
return readFileSync(path);
},
})
).toThrow('EIO');
// Renaming or removing the unreadable untracked file changes contentSha256.
const beforeRename = identity({
sourceRoot: repoDir,
readSourceFile: path => {
if (path === untrackedPath) {
throw fsError('EACCES', path);
}
return readFileSync(path);
},
});
const renamedPath = join(repoDir, '.bash_profile_renamed');
renameSync(untrackedPath, renamedPath);
const afterRename = identity({
sourceRoot: repoDir,
readSourceFile: path => {
if (path === renamedPath) {
throw fsError('EACCES', path);
}
return readFileSync(path);
},
});
expect(afterRename.source.contentSha256).not.toBe(beforeRename.source.contentSha256);
rmSync(renamedPath);
const afterRemove = identity({ sourceRoot: repoDir });
expect(afterRemove.source.contentSha256).not.toBe(afterRename.source.contentSha256);
expect(afterRemove.source.files).toBe(1);
});
});
test('identity handles real chmod 000 untracked files and rejects chmod 000 tracked files', () => {
if (process.getuid?.() === 0) {
return;
}
withTempGitRepo((repoDir, protectForCleanup) => {
const trackedPath = join(repoDir, 'tracked.txt');
const untrackedPath = join(repoDir, 'unreadable-untracked.txt');
writeFileSync(untrackedPath, 'secret\n');
chmodSync(untrackedPath, 0o000);
protectForCleanup(untrackedPath);
const first = identity({ sourceRoot: repoDir });
const second = identity({ sourceRoot: repoDir });
expect(first.source.contentSha256).toBe(second.source.contentSha256);
expect(first.source.contentSha256).toBe(
expectedSourceSha256([
['tracked.txt', sha256(readFileSync(trackedPath))],
['unreadable-untracked.txt', 'unreadable'],
])
);
expect(first.source.files).toBe(2);
writeFileSync(trackedPath, 'tracked-v2\n');
const afterEdit = identity({ sourceRoot: repoDir });
expect(afterEdit.source.contentSha256).not.toBe(first.source.contentSha256);
chmodSync(trackedPath, 0o000);
protectForCleanup(trackedPath);
expect(() => identity({ sourceRoot: repoDir })).toThrow(/EACCES|permission denied/i);
});
});
test('identity hashes deleted unstaged tracked files with the deleted marker', () => {
withTempGitRepo(repoDir => {
const trackedPath = join(repoDir, 'tracked.txt');
const beforeDelete = identity({ sourceRoot: repoDir });
rmSync(trackedPath);
const afterDelete = identity({ sourceRoot: repoDir });
expect(afterDelete.source.contentSha256).not.toBe(beforeDelete.source.contentSha256);
expect(afterDelete.source.contentSha256).toBe(
expectedSourceSha256([['tracked.txt', 'deleted']])
);
expect(afterDelete.source.files).toBe(1);
expect(afterDelete.source.dirty).toBe(true);
});
});
});