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>;

View file

@ -1,8 +1,8 @@
# Revised development roadmap
Baseline `b7aeca4` · reviewed 2026-10-22 · **F04/F05 committed; F06 independently reviewed and validated, uncommitted**
Baseline `b7aeca4` · handoff 2026-10-23 · **F06 committed; F07 validated, uncommitted**
Authorization update: the latest owner request “commit all and do it” authorized committing the reviewed F04/F05 source and planning changes (`ccf333c`), then implementing F06. Its worktree starts at that commit; no prerequisite overlay is needed. No other ADR is approved. Pushes, PRs, trading operations and further task implementation remain outside scope.
Authorization update: the latest owner request “commit and continue” authorized committing the reviewed F06 source and planning changes (`417a7bd`), then implementing F07. Its isolated worktree starts at that commit. No other ADR or multi-asset mark policy is approved. Pushes, PRs, trading operations and further task implementation remain outside scope.
## Strategy and review outcome
@ -255,6 +255,22 @@ Release measurement: one/two assets, 1k/10k/100k execution bars plus one cadence
Other limits: trusted internal prepared bars only; F07 must verify/adapt frozen D01 inputs and preserve provenance/model limitations. Quote replay and abutting sessions explicitly reject. Event budget bounds count, not wall time. Active legacy simulator, native API, SQL/paper and web paths are unchanged; no PostgreSQL/Redis, browser or Python rerun was needed. Existing build warnings remain. No services/data removed; worktree/logs retained. **F06 remains uncommitted. Next after acceptance: F07 native pull-session/dataset adapter**; F08 result projection may follow with coordinated contract ownership. No push, PR, trading operation or further task implementation occurred.
## Eleventh-wave handoff — 2026-10-23
F06 was accepted and committed as `417a7bd` at owner request, superseding its uncommitted handoff status above. F07 is independently reviewed and `validated_uncommitted`. Isolated worktree `/tmp/stock-bot-wave11.l8cJnN/f07` starts at that commit. One native/worker owner implemented; a second owner supplied three disjoint benchmark files reviewed by root. Independent boundary/lifecycle and data/quant reviews accepted the boundary. Root integrated 22 matching source/test files. See [F07 clarifications](backlog/tasks/F07.md#execution-handoff-clarifications).
- **FinancialReplaySession:** thin NAPI export over one ReplayHost/F06 core; strict identity/version envelopes, event-count-bounded progress/decision/complete/failed steps, synchronized admission revisions, complete-batch submission, terminal success gate and disposal. One read-only observation-range accessor avoids checkpoint copies. The exact host is tested against direct Rust Replay with identical barriers, outcomes and receipts; TS uses the same frozen fixture and independent arithmetic.
- **TypeScript/worker:** existing D01 validator verifies actual data and derived eligibility/limitations. Numeric ingress expands scientific notation and rejects unsupported precision without rounding. Calendars, execution feed and availability are retained. Callbacks receive only shared immutable published deltas and financial views. Exceptions submit no partial batch; worker results must match captured identity/policy. Existing process cancellation, crash, wait-for-close and lease protections remain.
- **Scope:** fixed trace and fixture callbacks only, not S01 production strategy state/RNG or a DSL. The legacy request, durable runner default and paper/live behavior are unchanged. Exact architecture tests permit only the worker and its helper to reach native replay; shared schemas still cannot import native/data/services.
Final validation: `CARGO_BUILD_JOBS=2 bun run check` passed build/types/contracts/lint/audit plus **63 tooling, 43 utility, 35 calculation, 353 integration and 133 Rust tests**, zero failures. Four earlier manual Rust measurements remain intentionally ignored by the ordinary suite. Independent frozen-artifact review ran 69 focused TS tests and 29 replay-related Rust cases (overlapping totals). Disposable PostgreSQL/Redis suites passed **58 tests / 345 assertions** before and after integration. Release-addon replay/binding tests passed **17 tests / 120 assertions**. Extra strict TypeScript for affected scripts/tests, scoped ESLint, rustfmt and diff checks passed. Explicit lint of the normally ignored architecture test confirms the same 13 pre-existing curly-style errors at HEAD and in the worktree; no new ones. The clean isolated build initially needed the existing logger prerequisite built manually; no build-system rewrite.
Release measurement: 1k/10k total bars, one asset/owner or ten assets/two owners, two fresh processes with two fresh native sessions each; alternate one-unit buy/sell targets. Full normalized results match across repeats, reverse callback order and debug/release profiles. Independent integer-cent cash/equity/basis/fee/fill checks pass. At 10k, release whole-trial times were **2.65–2.93s single / 3.51–3.61s multi**; finalization alone was **0.89–1.03s / 1.34–1.40s**. Final receipt payloads were approximately **66.7MB / 103.6MB**, not RSS. Cold imports and detached dataset verification, mapping, session load, real advance/submit/decision timings, bytes and process RSS are recorded separately in the manifest/logs. This is order-heavy component conformance throughput, not empty-crossing overhead, a production research benchmark, an isolated-host SLA or a legacy-engine speedup. No cache, batch pool, compaction or DSL was introduced.
Limits remain explicit: trusted host interface, not an untrusted-code sandbox; native prepared input does not independently authenticate D01. Quote/abutting-session replay remains unsupported; event count is not a wall-time guarantee. Sequential equal-time marks can still latch intermediate risk halts; R05's owner policy gate remains unresolved. Full receipts are retained and serialized; F08 can use these measurements when designing canonical results without prematurely adding a general storage framework.
Only the two named disposable fixture containers and their recreatable synthetic data were removed; development services were untouched. Worktree/logs retained. Browser/Python suites were not rerun because those boundaries did not change. **F07 remains uncommitted. Next recommended: F08 canonical metrics/result projections**, now code/ADR-ready but not yet authorized. S01 requires ADR-005 approval. No push, PR, default cutover or trading operation occurred.
## Deferred and rejected
Conditional: shared feature cache D04; cross-trial resident datasets P03; large-detail pagination/storage P05; tiny DSL P06; expanded cross-service monitoring O02. Each has a measured/real-need trigger and is not a prerequisite for scheduled work.

View file

@ -1,6 +1,6 @@
# Canonical development backlog
**First nine waves committed; F06 independently reviewed and validated, uncommitted.** Consult manifest execution_scope, [ROADMAP](../ROADMAP.md), [skeptical review](../REVIEW.md) and [first-wave handoff](../FIRST-WAVE.md). ADR-002/003/004 are approved. The owner authorized the F04/F05 commit (`ccf333c`) and F06 continuation. Other tasks/policies remain gated.
**First ten waves committed; F07 reviewed and validated, uncommitted.** Consult manifest execution_scope, [ROADMAP](../ROADMAP.md), [skeptical review](../REVIEW.md) and [first-wave handoff](../FIRST-WAVE.md). ADR-002/003/004 are approved. The owner authorized the F06 commit (`417a7bd`) and F07 continuation. Other tasks/policies remain gated.
## One source of truth
@ -34,9 +34,9 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
| [F03 Add strategy-owned position books and fill allocations](tasks/F03.md) | P0 / merged → F02 | None | — | Rust portfolio accounting / M |
| [F04 Enforce cash reservations and portfolio risk centrally](tasks/F04.md) | P0 / done | F02, ADR-002, ADR-003 | — | Rust financial risk / L |
| [F05 Unify matching and order lifecycle on the ledger](tasks/F05.md) | P0 / done | F04, ADR-003 | F06 | Rust execution semantics / L |
| [F06 Implement deterministic replay once, with linear historical traversal](tasks/F06.md) | P0 / review | F05, D01, P01, ADR-003 | — | Rust deterministic replay / M |
| [F07 Expose bounded Rust step sessions through existing NAPI workers](tasks/F07.md) | P0 / blocked | F06, C02, ADR-004 | — | Rust/TypeScript integration / M |
| [F08 Publish canonical metrics and versioned result projections](tasks/F08.md) | P1 / blocked | F06, ADR-002, ADR-003 | — | Quant analytics/Rust integration / M |
| [F06 Implement deterministic replay once, with linear historical traversal](tasks/F06.md) | P0 / done | F05, D01, P01, ADR-003 | — | Rust deterministic replay / M |
| [F07 Expose bounded Rust step sessions through existing NAPI workers](tasks/F07.md) | P0 / review | F06, C02, ADR-004 | — | Rust/TypeScript integration / M |
| [F08 Publish canonical metrics and versioned result projections](tasks/F08.md) | P1 / ready | F06, ADR-002, ADR-003 | — | Quant analytics/Rust integration / M |
### E3 — Point-in-time datasets and features
@ -115,4 +115,4 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
Before any wave: unique IDs; existing task/ADR references; acyclic implementation graph; no scheduled task dependent on merged/deferred work; approvals/readiness; actual file locks; isolated native build outputs/workspace dependencies and test databases. Release gates are checked separately at activation.
The first nine waves are independently reviewed, validated and committed with owner approval. Evidence is recorded in [FIRST-WAVE.md](../FIRST-WAVE.md#execution-record--2026-10-22), the [ROADMAP handoffs](../ROADMAP.md#tenth-wave-handoff--2026-10-22) and the manifest. The latest owner request committed F04/F05 as `ccf333c` and authorized **F06**, now reviewed and `validated_uncommitted`. Next after acceptance: F07's verified dataset/native adapter. F08 is another eligible component successor after acceptance; coordinate any shared result/native contracts. R01 still needs ADR-006. The manifest's canonical release gate records the unresolved multi-asset mark-policy decision; this does not block additive adapter work. No push, PR, trading operation or further task implementation is authorized.
The first ten waves are independently reviewed, validated and committed with owner approval. F07 is reviewed and validated but uncommitted; see the [eleventh-wave handoff](../ROADMAP.md#eleventh-wave-handoff--2026-10-23) and manifest evidence. Next recommended after acceptance: **F08 canonical metrics/result projections**, whose code and ADR prerequisites are satisfied; readiness is not execution authority. S01 still needs ADR-005 and R01 needs ADR-006. The unresolved multi-asset mark-policy gate still blocks default activation, not additive components. No push, PR, trading operation or further task implementation is authorized.

View file

@ -1,13 +1,13 @@
{
"schema_version": 1,
"plan_revision": "2026-10-22.23",
"plan_revision": "2026-10-23.25",
"repository_base": "b7aeca4",
"plan_status": "tenth_wave_validated_uncommitted",
"plan_status": "eleventh_wave_review",
"execution_authorized": true,
"execution_scope": {
"authorized_by": "User: commit all and do it (2026-10-22), authorizing the F04/F05 commit and proposed F06 continuation",
"authorized_by": "User: commit and continue (2026-10-22), authorizing the F06 commit and proposed F07 continuation",
"tasks": [
"F06"
"F07"
],
"permissions": [
"isolated_implementation",
@ -538,7 +538,7 @@
"epic": "E2",
"priority": "P0",
"severity": "Critical",
"status": "review",
"status": "done",
"dependencies": [
"F05",
"D01",
@ -562,7 +562,7 @@
"assignment": "/root/wave10_f06",
"branch": "wave10/f06-replay",
"pull_request": null,
"completed_commit": null,
"completed_commit": "417a7bd21efc3cf906ae88001066ad9984a19324",
"blocker": null,
"release_gates": [],
"worktree": "/tmp/stock-bot-wave10.8uCLfa/f06",
@ -572,13 +572,14 @@
"apps/stock/engine/src/financial/replay_tests.rs",
"apps/stock/engine/src/financial/mod.rs"
],
"integration_state": "validated_uncommitted",
"review_notes": "Both independent reviewers accepted exact frozen source; combined repository gates and integrated release replay measurement passed. Internal bar replay only; active simulator/NAPI/SQL unchanged. Material sequential equal-time risk approximation remains the canonical multi-asset default policy gate.",
"integration_state": "validated_committed",
"review_notes": "Both independent reviewers accepted exact frozen source; combined repository gates and integrated release replay measurement passed. Internal bar replay only; active simulator/NAPI/SQL unchanged. Material sequential equal-time risk approximation remains the canonical multi-asset default policy gate. Subsequently committed at owner request as 417a7bd.",
"reviewed_by": [
"/root/wave10_replay_review",
"/root/wave10_quant_review"
],
"verification_reference": "ROADMAP.md#tenth-wave-handoff--2026-10-22"
"verification_reference": "ROADMAP.md#tenth-wave-handoff--2026-10-22",
"accepted_by": "Owner: commit and continue (2026-10-22); accepted F06 and authorized proposed F07"
},
{
"id": "F07",
@ -586,7 +587,7 @@
"epic": "E2",
"priority": "P0",
"severity": "Critical",
"status": "blocked",
"status": "review",
"dependencies": [
"F06",
"C02"
@ -607,12 +608,38 @@
"worker-protocol"
],
"parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.",
"assignment": null,
"branch": null,
"assignment": "/root/wave11_f07",
"branch": "wave11/f07-native-sessions",
"pull_request": null,
"completed_commit": null,
"blocker": null,
"release_gates": []
"release_gates": [],
"worktree": "/tmp/stock-bot-wave11.l8cJnN/f07",
"integration_base": "417a7bd21efc3cf906ae88001066ad9984a19324",
"integration_state": "validated_uncommitted",
"concrete_write_scope": [
"apps/stock/engine/src/api/",
"apps/stock/engine/index.mjs",
"apps/stock/engine/dist/index.d.ts (generated, not authored)",
"apps/stock/orchestrator/src/backtest/native*",
"apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts",
"apps/stock/orchestrator/src/contracts/native-replay.ts (schema-only)",
"apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts (legacy request type narrowing only)",
"test/integration/native-replay*.test.ts",
"test/fixtures/native-replay*",
"scripts/benchmark-research.ts",
"scripts/benchmark-replay.ts",
"scripts/test/benchmark-replay.test.ts",
"scripts/test/architecture.test.ts (exact worker-helper reachability gate)",
"scripts/test/native-bindings.test.ts",
"test/fixtures/native-backtest-worker.ts (request union/type adaptation)",
"apps/stock/engine/src/financial/mod.rs (test-only adapter include)",
"apps/stock/engine/src/financial/replay.rs (read-only prefix range accessor only)",
"apps/stock/engine/src/financial/replay_tests.rs (accessor regression only)"
],
"review_notes": "Independent boundary and data/quant reviewers accepted frozen production code. Boundary reviewer implemented disjoint benchmark files; root independently reviewed those. Root integrated 22 matching files, validated final tests/build, disposable durability suites and debug/release measured workloads. Native module ordering and three test-only type corrections were revalidated. No active runner cutover, S01 state framework, F08 metrics or SQL changes.",
"reviewed_by": ["/root/wave11_boundary_review", "/root/wave11_data_review", "/root"],
"verification_reference": "ROADMAP.md#eleventh-wave-handoff--2026-10-23"
},
{
"id": "F08",
@ -620,7 +647,7 @@
"epic": "E2",
"priority": "P1",
"severity": "High",
"status": "blocked",
"status": "ready",
"dependencies": [
"F06"
],
@ -3362,5 +3389,468 @@
],
"handoff": "F04/F05 committed ccf333c at owner request. F06 independently reviewed and validated, uncommitted. Next after acceptance: F07 verified dataset/native pull adapter; F08 result projection may follow with coordinated contracts. No push, PR, other task implementation or trading operation.",
"cleanup": "No services/data removed; isolated worktree and logs retained."
},
"eleventh_wave": [
"F07"
],
"eleventh_wave_base": "417a7bd21efc3cf906ae88001066ad9984a19324",
"eleventh_wave_notes": [
"Owner authorized committing reviewed F06 and continuing F07; prior work committed417a7bd. No push/PR/trading or other task implementation.",
"One isolated native/worker boundary owner and two independent reviewers; root owns integration/planning. F06/C02 committed, ADR004 approved.",
"Canonical frozen dataset/session path is additive. Preserve legacy run/default, existing process supervision and durable lease/cancellation behavior.",
"Only read-only replay prefix-range accessor allowed in financial core; no accounting/matching/risk policy change. Sequential equal-time mark default-release gate remains unresolved."
],
"eleventh_wave_validation": {
"base": "417a7bd21efc3cf906ae88001066ad9984a19324",
"integration_state": "validated_uncommitted",
"repository_check": {
"command": "CARGO_BUILD_JOBS=2 bun run check",
"log": "/tmp/stock-bot-wave11.l8cJnN/integration-check-final.log",
"exit_code": 0,
"passed": {
"tooling": 63,
"utils": 43,
"calculations": 35,
"integration": 353,
"rust": 133
},
"rust_manual_benchmarks_ignored": 4,
"other_gates": "Build, typecheck, contracts, lint and secret audit passed on final source."
},
"durability": {
"command": "PIPELINE_TEST_DATABASE_URL=postgres://fixture:fixture@127.0.0.1:32805/stock_bot_safety BACKTEST_TEST_REDIS_URL=redis://127.0.0.1:32806/15 bun run test:postgres",
"baseline_log": "/tmp/stock-bot-wave11.l8cJnN/baseline-postgres.log",
"integrated_log": "/tmp/stock-bot-wave11.l8cJnN/integration-postgres.log",
"exit_code": 0,
"passed": 58,
"assertions": 345,
"note": "Before and after boundary integration; final subsequent edits were test typing and native module ordering only. Dedicated disposable PostgreSQL tmpfs and Redis DB15; development services untouched."
},
"independent_review": {
"boundary": "/root/wave11_boundary_review accepted production boundary, host delegation, identity/policy, cursor/disposal, cancellation and exact architecture gate. Authored three disjoint benchmark files, excluded them from independent signoff; root independently accepted benchmark implementation.",
"data": "/root/wave11_data_review accepted frozen boundary/data semantics and subsequent three-file type-only test correction; independently ran 69 focused TS tests/484 assertions and 29 replay-related Rust tests, zero failures; one manual Rust benchmark ignored. No rebuilds/source changes during review.",
"logs": [
"/tmp/stock-bot-wave11.l8cJnN/data-review-focused.log",
"/tmp/stock-bot-wave11.l8cJnN/data-review-rust-replay.log"
],
"reviewed_debug_addon_sha256": "d15dd24224af882a3bca0de8a36b78cf56698c0f23dee043a339634b6951de07",
"reviewed_rust_binary_sha256": "b7d70937857422e3b878fb60cf8b8726b89eeb5fe511e9d0db14ee5a1c0c80a9",
"note": "Root subsequently sorted two api/mod.rs declarations per rustfmt; no bodies changed. Final combined build/tests validated the exact integrated source."
},
"scoped_checks": [
"Strict affected scripts/tests TypeScript: bun run node_modules/typescript/bin/tsc --project /tmp/stock-bot-wave11.l8cJnN/tsconfig.scoped.json --noEmit; exit0. Temporary config extends root check options, explicitly includes affected tests/scripts and repository type roots.",
"Explicit ESLint --no-ignore for affected benchmark/fixture/integration/binding files: exit0. Normally ignored architecture.test.ts independently compared at HEAD and worktree: same13 pre-existing curly errors, no new errors.",
"rustfmt --edition2021 --check --config skip_children=true on five changed Rust files: exit0.",
"git diff --check; exact22-file source equality against isolated worktree; final manifest DAG/readiness/reference checks."
],
"source_hashes": {
"apps/stock/engine/index.mjs": "cc085e5b5e111c64c301c395dda0928e85586d39d9fd77c826c67f7a41f14738",
"apps/stock/engine/src/api/mod.rs": "b57ed60e9c138f82e5b0597baf1a5fbcd770f3e884d10dcdd0f900461c063c36",
"apps/stock/engine/src/api/replay.rs": "71e5d8aebb28e43e0cc4694fa60ba3320002027221d38b75737e8abdf4d6685a",
"apps/stock/engine/src/financial/mod.rs": "b359e505b67bb16faa7c06fbae3ec12f16674270f2d806f641c2a9f3e957cfa8",
"apps/stock/engine/src/financial/replay.rs": "a81f9316f9638f9aa9ce27a829ec42c1585fd3cb08feb48cb34f0a0a7417343a",
"apps/stock/engine/src/financial/replay_tests.rs": "d67aabb5331f91a01b9a0b91430fb1a0c3bf1d502baf7ad8728b0c1987b78886",
"apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts": "c3491bd8c814b77a6cea70b1b77dd848153decbfc78f80e095efb989edef3a66",
"apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts": "3d8a3069787f7c84f106122c24bc16f8efdd025e276d03291a2667eeda8811e4",
"apps/stock/orchestrator/src/backtest/native-replay.ts": "fa422e95d249bc9c578525f5b25e2066d964a34801b8a0e4e365bad9b92d94ad",
"apps/stock/orchestrator/src/backtest/native-worker-protocol.ts": "9cf92049ae0cd9405b780d34fa37bf7a6b4a204617ee7ae0830d8b3ee0d8d5a7",
"apps/stock/orchestrator/src/backtest/native-worker.ts": "8bf5ee81b67f6bc58c278b5441ef3d57691a3de5ea1e665efcbb1012dd5b5689",
"apps/stock/orchestrator/src/contracts/native-replay.ts": "b65cd1fce35fb44717548b71c64387588f5157795b2f2ac80fb06c911c2e9134",
"scripts/benchmark-replay.ts": "e6ccf35dc45860891bcecfad296493684b2ecdbc36f55bd1febc5edc1aca357a",
"scripts/benchmark-research.ts": "58083373e812f856bb8546ceffb47ef827e7256ba4e1b095a68810553c02e32c",
"scripts/test/architecture.test.ts": "fb370e932678308806b64cabe7841d1194048897c1fb3733bd0283f1d2f4916f",
"scripts/test/benchmark-replay.test.ts": "8005192fd2e547926ebc880fdd6c86f48a46620be08ce5e48e872ab8a5a095ff",
"scripts/test/native-bindings.test.ts": "2504a4888434cc0d8caee7cd2905321430be8c3a07b8cc75121e269c32fb6d52",
"test/fixtures/native-backtest-worker.ts": "5dcedb6fcd5dcff9b3088c94c8cd0173097e60bdf932eb1807f521f9486aac0a",
"test/fixtures/native-replay-load.json": "b56a005eaac06c52947abd079a2678b12b4889a58ac1d292f84955b58f40d96f",
"test/fixtures/native-replay-worker.ts": "32327bf7990dbcc657ebafb6ac43b0937e612ea5aacf8112f6a0eeedee97549d",
"test/fixtures/native-replay.ts": "7a6df7a2c499c27f2572489fe0d8d67835f7615bbea9cb06da84a7011722b00e",
"test/integration/native-replay.test.ts": "515227ae92e7f373a836fc0e1d6875bb39ff4b768ad25496015078f388332b1b"
},
"release_native": {
"path": "apps/stock/engine/dist/engine.node",
"sha256": "b62e85283325020de09d44dccb27ae5ec5da97cc514ccd92c9b510c0fd814aad",
"matching_library": "target/release/libengine.so",
"build_command": "CARGO_BUILD_JOBS=2 bun run --cwd apps/stock/engine build:release",
"build_log": "/tmp/stock-bot-wave11.l8cJnN/integration-release-build.log",
"test_command": "bun test test/integration/native-replay.test.ts scripts/test/native-bindings.test.ts",
"test_log": "/tmp/stock-bot-wave11.l8cJnN/integration-release-focused.log",
"passed": 17,
"assertions": 120,
"exit_code": 0
},
"measurement": {
"command": "bun run scripts/benchmark-research.ts --session --measure",
"release_report": "/tmp/stock-bot-wave11.l8cJnN/integration-session-release.json",
"release_log": "/tmp/stock-bot-wave11.l8cJnN/integration-session-release.log",
"debug_report": "/tmp/stock-bot-wave11.l8cJnN/integration-session-benchmark.json",
"exit_code": 0,
"host": {
"platform": "linux",
"arch": "x64",
"kernel": "6.8.0-146-generic",
"cpu": "AMD Ryzen 9 9950X3D 16-Core Processor",
"logicalCpus": 32,
"availableParallelism": 32,
"totalMemoryBytes": 98683457536,
"sha256": "917b26b1f87814e6cb82648bbbb8ae255a930da13b57abb3a9e463b4507f1c4c"
},
"runtime": {
"bun": "1.2.17",
"nodeCompatibility": "v22.6.0",
"executableSha256": "6cd2f181c30d3cb1497b0b9d4bc9d63eb1ec4a9142f809183fed18fcc4e1051b",
"rustc": "rustc 1.88.0 (6b00bc388 2025-06-23)",
"lockSha256": "1a2b653bbaaeb5075785b860487557b8fc379f0c50cbe8f2554c90e4a3ac4514",
"cargoLockSha256": "8f2ecaa4f1790f14e1650326f78fbf246f454dad6139dc4cb0d61383b9e301e8"
},
"source_snapshot": {
"commit": "417a7bd21efc3cf906ae88001066ad9984a19324",
"dirty": true,
"contentSha256": "5710c547b6dce71be2c4ecd3b33a87ae3e95459effff9dcaea3be413c2c73339",
"files": 1153,
"scope": "Tracked and nonignored untracked file paths/content, including dirty changes; generated ignored artifacts excluded."
},
"workload": "1k/10k total bars;1asset/1owner or10assets/2owners;2fresh processes ×2fresh native sessions, second reverses callback evaluation. Alternating unit targets,1% fee,initialcapital1000000,600bars/session with retained gaps. No randomness, storage, queue, indicators or parallel simulation.",
"equality": "Exact complete normalized result hashes match every repeat and debug/release profile. Independent integer-cent cash/equity/remaining basis/owner fees/fill count oracle passes. Economically different results invalidate measurement.",
"timing": "Report separates imports, detached D01 verify, once-per-child prepared-JS mapping, fresh native load, actual advance/submit/decision/finalize and validation/hash. Native call timers include JS encoding/schema/immutable projection plus Rust work/serialization, not pure crossing cost. Trial wall includes load+replay+finalization+oracle/hash, excludes one-time preparation/import and parent aggregation. No explicit warmup or OS-cache flush; means only, not latency distributions. Shared host; release focused checks briefly overlapped initial measurement, so not an isolated performance SLA.",
"workloads": [
{
"workload": {
"totalBars": 1000,
"assets": 1,
"owners": 1,
"eventBudget": 64
},
"dataset_hash": "d7373071536b302c95938e7b174207086d86f39e070c7d735adeaff4746012ab",
"policy_hash": "5033c5bc74a54e41bc443bb7a0c9159a0c6e863a9f8a81514fc81deaf9753712",
"result_hash": "dbf14999e978f2d1b970c794aa9306e7278cb071dc1419b3cbf62a5c791f2c55",
"economic_oracle": {
"cash": "998700.10000000",
"equity": "998749.10000000",
"feePerOwner": "289.90000000",
"quantity": "1.00000000",
"remainingCost": "48.00000000",
"fills": 999,
"decisions": 999,
"fees": 999
},
"calls_per_trial": {
"create": 1,
"advance": 1000,
"submit": 999,
"finalize": 1,
"dispose": 1,
"decisions": 999
},
"bytes_per_trial": {
"createRequest": 298995,
"advanceRequests": 150000,
"advanceResponses": 1594052,
"submitRequests": 474197,
"submitResponses": 1653733,
"finalizeRequest": 120,
"finalizeResponse": 6618188
},
"cold_processes": [
{
"processRepeat": 0,
"processWallMs": 661.6411169999999,
"phasesMs": {
"entryUptimeMs": 17.989492,
"applicationImportMs": 7.721003000000003,
"addonImportMs": 3.302654999999998,
"adapterImportMs": 1.8754419999999996,
"fixtureGenerationMs": 26.622123,
"datasetTransportRoundtripMs": 1.1517809999999997,
"frozenDatasetVerificationMs": 6.792315000000002,
"preparedReuseAndMappingMs": 2.202702000000002,
"requestSizingMs": 0.6443500000000029,
"childWallMs": 627.174377
},
"peakRssBytes": 301342720
},
{
"processRepeat": 1,
"processWallMs": 655.0907609999999,
"phasesMs": {
"entryUptimeMs": 17.513791,
"applicationImportMs": 8.486132999999999,
"addonImportMs": 3.8382700000000014,
"adapterImportMs": 1.7702929999999988,
"fixtureGenerationMs": 24.009442999999997,
"datasetTransportRoundtripMs": 1.1287380000000056,
"frozenDatasetVerificationMs": 8.813603,
"preparedReuseAndMappingMs": 2.3357539999999943,
"requestSizingMs": 0.8061170000000004,
"childWallMs": 615.3559439999999
},
"peakRssBytes": 301826048
}
],
"raw_rows": [
"process=0 repeat=0 reverse=false create_ms=5.837 advance_ms=111.434 submit_ms=48.305 decision_ms=5.820 finalize_ms=103.084 run_ms=282.927 validation_hash_ms=16.111 trial_ms=304.885 rss_bytes=259719168",
"process=0 repeat=1 reverse=true create_ms=11.309 advance_ms=88.767 submit_ms=41.545 decision_ms=4.419 finalize_ms=88.671 run_ms=238.374 validation_hash_ms=15.971 trial_ms=271.152 rss_bytes=296042496",
"process=1 repeat=0 reverse=false create_ms=5.872 advance_ms=105.751 submit_ms=45.869 decision_ms=7.073 finalize_ms=96.598 run_ms=270.411 validation_hash_ms=18.130 trial_ms=294.422 rss_bytes=256008192",
"process=1 repeat=1 reverse=true create_ms=9.696 advance_ms=96.633 submit_ms=45.206 decision_ms=4.885 finalize_ms=88.541 run_ms=244.470 validation_hash_ms=14.739 trial_ms=268.963 rss_bytes=296484864"
]
},
{
"workload": {
"totalBars": 1000,
"assets": 10,
"owners": 2,
"eventBudget": 64
},
"dataset_hash": "2c09236354f09d017cac5c2564e64801827ca2c62c5ae26cd33cf42cd45db591",
"policy_hash": "2e55eb1dcae65f847ab53914a7a11afaa46b0c9a199b20565dafe08cc1b94c95",
"result_hash": "02ec46d0810d9015856dbe682a543dd89cfd35642c4a60c6929750e043753f30",
"economic_oracle": {
"cash": "997222.00000000",
"equity": "998202.00000000",
"feePerOwner": "289.00000000",
"quantity": "1.00000000",
"remainingCost": "48.00000000",
"fills": 1980,
"decisions": 198,
"fees": 1980
},
"calls_per_trial": {
"create": 1,
"advance": 100,
"submit": 99,
"finalize": 1,
"dispose": 1,
"decisions": 198
},
"bytes_per_trial": {
"createRequest": 304030,
"advanceRequests": 15000,
"advanceResponses": 771228,
"submitRequests": 161669,
"submitResponses": 2870078,
"finalizeRequest": 120,
"finalizeResponse": 10211261
},
"cold_processes": [
{
"processRepeat": 0,
"processWallMs": 788.2048580000001,
"phasesMs": {
"entryUptimeMs": 15.259431,
"applicationImportMs": 8.28377,
"addonImportMs": 4.707255,
"adapterImportMs": 5.777583,
"fixtureGenerationMs": 26.400312,
"datasetTransportRoundtripMs": 1.6383530000000022,
"frozenDatasetVerificationMs": 10.224725999999997,
"preparedReuseAndMappingMs": 3.6051980000000015,
"requestSizingMs": 1.0060459999999978,
"childWallMs": 748.412532
},
"peakRssBytes": 368349184
},
{
"processRepeat": 1,
"processWallMs": 821.422493,
"phasesMs": {
"entryUptimeMs": 13.583367,
"applicationImportMs": 13.815114999999999,
"addonImportMs": 6.963970000000003,
"adapterImportMs": 4.928774999999995,
"fixtureGenerationMs": 23.262509,
"datasetTransportRoundtripMs": 1.7333030000000065,
"frozenDatasetVerificationMs": 10.020107999999993,
"preparedReuseAndMappingMs": 3.5597620000000063,
"requestSizingMs": 1.041753,
"childWallMs": 786.7616939999999
},
"peakRssBytes": 359272448
}
],
"raw_rows": [
"process=0 repeat=0 reverse=false create_ms=6.549 advance_ms=99.120 submit_ms=63.205 decision_ms=4.502 finalize_ms=135.594 run_ms=325.784 validation_hash_ms=20.771 trial_ms=353.111 rss_bytes=307449856",
"process=0 repeat=1 reverse=true create_ms=10.039 advance_ms=95.032 submit_ms=56.225 decision_ms=2.315 finalize_ms=122.526 run_ms=298.653 validation_hash_ms=21.863 trial_ms=333.230 rss_bytes=362307584",
"process=1 repeat=0 reverse=false create_ms=6.779 advance_ms=107.722 submit_ms=65.977 decision_ms=3.926 finalize_ms=142.593 run_ms=338.320 validation_hash_ms=31.209 trial_ms=376.321 rss_bytes=305405952",
"process=1 repeat=1 reverse=true create_ms=8.583 advance_ms=101.354 submit_ms=58.865 decision_ms=2.515 finalize_ms=127.850 run_ms=310.347 validation_hash_ms=22.903 trial_ms=344.188 rss_bytes=354123776"
]
},
{
"workload": {
"totalBars": 10000,
"assets": 1,
"owners": 1,
"eventBudget": 64
},
"dataset_hash": "3cca7ed706f28a56a9ea463df1a310bb72dae8c52366ad631330ea439f2b7396",
"policy_hash": "5033c5bc74a54e41bc443bb7a0c9159a0c6e863a9f8a81514fc81deaf9753712",
"result_hash": "492467b561adb8792f6b75a6d8754e10fc5361772218bd7bcdbb1984748953bd",
"economic_oracle": {
"cash": "987090.10000000",
"equity": "987139.10000000",
"feePerOwner": "2899.90000000",
"quantity": "1.00000000",
"remainingCost": "48.00000000",
"fills": 9999,
"decisions": 9999,
"fees": 9999
},
"calls_per_trial": {
"create": 1,
"advance": 10000,
"submit": 9999,
"finalize": 1,
"dispose": 1,
"decisions": 9999
},
"bytes_per_trial": {
"createRequest": 2974606,
"advanceRequests": 1500000,
"advanceResponses": 16031754,
"submitRequests": 4796202,
"submitResponses": 16682062,
"finalizeRequest": 120,
"finalizeResponse": 66707481
},
"cold_processes": [
{
"processRepeat": 0,
"processWallMs": 5901.124175999999,
"phasesMs": {
"entryUptimeMs": 17.556242,
"applicationImportMs": 6.730817999999999,
"addonImportMs": 5.032081000000002,
"adapterImportMs": 4.58794,
"fixtureGenerationMs": 84.677629,
"datasetTransportRoundtripMs": 14.557602000000003,
"frozenDatasetVerificationMs": 62.00848399999998,
"preparedReuseAndMappingMs": 20.191041000000013,
"requestSizingMs": 8.44956400000001,
"childWallMs": 5777.450008
},
"peakRssBytes": 1954250752
},
{
"processRepeat": 1,
"processWallMs": 5903.965668999999,
"phasesMs": {
"entryUptimeMs": 18.012255,
"applicationImportMs": 10.324835,
"addonImportMs": 5.431056000000002,
"adapterImportMs": 2.3624650000000003,
"fixtureGenerationMs": 89.00218899999999,
"datasetTransportRoundtripMs": 12.282512999999994,
"frozenDatasetVerificationMs": 55.98375300000001,
"preparedReuseAndMappingMs": 14.392830000000004,
"requestSizingMs": 6.046502000000004,
"childWallMs": 5779.638424000001
},
"peakRssBytes": 1863028736
}
],
"raw_rows": [
"process=0 repeat=0 reverse=false create_ms=79.629 advance_ms=951.834 submit_ms=423.590 decision_ms=48.473 finalize_ms=1030.548 run_ms=2679.932 validation_hash_ms=165.799 trial_ms=2925.392 rss_bytes=1496563712",
"process=0 repeat=1 reverse=true create_ms=74.777 advance_ms=851.794 submit_ms=407.244 decision_ms=40.309 finalize_ms=896.594 run_ms=2410.872 validation_hash_ms=159.670 trial_ms=2645.348 rss_bytes=1947648000",
"process=1 repeat=0 reverse=false create_ms=78.815 advance_ms=961.375 submit_ms=435.331 decision_ms=50.952 finalize_ms=1032.592 run_ms=2675.814 validation_hash_ms=164.248 trial_ms=2918.895 rss_bytes=1493749760",
"process=1 repeat=1 reverse=true create_ms=108.628 advance_ms=845.282 submit_ms=403.395 decision_ms=41.444 finalize_ms=890.541 run_ms=2397.735 validation_hash_ms=158.155 trial_ms=2664.540 rss_bytes=1857527808"
]
},
{
"workload": {
"totalBars": 10000,
"assets": 10,
"owners": 2,
"eventBudget": 64
},
"dataset_hash": "ebaf4f6908d3897539ab7c52bb5003d81a10e099d66aa3ab3e60c43c97bc93ef",
"policy_hash": "2e55eb1dcae65f847ab53914a7a11afaa46b0c9a199b20565dafe08cc1b94c95",
"result_hash": "b065da3a8ff7c0a341bf8d4326c455fac0a029027446f9734d13ac117ea13e4c",
"economic_oracle": {
"cash": "974002.00000000",
"equity": "974982.00000000",
"feePerOwner": "2899.00000000",
"quantity": "1.00000000",
"remainingCost": "48.00000000",
"fills": 19980,
"decisions": 1998,
"fees": 19980
},
"calls_per_trial": {
"create": 1,
"advance": 1000,
"submit": 999,
"finalize": 1,
"dispose": 1,
"decisions": 1998
},
"bytes_per_trial": {
"createRequest": 2969186,
"advanceRequests": 150000,
"advanceResponses": 7818768,
"submitRequests": 1640280,
"submitResponses": 29200102,
"finalizeRequest": 120,
"finalizeResponse": 103598570
},
"cold_processes": [
{
"processRepeat": 0,
"processWallMs": 7471.874861,
"phasesMs": {
"entryUptimeMs": 15.425926,
"applicationImportMs": 6.739083999999998,
"addonImportMs": 3.763588000000002,
"adapterImportMs": 3.005122,
"fixtureGenerationMs": 86.40961899999999,
"datasetTransportRoundtripMs": 15.727568000000005,
"frozenDatasetVerificationMs": 55.450342000000006,
"preparedReuseAndMappingMs": 19.996653999999978,
"requestSizingMs": 7.253488000000004,
"childWallMs": 7308.53601
},
"peakRssBytes": 2546876416
},
{
"processRepeat": 1,
"processWallMs": 7542.137738999998,
"phasesMs": {
"entryUptimeMs": 13.804856,
"applicationImportMs": 7.877509000000002,
"addonImportMs": 14.412988999999996,
"adapterImportMs": 5.680057000000005,
"fixtureGenerationMs": 88.133104,
"datasetTransportRoundtripMs": 10.459769999999992,
"frozenDatasetVerificationMs": 64.49405099999998,
"preparedReuseAndMappingMs": 13.91592700000001,
"requestSizingMs": 6.098469999999992,
"childWallMs": 7403.1065260000005
},
"peakRssBytes": 2554671104
}
],
"raw_rows": [
"process=0 repeat=0 reverse=false create_ms=78.571 advance_ms=964.182 submit_ms=614.812 decision_ms=21.184 finalize_ms=1394.367 run_ms=3286.854 validation_hash_ms=235.141 trial_ms=3600.595 rss_bytes=2048065536",
"process=0 repeat=1 reverse=true create_ms=123.926 advance_ms=934.619 submit_ms=567.542 decision_ms=19.933 finalize_ms=1341.980 run_ms=3158.524 validation_hash_ms=226.714 trial_ms=3509.189 rss_bytes=2541584384",
"process=1 repeat=0 reverse=false create_ms=79.123 advance_ms=976.004 submit_ms=617.892 decision_ms=23.249 finalize_ms=1398.552 run_ms=3295.705 validation_hash_ms=230.761 trial_ms=3605.613 rss_bytes=2052440064",
"process=1 repeat=1 reverse=true create_ms=121.809 advance_ms=951.035 submit_ms=578.639 decision_ms=20.921 finalize_ms=1371.665 run_ms=3222.154 validation_hash_ms=241.815 trial_ms=3585.798 rss_bytes=2548953088"
]
}
],
"limits": "Order-heavy conformance component, not production strategy, durable research throughput, legacy speedup or pure NAPI probe. Native data reloads each trial. Journals/results grow with history; finalized10k receipt payloads~66.7MB single/~103.6MB multi, not RSS. No caching, compaction, shared feature model or DSL. Sequential multi-asset risk mark semantics unchanged."
},
"not_run": [
"Browser E2E and Python analytics: UI/API/Python behavior unchanged.",
"100k --large session benchmark, earlier manual ledger/risk/matching/replay benchmarks: not required for this boundary; no claim of those throughput gates."
],
"limitations": [
"Trusted host API, not an untrusted-code sandbox. TS worker verifies D01; native prepared payload/hash labels alone are not dataset authentication.",
"Exact represented numeric decimal ingress; values needing more than8fractional digits or exceeding range reject, including feature OHLCV. No silent rounding.",
"Fixed intent traces/fixture callbacks only. S01 production strategy artifacts/state/RNG and recovery, F08 metrics/projections and R05 durable canonical default remain separate.",
"Opaque read-only order/reservation/effect diagnostics are not another admission API or finalized F08 reporting schema.",
"Quote/abutting-session replay unsupported. Event budget counts events, not wall time.",
"Sequential equal-time marks can latch intermediate loss/drawdown; canonical_release_gates.multi_asset_mark_policy remains unresolved.",
"Existing build warnings remain. Clean isolated build required explicit existing logger prerequisite. No unrelated dependency/build-system cleanup."
],
"cleanup": "Stopped/removed only disposable containers4843a8d42953aefac9c323ff0a8913f0d5e0c39dd862273f149c1ba9cfc3bf63 and4a518cf5400aef08eae49e029d1ddd6649d3af152e051f17bc5fbc082e2a9915, deleting recreatable synthetic fixture state. Development services untouched; worktree/logs retained.",
"handoff": "F06 committed417a7bd. F07 independently accepted and validated, uncommitted. F08 now ready by existing code/approved ADR prerequisites, recommended after owner acceptance; not authorized yet. S01 needs ADR005. No push, PR, default-engine activation or paper/live operation."
}
}

View file

@ -18,16 +18,30 @@ F06 consumes internal typed prepared bars/session tables, not an independently a
Expose recorded model limitations, including F06's explicitly unsupported abutting venue sessions and F04/F05's sequential equal-time portfolio marks (intermediate valuations can latch risk halts). An event budget bounds event count, not wall time or the cost of an individual matching transition. These are not promises of atomic multi-asset valuation, arbitrary-calendar support or constant-latency cancellation.
## Execution handoff clarifications
- Add a separate NAPI FinancialReplaySession and a fixed-intent-trace request variant in the existing worker. Keep the legacy run request and durable runner default unchanged. The trace path is for conformance/debugging, not a declarative strategy language or S01 strategy runtime.
- Verify frozen D01 inputs inside the worker before native creation; native prepared input remains a trusted host boundary, not independent proof of a supplied dataset hash. Convert represented numeric values to plain decimal strings, expanding scientific notation and rejecting precision/range loss rather than silently rounding.
- Pin a strict version/session/dataset envelope and validate response identities. Emit prefix observation deltas and one shared financial/order/risk view; never pass full prepared data/checkpoints to a callback or clone retained checkpoints in the hot loop. A small read-only F06 range accessor is permitted; replay and risk semantics are not changed.
- Permit a test-only include of the new adapter from the financial test module: the crate excludes its API module from ordinary unit builds. Exercise the production host/direct-Replay parity without enabling unrelated legacy NAPI wrappers or changing production module direction. The thin exported wrapper delegates one-to-one to that host and is separately tested through the built addon.
- The conformance loop may evaluate fixture callbacks in varied order, but submits the complete due-owner batch once. Callback failure fails/disposes the attempt; no partial submission or later successful finalization. Production strategy state/RNG, artifact imports and durable canonical cutover remain S01/R05.
- Preserve existing process supervision: one process/request, hard cancellation, wait for close after a result, rejection after abort, failed worker reuse and stale attempt protection. Run existing runner cancellation/lease regressions, including the disposable PostgreSQL suite at integration.
- Extend the existing P01 harness with actual session preparation/load, advance/submit call timings and counts, context/delta bytes and finalization. Calls include real Rust/serialization work; do not label them empty crossings or end-to-end strategy throughput.
## Exclusions
No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results.
## Likely files and ownership
- apps/stock/engine/src/api/backtest.rs
- apps/stock/engine/src/api/replay.rs (additive session; existing backtest API unchanged)
- apps/stock/engine/src/financial/replay.rs (read-only published-observation range accessor only)
- apps/stock/orchestrator/src/backtest/native-replay.ts
- apps/stock/orchestrator/src/contracts/native-replay.ts (schema-only boundary)
- apps/stock/orchestrator/src/backtest/native-worker.ts
- apps/stock/orchestrator/src/backtest/native-worker-protocol.ts
- apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts
- scripts/benchmark-research.ts and focused native/worker fixtures
Write locks: native-public-api, worker-protocol. One agent owns this change. Lock names do not override actual overlapping files.

378
scripts/benchmark-replay.ts Normal file
View file

@ -0,0 +1,378 @@
/** F07 extension of P01, invoked only through benchmark-research.ts --session. */
import { createHash } from 'node:crypto';
import { readFileSync } from 'node:fs';
import type { ReplayResult } from '../apps/stock/orchestrator/src/contracts/native-replay';
type SessionWorkload = { totalBars: number; assets: number; owners: number; eventBudget: number };
const hash = (value: string) => createHash('sha256').update(value).digest('hex');
const capital = '1000000.00000000';
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 turnoverOracle(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;
for (let step = 1; step < barsPerAsset; step++) {
const price = BigInt(10 + (step % 20) * 2);
cashDelta += (step % 2 ? -price : price) * 100n - price;
fee += price;
}
const books = BigInt(assets * owners),
holding = (barsPerAsset - 1) % 2;
const lastOpen = BigInt(10 + ((barsPerAsset - 1) % 20) * 2);
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: (barsPerAsset - 1) * assets * owners,
decisions: (barsPerAsset - 1) * owners,
};
}
function assertEconomics(result: ReplayResult, workload: SessionWorkload) {
const expected = turnoverOracle(
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.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');
}
let fills = 0,
fees = 0;
for (const receipt of result.receipts) {
for (const effect of receipt.outcome.effects) {
if (!('Risk' in effect)) {
continue;
}
const risk = effect.Risk as {
outcome: {
disposition: unknown;
financial: null | { replayed: boolean; effects: { effects: { kind: string }[] } };
};
};
if (risk.outcome.disposition !== 'Accepted') {
throw new Error('Unexpected benchmark risk rejection');
}
if (!risk.outcome.financial) {
continue;
}
if (risk.outcome.financial.replayed) {
throw new Error('Unexpected benchmark duplicate effect');
}
for (const financial of risk.outcome.financial.effects.effects) {
if (financial.kind === 'fillApplied') {
fills++;
}
if (financial.kind === 'feeApplied') {
fees++;
}
}
}
}
if (fills !== expected.fills || fees !== fills) {
throw new Error('Unexpected benchmark fill/fee count');
}
return { ...expected, fees };
}
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();
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);
return {
mode: 'target',
targets: fixture.instruments.map(instrumentId => ({
instrumentId,
quantity: decision % 2 ? zero : one,
})),
};
},
{ eventBudget: workload.eventBudget, reverseCallbacks: repeat === 1 }
);
const runWallMs = performance.now() - runStart;
const validationStart = performance.now();
const economic = assertEconomics(result, workload);
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 validationAndHashMs = performance.now() - validationStart;
const wallMs = performance.now() - trialStart;
trials.push({
repeat,
reverseCallbacks: repeat === 1,
resultHash,
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,
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,
datasetHash: dataset.manifest.hash,
policyHash: hash(
JSON.stringify({ config: load.config, strategy: 'alternating-unit-target-v1' })
),
datasetBytes: Buffer.byteLength(wireDataset),
policy: load.config,
phasesMs: {
entryUptimeMs,
applicationImportMs,
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; trials: { resultHash: string }[] }[]
) {
const first = samples[0],
expected = first?.trials[0]?.resultHash;
if (!first || !expected) {
throw new Error('Missing canonical benchmark samples');
}
for (const sample of samples) {
if (
sample.datasetHash !== first.datasetHash ||
sample.policyHash !== first.policyHash ||
!sample.trials.length ||
sample.trials.some(trial => trial.resultHash !== expected)
) {
throw new Error('Canonical dataset/policy/result mismatch; no timing comparison is valid');
}
}
}
export async function sessionBenchmark(
root: string,
entry: string,
metadata: object,
measured: boolean,
large: boolean
) {
const workloads = (measured ? (large ? [1000, 10000, 100000] : [1000, 10000]) : [8]).flatMap(
bars => [
{ totalBars: bars, assets: 1, owners: 1, eventBudget: 64 },
{
totalBars: measured ? bars : bars * 2,
assets: measured ? 10 : 2,
owners: 2,
eventBudget: 64,
},
]
);
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);
measurements.push({ workload, repeatedResultHashesMatch: true, samples });
process.stderr.write(
`Verified canonical ${workload.totalBars} bars / ${workload.assets} assets / ${workload.owners} owners, 2 fresh processes × 2 fresh sessions\n`
);
}
process.stdout.write(
JSON.stringify(
{
schemaVersion: 1,
path: 'canonical-pull-session',
mode: measured ? 'measurement' : 'self-test',
...metadata,
strategy: {
definition: 'alternating-unit-target-v1',
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.',
},
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.',
'Full retained receipts are finalized and parsed; RSS is process-wide, not native residency. Metadata hashing and parent aggregation are outside child timings.',
'An event budget bounds event count, not elapsed time. JSON throughput and actual decision costs are measured together with boundary work.',
],
measurements,
},
null,
2
) + '\n'
);
}

