/** * Active TypeScript-to-Rust replay boundary used by strategy-runtime and the * isolated candidate host. This module validates native messages and drives a * pull loop; Rust owns the clock, order matching, risk and financial state. * Controllers receive published observations and decision views, never the handle. */ import { FinancialReplaySession } from '@stock-bot/engine'; import { parseFinancialDecimal, parseFinancialStrategyDecision, type FinancialStrategyDecision, type FinancialStrategyIntent, } from '@stock-bot/types'; import { parseReplayProjectionValue, parseReplayReportValue, parseReplayResultValue, replayConfigSchema, replayTraceSchema, sameIdentity, stepSchema, submissionSchema, type DecisionContext, type PublishedObservation, type ReplayConfig, type ReplayIdentity, type ReplayOutput, type ReplayProjectionResult, type ReplayReportResult, type ReplayResult, type ReplayResultFormat, type ReplayStep, type ReplaySubmissionOutcome, type ReplayTraceRequest, } from '@stock-bot/stock-config/canonical-replay'; import { validateDatasetV2 } from '../data/historical-dataset-v2'; export type { ReplayConfig, ReplayIdentity, ReplayStep, ReplayResult, ReplayProjectionResult, ReplayReportResult, ReplayOutput, ReplayResultFormat, DecisionContext, PublishedObservation, ReplayTraceRequest, } from '@stock-bot/stock-config/canonical-replay'; /** Expand Number's exact shortest lexical representation, never round toFixed. * D01 already owns numeric data precision; >8 decimals cannot enter the ledger. */ export function marketDecimal(value: number): string { if (!Number.isFinite(value)) { throw new Error('Non-finite market decimal'); } const source = String(value); if (!/[eE]/.test(source)) { return parseFinancialDecimal(source); } const [mantissa = '', exponent = ''] = source.toLowerCase().split('e'); const negative = mantissa.startsWith('-'); const [whole = '', fractional = ''] = (negative ? mantissa.slice(1) : mantissa).split('.'); const digits = whole + fractional, point = whole.length + Number(exponent); const plain = point <= 0 ? `0.${'0'.repeat(-point)}${digits}` : point >= digits.length ? digits + '0'.repeat(point - digits.length) : `${digits.slice(0, point)}.${digits.slice(point)}`; return parseFinancialDecimal(`${negative ? '-' : ''}${plain}`); } /** * Verify the retained payload, bind execution series and translate domain names * into the native wire format. Prices become checked decimal strings; timestamp * and availability declarations are preserved rather than inferred here. * The worker verifies actual content instead of trusting an upstream hash label. */ export function prepareReplayLoad(datasetInput: unknown, configInput: ReplayConfig) { const dataset = validateDatasetV2(datasetInput), manifest = dataset.manifest; const config = replayConfigSchema.parse(configInput); const actual = config.matching.series.map(s => [s.instrumentId, s.seriesId]).sort(); const expected = manifest.executionSeries.map(s => [s.instrumentId, s.seriesId]).sort(); if (JSON.stringify(actual) !== JSON.stringify(expected)) { throw new Error('Execution series must exactly match the verified dataset'); } const identity: ReplayIdentity = { version: 1, sessionId: config.matching.risk.ledger.sessionId, datasetHash: manifest.hash, }; return { identity, config, manifest, prepared: { dataset_id: manifest.hash, eligibility: { eligible: 'Eligible', exploratory: 'Exploratory', ineligible: 'Ineligible' }[ manifest.eligibility ], limitations: manifest.limitations, bounds: { warmup_start: manifest.bounds.warmupStart, trade_start: manifest.bounds.tradeStart, trade_end: manifest.bounds.tradeEnd, }, series: manifest.series.map(series => { const calendar = manifest.calendars.find(c => c.id === series.calendarId); if (!calendar) { throw new Error('Missing retained calendar'); } return { series_id: series.id, instrument_id: series.instrumentId, adjustment: series.adjustment === 'raw' ? 'Raw' : 'ProviderAdjusted', sessions: calendar.sessions .filter( session => session.close > manifest.bounds.warmupStart && session.open < manifest.bounds.tradeEnd ) .map(session => ({ sessionId: JSON.stringify([calendar.id, calendar.revision, session.date]), opensAt: session.open, closesAt: session.close, })), }; }), bars: dataset.bars.map(bar => ({ series_id: bar.seriesId, instrument_id: bar.instrumentId, interval_start: bar.intervalStart, interval_end: bar.intervalEnd, event_time: bar.eventTime, available_at: bar.availableAt, source_sequence: bar.sourceSequence, open: marketDecimal(bar.open), high: marketDecimal(bar.high), low: marketDecimal(bar.low), close: marketDecimal(bar.close), volume: marketDecimal(bar.volume), })), }, }; } function freeze(value: T): T { if (value && typeof value === 'object' && !Object.isFrozen(value)) { Object.values(value).forEach(freeze); Object.freeze(value); } return value; } /** * Checked JSON facade over the NAPI FinancialReplaySession owned by this process. * Every response is schema/identity checked. The supported StrategyContext does * not expose this handle; trusted in-process code is not a security sandbox. * Byte/timing counters measure boundary overhead, not financial performance. * This research facade exposes no financial checkpoint restore operation. */ export class NativeReplaySession { readonly identity: ReplayIdentity; private readonly native: FinancialReplaySession; readonly transport = { advanceResponseBytes: 0, submitRequestBytes: 0, submitResponseBytes: 0, resultBytes: 0, }; readonly finalization = { nativeMs: 0, decodeMs: 0, validationMs: 0 }; constructor(load: ReturnType) { this.identity = freeze({ ...load.identity }); this.native = new FinancialReplaySession(JSON.stringify(load)); } /** Advance at most this many replay events, stopping earlier for a decision or completion. */ advance(eventBudget: number): ReplayStep { const raw = this.native.advance(JSON.stringify({ identity: this.identity, eventBudget })); this.transport.advanceResponseBytes += Buffer.byteLength(raw); const result = stepSchema.parse(JSON.parse(raw)); sameIdentity(result.identity, this.identity); if ( result.step.type === 'decisionBatch' && (result.step.view.admissionRevision !== result.step.barrier.revision || result.step.view.portfolio.sessionId !== this.identity.sessionId) ) { throw new Error('Native barrier view mismatch'); } return freeze(result); } /** Submit the complete due-owner batch; admission feedback is not later fill feedback. */ submit(barrierId: string, decisions: FinancialStrategyDecision[]) { const request = JSON.stringify({ identity: this.identity, barrierId, decisions: decisions.map(parseFinancialStrategyDecision), }); this.transport.submitRequestBytes += Buffer.byteLength(request); const raw = this.native.submit(request); this.transport.submitResponseBytes += Buffer.byteLength(raw); const result = submissionSchema.parse(JSON.parse(raw)); sameIdentity(result.identity, this.identity); return freeze(result.outcome); } finalize(): ReplayResult { const identity = JSON.stringify(this.identity); return this.finish( () => this.native.finalize(identity), input => parseReplayResultValue(input, this.identity) ); } project(): ReplayProjectionResult { const identity = JSON.stringify(this.identity); return this.finish( () => this.native.project(identity), input => parseReplayProjectionValue(input, this.identity) ); } report(): ReplayReportResult { const identity = JSON.stringify(this.identity); return this.finish( () => this.native.report(identity), input => parseReplayReportValue(input, this.identity) ); } private finish(native: () => string, validate: (input: unknown) => T): T { let start = performance.now(); const raw = native(); this.finalization.nativeMs += performance.now() - start; this.transport.resultBytes += Buffer.byteLength(raw); start = performance.now(); const decoded: unknown = JSON.parse(raw); this.finalization.decodeMs += performance.now() - start; start = performance.now(); const result = validate(decoded); this.finalization.validationMs += performance.now() - start; return result; } dispose(): void { this.native.dispose(); } } export interface ReplayMetrics { advanceCalls: number; submitCalls: number; contextBytes: number; submissionBytes: number; outcomeBytes: number; resultBytes: number; advanceMs: number; submitMs: number; decisionMs: number; finalizeMs: number; finalizeNativeMs: number; finalizeDecodeMs: number; finalizeValidationMs: number; disposeMs: number; } type Decide = ( ownerId: string, context: DecisionContext, observations: readonly PublishedObservation[] ) => FinancialStrategyIntent; export interface ReplayOptions { eventBudget?: number; reverseCallbacks?: boolean; onProgress?: (step: ReplayStep) => void; resultFormat?: ReplayResultFormat; } /** Internal trusted-host seam. All due decisions are staged before one native * submission. A controller never receives the native handle. */ export interface ReplayController { stage( context: DecisionContext, observations: readonly PublishedObservation[] ): FinancialStrategyDecision[]; committed?(outcome: ReplaySubmissionOutcome): void; } /** Restricted hosts communicate asynchronously; financial transitions still run * on the same native session and the same ordered pull loop. */ export interface AsyncReplayController { stage( context: DecisionContext, observations: readonly PublishedObservation[] ): Promise; committed?(outcome: ReplaySubmissionOutcome): Promise; } /* eslint-disable no-redeclare -- TypeScript overloads preserve the existing trace result type. */ export function runReplayConformance( session: NativeReplaySession, decide: Decide, options: ReplayOptions & { resultFormat: 'report' } ): { result: ReplayReportResult; metrics: ReplayMetrics }; export function runReplayConformance( session: NativeReplaySession, decide: Decide, options: ReplayOptions & { resultFormat: 'projection' } ): { result: ReplayProjectionResult; metrics: ReplayMetrics }; export function runReplayConformance( session: NativeReplaySession, decide: Decide, options?: ReplayOptions & { resultFormat?: 'trace' } ): { result: ReplayResult; metrics: ReplayMetrics }; export function runReplayConformance( session: NativeReplaySession, decide: Decide, options: ReplayOptions ): { result: ReplayOutput; metrics: ReplayMetrics }; /** Conformance driver only. No persisted strategy states/RNG, dynamic code, or * production strategy framework. Shared view is frozen before any fixture runs. */ export function runReplayConformance( session: NativeReplaySession, decide: Decide, options: ReplayOptions = {} ) { /* eslint-enable no-redeclare */ let sequence = 0; return runReplaySession( session, { stage(context, observations) { const owners = [...context.barrier.owner_ids]; if (options.reverseCallbacks) { owners.reverse(); } const decisions = owners.map(ownerId => parseFinancialStrategyDecision({ version: 1, sessionId: session.identity.sessionId, barrierId: context.barrier.barrier_id, revision: context.barrier.revision, decision: { ownerId, decisionId: JSON.stringify(['trace', sequence, ownerId]), sequence, }, intent: decide(ownerId, context, observations), }) ); sequence++; return decisions; }, }, options ); } /** One pull loop for conformance and stateful programs. Always disposes the * attempt, including ambiguous submissions or failures in host callbacks. */ export function runReplaySession( session: NativeReplaySession, controller: ReplayController, options: ReplayOptions = {} ) { const loop = replaySteps(session, options); try { let step = loop.next(); while (!step.done) { const action = step.value; step = loop.next( action.kind === 'stage' ? controller.stage(action.context, action.observations) : controller.committed?.(action.outcome) ); } return step.value; } finally { // A controller may throw while the generator is suspended at a decision. // Closing it runs the native disposal even without another advance call. loop.return(undefined as never); } } /** The isolated candidate controller may await IPC; it shares the synchronous driver's loop. */ export async function runReplaySessionAsync( session: NativeReplaySession, controller: AsyncReplayController, options: ReplayOptions = {} ) { const loop = replaySteps(session, options); try { let step = loop.next(); while (!step.done) { const action = step.value; step = loop.next( action.kind === 'stage' ? await controller.stage(action.context, action.observations) : await controller.committed?.(action.outcome) ); } return step.value; } finally { loop.return(undefined as never); } } type ReplayAction = | { kind: 'stage'; context: DecisionContext; observations: readonly PublishedObservation[]; } | { kind: 'committed'; outcome: ReplaySubmissionOutcome }; /** * One ordered loop serves both trusted synchronous and isolated async decisions. * Observations accumulate across progress steps until a barrier; stage produces * all due intents, Rust admits them together, then committed confirms host state. * Generator cleanup disposes the native session even if a callback/IPC fails. */ function* replaySteps( session: NativeReplaySession, options: ReplayOptions ): Generator< ReplayAction, { result: ReplayOutput; metrics: ReplayMetrics }, FinancialStrategyDecision[] | void > { const metrics: ReplayMetrics = { advanceCalls: 0, submitCalls: 0, contextBytes: 0, submissionBytes: 0, outcomeBytes: 0, resultBytes: 0, advanceMs: 0, submitMs: 0, decisionMs: 0, finalizeMs: 0, finalizeNativeMs: 0, finalizeDecodeMs: 0, finalizeValidationMs: 0, disposeMs: 0, }; let observations: PublishedObservation[] = []; try { for (;;) { const start = performance.now(), step = session.advance(options.eventBudget ?? 256); metrics.advanceMs += performance.now() - start; metrics.advanceCalls++; for (const observation of step.observations) { observations.push(observation); } options.onProgress?.(step); switch (step.step.type) { case 'progress': break; case 'failed': throw new Error(step.step.diagnostic); case 'complete': { const start = performance.now(), result = options.resultFormat === 'report' ? session.report() : options.resultFormat === 'projection' ? session.project() : session.finalize(); metrics.finalizeMs = performance.now() - start; metrics.finalizeNativeMs = session.finalization.nativeMs; metrics.finalizeDecodeMs = session.finalization.decodeMs; metrics.finalizeValidationMs = session.finalization.validationMs; metrics.contextBytes = session.transport.advanceResponseBytes; metrics.submissionBytes = session.transport.submitRequestBytes; metrics.outcomeBytes = session.transport.submitResponseBytes; metrics.resultBytes = session.transport.resultBytes; return { result, metrics }; } case 'decisionBatch': { const context = step.step, start = performance.now(); const publishedDelta = Object.freeze(observations); observations = []; // Stage all decisions before one admission. A thrown fixture disposes // the attempt; it cannot publish a partial barrier or successful run. const decisions = yield { kind: 'stage', context, observations: publishedDelta }; if (!Array.isArray(decisions)) { throw new Error('Replay controller did not return decisions'); } metrics.decisionMs += performance.now() - start; const submitStart = performance.now(), outcome = session.submit(context.barrier.barrier_id, decisions); metrics.submitMs += performance.now() - submitStart; metrics.submitCalls++; if (typeof outcome.status === 'object') { throw new Error(outcome.status.Failed.diagnostic); } const commitStart = performance.now(); yield { kind: 'committed', outcome }; metrics.decisionMs += performance.now() - commitStart; break; } } } } finally { const start = performance.now(); session.dispose(); metrics.disposeMs = performance.now() - start; } } /** Bounded fixed intent trace for conformance/debug, not a declarative strategy DSL. */ /* eslint-disable no-redeclare -- TypeScript overloads narrow the selected result format. */ export function executeReplayTrace( input: ReplayTraceRequest & { resultFormat: 'report' }, onProgress?: (step: ReplayStep) => void ): { result: ReplayReportResult; metrics: ReplayMetrics }; export function executeReplayTrace( input: ReplayTraceRequest & { resultFormat: 'projection' }, onProgress?: (step: ReplayStep) => void ): { result: ReplayProjectionResult; metrics: ReplayMetrics }; export function executeReplayTrace( input: ReplayTraceRequest & { resultFormat?: 'trace' }, onProgress?: (step: ReplayStep) => void ): { result: ReplayResult; metrics: ReplayMetrics }; export function executeReplayTrace( input: ReplayTraceRequest, onProgress?: (step: ReplayStep) => void ): { result: ReplayOutput; metrics: ReplayMetrics }; export function executeReplayTrace( input: ReplayTraceRequest, onProgress: (step: ReplayStep) => void = () => {} ) { /* eslint-enable no-redeclare */ const request = replayTraceSchema.parse(input), load = prepareReplayLoad(request.dataset, request.config); const trace = new Map(); for (const entry of request.trace) { const key = JSON.stringify([entry.at, entry.ownerId]); if (trace.has(key)) { throw new Error('Duplicate trace decision'); } trace.set(key, entry.intent); } return runReplayConformance( new NativeReplaySession(load), (ownerId, context) => { const key = JSON.stringify([context.barrier.at, ownerId]), intent = trace.get(key); if (!intent) { throw new Error('Missing trace decision for due owner'); } trace.delete(key); return intent; }, { eventBudget: request.eventBudget, resultFormat: request.resultFormat, onProgress: step => { if (step.step.type === 'complete' && trace.size) { throw new Error('Unused trace decisions'); } onProgress(step); }, } ); }