stock-bot/scripts/benchmark-replay.ts

687 lines
24 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/** F07 extension of P01, invoked only through benchmark-research.ts --session. */
import { createHash } from 'node:crypto';
import { readFileSync } from 'node:fs';
import type { FinancialEffects } from '@stock-bot/types';
import type {
ReplayOutput,
ReplayProjectionResult,
ReplayResultFormat,
} from '../apps/stock/orchestrator/src/contracts/native-replay';
export const replayProfiles = ['none', 'sparse', 'turnover'] as const;
export type ReplayProfile = (typeof replayProfiles)[number];
export type SessionOptions = {
profiles: ReplayProfile[];
resultFormat: ReplayResultFormat | 'both';
totalBars?: number;
};
type SessionWorkload = {
totalBars: number;
assets: number;
owners: number;
eventBudget: number;
profile: ReplayProfile;
resultFormat: ReplayResultFormat;
};
const hash = (value: string) => createHash('sha256').update(value).digest('hex');
const capital = '1000000.00000000';
const profileDefinitions: Record<ReplayProfile, string> = {
none: 'no-targets-v1',
sparse: 'first-last-unit-target-v1',
turnover: 'alternating-unit-target-v1',
};
function cents(value: bigint): string {
const magnitude = value < 0n ? -value : value;
return `${value < 0n ? '-' : ''}${magnitude / 100n}.${String(magnitude % 100n).padStart(2, '0')}000000`;
}
/** Independent integer-cent oracle for this fixture only, not a second simulator.
* One unit per owner/asset alternates buy/sell at opens 1..N-1, with a 1% fee.
* Final position is marked at last close (open+1); no invented liquidation. */
export function profileOracle(
profile: ReplayProfile,
barsPerAsset: number,
assets: number,
owners: number
) {
if (
![barsPerAsset, assets, owners].every(Number.isSafeInteger) ||
barsPerAsset < 3 ||
assets < 1 ||
owners < 1
) {
throw new Error('Expected at least three bars and positive asset/owner counts');
}
let cashDelta = 0n,
fee = 0n,
fillsPerBook = 0;
const lastOpen = BigInt(10 + ((barsPerAsset - 1) % 20) * 2);
if (profile === 'turnover') {
for (let step = 1; step < barsPerAsset; step++) {
const price = BigInt(10 + (step % 20) * 2);
cashDelta += (step % 2 ? -price : price) * 100n - price;
fee += price;
}
fillsPerBook = barsPerAsset - 1;
} else if (profile === 'sparse') {
// Exactly one unit bought at first eligible open12 and sold at last open.
cashDelta = (lastOpen - 12n) * 100n - 12n - lastOpen;
fee = 12n + lastOpen;
fillsPerBook = 2;
} else if (profile !== 'none') {
throw new Error('Unknown replay profile');
}
const books = BigInt(assets * owners),
holding = profile === 'turnover' ? (barsPerAsset - 1) % 2 : 0;
const cash = 100_000_000n + cashDelta * books;
return {
cash: cents(cash),
equity: cents(cash + BigInt(holding) * (lastOpen + 1n) * 100n * books),
feePerOwner: cents(fee * BigInt(assets)),
quantity: `${holding}.00000000`,
remainingCost: cents(BigInt(holding) * lastOpen * 100n),
fills: fillsPerBook * assets * owners,
decisions: (barsPerAsset - 1) * owners,
};
}
export function turnoverOracle(barsPerAsset: number, assets: number, owners: number) {
return profileOracle('turnover', barsPerAsset, assets, owners);
}
/** A desired unit target only, not an accounting/fill model. null means hold. */
export function profileTarget(
profile: ReplayProfile,
decision: number,
barsPerAsset: number
): 0 | 1 | null {
if (profile === 'none') {
return null;
}
if (profile === 'turnover') {
return decision % 2 ? 0 : 1;
}
if (decision === 0) {
return 1;
}
return decision === barsPerAsset - 2 ? 0 : null;
}
type SharedFill = Pick<
ReplayProjectionResult['projection']['fills'][number],
| 'commandId'
| 'eventTime'
| 'ownerId'
| 'orderId'
| 'fillId'
| 'instrumentId'
| 'price'
| 'cashDelta'
| 'quantityDelta'
| 'releasedBasis'
| 'realizedGrossPnl'
| 'fee'
>;
function sharedFill(fill: SharedFill): SharedFill {
return {
commandId: fill.commandId,
eventTime: fill.eventTime,
ownerId: fill.ownerId,
orderId: fill.orderId,
fillId: fill.fillId,
instrumentId: fill.instrumentId,
price: fill.price,
cashDelta: fill.cashDelta,
quantityDelta: fill.quantityDelta,
releasedBasis: fill.releasedBasis,
realizedGrossPnl: fill.realizedGrossPnl,
fee: { feeId: fill.fee.feeId, amount: fill.fee.amount },
};
}
/** Benchmark-only copy of shared authoritative fields. No valuation, fee or P&L
* arithmetic. The trace has no LedgerValuation; that extra compact projection
* remains covered by Rust/independent fixtures, not synthesized in this hash. */
export function commonFinancialProjection(result: ReplayOutput) {
const fills: SharedFill[] = [];
if ('projection' in result) {
for (const fill of result.projection.fills) {
fills.push(sharedFill(fill));
}
} else {
for (const receipt of result.receipts) {
if (receipt.outcome.replayed) {
continue;
}
for (const effect of receipt.outcome.effects) {
if (!('Risk' in effect)) {
continue;
}
const risk = effect.Risk as {
outcome: {
replayed: boolean;
disposition: unknown;
financial: null | { replayed: boolean; effects: FinancialEffects };
};
};
if (risk.outcome.replayed) {
continue;
}
if (risk.outcome.disposition !== 'Accepted') {
throw new Error('Unexpected benchmark risk rejection');
}
const financial = risk.outcome.financial;
if (!financial || financial.replayed) {
continue;
}
const applied = financial.effects.effects.filter(e => e.kind === 'fillApplied');
const fees = financial.effects.effects.filter(e => e.kind === 'feeApplied');
if (!applied.length && !fees.length) {
continue;
}
const fill = applied[0],
fee = fees[0];
if (
applied.length !== 1 ||
fees.length !== 1 ||
!fill ||
!fee ||
fill.ownerId !== fee.ownerId ||
fill.fillId !== fee.fillId
) {
throw new Error('Malformed trace fill/fee pair');
}
fills.push(
sharedFill({
...fill,
commandId: financial.effects.commandId,
eventTime: financial.effects.eventTime,
fee: { feeId: fee.feeId, amount: fee.amount },
})
);
}
}
}
return {
identity: result.identity,
status: result.status,
manifest: result.manifest,
policy: result.policy,
view: result.view,
limitations: result.limitations,
modelLimitations: result.modelLimitations,
fills,
};
}
export function assertResultFormat(result: ReplayOutput, expected: ReplayResultFormat): void {
if (('projection' in result ? 'projection' : 'trace') !== expected) {
throw new Error('Benchmark result format mismatch');
}
}
function assertEconomics(
result: ReplayOutput,
workload: SessionWorkload,
fills: readonly SharedFill[]
) {
const expected = profileOracle(
workload.profile,
workload.totalBars / workload.assets,
workload.assets,
workload.owners
);
const portfolio = result.view.portfolio;
if (
portfolio.cash !== expected.cash ||
result.view.equity !== expected.equity ||
portfolio.positions.length !==
(workload.profile === 'none' ? 0 : workload.assets * workload.owners) ||
portfolio.positions.some(
p => p.quantity !== expected.quantity || p.remainingCost !== expected.remainingCost
) ||
portfolio.fees.length !== workload.owners ||
portfolio.fees.some(f => f.amount !== expected.feePerOwner) ||
result.view.orders.length ||
result.view.reservations.length
) {
throw new Error('Canonical benchmark failed independent cash/equity/owner/basis/fee oracle');
}
if (fills.length !== expected.fills) {
throw new Error('Unexpected benchmark fill/fee count');
}
return { ...expected, fees: fills.length };
}
export async function sessionChild(workload: SessionWorkload) {
const entryUptimeMs = process.uptime() * 1000,
start = performance.now();
let clock = start;
const elapsed = () => {
const now = performance.now(),
duration = now - clock;
clock = now;
return duration;
};
const { validateDatasetV2 } = await import(
'../apps/stock/orchestrator/src/data/historical-dataset-v2'
);
const { nativeReplayFixture } = await import('../test/fixtures/native-replay');
const { parseFinancialDecimal } = await import('@stock-bot/types');
const applicationImportMs = elapsed();
const nativeSha256 = createHash('sha256')
.update(readFileSync(new URL('../apps/stock/engine/dist/engine.node', import.meta.url)))
.digest('hex');
const artifactIdentityMs = elapsed();
await import('@stock-bot/engine');
const addonImportMs = elapsed();
const { prepareReplayLoad, NativeReplaySession, runReplayConformance } = await import(
'../apps/stock/orchestrator/src/backtest/native-replay'
);
const adapterImportMs = elapsed();
const ownerIds = Array.from({ length: workload.owners }, (_, i) => `owner-${i}`);
const fixture = nativeReplayFixture(
workload.totalBars / workload.assets,
workload.assets,
ownerIds
);
fixture.config.matching.risk.ledger.initialCapital = capital;
const fixtureGenerationMs = elapsed();
// Detach so the first verification cannot hit D01's immutable-object cache.
const wireDataset = JSON.stringify(fixture.dataset);
const detached = JSON.parse(wireDataset);
const datasetTransportRoundtripMs = elapsed();
const dataset = validateDatasetV2(detached);
const frozenDatasetVerificationMs = elapsed();
const load = prepareReplayLoad(dataset, fixture.config);
const preparedReuseAndMappingMs = elapsed();
const createRequestBytes = Buffer.byteLength(JSON.stringify(load));
const advanceRequestBytes = Buffer.byteLength(
JSON.stringify({ identity: load.identity, eventBudget: workload.eventBudget })
);
const finalizeRequestBytes = Buffer.byteLength(JSON.stringify(load.identity));
const requestSizingMs = elapsed();
const trials = [];
for (let repeat = 0; repeat < 2; repeat++) {
const trialStart = performance.now();
const session = new NativeReplaySession(load);
const nativeCreateMs = performance.now() - trialStart;
const counts = new Map<string, number>();
const one = parseFinancialDecimal('1'),
zero = parseFinancialDecimal('0');
const runStart = performance.now();
const { result, metrics } = runReplayConformance(
session,
owner => {
const decision = counts.get(owner) ?? 0;
counts.set(owner, decision + 1);
const quantity = profileTarget(
workload.profile,
decision,
workload.totalBars / workload.assets
);
return {
mode: 'target',
targets:
quantity === null
? []
: fixture.instruments.map(instrumentId => ({
instrumentId,
quantity: quantity === 0 ? zero : one,
})),
};
},
{
eventBudget: workload.eventBudget,
reverseCallbacks: repeat === 1,
resultFormat: workload.resultFormat,
}
);
const runWallMs = performance.now() - runStart;
const validationStart = performance.now();
assertResultFormat(result, workload.resultFormat);
const common = commonFinancialProjection(result);
const economic = assertEconomics(result, workload, common.fills);
const decisions = [...counts.values()].reduce((a, b) => a + b, 0);
if (decisions !== economic.decisions) {
throw new Error('Unexpected benchmark decision count');
}
// Exact complete normalized result bytes include provenance, ordered receipts,
// policy and terminal holdings, not just a selectively hashed P&L summary.
const resultHash = hash(JSON.stringify(result));
const commonFinancialHash = hash(JSON.stringify(common));
const validationAndHashMs = performance.now() - validationStart;
const wallMs = performance.now() - trialStart;
trials.push({
repeat,
reverseCallbacks: repeat === 1,
resultHash,
commonFinancialHash,
economic,
calls: {
create: 1,
advance: metrics.advanceCalls,
submit: metrics.submitCalls,
finalize: 1,
dispose: 1,
decisions,
},
bytes: {
createRequest: createRequestBytes,
advanceRequests: advanceRequestBytes * metrics.advanceCalls,
advanceResponses: metrics.contextBytes,
submitRequests: metrics.submissionBytes,
submitResponses: metrics.outcomeBytes,
finalizeRequest: finalizeRequestBytes,
finalizeResponse: metrics.resultBytes,
},
timingsMs: {
nativeCreateMs,
advance: metrics.advanceMs,
submit: metrics.submitMs,
decisions: metrics.decisionMs,
finalize: metrics.finalizeMs,
finalizeNative: metrics.finalizeNativeMs,
finalizeDecode: metrics.finalizeDecodeMs,
finalizeValidation: metrics.finalizeValidationMs,
dispose: metrics.disposeMs,
// This is measured time outside the named phases, not an inferred GC cost.
unattributedLoop:
runWallMs -
metrics.advanceMs -
metrics.submitMs -
metrics.decisionMs -
metrics.finalizeMs -
metrics.disposeMs,
runWallMs,
validationAndHashMs,
wallMs,
},
meanCallMs: {
advance: metrics.advanceMs / metrics.advanceCalls,
submit: metrics.submitMs / metrics.submitCalls,
},
rates: {
runBarsPerSecond: workload.totalBars / (runWallMs / 1000),
wholeTrialBarsPerSecond: workload.totalBars / (wallMs / 1000),
decisionsPerSecond: decisions / (runWallMs / 1000),
trialsPerSecond: 1000 / wallMs,
},
rssBytes: process.memoryUsage().rss,
});
}
const peakRss =
process.platform === 'linux'
? /^VmHWM:\s+(\d+) kB$/m.exec(readFileSync('/proc/self/status', 'utf8'))
: null;
return {
workload,
nativeSha256,
profile: workload.profile,
resultFormat: workload.resultFormat,
strategyHash: hash(profileDefinitions[workload.profile]),
datasetHash: dataset.manifest.hash,
policyHash: hash(
JSON.stringify({ config: load.config, strategy: profileDefinitions[workload.profile] })
),
datasetBytes: Buffer.byteLength(wireDataset),
policy: load.config,
phasesMs: {
entryUptimeMs,
applicationImportMs,
artifactIdentityMs,
addonImportMs,
adapterImportMs,
fixtureGenerationMs,
datasetTransportRoundtripMs,
frozenDatasetVerificationMs,
preparedReuseAndMappingMs,
requestSizingMs,
childWallMs: performance.now() - start,
},
peakRssBytes: peakRss ? Number(peakRss[1]) * 1024 : null,
peakRssSource: peakRss ? '/proc/self/status VmHWM' : 'unavailable',
trials,
};
}
export function verifySessionRepeats(
samples: {
datasetHash: string;
policyHash: string;
nativeSha256: string;
profile: ReplayProfile;
resultFormat: ReplayResultFormat;
strategyHash: string;
trials: { resultHash: string; commonFinancialHash: string }[];
}[],
expectedNativeHash?: string
) {
const first = samples[0],
expected = first?.trials[0]?.resultHash;
if (!first || !expected || !first.trials[0]?.commonFinancialHash) {
throw new Error('Missing canonical benchmark samples');
}
for (const sample of samples) {
if (
sample.datasetHash !== first.datasetHash ||
sample.policyHash !== first.policyHash ||
sample.nativeSha256 !== first.nativeSha256 ||
(expectedNativeHash !== undefined && sample.nativeSha256 !== expectedNativeHash) ||
sample.profile !== first.profile ||
sample.resultFormat !== first.resultFormat ||
sample.strategyHash !== first.strategyHash ||
!sample.trials.length ||
sample.trials.some(
trial =>
trial.resultHash !== expected ||
trial.commonFinancialHash !== first.trials[0]?.commonFinancialHash
)
) {
throw new Error('Canonical dataset/policy/result mismatch; no timing comparison is valid');
}
}
}
type SessionSample = Parameters<typeof verifySessionRepeats>[0][number];
export function verifyProjectionParity(
trace: SessionSample[],
projection: SessionSample[]
): string {
verifySessionRepeats(trace);
verifySessionRepeats(projection);
const a = trace[0],
b = projection[0],
sharedHash = a?.trials[0]?.commonFinancialHash;
if (
!a ||
!b ||
!sharedHash ||
a.resultFormat !== 'trace' ||
b.resultFormat !== 'projection' ||
a.datasetHash !== b.datasetHash ||
a.policyHash !== b.policyHash ||
a.strategyHash !== b.strategyHash ||
a.profile !== b.profile ||
a.nativeSha256 !== b.nativeSha256 ||
sharedHash !== b.trials[0]?.commonFinancialHash
) {
throw new Error('Compact/trace financial projection or provenance mismatch');
}
return sharedHash;
}
function median(values: number[]): number {
const sorted = [...values].sort((a, b) => a - b),
middle = Math.floor(sorted.length / 2),
upper = sorted[middle],
lower = sorted[Math.max(0, middle - 1)];
if (upper === undefined || lower === undefined) {
throw new Error('Missing measurement samples');
}
return sorted.length % 2 ? upper : (lower + upper) / 2;
}
export async function sessionBenchmark(
root: string,
entry: string,
metadata: { native: { sha256: string } },
measured: boolean,
large: boolean,
options: SessionOptions = { profiles: ['turnover'], resultFormat: 'trace' }
) {
const sizes = options.totalBars
? [options.totalBars]
: measured
? large
? [1000, 10000, 100000]
: [1000, 10000]
: [8];
const formats: ReplayResultFormat[] =
options.resultFormat === 'both' ? ['trace', 'projection'] : [options.resultFormat];
const workloads = options.profiles
.flatMap(profile =>
sizes.flatMap(bars => [
{
totalBars: bars,
assets: 1,
owners: 1,
eventBudget: 64,
profile,
resultFormat: 'trace' as const,
},
{
totalBars: measured ? bars : bars * 2,
assets: measured ? 10 : 2,
owners: 2,
eventBudget: 64,
profile,
resultFormat: 'trace' as const,
},
])
)
.flatMap(workload => formats.map(resultFormat => ({ ...workload, resultFormat })));
const measurements = [];
for (const workload of workloads) {
const samples = [];
for (let processRepeat = 0; processRepeat < 2; processRepeat++) {
const start = performance.now();
const worker = Bun.spawn(
[process.execPath, entry, '--session-child', JSON.stringify(workload)],
{
cwd: root,
stdout: 'pipe',
stderr: 'pipe',
env: { ...process.env, NODE_ENV: 'production' },
}
);
const [stdout, stderr, exit] = await Promise.all([
new Response(worker.stdout).text(),
new Response(worker.stderr).text(),
worker.exited,
]);
const processWallMs = performance.now() - start;
if (exit !== 0) {
throw new Error(`Canonical benchmark child failed (${exit}): ${stderr}\n${stdout}`);
}
const sample = JSON.parse(stdout) as Awaited<ReturnType<typeof sessionChild>>;
samples.push({
...sample,
processRepeat,
processWallMs,
nativeDiagnosticBytes: Buffer.byteLength(stderr),
processTrialsPerSecond: sample.trials.length / (processWallMs / 1000),
processBarsPerSecond: (workload.totalBars * sample.trials.length) / (processWallMs / 1000),
});
}
verifySessionRepeats(samples, metadata.native.sha256);
const trials = samples.flatMap(sample => sample.trials),
firstTrial = trials[0];
if (!firstTrial) {
throw new Error('Missing measurement trials');
}
const breakdown = {
samples: trials.length,
medianMs: Object.fromEntries(
Object.keys(firstTrial.timingsMs).map(key => [
key,
median(trials.map(trial => trial.timingsMs[key as keyof typeof trial.timingsMs])),
])
),
resultBytes: firstTrial.bytes.finalizeResponse,
};
measurements.push({ workload, repeatedResultHashesMatch: true, breakdown, samples });
process.stderr.write(
`Verified canonical ${workload.profile}/${workload.resultFormat}: ${workload.totalBars} bars / ${workload.assets} assets / ${workload.owners} owners, 2 fresh processes × 2 fresh sessions\n`
);
}
const comparisons = [];
if (options.resultFormat === 'both') {
for (let index = 0; index < measurements.length; index += 2) {
const trace = measurements[index],
projection = measurements[index + 1];
if (!trace || !projection) {
throw new Error('Missing paired measurements');
}
const commonFinancialHash = verifyProjectionParity(trace.samples, projection.samples);
comparisons.push({
profile: trace.workload.profile,
totalBars: trace.workload.totalBars,
assets: trace.workload.assets,
owners: trace.workload.owners,
commonFinancialHash,
trace: trace.breakdown,
projection: projection.breakdown,
});
}
}
process.stdout.write(
JSON.stringify(
{
schemaVersion: 2,
path: 'canonical-pull-session',
mode: measured ? 'measurement' : 'self-test',
...metadata,
strategy: {
profiles: options.profiles.map(profile => ({
profile,
definition: profileDefinitions[profile],
})),
randomness: 'None; controlled deterministic fixture/decision counters',
},
unavailable: {
storage: 'Synthetic fixture; no database I/O.',
queue: 'Direct child/session calls, not durable dispatch.',
allocations: 'No allocation counter or native/JS heap attribution.',
residentDataset: 'Every trial creates and reloads a fresh native session.',
pureBoundary:
'Timings include JS encoding/validation, native work and serialization; not empty NAPI crossing cost.',
sharedIndicators: 'No indicator cache or feature model in this conformance trace.',
parallelism: 'Sequential trials; no parallel simulation.',
perCallDistribution:
'Mean and total latency only; no latency histogram or cancellation wall-time claim.',
nativeInternals:
'Native-call timers include Rust work/serialization and NAPI; no Rust compute/serialization/allocation split.',
},
limitations: [
'Component conformance throughput, not a production strategy or durable research run; no comparison/speedup against legacy economics.',
'First imports and detached dataset verification are separate from once-per-child prepared-JS-object mapping and repeated fresh-session loads. OS page caches are not flushed.',
'First session and repeat are reported separately; no explicit warmup. Every repeated result, including reversed callback order, must match exactly.',
'Advance response bytes include immutable context, observation deltas and protocol envelopes; they are not feature payload bytes alone.',
'Financial oracle uses integer cents for this fixed-price/unit/1%-fee fixture only. Multi-asset sequential-mark risk semantics remain unchanged.',
'Trace returns full retained receipts; projection returns compact authoritative fields. Neither mode compacts internal journals. RSS is process-wide, not native residency.',
'Source/parent metadata hashing and aggregation are outside child timings. The child addon hash is measured separately in artifactIdentityMs and included in childWallMs.',
'Each format retains its own full normalized result hash. Cross-format comparison hashes shared provenance/view and copied fill/effect/fee fields; projection-only LedgerValuation is not recomputed in TypeScript.',
'Whole-trial time includes benchmark oracle and both result/projection hashes. runWallMs excludes that benchmark-only validation and includes separately measured disposal. Unattributed loop time is not labelled native work or GC.',
'An event budget bounds event count, not elapsed time. JSON throughput and actual decision costs are measured together with boundary work.',
],
measurements,
comparisons,
},
null,
2
) + '\n'
);
}