View file

@ -1,8 +1,10 @@
/**
* Existing one-shot native path only; no DB, broker, queue or strategy callbacks.
* Existing one-shot native path by default; no DB, broker or durable queue.
* bun run scripts/benchmark-research.ts # tiny deterministic self-test
* bun run scripts/benchmark-research.ts --measure # 1k/10k total bars, 1/10 assets
* bun run scripts/benchmark-research.ts --measure --large # additionally 100k (quadratic queue)
* bun run scripts/benchmark-research.ts --session # canonical pull-session self-test
* bun run scripts/benchmark-research.ts --session --measure # 1k/10k bars, actual TS decisions
* Build workspace libraries/config and the local engine first. JSON stdout; diagnostics stderr.
*/
import { createHash } from 'node:crypto';
@ -335,19 +337,37 @@ export function verifyRepeats(
}
async function main(args: string[]) {
if (args[0] === '--session-child') {
const { sessionChild } = await import('./benchmark-replay');
process.stdout.write(JSON.stringify(await sessionChild(JSON.parse(args[1] ?? ''))) + '\n');
return;
}
if (args[0] === '--child') {
process.stdout.write(JSON.stringify(await child(JSON.parse(args[1] ?? ''))) + '\n');
return;
}
if (
args.some(a => !['--self-test', '--measure', '--large'].includes(a)) ||
args.some(a => !['--self-test', '--measure', '--large', '--session'].includes(a)) ||
(args.includes('--large') && !args.includes('--measure')) ||
(args.includes('--self-test') && args.includes('--measure'))
) {
throw new Error('Use no flags/--self-test, --measure, or --measure --large');
throw new Error(
'Use no flags/--self-test, --measure, or --measure --large; optionally --session'
);
}
const metadata = identity(); // Excluded from workload timings.
const measured = args.includes('--measure');
if (args.includes('--session')) {
const { sessionBenchmark } = await import('./benchmark-replay');
await sessionBenchmark(
root,
fileURLToPath(import.meta.url),
metadata,
measured,
args.includes('--large')
);
return;
}
const workloads = measured
? (args.includes('--large') ? [1000, 10_000, 100_000] : [1000, 10_000]).flatMap(totalBars =>
[1, 10].map(assets => ({ totalBars, assets, seed: 42 }))

View file

@ -183,11 +183,15 @@ describe('orchestrator architecture boundaries', () => {
relative(root, file).startsWith('backtest/') &&
imports.get(file)?.includes('@stock-bot/engine')
);
expect(nativeEntrypoints.map(file => relative(root, file))).toEqual([
expect(nativeEntrypoints.map(file => relative(root, file)).sort()).toEqual([
'backtest/native-replay.ts',
'backtest/native-worker.ts',
]);
for (const file of files) {
const path = relative(root, file);
if (reachable(file).has(join(root, 'backtest/native-replay.ts'))) {
expect(['backtest/native-replay.ts', 'backtest/native-worker.ts']).toContain(path);
}
const source = ts.createSourceFile(
file,
readFileSync(file, 'utf8'),
@ -211,6 +215,12 @@ describe('orchestrator architecture boundaries', () => {
) {
expect(path).toBe('backtest/native-worker.ts');
}
if (
!binding.isTypeOnly &&
(binding.propertyName ?? binding.name).text === 'FinancialReplaySession'
) {
expect(path).toBe('backtest/native-replay.ts');
}
}
}
}

View file

@ -0,0 +1,81 @@
import { expect, test } from 'bun:test';
import { turnoverOracle, verifySessionRepeats } from '../benchmark-replay';
test('canonical benchmark 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',
trials: [{ resultHash: 'result' }, { resultHash: 'result' }],
};
expect(() => verifySessionRepeats([sample, structuredClone(sample)])).not.toThrow();
for (const changed of [
{ ...sample, datasetHash: 'changed' },
{ ...sample, policyHash: 'changed' },
{ ...sample, trials: [{ resultHash: 'changed' }] },
{ ...sample, trials: [] },
]) {
expect(() => verifySessionRepeats([sample, changed])).toThrow('mismatch');
}
expect(() => verifySessionRepeats([])).toThrow('Missing');
});
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);
}
}
}
});

