feat(research): isolate candidates and add reviewed paper promotion
This commit is contained in:
parent
26b97265c6
commit
25b5cbf481
128 changed files with 13038 additions and 1388 deletions
188
scripts/benchmark-candidate-isolation.ts
Normal file
188
scripts/benchmark-candidate-isolation.ts
Normal file
|
|
@ -0,0 +1,188 @@
|
|||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { cpus } from 'node:os';
|
||||
import { canonicalRunRequestSchema } from '../apps/stock/config/src/contracts/canonical-research';
|
||||
import { canonicalStrategyJson } from '../apps/stock/config/src/contracts/strategy';
|
||||
import {
|
||||
IsolatedCandidateController,
|
||||
readCandidateExecution,
|
||||
} from '../apps/stock/orchestrator/src/backtest/candidate-sandbox';
|
||||
import { readCanonicalBuildIdentity } from '../apps/stock/orchestrator/src/backtest/canonical-build';
|
||||
import {
|
||||
NativeReplaySession,
|
||||
prepareReplayLoad,
|
||||
runReplaySession,
|
||||
runReplaySessionAsync,
|
||||
} from '../apps/stock/orchestrator/src/backtest/native-replay';
|
||||
import { importRetainedProgram } from '../apps/stock/orchestrator/src/strategies/retained-program';
|
||||
import { StrategyController } from '../apps/stock/orchestrator/src/strategies/strategy-controller';
|
||||
import { packageBuiltinStrategies } from '../scripts/package-builtin-strategies';
|
||||
import { nativeReplayFixture } from '../test/fixtures/native-replay';
|
||||
|
||||
/** A diagnostic paired boundary measurement, not a capacity benchmark or optimization gate. */
|
||||
async function measure() {
|
||||
const sharedStarted = performance.now();
|
||||
const bars = 1000,
|
||||
versionId = '20000000-0000-4000-8000-000000000001',
|
||||
runId = '10000000-0000-4000-8000-000000000001',
|
||||
ownerId = `strategy:${versionId}`;
|
||||
const fixture = nativeReplayFixture(bars, 1, [ownerId]);
|
||||
fixture.config.matching.risk.ledger.sessionId = runId;
|
||||
fixture.config.matching.risk.ledger.accountId = `research:${runId}`;
|
||||
const pkg = (await packageBuiltinStrategies()).find(
|
||||
value => value.program.strategyId === 'sma_crossover'
|
||||
);
|
||||
if (!pkg) {
|
||||
throw new Error('Reviewed SMA benchmark package missing');
|
||||
}
|
||||
const request = canonicalRunRequestSchema.parse({
|
||||
kind: 'canonical-research/v1',
|
||||
runId,
|
||||
backtestId: '30000000-0000-4000-8000-000000000001',
|
||||
name: 'Candidate IPC fixture',
|
||||
datasetHash: fixture.dataset.manifest.hash,
|
||||
strategy: {
|
||||
familyId: '40000000-0000-4000-8000-000000000001',
|
||||
versionId,
|
||||
baselineVersionId: '50000000-0000-4000-8000-000000000001',
|
||||
origin: 'candidate',
|
||||
reviewId: null,
|
||||
package: { ...pkg, execution: { kind: 'isolated-candidate/v1', warmupBars: 0 } },
|
||||
execution: await readCandidateExecution(),
|
||||
selection: {
|
||||
ownerId,
|
||||
strategyId: pkg.program.strategyId,
|
||||
strategyVersion: pkg.program.strategyVersion,
|
||||
seed: 17,
|
||||
instrumentId: 'X0.US',
|
||||
seriesId: 'X0.US:1m',
|
||||
ownerBudget: '100',
|
||||
parameters: { fastPeriod: 2, slowPeriod: 3 },
|
||||
},
|
||||
},
|
||||
policy: fixture.config,
|
||||
analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null },
|
||||
modelArtifacts: [],
|
||||
build: await readCanonicalBuildIdentity(),
|
||||
});
|
||||
const sharedSetupMs = performance.now() - sharedStarted;
|
||||
const runs: Record<string, unknown>[] = [];
|
||||
async function trial(mode: 'trusted-fixture' | 'isolated', index: number) {
|
||||
const began = performance.now();
|
||||
let at = began;
|
||||
const load = prepareReplayLoad(fixture.dataset, request.policy);
|
||||
const preparationMs = performance.now() - at;
|
||||
at = performance.now();
|
||||
// This trusted branch imports only the locally authored, reviewed builtin fixture package.
|
||||
// Production research candidates never enter this branch.
|
||||
const controller =
|
||||
mode === 'isolated'
|
||||
? await IsolatedCandidateController.start(request, `stock-bot-candidate-${randomUUID()}`)
|
||||
: new StrategyController(
|
||||
load.identity,
|
||||
[await importRetainedProgram(request.strategy.package, request.strategy.selection)],
|
||||
load.config
|
||||
);
|
||||
const startupMs = performance.now() - at;
|
||||
at = performance.now();
|
||||
const session = new NativeReplaySession(load);
|
||||
const nativeLoadMs = performance.now() - at;
|
||||
at = performance.now();
|
||||
let result, replayMs: number, cleanupMs: number;
|
||||
try {
|
||||
result =
|
||||
controller instanceof IsolatedCandidateController
|
||||
? await runReplaySessionAsync(session, controller, { resultFormat: 'report' })
|
||||
: runReplaySession(session, controller, { resultFormat: 'report' });
|
||||
replayMs = performance.now() - at;
|
||||
at = performance.now();
|
||||
if (controller instanceof IsolatedCandidateController) {
|
||||
await controller.finish();
|
||||
await controller.dispose();
|
||||
}
|
||||
cleanupMs = performance.now() - at;
|
||||
} catch (error) {
|
||||
if (controller instanceof IsolatedCandidateController) {
|
||||
await controller.dispose();
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
const totalMs = performance.now() - began;
|
||||
const financialHash = createHash('sha256')
|
||||
.update(canonicalStrategyJson(result.result))
|
||||
.digest('hex');
|
||||
const row = {
|
||||
index,
|
||||
phase: index === 0 ? 'first-pair-in-process' : 'warm-pair',
|
||||
mode,
|
||||
preparationMs,
|
||||
startupMs,
|
||||
nativeLoadMs,
|
||||
replayMs,
|
||||
cleanupMs,
|
||||
totalMs,
|
||||
barsPerReplaySecond: bars / (replayMs / 1000),
|
||||
financialHash,
|
||||
metrics: result.metrics,
|
||||
};
|
||||
runs.push(row);
|
||||
return financialHash;
|
||||
}
|
||||
for (let i = 0; i < 6; i++) {
|
||||
const modes =
|
||||
i % 2 === 0
|
||||
? (['trusted-fixture', 'isolated'] as const)
|
||||
: (['isolated', 'trusted-fixture'] as const);
|
||||
const one = await trial(modes[0], i),
|
||||
two = await trial(modes[1], i);
|
||||
if (one !== two) {
|
||||
throw Error('Financial parity failed');
|
||||
}
|
||||
}
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
{
|
||||
version: 1,
|
||||
sharedSetupMs,
|
||||
measuredCommandMs: performance.now() - sharedStarted,
|
||||
timingNotes:
|
||||
'The first pair is first measured in this process, not OS-cold. No caches are flushed. Shared setup includes dataset construction, package generation and descriptor/build preflight; module imports and Bun startup precede measurement. Each trial total excludes shared setup and final hash comparison. This shared-host diagnostic does not certify capacity.',
|
||||
source: {
|
||||
package: pkg.source,
|
||||
artifactHash: pkg.artifact.sha256,
|
||||
dependencyLockHash: pkg.dependencyLock.sha256,
|
||||
harnessSha256: createHash('sha256')
|
||||
.update(await readFile(new URL(import.meta.url)))
|
||||
.digest('hex'),
|
||||
},
|
||||
workload: {
|
||||
bars,
|
||||
assets: 1,
|
||||
strategies: 1,
|
||||
warmPairs: 5,
|
||||
firstPairs: 1,
|
||||
source: 'retained nativeReplayFixture',
|
||||
parameters: request.strategy.selection.parameters,
|
||||
},
|
||||
runtime: {
|
||||
bun: Bun.version,
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
cpu: cpus()[0]?.model,
|
||||
},
|
||||
datasetHash: request.datasetHash,
|
||||
build: request.build,
|
||||
execution: request.strategy.origin === 'candidate' ? request.strategy.execution : null,
|
||||
runs,
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
);
|
||||
}
|
||||
if (import.meta.main) {
|
||||
if (process.argv.slice(2).join(' ') !== '--measure') {
|
||||
throw new Error('Usage: bun scripts/benchmark-candidate-isolation.ts --measure');
|
||||
}
|
||||
await measure();
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue