feat(engine): expose canonical replay sessions through native workers

This commit is contained in:
Boki 2026-10-23 00:54:36 -04:00
parent 417a7bd21e
commit e3635f23cf
26 changed files with 2693 additions and 33 deletions

View file

@ -12,6 +12,7 @@ const nativeBinding = require(join(__dirname, 'dist', 'engine.node'));
export const {
TradingEngine,
BacktestEngine,
FinancialReplaySession,
TechnicalIndicators,
IncrementalSma,
IncrementalEma,

View file

@ -1,10 +1,12 @@
mod backtest;
mod indicators;
mod replay;
mod risk;
mod strategy_parameters;
pub use backtest::BacktestEngine;
pub use indicators::{IncrementalEMA, IncrementalRSI, IncrementalSMA, TechnicalIndicators};
pub use replay::FinancialReplaySession;
pub use risk::{OrderbookAnalyzer, RiskAnalyzer};
use crate::risk::RiskLimits;

View file

@ -0,0 +1,280 @@
//! Trusted host-only NAPI adapter. The TS loader authenticates D01 data with
//! validateDatasetV2; this envelope binds identity but is not a second normalizer
//! or an untrusted-code sandbox. No mutable financial/clock handles are exported.
use crate::financial::{contract::*, matching::OrderStatus, replay::*};
use napi::{Error, Result};
#[cfg(not(test))]
use napi_derive::napi;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_json::{json, Value};
#[derive(Deserialize, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct Identity {
version: Version,
session_id: Id,
dataset_hash: String,
}
#[derive(Deserialize, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct Load {
identity: Identity,
prepared: PreparedReplay,
config: ReplayConfig,
manifest: Value,
}
#[derive(Deserialize, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct Advance {
identity: Identity,
event_budget: Counter,
}
#[derive(Deserialize, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct Submit {
identity: Identity,
barrier_id: Id,
decisions: Vec<StrategyDecision>,
}
fn error(error: impl std::fmt::Display) -> Error {
Error::from_reason(error.to_string())
}
// Internal replay types intentionally were not wire contracts. Reject unknown
// keys recursively at this adapter without changing their financial semantics.
fn keys_match(input: &Value, typed: &Value) -> bool {
match (input, typed) {
(Value::Object(a), Value::Object(b)) => {
a.len() == b.len()
&& a.iter()
.all(|(k, v)| b.get(k).is_some_and(|other| keys_match(v, other)))
}
(Value::Array(a), Value::Array(b)) => {
a.len() == b.len() && a.iter().zip(b).all(|(a, b)| keys_match(a, b))
}
_ => true,
}
}
fn parse<T: DeserializeOwned + Serialize>(input: &str) -> Result<T> {
let raw: Value = serde_json::from_str(input).map_err(error)?;
let typed: T = serde_json::from_str(input).map_err(error)?;
if !keys_match(&raw, &serde_json::to_value(&typed).map_err(error)?) {
return Err(error("unexpected or missing session contract fields"));
}
Ok(typed)
}
pub struct ReplayHost {
replay: Option<Replay>,
identity: Identity,
manifest: Value,
config: ReplayConfig,
delivered: usize,
}
impl ReplayHost {
pub fn new(input: String) -> Result<Self> {
let load: Load = parse(&input)?;
let hash = &load.identity.dataset_hash;
if hash.len() != 64
|| !hash
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
|| load.identity.session_id != load.config.matching.risk.ledger.session_id
|| serde_json::to_value(&load.prepared.dataset_id).map_err(error)? != json!(hash)
|| load.manifest.get("hash") != Some(&json!(hash))
|| load.manifest.get("version") != Some(&json!(2))
{
return Err(error("session/dataset identity or version mismatch"));
}
let replay = Replay::new(load.prepared, load.config.clone()).map_err(error)?;
Ok(Self {
replay: Some(replay),
identity: load.identity,
manifest: load.manifest,
config: load.config,
delivered: 0,
})
}
pub fn advance(&mut self, input: String) -> Result<String> {
let request: Advance = parse(&input)?;
self.check(&request.identity)?;
let replay = self.replay.as_mut().unwrap();
let step = replay
.advance(usize::try_from(request.event_budget.get()).map_err(error)?)
.map_err(error)?;
// Borrow a delta, not checkpoint/history clones. Only published bars can
// enter this array; the future vector is never serialized to callbacks.
let observations: Vec<_> = replay.observations_since(self.delivered).collect();
let delivered = self.delivered + observations.len();
let payload = match step {
ReplayStep::Progress { processed } => json!({"type":"progress", "processed":processed}),
ReplayStep::Decision(barrier) => {
json!({"type":"decisionBatch", "barrier":barrier, "view":view(replay)?})
}
ReplayStep::Complete => json!({"type":"complete"}),
ReplayStep::Failed { diagnostic } => json!({"type":"failed", "diagnostic":diagnostic}),
};
let output = serde_json::to_string(
&json!({"identity":self.identity,"step":payload,"observations":observations}),
)
.map_err(error)?;
self.delivered = delivered;
Ok(output)
}
pub fn submit(&mut self, input: String) -> Result<String> {
let request: Submit = parse(&input)?;
self.check(&request.identity)?;
let outcome = self
.replay
.as_mut()
.unwrap()
.submit(DecisionSubmission {
barrier_id: request.barrier_id,
decisions: request.decisions,
})
.map_err(error)?;
serde_json::to_string(&json!({"identity":self.identity,"outcome":outcome})).map_err(error)
}
pub fn finalize(&self, input: String) -> Result<String> {
let identity: Identity = parse(&input)?;
self.check(&identity)?;
let replay = self.replay.as_ref().unwrap();
if replay.status() != &ReplayStatus::Complete {
return Err(error("only a complete replay can finalize successfully"));
}
serde_json::to_string(&json!({
"identity":self.identity,"status":"complete", "manifest":self.manifest,
"policy":self.config,"view":view(replay)?,
"receipts":replay.financial().receipts(),
"limitations":replay.limitations(),"modelLimitations":replay.model_limitations()
}))
.map_err(error)
}
pub fn dispose(&mut self) {
self.replay = None;
}
}
// NAPI's impl macro requires literal method annotations. Keep this tiny
// delegation out of Rust unit tests; ReplayHost is the exact production host.
#[cfg(not(test))]
#[napi]
pub struct FinancialReplaySession(ReplayHost);
#[cfg(not(test))]
#[napi]
impl FinancialReplaySession {
#[napi(constructor)]
pub fn new(input: String) -> Result<Self> {
Ok(Self(ReplayHost::new(input)?))
}
#[napi]
pub fn advance(&mut self, input: String) -> Result<String> {
self.0.advance(input)
}
#[napi]
pub fn submit(&mut self, input: String) -> Result<String> {
self.0.submit(input)
}
#[napi]
pub fn finalize(&self, input: String) -> Result<String> {
self.0.finalize(input)
}
#[napi]
pub fn dispose(&mut self) {
self.0.dispose();
}
}
impl ReplayHost {
fn check(&self, identity: &Identity) -> Result<()> {
if self.replay.is_none() {
return Err(error("replay session is disposed"));
}
if identity.session_id != self.identity.session_id
|| identity.dataset_hash != self.identity.dataset_hash
{
return Err(error("session/dataset identity mismatch"));
}
Ok(())
}
}
fn view(replay: &Replay) -> Result<Value> {
let matching = replay.financial();
Ok(json!({
"admissionRevision":matching.admission_revision(),
"portfolio":matching.ledger().economic_snapshot(),
"equity":matching.ledger().equity().map_err(error)?,
"availableCash":matching.risk().available_cash(),
"orders":matching.risk().reservations().filter_map(|reservation| matching.order(&reservation.order.order_id)).filter(|order| order.status == OrderStatus::Open).collect::<Vec<_>>(),
"reservations":matching.risk().reservations().collect::<Vec<_>>(),
"risk":matching.risk().state()
}))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn native_intent_trace_matches_direct_replay_receipts() {
// The TS fixture asserts its verified D01 adaptation equals this exact
// load; compare the NAPI pull transport with direct authoritative replay.
let fixture = include_str!("../../../../../test/fixtures/native-replay-load.json");
let load: Load = parse(fixture).unwrap();
let mut direct = Replay::new(load.prepared, load.config).unwrap();
let mut native = ReplayHost::new(fixture.into()).unwrap();
let identity = serde_json::to_value(&load.identity).unwrap();
let mut sequence = 0;
loop {
let raw = native
.advance(json!({"identity":identity,"eventBudget":1}).to_string())
.unwrap();
let response: Value = serde_json::from_str(&raw).unwrap();
match direct.advance(1).unwrap() {
ReplayStep::Progress { .. } => assert_eq!(response["step"]["type"], "progress"),
ReplayStep::Decision(barrier) => {
assert_eq!(
response["step"]["barrier"],
serde_json::to_value(&barrier).unwrap()
);
let decisions:Vec<StrategyDecision>=serde_json::from_value(json!([{
"version":1,"sessionId":"f07-fixture","barrierId":barrier.barrier_id,"revision":barrier.revision,
"decision":{"ownerId":"A","decisionId":serde_json::to_string(&json!(["trace",sequence,"A"])).unwrap(),"sequence":sequence},
"intent":{"mode":"target","targets":if sequence==0 {json!([{"instrumentId":"X0.US","quantity":"2.00000000"}])} else {json!([])}}
}])).unwrap();
let native_out:Value=serde_json::from_str(&native.submit(json!({"identity":identity,"barrierId":barrier.barrier_id,"decisions":decisions}).to_string()).unwrap()).unwrap();
let outcome = direct
.submit(DecisionSubmission {
barrier_id: barrier.barrier_id,
decisions,
})
.unwrap();
assert_eq!(
native_out["outcome"],
serde_json::to_value(outcome).unwrap()
);
sequence += 1;
}
ReplayStep::Complete => break,
ReplayStep::Failed { diagnostic } => panic!("{diagnostic}"),
}
}
let final_result: Value =
serde_json::from_str(&native.finalize(identity.to_string()).unwrap()).unwrap();
assert_eq!(
final_result["receipts"],
serde_json::to_value(direct.financial().receipts()).unwrap()
);
assert_eq!(final_result["view"]["portfolio"]["cash"], "9975.76000000");
assert_eq!(final_result["view"]["equity"], "10005.76000000");
native.dispose();
assert!(native.finalize(identity.to_string()).is_err());
}
}

View file

@ -23,3 +23,8 @@ mod matching_tests;
#[cfg(test)]
mod replay_tests;
// Exercise the pure host adapter without linking every legacy NAPI export.
#[cfg(test)]
#[path = "../api/replay.rs"]
mod native_replay_tests;

View file

@ -634,6 +634,15 @@ impl Replay {
pub fn observations(&self) -> impl Iterator<Item = &PreparedBar> {
self.published.iter().map(|i| &self.input.bars[*i])
}
/// Host transfer cursor over the published prefix only. Beyond the current
/// prefix is empty; no future bar is revealed, and no preceding rows scan.
pub fn observations_since(&self, offset: usize) -> impl Iterator<Item = &PreparedBar> {
self.published
.get(offset..)
.unwrap_or_default()
.iter()
.map(|i| &self.input.bars[*i])
}
pub fn latest_observation(&self, series: &Id) -> Option<&PreparedBar> {
self.latest.get(series).map(|i| &self.input.bars[*i])
}

View file

@ -93,6 +93,18 @@ fn fixture() -> (PreparedReplay, ReplayConfig) {
},
)
}
#[test]
fn published_delta_cursor_bounds() {
let (input, config) = fixture();
let mut replay = Replay::new(input, config).unwrap();
assert_eq!(replay.observations_since(0).count(), 0);
assert_eq!(replay.observations_since(usize::MAX).count(), 0);
next(&mut replay).unwrap();
assert_eq!(replay.observations_since(0).count(), 1);
assert_eq!(replay.observations_since(1).count(), 0);
assert_eq!(replay.observations_since(usize::MAX).count(), 0);
}
fn next(r: &mut Replay) -> Option<DecisionBarrier> {
loop {
match r.advance(100).unwrap() {

View file

@ -1,5 +1,10 @@
import { fork, type ChildProcess } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import {
parseReplayResult,
replayConfigSchema,
replayIdentitySchema,
} from '../contracts/native-replay';
import { nativeWorkerMessageSchema, type NativeWorkerRequest } from './native-worker-protocol';
import { BacktestConflictError } from './run-repository';
@ -23,6 +28,19 @@ export class NativeBacktestWorker {
if (this.active) {
throw new BacktestConflictError('A native backtest worker is already running');
}
// Capture expected identity/policy before asynchronous execution. A caller
// mutating its request cannot change which completed child result is valid.
const expectedReplay =
request.type === 'runReplayTrace'
? {
identity: replayIdentitySchema.parse({
version: 1,
sessionId: request.config.matching.risk.ledger.sessionId,
datasetHash: (request.dataset as { manifest?: { hash?: unknown } })?.manifest?.hash,
}),
policy: replayConfigSchema.parse(request.config),
}
: undefined;
const child = fork(fileURLToPath(this.workerUrl), [], {
execPath: process.execPath,
execArgv: [],
@ -61,6 +79,14 @@ export class NativeBacktestWorker {
if (message.type === 'error') {
terminate(new Error(message.message));
} else if (message.type === 'result') {
if (expectedReplay) {
try {
parseReplayResult(message.result, expectedReplay.identity, expectedReplay.policy);
} catch (error) {
terminate(error instanceof Error ? error : new Error(String(error)));
return;
}
}
result = message.result;
} else {
try {

View file

@ -111,11 +111,11 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
config: BacktestConfig,
signal: AbortSignal,
resolver?: DatasetResolver
): Promise<NativeWorkerRequest['data']> {
): Promise<Extract<NativeWorkerRequest, { type: 'run' }>['data']> {
signal.throwIfAborted();
const dataset = await resolveDataset(this.dependencies.storage, config, resolver, signal);
signal.throwIfAborted();
const data: NativeWorkerRequest['data'] = [];
const data: Extract<NativeWorkerRequest, { type: 'run' }>['data'] = [];
for (const bar of dataset.bars) {
data.push({ ...bar, type: 'bar' });
if (data.length % PREPARATION_BATCH_SIZE === 0) {

View file

@ -0,0 +1,333 @@
/** Additive trusted-host F07 boundary, not an active runner or S01 strategy runtime. */
import { FinancialReplaySession } from '@stock-bot/engine';
import {
parseFinancialDecimal,
parseFinancialStrategyDecision,
type FinancialStrategyDecision,
type FinancialStrategyIntent,
} from '@stock-bot/types';
import {
parseReplayResult,
replayConfigSchema,
replayTraceSchema,
sameIdentity,
stepSchema,
submissionSchema,
type DecisionContext,
type PublishedObservation,
type ReplayConfig,
type ReplayIdentity,
type ReplayResult,
type ReplayStep,
type ReplayTraceRequest,
} from '../contracts/native-replay';
import { validateDatasetV2 } from '../data/historical-dataset-v2';
export type {
ReplayConfig,
ReplayIdentity,
ReplayStep,
ReplayResult,
DecisionContext,
PublishedObservation,
ReplayTraceRequest,
} from '../contracts/native-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 actual payload in the worker, not an upstream supplied 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<T>(value: T): T {
if (value && typeof value === 'object' && !Object.isFrozen(value)) {
Object.values(value).forEach(freeze);
Object.freeze(value);
}
return value;
}
/** JSON transport is intentionally explicit and measured. No history/checkpoint API. */
export class NativeReplaySession {
readonly identity: ReplayIdentity;
private readonly native: FinancialReplaySession;
readonly transport = {
advanceResponseBytes: 0,
submitRequestBytes: 0,
submitResponseBytes: 0,
resultBytes: 0,
};
constructor(load: ReturnType<typeof prepareReplayLoad>) {
this.identity = freeze({ ...load.identity });
this.native = new FinancialReplaySession(JSON.stringify(load));
}
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(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 raw = this.native.finalize(JSON.stringify(this.identity));
this.transport.resultBytes += Buffer.byteLength(raw);
return parseReplayResult(raw, this.identity);
}
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;
}
/** 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: (
ownerId: string,
context: DecisionContext,
observations: readonly PublishedObservation[]
) => FinancialStrategyIntent,
options: {
eventBudget?: number;
reverseCallbacks?: boolean;
onProgress?: (step: ReplayStep) => void;
} = {}
) {
const metrics: ReplayMetrics = {
advanceCalls: 0,
submitCalls: 0,
contextBytes: 0,
submissionBytes: 0,
outcomeBytes: 0,
resultBytes: 0,
advanceMs: 0,
submitMs: 0,
decisionMs: 0,
finalizeMs: 0,
};
let observations: PublishedObservation[] = [];
let sequence = 0;
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 = session.finalize();
metrics.finalizeMs = performance.now() - start;
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 owners = [...context.barrier.owner_ids];
if (options.reverseCallbacks) {
owners.reverse();
}
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 = 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, publishedDelta),
})
);
metrics.decisionMs += performance.now() - start;
sequence++;
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);
}
break;
}
}
}
} finally {
session.dispose();
}
}
/** Bounded fixed intent trace for conformance/debug, not a declarative strategy DSL. */
export function executeReplayTrace(
input: ReplayTraceRequest,
onProgress: (step: ReplayStep) => void = () => {}
) {
const request = replayTraceSchema.parse(input),
load = prepareReplayLoad(request.dataset, request.config);
const trace = new Map<string, FinancialStrategyIntent>();
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,
onProgress: step => {
if (step.step.type === 'complete' && trace.size) {
throw new Error('Unused trace decisions');
}
onProgress(step);
},
}
);
}

View file

@ -1,8 +1,9 @@
import { z } from 'zod';
import { replayTraceSchema } from '../contracts/native-replay';
import { BacktestConfigSchema } from '../types';
const finite = z.number().finite();
export const nativeWorkerRequestSchema = z.object({
const legacyRequestSchema = z.object({
type: z.literal('run'),
config: BacktestConfigSchema,
data: z.array(
@ -20,6 +21,8 @@ export const nativeWorkerRequestSchema = z.object({
),
});
export const nativeWorkerRequestSchema = z.union([legacyRequestSchema, replayTraceSchema]);
export const nativeWorkerMessageSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('progress'), progress: finite.min(0).max(100), message: z.string() }),
z.object({ type: z.literal('result'), result: z.string() }),

View file

@ -1,4 +1,5 @@
import { BacktestEngine } from '@stock-bot/engine';
import { executeReplayTrace } from './native-replay';
import { resolveNativeStrategies } from './native-strategies';
import { nativeWorkerRequestSchema, type NativeWorkerMessage } from './native-worker-protocol';
@ -15,7 +16,16 @@ function send(message: NativeWorkerMessage): Promise<void> {
process.once('message', async (input: unknown) => {
try {
const { config, data } = nativeWorkerRequestSchema.parse(input);
const request = nativeWorkerRequestSchema.parse(input);
if (request.type === 'runReplayTrace') {
await send({ type: 'progress', progress: 0, message: 'Canonical replay trace started' });
// One load and a local pull loop; no per-observation IPC. The supervisor
// can still SIGKILL native work, exactly as for the legacy one-shot path.
const { result } = executeReplayTrace(request);
await send({ type: 'result', result: JSON.stringify(result) });
return;
}
const { config, data } = request;
const engine = new BacktestEngine({
name: config.name ?? 'Backtest',
strategy: config.strategy,
@ -27,7 +37,9 @@ process.once('message', async (input: unknown) => {
slippage: config.slippage ?? 0.0001,
dataFrequency: config.dataFrequency,
});
if (config.riskLimits) {engine.updateRiskLimits(config.riskLimits);}
if (config.riskLimits) {
engine.updateRiskLimits(config.riskLimits);
}
for (const { strategy, name, id, parameters } of resolveNativeStrategies(config)) {
engine.addNativeStrategy(strategy, name, id, parameters);
}

View file

@ -0,0 +1,244 @@
/** Schema-only native session protocol. No runtime, storage or native imports. */
import { z } from 'zod';
import {
parseFinancialDecimal,
parseFinancialSnapshot,
parseFinancialStrategyDecision,
} from '@stock-bot/types';
const id = z
.string()
.min(1)
.refine(value =>
[...value].every(char => char.charCodeAt(0) >= 32 && char.charCodeAt(0) !== 127)
);
const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
const time = z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER);
const decimal = z.string().transform(value => parseFinancialDecimal(value));
const riskSession = z
.object({ calendarId: id, calendarRevision: id, sessionId: id, startsAt: time })
.strict();
export const replayIdentitySchema = z
.object({
version: z.literal(1),
sessionId: id,
datasetHash: z.string().regex(/^[a-f0-9]{64}$/),
})
.strict();
export const replayConfigSchema = z
.object({
matching: z
.object({
risk: z
.object({
ledger: z
.object({
version: z.literal(1),
sessionId: id,
accountId: id,
baseCurrency: id,
reserveOwnerId: id,
ownerIds: z.array(id),
initialCapital: decimal,
riskSession,
})
.strict(),
feeRate: decimal,
maxOrderQuantity: decimal,
maxPositionQuantity: decimal,
maxSymbolExposure: decimal,
maxGrossExposure: decimal,
maxDailyLoss: decimal,
maxDrawdownAmount: decimal,
maxMarkAgeMs: counter,
})
.strict(),
owners: z.array(z.object({ ownerId: id, mode: z.enum(['Target', 'Orders']) }).strict()),
series: z.array(
z.object({ instrumentId: id, seriesId: id, mode: z.literal('Open') }).strict()
),
halfSpreadRate: decimal,
slippageRate: decimal,
latencyMs: counter,
})
.strict(),
participation_rate: decimal,
cadence: z.array(z.object({ owner_id: id, series_ids: z.array(id) }).strict()),
allow_exploratory: z.boolean(),
risk_boundaries: z.array(riskSession),
})
.strict();
export type ReplayConfig = z.input<typeof replayConfigSchema>;
export type ReplayIdentity = z.infer<typeof replayIdentitySchema>;
const observationSchema = z
.object({
series_id: id,
instrument_id: id,
interval_start: time,
interval_end: time,
event_time: time,
available_at: time,
source_sequence: counter,
open: decimal,
high: decimal,
low: decimal,
close: decimal,
volume: decimal,
})
.strict();
const barrierSchema = z
.object({
barrier_id: id,
at: time,
revision: counter,
owner_ids: z.array(id),
observation_count: counter,
inputs: z.array(
z
.object({
series_id: id,
availability: z.union([
z.literal('Missing'),
z
.object({ Fresh: z.object({ event_time: time, available_at: time }).strict() })
.strict(),
z
.object({ Stale: z.object({ event_time: time, available_at: time }).strict() })
.strict(),
]),
})
.strict()
),
})
.strict();
const viewSchema = z
.object({
admissionRevision: counter,
portfolio: z.unknown().transform(value => parseFinancialSnapshot(value)),
equity: decimal,
availableCash: decimal,
// These are read-only native diagnostic projections, not a second admission API.
orders: z.array(z.record(z.unknown())),
reservations: z.array(z.record(z.unknown())),
risk: z
.object({
dailyBaseline: decimal,
peakEquity: decimal,
dailyHalted: z.boolean(),
drawdownHalted: z.boolean(),
riskSession,
lastEventTime: time,
})
.strict(),
})
.strict();
export const stepSchema = z
.object({
identity: replayIdentitySchema,
observations: z.array(observationSchema),
step: z.discriminatedUnion('type', [
z.object({ type: z.literal('progress'), processed: counter }).strict(),
z
.object({ type: z.literal('decisionBatch'), barrier: barrierSchema, view: viewSchema })
.strict(),
z.object({ type: z.literal('complete') }).strict(),
z.object({ type: z.literal('failed'), diagnostic: z.string() }).strict(),
]),
})
.strict();
const outcomeSchema = z
.object({
replayed: z.boolean(),
revision: counter,
status: z.union([
z.literal('Running'),
z.literal('Complete'),
z.object({ Failed: z.object({ diagnostic: z.string() }).strict() }).strict(),
]),
effects: z.array(z.record(z.unknown())),
})
.strict();
export const submissionSchema = z
.object({ identity: replayIdentitySchema, outcome: outcomeSchema })
.strict();
const resultSchema = z
.object({
identity: replayIdentitySchema,
status: z.literal('complete'),
manifest: z.record(z.unknown()),
policy: replayConfigSchema,
view: viewSchema,
receipts: z.array(z.object({ input: z.unknown(), outcome: outcomeSchema }).strict()),
limitations: z.array(z.string()),
modelLimitations: z.array(z.string()),
})
.strict();
export type ReplayStep = z.infer<typeof stepSchema>;
export type ReplayResult = z.infer<typeof resultSchema>;
export type DecisionContext = Extract<ReplayStep['step'], { type: 'decisionBatch' }>;
export type PublishedObservation = z.infer<typeof observationSchema>;
export function sameIdentity(actual: ReplayIdentity, expected: ReplayIdentity): void {
if (
actual.version !== expected.version ||
actual.sessionId !== expected.sessionId ||
actual.datasetHash !== expected.datasetHash
) {
throw new Error('Native replay identity mismatch');
}
}
export function parseReplayResult(
input: string,
identity: ReplayIdentity,
expectedPolicy?: ReplayConfig
): ReplayResult {
const result = resultSchema.parse(JSON.parse(input));
sameIdentity(result.identity, identity);
const ledger = result.policy.matching.risk.ledger,
portfolio = result.view.portfolio;
if (
result.manifest.version !== 2 ||
result.manifest.hash !== identity.datasetHash ||
ledger.sessionId !== identity.sessionId ||
portfolio.sessionId !== identity.sessionId ||
portfolio.accountId !== ledger.accountId ||
portfolio.baseCurrency !== ledger.baseCurrency ||
portfolio.reserveOwnerId !== ledger.reserveOwnerId ||
(expectedPolicy &&
JSON.stringify(result.policy) !== JSON.stringify(replayConfigSchema.parse(expectedPolicy)))
) {
throw new Error('Native replay result identity mismatch');
}
return result;
}
export const replayTraceSchema = z
.object({
type: z.literal('runReplayTrace'),
version: z.literal(1),
dataset: z.unknown(),
config: replayConfigSchema,
eventBudget: counter.positive(),
trace: z.array(
z
.object({
at: time,
ownerId: id,
intent: z.unknown().transform(
intent =>
parseFinancialStrategyDecision({
version: 1,
sessionId: 'trace',
barrierId: 'trace',
revision: 0,
decision: { ownerId: 'trace', decisionId: 'trace', sequence: 0 },
intent,
}).intent
),
})
.strict()
),
})
.strict();
export type ReplayTraceRequest = z.input<typeof replayTraceSchema>;