View file

@ -2,6 +2,7 @@ import { createRequire } from 'node:module';
import { describe, expect, it } from 'bun:test';
import {
BacktestEngine,
FinancialReplaySession,
IncrementalSMA,
TechnicalIndicators,
TradingEngine,
@ -70,6 +71,7 @@ describe('generated native bindings', () => {
const binding = createRequire(import.meta.url)('@stock-bot/engine');
expect(binding.TechnicalIndicators).toBe(TechnicalIndicators);
expect(binding.IncrementalSMA).toBe(IncrementalSMA);
expect(binding.FinancialReplaySession).toBe(FinancialReplaySession);
});
it('MACD keeps full-length EMA series aligned without out-of-bounds access', () => {

View file

@ -10,7 +10,11 @@ function send(message: NativeWorkerMessage | { invalid: boolean }): Promise<void
}
process.once('message', async (input: unknown) => {
const { config } = nativeWorkerRequestSchema.parse(input);
const request = nativeWorkerRequestSchema.parse(input);
if (request.type !== 'run') {
throw new Error('Legacy fixture only');
}
const { config } = request;
// Fixture controls are run labels, not unsupported production strategy parameters.
const behavior = config.name?.startsWith('fixture:')
? config.name.slice('fixture:'.length)
@ -18,7 +22,7 @@ process.once('message', async (input: unknown) => {
if (!behavior) {
// The same adapter can recover and run the actual Rust engine after a failed worker.
await import('../../apps/stock/orchestrator/src/backtest/native-worker');
process.emit('message', input);
process.emit('message', input, undefined);
return;
}
await send({ type: 'progress', progress: 0, message: `Fixture worker ready:${process.pid}` });
@ -43,6 +47,7 @@ process.once('message', async (input: unknown) => {
break;
case 'no-result':
process.exit(0);
return;
case 'result-then-block':
await send({ type: 'result', result: '{}' });
while (true) {

212
test/fixtures/native-replay-load.json vendored Normal file
View file

@ -0,0 +1,212 @@
{
"identity": {
"version": 1,
"sessionId": "f07-fixture",
"datasetHash": "ad6300d751db8b65bc2e499b029bbd3e9882b57d74528b0b10b591ff55556101"
},
"config": {
"matching": {
"risk": {
"ledger": {
"version": 1,
"sessionId": "f07-fixture",
"accountId": "research-only",
"baseCurrency": "USD",
"reserveOwnerId": "reserve",
"ownerIds": [
"A"
],
"initialCapital": "10000.00000000",
"riskSession": {
"calendarId": "account",
"calendarRevision": "1",
"sessionId": "risk",
"startsAt": 1704099600000
}
},
"feeRate": "0.01000000",
"maxOrderQuantity": "1000000.00000000",
"maxPositionQuantity": "1000000.00000000",
"maxSymbolExposure": "1000000.00000000",
"maxGrossExposure": "1000000.00000000",
"maxDailyLoss": "1000000.00000000",
"maxDrawdownAmount": "1000000.00000000",
"maxMarkAgeMs": 172800000
},
"owners": [
{
"ownerId": "A",
"mode": "Target"
}
],
"series": [
{
"instrumentId": "X0.US",
"seriesId": "X0.US:1m",
"mode": "Open"
}
],
"halfSpreadRate": "0.00000000",
"slippageRate": "0.00000000",
"latencyMs": 0
},
"participation_rate": "1.00000000",
"cadence": [
{
"owner_id": "A",
"series_ids": [
"X0.US:1m"
]
}
],
"allow_exploratory": false,
"risk_boundaries": []
},
"manifest": {
"calendars": [
{
"id": "fixture-calendar",
"venue": "TEST",
"timeZone": "UTC",
"revision": "1",
"source": "synthetic",
"startDate": "2024-01-01",
"endDate": "2024-01-02",
"sessions": [
{
"date": "2024-01-01",
"open": 1704099600000,
"close": 1704135600000
}
]
}
],
"series": [
{
"id": "X0.US:1m",
"instrumentId": "X0.US",
"interval": "1m",
"calendarId": "fixture-calendar",
"venue": "TEST",
"source": {
"provider": "synthetic",
"revision": "f07-v1"
},
"timestamp": "interval-start",
"availability": "explicit",
"adjustment": "raw"
}
],
"executionSeries": [
{
"instrumentId": "X0.US",
"seriesId": "X0.US:1m"
}
],
"bounds": {
"warmupStart": 1704099600000,
"tradeStart": 1704099660000,
"tradeEnd": 1704099780000
},
"universe": {
"selection": "point-in-time",
"asOf": 1704099600000,
"revision": "1",
"instrumentIds": [
"X0.US"
]
},
"corporateActions": [
{
"instrumentId": "X0.US",
"status": "action-free",
"start": 1704099600000,
"end": 1704099780000,
"revision": "1",
"actions": []
}
],
"version": 2,
"normalizationRevision": "historical-normalization-v2",
"parentDatasetHash": null,
"volumePolicy": "reported",
"qualityPolicy": "reject-invalid-no-interpolation",
"intradayPolicy": "full-duration-session-contained",
"eligibility": "eligible",
"limitations": [
"Open liquidity must use previously available volume; intraday partial bars are unsupported"
],
"barCount": 3,
"hash": "ad6300d751db8b65bc2e499b029bbd3e9882b57d74528b0b10b591ff55556101"
},
"prepared": {
"dataset_id": "ad6300d751db8b65bc2e499b029bbd3e9882b57d74528b0b10b591ff55556101",
"eligibility": "Eligible",
"limitations": [
"Open liquidity must use previously available volume; intraday partial bars are unsupported"
],
"bounds": {
"warmup_start": 1704099600000,
"trade_start": 1704099660000,
"trade_end": 1704099780000
},
"series": [
{
"series_id": "X0.US:1m",
"instrument_id": "X0.US",
"adjustment": "Raw",
"sessions": [
{
"sessionId": "[\"fixture-calendar\",\"1\",\"2024-01-01\"]",
"opensAt": 1704099600000,
"closesAt": 1704135600000
}
]
}
],
"bars": [
{
"series_id": "X0.US:1m",
"instrument_id": "X0.US",
"interval_start": 1704099600000,
"interval_end": 1704099660000,
"event_time": 1704099660000,
"available_at": 1704099660000,
"source_sequence": 0,
"open": "10.00000000",
"high": "11.00000000",
"low": "10.00000000",
"close": "11.00000000",
"volume": "1000.00000000"
},
{
"series_id": "X0.US:1m",
"instrument_id": "X0.US",
"interval_start": 1704099660000,
"interval_end": 1704099720000,
"event_time": 1704099720000,
"available_at": 1704099720000,
"source_sequence": 1,
"open": "12.00000000",
"high": "13.00000000",
"low": "12.00000000",
"close": "13.00000000",
"volume": "1000.00000000"
},
{
"series_id": "X0.US:1m",
"instrument_id": "X0.US",
"interval_start": 1704099720000,
"interval_end": 1704099780000,
"event_time": 1704099780000,
"available_at": 1704099780000,
"source_sequence": 2,
"open": "14.00000000",
"high": "15.00000000",
"low": "14.00000000",
"close": "15.00000000",
"volume": "1000.00000000"
}
]
}
}

41
test/fixtures/native-replay-worker.ts vendored Normal file
View file

@ -0,0 +1,41 @@
import { executeReplayTrace } from '../../apps/stock/orchestrator/src/backtest/native-replay';
import { replayTraceSchema } from '../../apps/stock/orchestrator/src/contracts/native-replay';
function send(message: unknown): Promise<void> {
return new Promise((resolve, reject) =>
process.send!(message, (error: Error | null) => (error ? reject(error) : resolve()))
);
}
process.once('message', async (input: unknown) => {
const request = replayTraceSchema.parse(input),
{ result } = executeReplayTrace(request);
const mode = request.config.matching.risk.ledger.accountId;
await send({ type: 'progress', progress: 0, message: 'Fixture ready' });
switch (mode) {
case 'wrong-version':
result.manifest.version = 1;
break;
case 'wrong-account':
result.view.portfolio.accountId = 'wrong';
break;
case 'wrong-policy':
result.policy.matching.risk.feeRate = '0.5' as typeof result.policy.matching.risk.feeRate;
break;
case 'wrong-session':
result.identity.sessionId = 'wrong';
break;
case 'wrong-dataset':
result.identity.datasetHash = '0'.repeat(64);
break;
case 'crash':
process.kill(process.pid, 'SIGKILL');
return;
}
await send({ type: 'result', result: JSON.stringify(result) });
if (mode === 'result-then-block') {
while (true) {
Math.sqrt(Math.random());
}
}
process.disconnect?.();
});

117
test/fixtures/native-replay.ts vendored Normal file
View file

@ -0,0 +1,117 @@
import type { ReplayConfig } from '../../apps/stock/orchestrator/src/contracts/native-replay';
import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
/** Retained synthetic sessions, raw executable bars, explicit availability. */
export function nativeReplayFixture(barsPerAsset = 3, assets = 1, owners = ['A']) {
const start = Date.parse('2024-01-01T09:00:00Z'),
minute = 60000,
day = 86400000;
const at = (step: number) => start + Math.floor(step / 600) * day + (step % 600) * minute;
const end = at(barsPerAsset - 1) + minute;
const instruments = Array.from({ length: assets }, (_, i) => `X${i}.US`);
const calendar = {
id: 'fixture-calendar',
venue: 'TEST',
timeZone: 'UTC',
revision: '1',
source: 'synthetic',
startDate: '2024-01-01',
endDate: new Date(end + day).toISOString().slice(0, 10),
sessions: Array.from({ length: Math.ceil(barsPerAsset / 600) }, (_, i) => ({
date: new Date(start + i * day).toISOString().slice(0, 10),
open: start + i * day,
close: start + i * day + 600 * minute,
})),
};
const dataset = createDatasetV2({
metadata: {
calendars: [calendar],
series: instruments.map(instrumentId => ({
id: `${instrumentId}:1m`,
instrumentId,
interval: '1m',
calendarId: calendar.id,
venue: calendar.venue,
source: { provider: 'synthetic', revision: 'f07-v1' },
timestamp: 'interval-start',
availability: 'explicit',
adjustment: 'raw',
})),
executionSeries: instruments.map(instrumentId => ({
instrumentId,
seriesId: `${instrumentId}:1m`,
})),
bounds: { warmupStart: start, tradeStart: start + minute, tradeEnd: end },
universe: {
selection: 'point-in-time',
asOf: start,
revision: '1',
instrumentIds: instruments,
},
corporateActions: instruments.map(instrumentId => ({
instrumentId,
status: 'action-free',
start,
end,
revision: '1',
actions: [],
})),
},
bars: instruments.flatMap(instrumentId =>
Array.from({ length: barsPerAsset }, (_, step) => ({
seriesId: `${instrumentId}:1m`,
timestamp: at(step),
availableAt: at(step) + minute,
sourceSequence: step,
open: 10 + (step % 20) * 2,
high: 11 + (step % 20) * 2,
low: 10 + (step % 20) * 2,
close: 11 + (step % 20) * 2,
volume: 1000,
}))
),
});
const config: ReplayConfig = {
matching: {
risk: {
ledger: {
version: 1,
sessionId: 'f07-fixture',
accountId: 'research-only',
baseCurrency: 'USD',
reserveOwnerId: 'reserve',
ownerIds: owners,
initialCapital: '10000',
riskSession: {
calendarId: 'account',
calendarRevision: '1',
sessionId: 'risk',
startsAt: start,
},
},
feeRate: '0.01',
maxOrderQuantity: '1000000',
maxPositionQuantity: '1000000',
maxSymbolExposure: '1000000',
maxGrossExposure: '1000000',
maxDailyLoss: '1000000',
maxDrawdownAmount: '1000000',
maxMarkAgeMs: day * 2,
},
owners: owners.map(ownerId => ({ ownerId, mode: 'Target' })),
series: instruments.map(instrumentId => ({
instrumentId,
seriesId: `${instrumentId}:1m`,
mode: 'Open',
})),
halfSpreadRate: '0',
slippageRate: '0',
latencyMs: 0,
},
participation_rate: '1',
cadence: owners.map(owner_id => ({ owner_id, series_ids: instruments.map(id => `${id}:1m`) })),
allow_exploratory: false,
risk_boundaries: [],
};
return { dataset, config, start, minute, instruments };
}

View file

@ -0,0 +1,347 @@
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,
marketDecimal,
NativeReplaySession,
prepareReplayLoad,
runReplayConformance,
} from '../../apps/stock/orchestrator/src/backtest/native-replay';
import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker';
import {
parseReplayResult,
replayConfigSchema,
} from '../../apps/stock/orchestrator/src/contracts/native-replay';
import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
import { datasetInput } from '../fixtures/historical-v2/dataset';
import { nativeReplayFixture } from '../fixtures/native-replay';
import sharedLoad from '../fixtures/native-replay-load.json';
const target = (quantity = '2') => ({
mode: 'target' as const,
targets: [{ instrumentId: 'X0.US', quantity: parseFinancialDecimal(quantity) }],
});
const hold = () => ({ mode: 'target' as const, targets: [] });
function fixture(owners = ['A']) {
const f = nativeReplayFixture(3, 1, owners);
return { ...f, load: prepareReplayLoad(f.dataset, f.config) };
}
function traceRequest() {
const f = fixture();
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: target() },
{ at: f.start + 2 * f.minute, ownerId: 'A', intent: hold() },
],
};
}
describe('canonical native replay session', () => {
test('step_tagged_union: bounded progress, decision and complete; exact next-open terminal economics', () => {
const f = fixture(),
seen = new Set<string>();
expect<unknown>(f.load).toEqual(sharedLoad); // Same input as Rust direct-Replay/transport receipt parity test.
const { result, metrics } = runReplayConformance(
new NativeReplaySession(f.load),
(_owner, c) => (c.barrier.at === f.start + f.minute ? target() : hold()),
{ eventBudget: 1, onProgress: s => seen.add(s.step.type) }
);
expect([...seen].sort()).toEqual(['complete', 'decisionBatch', 'progress']);
expect<string>(result.view.portfolio.cash).toBe('9975.76000000');
expect<string>(result.view.equity).toBe('10005.76000000');
expect<unknown>(result.view.portfolio.fees).toEqual([{ ownerId: 'A', amount: '0.24000000' }]);
expect(result.view.orders).toEqual([]);
expect(metrics.submitCalls).toBe(2);
expect(metrics.contextBytes).toBeGreaterThan(0);
expect<unknown>(result.manifest).toEqual(f.dataset.manifest);
expect(result.modelLimitations.some(s => s.includes('intermediate equity'))).toBe(true);
});
test('immutable_barrier_revision and reverse_callback_order: same shared frozen view, deterministic priority', () => {
const run = (reverseCallbacks: boolean) => {
const f = fixture(['B', 'A']),
views = new Map<number, object>();
return runReplayConformance(
new NativeReplaySession(f.load),
(_owner, c, observations) => {
expect(c.barrier.revision).toBe(c.view.admissionRevision);
expect(Object.isFrozen(c.view)).toBe(true);
expect(Object.isFrozen(observations)).toBe(true);
expect(observations.every(b => b.available_at <= c.barrier.at)).toBe(true);
const previous = views.get(c.barrier.at);
if (previous) {
expect(previous).toBe(c.view);
} else {
views.set(c.barrier.at, c.view);
}
return c.barrier.at === f.start + f.minute ? target('1') : hold();
},
{ eventBudget: 1, reverseCallbacks }
).result;
};
expect(run(true)).toEqual(run(false));
});
test('decision_exception_aborts_barrier: no partial submit and disposed attempt cannot finalize', () => {
const f = fixture(['A', 'B']),
session = new NativeReplaySession(f.load);
let submissions = 0;
const submit = session.submit.bind(session);
session.submit = (...args) => {
submissions++;
return submit(...args);
};
expect(() =>
runReplayConformance(session, owner => {
if (owner === 'B') {
throw new Error('fixture failure');
}
return target();
})
).toThrow('fixture failure');
expect(submissions).toBe(0);
expect(() => session.finalize()).toThrow('disposed');
});
test('rejected_intent_is_committed_outcome: risk rejection advances barrier without financial mutation', () => {
const f = fixture();
f.load.config.matching.risk.maxOrderQuantity = parseFinancialDecimal('1');
const { result } = runReplayConformance(new NativeReplaySession(f.load), () => target());
expect<string>(result.view.portfolio.cash).toBe('10000.00000000');
expect(
result.receipts.filter(r => JSON.stringify(r).includes('Rejected')).length
).toBeGreaterThan(0);
expect(
result.receipts.filter(r => JSON.stringify(r).includes('"decisionId"')).length
).toBeGreaterThan(0);
});
test('strict native identity/version/precision/disposal and pending retry validation', () => {
const f = fixture();
for (const mutate of [
(v: any) => (v.identity.version = 2),
(v: any) => (v.identity.datasetHash = '0'.repeat(64)),
(v: any) => (v.prepared.bars[0].future = true),
(v: any) => (v.prepared.bars[0].open = '1.000000001'),
(v: any) => (v.config.matching.risk.ledger.sessionId = 'wrong'),
]) {
const bad = structuredClone(f.load);
mutate(bad);
expect(() => new FinancialReplaySession(JSON.stringify(bad))).toThrow();
}
const native = new FinancialReplaySession(JSON.stringify(f.load)),
request = { identity: f.load.identity, eventBudget: 100 };
expect(() => native.finalize(JSON.stringify(f.load.identity))).toThrow('complete');
expect(() => native.advance(JSON.stringify({ ...request, eventBudget: 0 }))).toThrow(
'positive'
);
expect(() =>
native.advance(
JSON.stringify({ ...request, identity: { ...request.identity, sessionId: 'wrong' } })
)
).toThrow('identity');
const first = JSON.parse(native.advance(JSON.stringify(request))),
retry = JSON.parse(native.advance(JSON.stringify(request)));
expect(first.step).toEqual(retry.step);
expect(first.observations).toHaveLength(1);
expect(retry.observations).toEqual([]);
expect(() =>
native.submit(
JSON.stringify({
identity: f.load.identity,
barrierId: first.step.barrier.barrier_id,
decisions: [],
})
)
).toThrow('due owners');
expect(JSON.parse(native.advance(JSON.stringify(request))).step).toEqual(first.step);
native.dispose();
native.dispose();
expect(() => native.advance(JSON.stringify(request))).toThrow('disposed');
expect(() => native.finalize(JSON.stringify(f.load.identity))).toThrow('disposed');
expect(() =>
native.submit(
JSON.stringify({ identity: f.load.identity, barrierId: 'barrier', decisions: [] })
)
).toThrow('disposed');
});
test('failed_step_is_terminal_and_cannot_finalize: native numeric failure never yields successful result', () => {
const f = fixture(),
maximum = '792281625142643375935.43950335';
f.load.prepared.bars[0]!.high = maximum;
f.load.prepared.bars[0]!.close = maximum;
const native = new FinancialReplaySession(JSON.stringify(f.load)),
request = { identity: f.load.identity, eventBudget: 100 };
const first = JSON.parse(native.advance(JSON.stringify(request)));
const outcome = JSON.parse(
native.submit(
JSON.stringify({
identity: f.load.identity,
barrierId: first.step.barrier.barrier_id,
decisions: [
{
version: 1,
sessionId: f.load.identity.sessionId,
barrierId: first.step.barrier.barrier_id,
revision: first.step.barrier.revision,
decision: { ownerId: 'A', decisionId: 'overflow', sequence: 0 },
intent: target(),
},
],
})
)
);
expect(outcome.outcome.status).toHaveProperty('Failed');
expect(JSON.parse(native.advance(JSON.stringify(request))).step.type).toBe('failed');
expect(() => native.finalize(JSON.stringify(f.load.identity))).toThrow('complete');
native.dispose();
});
test('verified frozen loader preserves exact provenance and rejects forged datasets/precision/execution mapping', () => {
const f = fixture();
expect(f.load.prepared.bars[0]?.open).toBe('10.00000000');
expect(f.load.prepared.series[0]?.sessions[0]?.opensAt).toBe(f.start);
for (const mutate of [
(v: any) => v.bars[0].close++,
(v: any) => (v.manifest.hash = '0'.repeat(64)),
(v: any) => (v.manifest.limitations = []),
]) {
const bad = structuredClone(f.dataset);
mutate(bad);
expect(() => prepareReplayLoad(bad, f.config)).toThrow();
}
const bad = structuredClone(f.config);
bad.matching.series[0]!.seriesId = 'wrong';
expect(() => prepareReplayLoad(f.dataset, bad)).toThrow('Execution series');
expect(marketDecimal(1e-8)).toBe('0.00000001');
expect(marketDecimal(1e20)).toBe('100000000000000000000.00000000');
expect(() => marketDecimal(1e-9)).toThrow('8 fractional');
expect(() => marketDecimal(NaN)).toThrow('Non-finite');
});
test('worker trace equals local callback trace; real cancellation cannot publish successful results', async () => {
const request = traceRequest(),
expected = executeReplayTrace(request).result,
worker = new NativeBacktestWorker();
const raw = await worker.execute(request, new AbortController().signal, () => {});
expect(parseReplayResult(raw, expected.identity)).toEqual(expected);
const cancel = new AbortController();
await expect(
worker.execute(request, cancel.signal, () => cancel.abort(new Error('cancel fixture')))
).rejects.toThrow('cancel fixture');
expect(
JSON.parse(await worker.execute(request, new AbortController().signal, () => {})).status
).toBe('complete');
});
test('worker captures expected policy/identity before caller mutation; malformed and stale successes reject', async () => {
const request = structuredClone(traceRequest()),
worker = new NativeBacktestWorker();
const raw = await worker.execute(request, new AbortController().signal, () => {
request.config.matching.risk.ledger.sessionId = 'mutated';
request.config.matching.risk.feeRate = parseFinancialDecimal('0.5');
(request.dataset.manifest as { hash: string }).hash = '0'.repeat(64);
});
expect(JSON.parse(raw).identity.sessionId).toBe('f07-fixture');
const fixtureWorker = new NativeBacktestWorker(
new URL('../fixtures/native-replay-worker.ts', import.meta.url)
);
for (const mode of [
'wrong-version',
'wrong-account',
'wrong-policy',
'wrong-session',
'wrong-dataset',
'crash',
]) {
const request = traceRequest();
request.config.matching.risk.ledger.accountId = mode;
await expect(
fixtureWorker.execute(request, new AbortController().signal, () => {})
).rejects.toThrow();
}
const block = traceRequest();
block.config.matching.risk.ledger.accountId = 'result-then-block';
const cancel = new AbortController();
let observedResult = false;
await expect(
fixtureWorker.execute(block, cancel.signal, () => {
// Test-only observation of the already-created child. Registered after
// the supervisor listener, so abort happens after it stores the result.
const child = (fixtureWorker as unknown as { active: ChildProcess }).active;
child.on('message', (message: any) => {
if (message.type === 'result') {
observedResult = true;
cancel.abort(new Error('pending success cancelled'));
}
});
})
).rejects.toThrow('pending success cancelled');
expect(observedResult).toBe(true);
});
test('future suffix mutation cannot change published decision view, observations or intents', () => {
const first = fixture(),
second = fixture();
second.load.prepared.bars[2]!.high = '999.00000000';
second.load.prepared.bars[2]!.close = '999.00000000';
const early = (load: typeof first.load) => {
const session = new NativeReplaySession(load),
observations: any[] = [];
try {
for (;;) {
const step = session.advance(1);
expect(JSON.stringify(step)).not.toMatch(/"(prepared|binding|checkpoint|manifest)"/);
observations.push(...step.observations);
if (step.step.type === 'decisionBatch') {
return {
context: step.step,
observations,
intent: observations[0]?.close === '11.00000000' ? target() : hold(),
};
}
}
} finally {
session.dispose();
}
};
expect(early(second.load)).toEqual(early(first.load));
});
test('D01 eligibility, exact calendars, actual market precision and source sequences survive adaptation', () => {
const input = structuredClone(datasetInput()) as any;
const config = fixture().config;
config.matching.series = [{ instrumentId: 'A.US', seriesId: 'A.US:daily:raw', mode: 'Open' }];
config.cadence = [{ owner_id: 'A', series_ids: ['A.US:daily:raw'] }];
config.matching.risk.ledger.riskSession.startsAt = input.metadata.bounds.warmupStart;
const dataset = createDatasetV2(input),
load = prepareReplayLoad(dataset, config);
expect(load.prepared.series[0]!.sessions.map(s => [s.opensAt, s.closesAt])).toEqual(
input.metadata.calendars[0].sessions.map((s: any) => [s.open, s.close])
);
input.bars[0].sourceSequence = 7;
input.bars[1].sourceSequence = 3;
input.bars[2].sourceSequence = 9;
const sequenceLoad = prepareReplayLoad(createDatasetV2(input), config);
expect(sequenceLoad.prepared.bars.map(b => b.source_sequence)).toEqual([7, 3, 9]);
input.metadata.universe.selection = 'unknown';
const exploratory = createDatasetV2(input);
expect(() => new NativeReplaySession(prepareReplayLoad(exploratory, config))).toThrow(
'eligibility'
);
const allowed = { ...config, allow_exploratory: true };
new NativeReplaySession(prepareReplayLoad(exploratory, allowed)).dispose();
const forged = structuredClone(exploratory) as any;
forged.manifest.eligibility = 'eligible';
const { hash: _hash, ...manifest } = forged.manifest;
forged.manifest.hash = createHash('sha256')
.update(JSON.stringify({ manifest, bars: forged.bars }))
.digest('hex');
expect(() => prepareReplayLoad(forged, allowed)).toThrow('derived policy');
input.metadata.series[0].adjustment = 'provider-adjusted';
const ineligible = createDatasetV2(input);
expect(() => new NativeReplaySession(prepareReplayLoad(ineligible, allowed))).toThrow();
input.metadata.series[0].adjustment = 'raw';
input.bars[0].open = 100.000000001;
expect(() => prepareReplayLoad(createDatasetV2(input), allowed)).toThrow('8 fractional');
});
});