import { expect, test } from 'bun:test'; import { parseFinancialDecimal } from '@stock-bot/types'; import { executeReplayTrace } from '../../apps/stock/orchestrator/src/backtest/native-replay'; import { nativeReplayFixture } from '../../test/fixtures/native-replay'; import { assertResultFormat, commonFinancialProjection, profileOracle, profileTarget, turnoverOracle, verifyProjectionParity, verifySessionRepeats, } from '../benchmark-replay'; import { parseBenchmarkArguments } from '../benchmark-research'; test('profile_none invokes the same cadence without orders, fees or position books', () => { expect(profileOracle('none', 602, 2, 2)).toEqual({ cash: '1000000.00000000', equity: '1000000.00000000', feePerOwner: '0.00000000', quantity: '0.00000000', remainingCost: '0.00000000', fills: 0, decisions: 1202, }); for (let decision = 0; decision < 601; decision++) { expect(profileTarget('none', decision, 602)).toBeNull(); } }); test('profile_sparse buys first and sells last across retained session gaps', () => { expect(profileOracle('sparse', 602, 2, 2)).toEqual({ cash: '999999.04000000', equity: '999999.04000000', feePerOwner: '0.48000000', quantity: '0.00000000', remainingCost: '0.00000000', fills: 8, decisions: 1202, }); expect(profileTarget('sparse', 0, 602)).toBe(1); expect(profileTarget('sparse', 600, 602)).toBe(0); for (let decision = 1; decision < 600; decision++) { expect(profileTarget('sparse', decision, 602)).toBeNull(); } expect(profileOracle('sparse', 4, 1, 1).cash).toBe('1000003.72000000'); }); test('benchmark_profile_arguments preserves defaults and rejects unsupported combinations', () => { expect(parseBenchmarkArguments([])).toMatchObject({ session: false, measured: false, profile: 'turnover', resultFormat: 'trace', }); expect(parseBenchmarkArguments(['--session'])).toMatchObject({ session: true, profile: 'turnover', }); expect( parseBenchmarkArguments([ '--session', '--measure', '--profile=all', '--format=trace', '--bars=100000', ]) ).toMatchObject({ session: true, measured: true, profile: 'all', resultFormat: 'trace', totalBars: 100000, }); for (const resultFormat of ['trace', 'projection', 'both'] as const) { expect(parseBenchmarkArguments(['--session', `--format=${resultFormat}`]).resultFormat).toBe( resultFormat ); } for (const args of [ ['--profile=none'], ['--session', '--profile=unknown'], ['--session', '--format=unknown'], ['--session', '--bars=10000'], ['--session', '--measure', '--bars=99'], ['--large'], ['--session', '--measure', '--large', '--bars=10000'], ['--self-test', '--measure'], ['--session=yes'], ['--session', '--session'], ['--session', '--profile=none=extra'], ]) { expect(() => parseBenchmarkArguments(args)).toThrow(); } }); test('profile_turnover integer-cent oracle includes fees and terminal marks', () => { expect(turnoverOracle(3, 1, 1)).toEqual({ cash: '1000001.74000000', equity: '1000001.74000000', feePerOwner: '0.26000000', quantity: '0.00000000', remainingCost: '0.00000000', fills: 2, decisions: 2, }); expect(turnoverOracle(4, 2, 2)).toEqual({ cash: '999942.32000000', equity: '1000010.32000000', feePerOwner: '0.84000000', quantity: '1.00000000', remainingCost: '16.00000000', fills: 12, decisions: 6, }); expect(() => turnoverOracle(2, 1, 1)).toThrow('three bars'); }); test('canonical benchmark rejects any changed provenance or complete result hash', () => { const sample = { datasetHash: 'dataset', policyHash: 'policy', nativeSha256: 'native', profile: 'turnover' as const, resultFormat: 'trace' as const, strategyHash: 'strategy', trials: [ { resultHash: 'result', commonFinancialHash: 'common' }, { resultHash: 'result', commonFinancialHash: 'common' }, ], }; expect(() => verifySessionRepeats([sample, structuredClone(sample)])).not.toThrow(); for (const changed of [ { ...sample, datasetHash: 'changed' }, { ...sample, policyHash: 'changed' }, { ...sample, nativeSha256: 'changed' }, { ...sample, strategyHash: 'changed' }, { ...sample, profile: 'none' as const }, { ...sample, resultFormat: 'projection' as const }, { ...sample, trials: [{ resultHash: 'changed', commonFinancialHash: 'common' }] }, { ...sample, trials: [{ resultHash: 'result', commonFinancialHash: 'changed' }] }, { ...sample, trials: [] }, ]) { expect(() => verifySessionRepeats([sample, changed])).toThrow('mismatch'); } expect(() => verifySessionRepeats([])).toThrow('Missing'); expect(() => verifySessionRepeats([ { ...sample, trials: [{ resultHash: 'result', commonFinancialHash: '' }] }, ]) ).toThrow('Missing'); expect(() => verifySessionRepeats([sample], 'different-artifact')).toThrow('mismatch'); }); function normalizerFixture() { const fixture = nativeReplayFixture(); const input = { type: 'runReplayTrace' as const, version: 1 as const, dataset: fixture.dataset, config: fixture.config, eventBudget: 1, trace: [ { at: fixture.start + fixture.minute, ownerId: 'A', intent: { mode: 'target' as const, targets: [{ instrumentId: 'X0.US', quantity: parseFinancialDecimal('2') }], }, }, { at: fixture.start + 2 * fixture.minute, ownerId: 'A', intent: { mode: 'target' as const, targets: [] }, }, ], }; return { trace: executeReplayTrace(input).result, projection: executeReplayTrace({ ...input, resultFormat: 'projection' }).result, }; } test('common financial projection copies authoritative fill facts without valuing positions', () => { const { trace, projection } = normalizerFixture(); const common = commonFinancialProjection(trace); expect(commonFinancialProjection(projection)).toEqual(common); expect(common).not.toHaveProperty('valuation'); expect(common.fills).toHaveLength(1); expect(common.fills[0]).toMatchObject({ cashDelta: '-24.00000000', fee: { amount: '0.24000000' }, }); for (const field of [ 'commandId', 'eventTime', 'ownerId', 'orderId', 'fillId', 'instrumentId', 'price', 'cashDelta', 'quantityDelta', 'releasedBasis', 'realizedGrossPnl', ] as const) { const changed = structuredClone(projection); const fill = changed.projection.fills[0]!; Object.assign(fill, { [field]: typeof fill[field] === 'number' ? Number(fill[field]) + 1 : 'changed', }); expect(commonFinancialProjection(changed)).not.toEqual(common); } for (const field of ['feeId', 'amount'] as const) { const changed = structuredClone(projection); Object.assign(changed.projection.fills[0]!.fee, { [field]: 'changed' }); expect(commonFinancialProjection(changed)).not.toEqual(common); } expect(() => assertResultFormat(trace, 'trace')).not.toThrow(); expect(() => assertResultFormat(projection, 'projection')).not.toThrow(); expect(() => assertResultFormat(trace, 'projection')).toThrow('format mismatch'); expect(() => assertResultFormat(projection, 'trace')).toThrow('format mismatch'); }); test('common projection skips matching, risk and financial replay aliases independently', () => { const { trace } = normalizerFixture(); const receipt = trace.receipts.find(r => r.outcome.effects.some((effect: any) => effect.Risk?.outcome.financial?.effects.effects.some((e: any) => e.kind === 'fillApplied') ) )!; expect(receipt).toBeDefined(); for (const level of ['matching', 'risk', 'financial']) { const alias = structuredClone(receipt); const risk: any = alias.outcome.effects.find((effect: any) => effect.Risk?.outcome.financial?.effects.effects.some((e: any) => e.kind === 'fillApplied') )!.Risk; if (level === 'matching') { alias.outcome.replayed = true; } else if (level === 'risk') { risk.outcome.replayed = true; } else { risk.outcome.financial.replayed = true; } expect(commonFinancialProjection({ ...trace, receipts: [receipt, alias] }).fills).toHaveLength( 1 ); expect(commonFinancialProjection({ ...trace, receipts: [alias] }).fills).toHaveLength(0); } }); test('common projection handles 100k multi-owner turnover without argument spreading', () => { const { projection } = normalizerFixture(); projection.projection.fills = Array.from( { length: 200000 }, () => projection.projection.fills[0]! ); const common = commonFinancialProjection(projection); expect(common.fills).toHaveLength(200000); expect(common.fills.at(-1)).toEqual(common.fills[0]!); }); test('common projection rejects missing, duplicate or mismatched financial fee pairs', () => { const { trace } = normalizerFixture(); for (const change of ['missing', 'extra', 'owner', 'fill', 'rejection']) { const invalid = structuredClone(trace); const risk: any = invalid.receipts .flatMap(r => r.outcome.effects) .map(effect => effect.Risk) .find((r: any) => r?.outcome.financial?.effects.effects.some((e: any) => e.kind === 'fillApplied') ); const effects = risk.outcome.financial.effects.effects; const fee = effects.find((e: any) => e.kind === 'feeApplied'); if (change === 'missing') { effects.splice(effects.indexOf(fee), 1); } else if (change === 'extra') { effects.push(structuredClone(fee)); } else if (change === 'owner') { fee.ownerId = 'other'; } else if (change === 'fill') { fee.fillId = 'other'; } else { risk.outcome.disposition = { Rejected: 'fixture' }; } expect(() => commonFinancialProjection(invalid)).toThrow(); } }); test('paired comparison requires shared economics and provenance while retaining distinct full hashes', () => { const trace = { datasetHash: 'dataset', policyHash: 'policy', nativeSha256: 'native', profile: 'sparse' as const, resultFormat: 'trace' as const, strategyHash: 'strategy', trials: [{ resultHash: 'full-trace', commonFinancialHash: 'common' }], }; const projection = { ...trace, resultFormat: 'projection' as const, trials: [{ resultHash: 'compact-projection', commonFinancialHash: 'common' }], }; expect(verifyProjectionParity([trace], [projection])).toBe('common'); for (const changed of [ { ...projection, datasetHash: 'changed' }, { ...projection, policyHash: 'changed' }, { ...projection, nativeSha256: 'changed' }, { ...projection, strategyHash: 'changed' }, { ...projection, profile: 'none' as const }, { ...projection, resultFormat: 'trace' as const }, { ...projection, trials: [{ resultHash: 'compact-projection', commonFinancialHash: 'changed' }], }, ]) { expect(() => verifyProjectionParity([trace], [changed])).toThrow('mismatch'); } }); test('all tiny replay profiles pin financial expectations and distinct strategy identities', async () => { const worker = Bun.spawn( [ process.execPath, 'scripts/benchmark-research.ts', '--session', '--profile=all', '--format=both', ], { 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.measurements).toHaveLength(12); expect(report.comparisons).toHaveLength(6); for (const comparison of report.comparisons) { expect(comparison.commonFinancialHash).toMatch(/^[a-f0-9]{64}$/); expect(comparison.projection.resultBytes).toBeLessThan(comparison.trace.resultBytes); } expect(new Set(report.measurements.map((m: any) => m.samples[0].strategyHash)).size).toBe(3); for (const measurement of report.measurements) { verifySessionRepeats(measurement.samples, report.native.sha256); const workload = measurement.workload; const expected = profileOracle( workload.profile, workload.totalBars / workload.assets, workload.assets, workload.owners ); for (const sample of measurement.samples) { expect(sample.profile).toBe(workload.profile); expect(sample.resultFormat).toBe(workload.resultFormat); for (const trial of sample.trials) { expect(trial.economic).toEqual({ ...expected, fees: expected.fills }); for (const value of Object.values(trial.timingsMs) as number[]) { expect(Number.isFinite(value)).toBe(true); expect(value).toBeGreaterThanOrEqual(0); } expect(trial.timingsMs.finalize).toBeGreaterThanOrEqual( trial.timingsMs.finalizeNative + trial.timingsMs.finalizeDecode + trial.timingsMs.finalizeValidation ); } } } }); test('canonical self-test measures real sessions and verifies repeated full-result hashes', async () => { const worker = Bun.spawn([process.execPath, 'scripts/benchmark-research.ts', '--session'], { 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.path).toBe('canonical-pull-session'); expect(report.mode).toBe('self-test'); expect(report.native.sha256).toMatch(/^[a-f0-9]{64}$/); expect(report.measurements.map((m: any) => m.workload.owners)).toEqual([1, 2]); for (const measurement of report.measurements) { verifySessionRepeats(measurement.samples); expect(measurement.samples).toHaveLength(2); for (const sample of measurement.samples) { expect(sample.trials).toHaveLength(2); expect(sample.phasesMs.frozenDatasetVerificationMs).toBeGreaterThanOrEqual(0); expect(sample.phasesMs.preparedReuseAndMappingMs).toBeGreaterThanOrEqual(0); for (const trial of sample.trials) { expect(trial.resultHash).toMatch(/^[a-f0-9]{64}$/); expect(trial.calls.decisions).toBe(trial.economic.decisions); expect(trial.economic.fees).toBe(trial.economic.fills); expect(trial.calls.advance).toBeGreaterThan(trial.calls.submit); expect(trial.bytes.advanceResponses).toBeGreaterThan(0); expect(trial.bytes.submitRequests).toBeGreaterThan(0); expect(trial.bytes.finalizeResponse).toBeGreaterThan(0); expect(trial.timingsMs.nativeCreateMs).toBeGreaterThanOrEqual(0); expect(trial.timingsMs.finalize).toBeGreaterThanOrEqual(0); } } } });