import type { ChildProcess } from 'node:child_process'; import { createHash } from 'node:crypto'; import { describe, expect, test } from 'bun:test'; import { FinancialReplaySession } from '@stock-bot/engine'; import { parseFinancialDecimal } from '@stock-bot/types'; import { executeReplayTrace, NativeReplaySession, prepareReplayLoad, runReplayConformance, } from '../../apps/stock/orchestrator/src/backtest/native-replay'; import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker'; import { parseReplayProjectionResult, parseReplayResult, replayConfigSchema, } from '@stock-bot/stock-config/canonical-replay'; import { nativeReplayFixture } from '../fixtures/native-replay'; const intent = (quantity = '2') => ({ mode: 'target' as const, targets: [{ instrumentId: 'X0.US', quantity: parseFinancialDecimal(quantity) }], }); const hold = () => ({ mode: 'target' as const, targets: [] }); function request() { const f = nativeReplayFixture(); return { type: 'runReplayTrace' as const, version: 1 as const, dataset: f.dataset, config: replayConfigSchema.parse(f.config), eventBudget: 1, trace: [ { at: f.start + f.minute, ownerId: 'A', intent: intent() }, { at: f.start + 2 * f.minute, ownerId: 'A', intent: hold() }, ], }; } describe('compact canonical replay projection', () => { test('compact_full_financial_parity and unchanged diagnostic hash', () => { const input = request(), trace = executeReplayTrace(input), compact = executeReplayTrace({ ...input, resultFormat: 'projection' }); // Captured from committed F07 before implementing this projection. expect(createHash('sha256').update(JSON.stringify(trace.result)).digest('hex')).toBe( 'bb46165ddfe2de122689bdc47d5b1cc4065d55fdfc58a991cb3a61a91f4ad880' ); expect(compact.result.view).toEqual(trace.result.view); expect(compact.result.policy).toEqual(trace.result.policy); expect(compact.result.manifest).toEqual(trace.result.manifest); expect(compact.result.limitations).toEqual(trace.result.limitations); expect(compact.result.modelLimitations).toEqual(trace.result.modelLimitations); expect(compact.result).not.toHaveProperty('receipts'); expect(compact.result.projection.valuation.cash).toBe('9975.76000000'); expect(compact.result.projection.valuation.equity).toBe('10005.76000000'); expect(compact.result.projection.valuation.fees).toBe('0.24000000'); expect(compact.result.projection.fills).toHaveLength(1); const fill = compact.result.projection.fills[0]!; expect(fill.cashDelta).toBe('-24.00000000'); expect(fill.fee.amount).toBe('0.24000000'); expect(fill.releasedBasis).toBe('0.00000000'); expect(fill.ownerId).toBe('A'); expect(fill.decision.ownerId).toBe('A'); const fullEffects = trace.result.receipts .flatMap(r => (r.outcome.replayed ? [] : r.outcome.effects)) .flatMap((effect: any) => effect.Risk?.outcome.replayed || effect.Risk?.outcome.financial?.replayed ? [] : (effect.Risk?.outcome.financial?.effects.effects ?? []) ); const applied = fullEffects.filter((e: any) => e.kind === 'fillApplied'); const fee = fullEffects.filter((e: any) => e.kind === 'feeApplied'); expect(applied).toHaveLength(1); expect(fee).toHaveLength(1); for (const key of [ 'ownerId', 'orderId', 'fillId', 'instrumentId', 'price', 'cashDelta', 'quantityDelta', 'releasedBasis', 'realizedGrossPnl', ] as const) { expect(fill[key]).toEqual(applied[0][key]); } expect(fill.fee.amount).toEqual(fee[0].amount); expect(fill.fee.feeId).toEqual(fee[0].feeId); expect(compact.metrics.resultBytes).toBeLessThan(trace.metrics.resultBytes); for (const metrics of [compact.metrics, trace.metrics]) { for (const value of [ metrics.finalizeNativeMs, metrics.finalizeDecodeMs, metrics.finalizeValidationMs, metrics.disposeMs, ]) { expect(Number.isFinite(value)).toBe(true); expect(value).toBeGreaterThanOrEqual(0); } } expect(JSON.stringify(compact.result)).not.toContain('finalizeNativeMs'); }); test('two owners share one financial projection and reverse callbacks preserve it', () => { const f = nativeReplayFixture(3, 1, ['B', 'A']); const run = (reverseCallbacks: boolean) => runReplayConformance( new NativeReplaySession(prepareReplayLoad(f.dataset, f.config)), (_owner, c) => (c.barrier.at === f.start + f.minute ? intent('1') : hold()), { resultFormat: 'projection', reverseCallbacks } ).result; const output = run(false); expect(run(true)).toEqual(output); expect(output.projection.fills.map(f => f.ownerId)).toEqual(['A', 'B']); expect(output.projection.valuation.fees).toBe('0.24000000'); expect(output.projection.valuation.equity).toBe('10005.76000000'); }); test('projection_is_read_only preserves native diagnostic bytes across repeated projections', () => { const f = nativeReplayFixture(), load = prepareReplayLoad(f.dataset, f.config); const native = new FinancialReplaySession(JSON.stringify(load)), identity = JSON.stringify(load.identity); let sequence = 0; try { for (;;) { const response = JSON.parse( native.advance(JSON.stringify({ identity: load.identity, eventBudget: 100 })) ); if (response.step.type === 'complete') { break; } if (response.step.type === 'failed') { throw new Error(response.step.diagnostic); } if (response.step.type === 'decisionBatch') { const barrier = response.step.barrier; native.submit( JSON.stringify({ identity: load.identity, barrierId: barrier.barrier_id, decisions: [ { version: 1, sessionId: load.identity.sessionId, barrierId: barrier.barrier_id, revision: barrier.revision, decision: { ownerId: 'A', decisionId: `native-${sequence}`, sequence: sequence++, }, intent: barrier.at === f.start + f.minute ? intent() : hold(), }, ], }) ); } } const before = native.finalize(identity), first = native.project(identity); expect(native.project(identity)).toBe(first); expect(native.finalize(identity)).toBe(before); expect(JSON.parse(first).view).toEqual(JSON.parse(before).view); expect(JSON.parse(first).projection.fills).toHaveLength(1); } finally { native.dispose(); } }); test('projection_terminal_guard covers incomplete, failed, disposed and wrong identity', () => { const f = nativeReplayFixture(), load = prepareReplayLoad(f.dataset, f.config); load.prepared.bars[0]!.high = '792281625142643375935.43950335'; load.prepared.bars[0]!.close = '792281625142643375935.43950335'; const native = new FinancialReplaySession(JSON.stringify(load)), identity = JSON.stringify(load.identity); expect(() => native.project(identity)).toThrow('complete'); expect(() => native.project(JSON.stringify({ ...load.identity, version: 2 }))).toThrow(); expect(() => native.project(JSON.stringify({ ...load.identity, sessionId: 'wrong' }))).toThrow( 'identity' ); const step = JSON.parse( native.advance(JSON.stringify({ identity: load.identity, eventBudget: 100 })) ); const submission = JSON.parse( native.submit( JSON.stringify({ identity: load.identity, barrierId: step.step.barrier.barrier_id, decisions: [ { version: 1, sessionId: load.identity.sessionId, barrierId: step.step.barrier.barrier_id, revision: step.step.barrier.revision, decision: { ownerId: 'A', decisionId: 'overflow', sequence: 0 }, intent: intent(), }, ], }) ) ); expect(submission.outcome.status).toHaveProperty('Failed'); expect(() => native.project(identity)).toThrow('complete'); native.dispose(); expect(() => native.project(identity)).toThrow('disposed'); }); test('projection_identity_policy_format rejects incompatible and inconsistent payloads', () => { const input = request(), trace = executeReplayTrace(input).result, output = executeReplayTrace({ ...input, resultFormat: 'projection' }).result; expect(() => parseReplayProjectionResult(JSON.stringify(trace), output.identity)).toThrow(); expect(() => parseReplayResult(JSON.stringify(output), output.identity)).toThrow(); for (const mutate of [ (r: any) => (r.projectionVersion = 2), (r: any) => (r.financialVersion = 2), (r: any) => (r.receipts = []), (r: any) => (r.projection.valuation.cash = '1'), (r: any) => (r.projection.valuation.equity = '1'), (r: any) => (r.projection.fills[0].ownerId = 'B'), (r: any) => (r.projection.fills[0].fee.amount = '-1'), (r: any) => (r.policy.matching.risk.feeRate = '0.5'), ]) { const bad = structuredClone(output); mutate(bad); expect(() => parseReplayProjectionResult(JSON.stringify(bad), output.identity, input.config) ).toThrow(); } }); test('worker captures projection format and preserves post-result cancellation', async () => { const input = { ...request(), resultFormat: 'projection' as const }, worker = new NativeBacktestWorker(); const expected = executeReplayTrace(input).result; const mutable: { resultFormat: 'projection' | 'trace' } & typeof input = { ...input }; const raw = await worker.execute(mutable, new AbortController().signal, () => { (mutable as { resultFormat: string }).resultFormat = 'trace'; }); expect(parseReplayProjectionResult(raw, expected.identity, input.config)).toEqual(expected); const fixture = new NativeBacktestWorker( new URL('../fixtures/native-replay-worker.ts', import.meta.url) ); for (const resultFormat of ['projection', 'trace'] as const) { const bad = { ...request(), resultFormat }; bad.config.matching.risk.ledger.accountId = 'wrong-format'; await expect(fixture.execute(bad, new AbortController().signal, () => {})).rejects.toThrow(); } const blocked = { ...request(), resultFormat: 'projection' as const }; blocked.config.matching.risk.ledger.accountId = 'result-then-block'; const cancel = new AbortController(); let observed = false; const running = fixture.execute(blocked, cancel.signal, () => {}); const child = (fixture as unknown as { active: ChildProcess }).active; child.on('message', (message: any) => { if (message.type === 'result') { observed = true; cancel.abort(new Error('compact result cancelled')); } }); await expect(running).rejects.toThrow('compact result cancelled'); expect(observed).toBe(true); expect( JSON.parse(await fixture.execute(input, new AbortController().signal, () => {})).format ).toBe('projection'); }); });