diff --git a/apps/stock/engine/src/api/replay.rs b/apps/stock/engine/src/api/replay.rs index 2392a061..1af86ab5 100644 --- a/apps/stock/engine/src/api/replay.rs +++ b/apps/stock/engine/src/api/replay.rs @@ -1,13 +1,7 @@ //! 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::*, - reporting::ReportingFacts, - result::{project, FinancialProjection}, -}; +use crate::financial::{contract::*, matching::OrderStatus, replay::*}; use napi::{Error, Result}; #[cfg(not(test))] use napi_derive::napi; @@ -43,33 +37,6 @@ struct Submit { decisions: Vec, } -/// Borrow retained provenance and flattened financial facts instead of building -/// a serde_json::Value tree for the entire nested journal. -#[derive(Serialize)] -#[serde(rename_all = "camelCase")] -struct ProjectionResult<'a> { - format: &'static str, - projection_version: Version, - financial_version: Version, - identity: &'a Identity, - status: &'static str, - manifest: &'a Value, - policy: &'a ReplayConfig, - view: Value, - limitations: &'a [String], - model_limitations: &'static [&'static str], - projection: FinancialProjection<'a>, -} - -#[derive(Serialize)] -#[serde(rename_all = "camelCase")] -struct ReportResult<'a> { - #[serde(flatten)] - financial: ProjectionResult<'a>, - reporting_version: Version, - reporting: &'a ReportingFacts, -} - fn error(error: impl std::fmt::Display) -> Error { Error::from_reason(error.to_string()) } @@ -191,54 +158,6 @@ impl ReplayHost { pub fn dispose(&mut self) { self.replay = None; } - - pub fn project(&self, input: String) -> Result { - 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 project successfully")); - } - serde_json::to_string(&ProjectionResult { - format: "projection", - projection_version: Version, - financial_version: Version, - identity: &self.identity, - status: "complete", - manifest: &self.manifest, - policy: &self.config, - view: view(replay)?, - limitations: replay.limitations(), - model_limitations: replay.model_limitations(), - projection: project(replay.financial().ledger()).map_err(error)?, - }) - .map_err(error) - } - - pub fn report(&self, input: String) -> Result { - let identity: Identity = parse(&input)?; - self.check(&identity)?; - let replay = self.replay.as_ref().unwrap(); - let reporting = replay.reporting().map_err(error)?; - serde_json::to_string(&ReportResult { - financial: ProjectionResult { - format: "report", - projection_version: Version, - financial_version: Version, - identity: &self.identity, - status: "complete", - manifest: &self.manifest, - policy: &self.config, - view: view(replay)?, - limitations: replay.limitations(), - model_limitations: replay.model_limitations(), - projection: project(replay.financial().ledger()).map_err(error)?, - }, - reporting_version: Version, - reporting, - }) - .map_err(error) - } } // NAPI's impl macro requires literal method annotations. Keep this tiny @@ -267,14 +186,6 @@ impl FinancialReplaySession { self.0.finalize(input) } #[napi] - pub fn project(&self, input: String) -> Result { - self.0.project(input) - } - #[napi] - pub fn report(&self, input: String) -> Result { - self.0.report(input) - } - #[napi] pub fn dispose(&mut self) { self.0.dispose(); } @@ -363,37 +274,7 @@ mod tests { ); assert_eq!(final_result["view"]["portfolio"]["cash"], "9975.76000000"); assert_eq!(final_result["view"]["equity"], "10005.76000000"); - let before = native.replay.as_ref().unwrap().checkpoint(); - let compact = native.project(identity.to_string()).unwrap(); - assert_eq!(native.project(identity.to_string()).unwrap(), compact); - assert_eq!(native.replay.as_ref().unwrap().checkpoint(), before); - assert_eq!( - serde_json::from_str::(&native.finalize(identity.to_string()).unwrap()).unwrap(), - final_result - ); - let projected: Value = serde_json::from_str(&compact).unwrap(); - let report = native.report(identity.to_string()).unwrap(); - assert_eq!(native.report(identity.to_string()).unwrap(), report); - assert_eq!(native.project(identity.to_string()).unwrap(), compact); - assert_eq!(native.replay.as_ref().unwrap().checkpoint(), before); - let reported: Value = serde_json::from_str(&report).unwrap(); - assert_eq!(reported["projection"], projected["projection"]); - assert_eq!(reported["reporting"]["occupiedMs"], "120000"); - assert_eq!(projected["view"], final_result["view"]); - assert!(projected.get("receipts").is_none()); - let load: Load = parse(fixture).unwrap(); - let restored = Replay::restore(load.prepared, load.config, &before).unwrap(); - assert_eq!( - projected["projection"], - serde_json::to_value(project(restored.financial().ledger()).unwrap()).unwrap() - ); - assert_eq!( - reported["reporting"], - serde_json::to_value(restored.reporting().unwrap()).unwrap() - ); native.dispose(); assert!(native.finalize(identity.to_string()).is_err()); - assert!(native.project(identity.to_string()).is_err()); - assert!(native.report(identity.to_string()).is_err()); } } diff --git a/apps/stock/engine/src/financial/ledger.rs b/apps/stock/engine/src/financial/ledger.rs index eaee5088..0656fa86 100644 --- a/apps/stock/engine/src/financial/ledger.rs +++ b/apps/stock/engine/src/financial/ledger.rs @@ -67,8 +67,7 @@ pub struct LedgerCheckpoint { pub receipts: Vec, } -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] -#[serde(rename_all = "camelCase")] +#[derive(Debug, Clone, PartialEq, Eq)] pub struct OwnerValuation { pub owner_id: Id, pub initial_capital: Posting, @@ -82,8 +81,7 @@ pub struct OwnerValuation { pub equity_contribution: Posting, } -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] -#[serde(rename_all = "camelCase")] +#[derive(Debug, Clone, PartialEq, Eq)] pub struct LedgerValuation { pub cash: Posting, pub marked_holdings: Posting, @@ -695,12 +693,6 @@ impl Ledger { }) } - /// Read-only accepted financial history, including replay-labelled aliases. - /// Reporting must skip aliases; this does not copy a restorable checkpoint. - pub fn receipts(&self) -> &[LedgerReceipt] { - &self.receipts - } - pub fn checkpoint(&self) -> LedgerCheckpoint { LedgerCheckpoint { version: Version, diff --git a/apps/stock/engine/src/financial/mod.rs b/apps/stock/engine/src/financial/mod.rs index 01020b77..03e13e81 100644 --- a/apps/stock/engine/src/financial/mod.rs +++ b/apps/stock/engine/src/financial/mod.rs @@ -6,8 +6,6 @@ pub mod contract; pub mod ledger; pub mod matching; pub mod replay; -pub mod reporting; -pub mod result; pub mod risk; pub mod scalar; @@ -26,12 +24,6 @@ mod matching_tests; #[cfg(test)] mod replay_tests; -#[cfg(test)] -mod result_tests; - -#[cfg(test)] -mod reporting_tests; - // Exercise the pure host adapter without linking every legacy NAPI export. #[cfg(test)] #[path = "../api/replay.rs"] diff --git a/apps/stock/engine/src/financial/replay.rs b/apps/stock/engine/src/financial/replay.rs index 34dca015..b0c199a4 100644 --- a/apps/stock/engine/src/financial/replay.rs +++ b/apps/stock/engine/src/financial/replay.rs @@ -13,7 +13,6 @@ use super::{ contract::*, matching::*, - reporting::{Reporting, ReportingFacts}, scalar::{Posting, ScalarError}, }; use serde::{Deserialize, Serialize}; @@ -215,7 +214,6 @@ pub struct Replay { status: ReplayStatus, submissions: Vec, matching: MatchingAccount, - reporting: Reporting, } impl Replay { @@ -232,12 +230,6 @@ impl Replay { .iter() .map(|s| s.series_id.clone()) .collect(); - let reporting = Reporting::new( - &config.matching.risk.ledger.risk_session, - &config.risk_boundaries, - &input.bounds, - matching.ledger().cash(), - ); Ok(Self { input, config, @@ -251,7 +243,6 @@ impl Replay { status: ReplayStatus::Running, submissions: Vec::new(), matching, - reporting, }) } fn canonicalize(input: &mut PreparedReplay, config: &mut ReplayConfig) { @@ -661,12 +652,6 @@ impl Replay { pub fn model_limitations(&self) -> &'static [&'static str] { MODEL_LIMITATIONS } - pub fn reporting(&self) -> Result<&ReportingFacts, &str> { - if self.status != ReplayStatus::Complete { - return Err("only a complete replay can report successfully"); - } - self.reporting.facts() - } fn command( &mut self, @@ -674,13 +659,11 @@ impl Replay { key: EventKey, body: MatchingCommandBody, ) -> Result<(), ReplayError> { - let at = key.at; let out = self.matching.apply(&MatchingCommand { command_id: id(("replay", index)), key, body, })?; - self.reporting.committed(at, &out, self.matching.ledger()); if let AttemptStatus::Failed { diagnostic } = out.status { self.status = ReplayStatus::Failed { diagnostic }; } @@ -783,7 +766,6 @@ impl Replay { self.command(index, key, MatchingCommandBody::Finish)?; if self.status == ReplayStatus::Running { self.status = ReplayStatus::Complete; - self.reporting.finish(self.matching.ledger()); } } } @@ -800,8 +782,6 @@ impl Replay { while self.status == ReplayStatus::Running && processed < budget { let index = self.next_event; let event = self.events[index].clone(); - let at = event.key.at; - let observation = event.key.phase == EventPhase::Observation; self.next_event += 1; processed += 1; if let Err(error) = self.process(index, event) { @@ -809,15 +789,6 @@ impl Replay { diagnostic: error.to_string(), }; } - if observation - && self.status == ReplayStatus::Running - && self.events.get(self.next_event).is_none_or(|next| { - next.key.at != at || next.key.phase != EventPhase::Observation - }) - { - self.reporting - .after_observations(at, self.matching.ledger()); - } if let Some(barrier) = &self.pending { return Ok(ReplayStep::Decision(barrier.clone())); } diff --git a/apps/stock/engine/src/financial/replay_tests.rs b/apps/stock/engine/src/financial/replay_tests.rs index e7b340c9..4fbf7cc3 100644 --- a/apps/stock/engine/src/financial/replay_tests.rs +++ b/apps/stock/engine/src/financial/replay_tests.rs @@ -570,158 +570,6 @@ fn restore_before_and_after_every_decision_and_at_complete() { target(&mut uninterrupted, &b, "2"); } assert_eq!(r.checkpoint(), uninterrupted.checkpoint()); - assert_eq!(r.reporting().unwrap(), uninterrupted.reporting().unwrap()); -} - -fn reporting_boundary(name: &str, at: i64) -> RiskSessionIdentity { - RiskSessionIdentity { - calendar_id: id("account"), - calendar_revision: id("1"), - session_id: id(name), - starts_at: t(at), - } -} - -#[test] -fn two_session_marks_follow_observations_without_changing_earlier_risk_reset() { - let (mut input, mut config) = fixture(); - input.bounds.trade_start = t(0); - config.risk_boundaries = vec![ - reporting_boundary("risk2", 20), - reporting_boundary("risk3", 30), - ]; - let mut r = Replay::new(input, config).unwrap(); - assert!(r.reporting().is_err()); - let b = next(&mut r).unwrap(); - target(&mut r, &b, "2"); - let b = next(&mut r).unwrap(); - assert_eq!(b.at, t(20)); - // Existing reset runs before the completed observation's13 mark. - assert_eq!( - Posting::from(r.financial().risk().state().daily_baseline), - p("9999.76") - ); - no_change(&mut r, &b); - complete(&mut r); - let facts = r.reporting().unwrap(); - assert_eq!(facts.initial_equity, p("10000")); - assert_eq!(facts.sessions.len(), 2); - assert_eq!(facts.sessions[0].session.session_id, id("risk1")); - assert_eq!(facts.sessions[0].period_start, t(0)); - assert_eq!(facts.sessions[0].period_end, t(20)); - assert_eq!(facts.sessions[0].equity, p("10001.76")); - assert_eq!(facts.sessions[1].equity, p("10005.76")); - assert!(!facts - .sessions - .iter() - .any(|s| s.partial_start || s.partial_end)); - assert_eq!(facts.occupied_ms, "20"); - assert_eq!(facts.elapsed_ms, "30"); -} - -#[test] -fn reporting_clips_warmup_initial_and_final_periods_and_deduplicates_exact_end() { - for exact_start in [false, true] { - for exact_end in [false, true] { - let (input, mut config) = fixture(); - config.risk_boundaries = vec![ - reporting_boundary("warmup", 5), - reporting_boundary("risk2", 20), - ]; - if exact_start { - config.risk_boundaries.push(reporting_boundary("start", 10)); - } - if exact_end { - config.risk_boundaries.push(reporting_boundary("end", 30)); - } - let mut r = Replay::new(input, config).unwrap(); - complete(&mut r); - let facts = r.reporting().unwrap(); - assert_eq!(facts.sessions.len(), 2); - assert_eq!( - facts.sessions[0].session.session_id, - id(if exact_start { "start" } else { "warmup" }) - ); - assert_eq!(facts.sessions[0].period_start, t(10)); - assert_eq!(facts.sessions[0].partial_start, !exact_start); - assert!(!facts.sessions[0].partial_end); - assert_eq!(facts.sessions[1].partial_end, !exact_end); - assert_eq!(facts.sessions[1].period_end, t(30)); - assert!(facts.sessions.iter().all(|s| s.equity == p("10000"))); - assert_eq!(facts.occupied_ms, "0"); - assert!(facts.occupied_intervals.is_empty()); - } - } -} - -#[test] -fn reporting_boundary_without_decision_and_terminal_stale_mark_use_only_available_facts() { - let (mut input, mut config) = fixture(); - config.risk_boundaries = vec![reporting_boundary("risk2", 15)]; - input.bars[2].available_at = t(31); // Final close15 is not available by end30. - let mut r = Replay::new(input, config).unwrap(); - let b = next(&mut r).unwrap(); - target(&mut r, &b, "2"); - complete(&mut r); - let facts = r.reporting().unwrap(); - assert_eq!(facts.sessions[0].period_end, t(15)); - assert_eq!(facts.sessions[0].equity, p("9999.76")); - // Last available authoritative mark is the open14, not the future close15. - assert_eq!(facts.sessions[1].equity, p("10003.76")); - assert_eq!( - facts.sessions[1].equity, - r.financial().ledger().equity().unwrap() - ); - assert_eq!(r.observations().count(), 2); -} - -#[test] -fn reporting_restore_every_event_including_partial_observation_groups() { - let (mut input, mut config) = fixture(); - input.series.push(series("Y-bars", "Y")); - input - .bars - .extend(input.bars.clone().into_iter().map(|mut bar| { - bar.series_id = id("Y-bars"); - bar.instrument_id = id("Y"); - bar - })); - config.matching.series.push(ExecutionSeries { - instrument_id: id("Y"), - series_id: id("Y-bars"), - mode: ExecutionMode::Open, - }); - config.risk_boundaries = vec![ - reporting_boundary("risk2", 20), - reporting_boundary("risk3", 30), - ]; - let mut uninterrupted = Replay::new(input.clone(), config.clone()).unwrap(); - while let Some(b) = next(&mut uninterrupted) { - target(&mut uninterrupted, &b, "2"); - } - let mut resumed = Replay::new(input.clone(), config.clone()).unwrap(); - loop { - let step = resumed.advance(1).unwrap(); - let cp = resumed.checkpoint(); - resumed = Replay::restore(input.clone(), config.clone(), &cp).unwrap(); - assert_eq!(resumed.checkpoint(), cp); - match step { - ReplayStep::Decision(b) => { - target(&mut resumed, &b, "2"); - resumed = - Replay::restore(input.clone(), config.clone(), &resumed.checkpoint()).unwrap(); - } - ReplayStep::Complete => break, - ReplayStep::Progress { .. } => {} - other => panic!("unexpected {other:?}"), - } - } - assert_eq!(uninterrupted.checkpoint(), resumed.checkpoint()); - assert_eq!( - uninterrupted.reporting().unwrap(), - resumed.reporting().unwrap() - ); - assert_eq!(resumed.reporting().unwrap().sessions.len(), 2); } #[test] fn altered_input_config_and_checkpoint_rejected() { @@ -960,9 +808,6 @@ fn sequential_equal_time_marks_can_latch_risk_before_synchronized_barrier() { config.matching.risk.fee_rate = nn("0"); config.matching.risk.max_daily_loss = pos("10"); config.matching.risk.max_drawdown_amount = pos("10"); - // A reporting sample uses the final observation-group equity without - // changing the existing sequential risk latch. - config.risk_boundaries.push(reporting_boundary("risk2", 20)); let mut permuted = input.clone(); permuted.bars.reverse(); let mut checkpoints = vec![]; @@ -1002,11 +847,6 @@ fn sequential_equal_time_marks_can_latch_risk_before_synchronized_barrier() { assert!(r.financial().risk().state().daily_halted); assert!(r.financial().risk().state().drawdown_halted); checkpoints.push(r.checkpoint()); - no_change(&mut r, &b); - complete(&mut r); - assert_eq!(r.reporting().unwrap().sessions[0].equity, p("10000")); - assert!(r.financial().risk().state().daily_halted); - assert!(r.financial().risk().state().drawdown_halted); } assert_eq!(checkpoints[0], checkpoints[1]); assert!(MODEL_LIMITATIONS diff --git a/apps/stock/engine/src/financial/reporting.rs b/apps/stock/engine/src/financial/reporting.rs deleted file mode 100644 index 565e3369..00000000 --- a/apps/stock/engine/src/financial/reporting.rs +++ /dev/null @@ -1,238 +0,0 @@ -//! Reporting-only facts sampled during the existing replay. This state cannot -//! submit financial commands and is rebuilt by the normal checkpoint restore. -use super::{ - contract::*, - ledger::Ledger, - matching::{MatchingEffect, MatchingOutcome}, - replay::ReplayBounds, - scalar::Posting, -}; -use serde::Serialize; - -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct SessionEquity { - pub session: RiskSessionIdentity, - pub period_start: EventTime, - pub period_end: EventTime, - pub partial_start: bool, - pub partial_end: bool, - pub equity: Posting, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct OccupiedInterval { - pub start: EventTime, - pub end: EventTime, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct ReportingFacts { - pub calendar_id: Id, - pub calendar_revision: Id, - pub trade_start: EventTime, - pub trade_end: EventTime, - pub initial_equity: Posting, - pub sampling: &'static str, - pub exposure_basis: &'static str, - pub sessions: Vec, - pub occupied_intervals: Vec, - pub occupied_ms: String, - pub elapsed_ms: String, -} - -#[derive(Debug)] -pub(super) struct Reporting { - facts: ReportingFacts, - session: RiskSessionIdentity, - period_start: EventTime, - boundaries: Vec, - next_boundary: usize, - occupied_since: Option, - failure: Option, - complete: bool, -} - -impl Reporting { - pub fn new( - initial: &RiskSessionIdentity, - boundaries: &[RiskSessionIdentity], - bounds: &ReplayBounds, - initial_equity: Posting, - ) -> Self { - // Replay has already validated/canonicalized this account calendar. - let session = boundaries - .iter() - .rev() - .find(|b| b.starts_at.get() <= bounds.trade_start.get()) - .unwrap_or(initial) - .clone(); - Self { - facts: ReportingFacts { - calendar_id: initial.calendar_id.clone(), - calendar_revision: initial.calendar_revision.clone(), - trade_start: bounds.trade_start, - trade_end: bounds.trade_end, - initial_equity, - sampling: "account-boundary-after-observations-v1", - exposure_basis: "elapsed-calendar-time", - sessions: Vec::new(), - occupied_intervals: Vec::new(), - occupied_ms: "0".into(), - // Both endpoints are safe i64 timestamps; their difference may - // exceed JS's safe integer domain but cannot overflow i64. - elapsed_ms: (bounds.trade_end.get() - bounds.trade_start.get()).to_string(), - }, - session, - period_start: bounds.trade_start, - boundaries: boundaries - .iter() - .filter(|b| b.starts_at.get() > bounds.trade_start.get()) - .cloned() - .collect(), - next_boundary: 0, - occupied_since: None, - failure: None, - complete: false, - } - } - - /// Called only after the complete equal-time Observation group. No extra - /// event enters Replay.events, and the earlier risk reset is untouched. - pub fn after_observations(&mut self, at: EventTime, ledger: &Ledger) { - if self.failure.is_some() || self.complete { - return; - } - let Some(boundary) = self.boundaries.get(self.next_boundary) else { - return; - }; - if boundary.starts_at != at { - return; - } - let next_session = boundary.clone(); - if self.sample(at, false, ledger) { - self.session = next_session; - self.period_start = at; - self.next_boundary += 1; - } - } - - fn sample(&mut self, at: EventTime, partial_end: bool, ledger: &Ledger) -> bool { - match ledger.equity() { - Ok(equity) => { - self.facts.sessions.push(SessionEquity { - session: self.session.clone(), - period_start: self.period_start, - period_end: at, - partial_start: self.period_start != self.session.starts_at, - partial_end, - equity, - }); - true - } - Err(error) => { - self.failure = Some(format!("reporting equity unavailable: {error}")); - false - } - } - } - - /// Only a committed fill can change occupancy. Query authoritative current - /// holdings once per matching outcome; never reconstruct quantities/deltas. - pub fn committed(&mut self, at: EventTime, outcome: &MatchingOutcome, ledger: &Ledger) { - if self.failure.is_some() || self.complete || outcome.replayed { - return; - } - let filled = outcome.effects.iter().any(|effect| match effect { - MatchingEffect::Risk { outcome, .. } if !outcome.replayed => outcome - .financial - .as_ref() - .filter(|financial| !financial.replayed) - .is_some_and(|financial| { - financial - .effects - .effects - .iter() - .any(|effect| matches!(effect, FinancialEffect::FillApplied { .. })) - }), - _ => false, - }); - if !filled { - return; - } - let occupied = ledger.owned_quantities().next().is_some(); - match (self.occupied_since, occupied) { - (None, true) => self.occupied_since = Some(at), - (Some(start), false) => { - self.interval(start, at); - self.occupied_since = None; - } - _ => {} - } - } - - fn interval(&mut self, start: EventTime, end: EventTime) { - let start = if start.get() < self.facts.trade_start.get() { - self.facts.trade_start - } else { - start - }; - let end = if end.get() > self.facts.trade_end.get() { - self.facts.trade_end - } else { - end - }; - if start.get() >= end.get() { - return; - } - if let Some(last) = self.facts.occupied_intervals.last_mut() { - if last.end.get() >= start.get() { - if end.get() > last.end.get() { - last.end = end; - } - return; - } - } - self.facts - .occupied_intervals - .push(OccupiedInterval { start, end }); - } - - pub fn finish(&mut self, ledger: &Ledger) { - if self.failure.is_some() || self.complete { - return; - } - if self.next_boundary != self.boundaries.len() { - self.failure = Some("reporting boundary was not sampled".into()); - return; - } - if self.period_start.get() < self.facts.trade_end.get() - && !self.sample(self.facts.trade_end, true, ledger) - { - return; - } - if let Some(start) = self.occupied_since.take() { - self.interval(start, self.facts.trade_end); - } - let occupied: i64 = self - .facts - .occupied_intervals - .iter() - .map(|interval| interval.end.get() - interval.start.get()) - .sum(); - self.facts.occupied_ms = occupied.to_string(); - self.complete = true; - } - - pub fn facts(&self) -> Result<&ReportingFacts, &str> { - if let Some(failure) = &self.failure { - Err(failure) - } else if !self.complete { - Err("reporting is incomplete") - } else { - Ok(&self.facts) - } - } -} diff --git a/apps/stock/engine/src/financial/reporting_tests.rs b/apps/stock/engine/src/financial/reporting_tests.rs deleted file mode 100644 index 771a0026..00000000 --- a/apps/stock/engine/src/financial/reporting_tests.rs +++ /dev/null @@ -1,159 +0,0 @@ -use super::{contract::*, ledger::Ledger, matching::*, replay::ReplayBounds, reporting::Reporting}; -use serde_json::{json, Value}; - -fn time(at: i64) -> EventTime { - at.try_into().unwrap() -} -fn ledger() -> Ledger { - Ledger::new( - serde_json::from_value(json!({ - "version":1,"sessionId":"s","accountId":"a","baseCurrency":"USD", - "reserveOwnerId":"reserve","ownerIds":["A","B"],"initialCapital":"10000", - "riskSession":{"calendarId":"c","calendarRevision":"1","sessionId":"d","startsAt":0} - })) - .unwrap(), - ) - .unwrap() -} -fn initial() -> RiskSessionIdentity { - serde_json::from_value( - json!({"calendarId":"c","calendarRevision":"1","sessionId":"d","startsAt":0}), - ) - .unwrap() -} -fn reporting(ledger: &Ledger, start: i64, end: i64) -> Reporting { - let mut initial = initial(); - initial.starts_at = time(start.min(0)); - Reporting::new( - &initial, - &[], - &ReplayBounds { - warmup_start: time(start), - trade_start: time(start), - trade_end: time(end), - }, - ledger.cash(), - ) -} -fn apply(ledger: &mut Ledger, at: i64, name: &str, body: Value) -> MatchingOutcome { - let command: EngineFinancialCommand = serde_json::from_value(json!({ - "version":1,"sessionId":"s","accountId":"a","commandId":name,"eventTime":at,"body":body, - })) - .unwrap(); - let financial = ledger.apply(&command).unwrap(); - // A reporting unit fixture wraps an actual ledger receipt, not invented deltas. - serde_json::from_value(json!({"replayed":false,"revision":1,"status":"Running","effects":[{ - "Risk":{"command":{"commandId":name,"eventTime":at,"body":{"kind":"mark","instrumentId":"X","price":"10","observedAt":at}}, - "outcome":{"replayed":false,"revision":1,"disposition":"Accepted","financial":financial, - "remaining":null,"releasedOrder":null,"resetBaseline":null}} - }]})).unwrap() -} -fn fill(ledger: &mut Ledger, at: i64, owner: &str, side: &str) -> MatchingOutcome { - let name = format!("{owner}-{side}-{at}"); - apply( - ledger, - at, - &name, - json!({"kind":"applyFill","decision":{"ownerId":owner,"decisionId":name,"sequence":0}, - "orderId":name,"fillId":name,"instrumentId":"X","side":side,"quantity":"1","price":"10", - "fee":{"feeId":name,"amount":"0"}}), - ) -} - -#[test] -fn overlapping_positions_open_position_exposure_and_same_time_handoff() { - let mut ledger = ledger(); - apply( - &mut ledger, - 0, - "mark", - json!({"kind":"mark","instrumentId":"X","price":"10"}), - ); - let mut report = reporting(&ledger, 0, 50); - for (at, owner, side) in [ - (10, "A", "buy"), - (20, "B", "buy"), - (25, "A", "sell"), - (30, "B", "sell"), - (30, "A", "buy"), - (40, "A", "sell"), - (40, "B", "buy"), - ] { - let outcome = fill(&mut ledger, at, owner, side); - report.committed(time(at), &outcome, &ledger); - } - report.finish(&ledger); - let facts = report.facts().unwrap(); - assert_eq!(facts.occupied_ms, "40"); - assert_eq!(facts.elapsed_ms, "50"); - assert_eq!(facts.occupied_intervals.len(), 1); - assert_eq!(facts.occupied_intervals[0].start, time(10)); - assert_eq!(facts.occupied_intervals[0].end, time(50)); - assert!(ledger.owned_quantities().next().is_some()); -} - -#[test] -fn reporting_skips_each_nested_replayed_alias_and_zero_length_occupancy() { - for level in 0..3 { - let mut ledger = ledger(); - apply( - &mut ledger, - 0, - "mark", - json!({"kind":"mark","instrumentId":"X","price":"10"}), - ); - let mut report = reporting(&ledger, 0, 30); - let outcome = fill(&mut ledger, 10, "A", "buy"); - let mut alias = outcome.clone(); - if level == 0 { - alias.replayed = true; - } - let MatchingEffect::Risk { outcome: risk, .. } = &mut alias.effects[0] else { - panic!() - }; - if level == 1 { - risk.replayed = true; - } - if level == 2 { - risk.financial.as_mut().unwrap().replayed = true; - } - report.committed(time(0), &alias, &ledger); - report.committed(time(10), &outcome, &ledger); - let sell = fill(&mut ledger, 10, "A", "sell"); - report.committed(time(10), &sell, &ledger); - report.finish(&ledger); - assert!(report.facts().unwrap().occupied_intervals.is_empty()); - assert_eq!(report.facts().unwrap().occupied_ms, "0"); - } -} - -#[test] -fn reporting_failure_retains_financial_state_and_cannot_return_success() { - let mut ledger = ledger(); - let mut report = reporting(&ledger, 0, 20); - fill(&mut ledger, 10, "A", "buy"); // No mark: ledger equity is explicitly unavailable. - let checkpoint = ledger.checkpoint(); - report.finish(&ledger); - assert!(report.facts().unwrap_err().contains("equity unavailable")); - assert_eq!(ledger.checkpoint(), checkpoint); - apply( - &mut ledger, - 15, - "mark", - json!({"kind":"mark","instrumentId":"X","price":"10"}), - ); - report.finish(&ledger); // A failed report cannot silently become successful later. - assert!(report.facts().is_err()); -} - -#[test] -fn duration_strings_cover_the_entire_safe_timestamp_domain_without_rounding() { - let ledger = ledger(); - let mut report = reporting(&ledger, -9_007_199_254_740_991, 9_007_199_254_740_990); - assert!(report.facts().is_err()); - report.finish(&ledger); - let facts = report.facts().unwrap(); - assert_eq!(facts.elapsed_ms, "18014398509481981"); - assert_eq!(facts.occupied_ms, "0"); - assert!(!facts.sessions[0].partial_start && facts.sessions[0].partial_end); -} diff --git a/apps/stock/engine/src/financial/result.rs b/apps/stock/engine/src/financial/result.rs deleted file mode 100644 index 3607f1ba..00000000 --- a/apps/stock/engine/src/financial/result.rs +++ /dev/null @@ -1,115 +0,0 @@ -//! Read-only reporting from committed financial facts. No matching, accounting, -//! history replay, checkpoint copies or statistical/round-trip interpretation. -use super::{ - contract::*, - ledger::{Ledger, LedgerError, LedgerValuation}, - scalar::Posting, -}; -use serde::Serialize; - -#[derive(Debug, PartialEq, Eq, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct OwnedFill<'a> { - pub command_id: &'a Id, - pub event_time: EventTime, - pub owner_id: &'a Id, - pub decision: &'a DecisionIdentity, - pub order_id: &'a Id, - pub fill_id: &'a Id, - pub instrument_id: &'a Id, - pub side: Side, - pub quantity: Positive, - pub price: Positive, - pub fee: &'a Fee, - pub cash_delta: Posting, - pub quantity_delta: Posting, - pub released_basis: NonNegative, - pub realized_gross_pnl: Posting, -} - -#[derive(Debug, PartialEq, Eq, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct FinancialProjection<'a> { - pub valuation: LedgerValuation, - pub fills: Vec>, -} - -#[derive(Debug, thiserror::Error)] -pub enum ProjectionError { - #[error(transparent)] - Ledger(#[from] LedgerError), - #[error("committed fill receipt has inconsistent financial effects")] - InconsistentReceipt, -} - -pub fn project(ledger: &Ledger) -> Result, ProjectionError> { - let valuation = ledger.valuation()?; - let mut fills = Vec::new(); - for receipt in ledger.receipts() { - if receipt.outcome.replayed { - continue; - } - let EngineCommandBody::ApplyFill { - decision, - order_id, - fill_id, - instrument_id, - side, - quantity, - price, - fee, - } = &receipt.command.body - else { - continue; - }; - let [FinancialEffect::FillApplied { - owner_id: effect_owner, - order_id: effect_order, - fill_id: effect_fill, - instrument_id: effect_instrument, - price: effect_price, - cash_delta, - quantity_delta, - released_basis, - realized_gross_pnl, - }, FinancialEffect::FeeApplied { - owner_id: fee_owner, - fill_id: fee_fill, - fee_id, - amount, - }] = receipt.outcome.effects.effects.as_slice() - else { - return Err(ProjectionError::InconsistentReceipt); - }; - if effect_owner != &decision.owner_id - || effect_order != order_id - || effect_fill != fill_id - || effect_instrument != instrument_id - || effect_price != price - || fee_owner != effect_owner - || fee_fill != fill_id - || fee_id != &fee.fee_id - || amount != &fee.amount - { - return Err(ProjectionError::InconsistentReceipt); - } - fills.push(OwnedFill { - command_id: &receipt.command.command_id, - event_time: receipt.command.event_time, - owner_id: &decision.owner_id, - decision, - order_id, - fill_id, - instrument_id, - side: *side, - quantity: *quantity, - price: *price, - fee, - cash_delta: *cash_delta, - quantity_delta: *quantity_delta, - released_basis: *released_basis, - realized_gross_pnl: *realized_gross_pnl, - }); - } - Ok(FinancialProjection { valuation, fills }) -} diff --git a/apps/stock/engine/src/financial/result_tests.rs b/apps/stock/engine/src/financial/result_tests.rs deleted file mode 100644 index f7daa77c..00000000 --- a/apps/stock/engine/src/financial/result_tests.rs +++ /dev/null @@ -1,146 +0,0 @@ -use super::{contract::*, ledger::*, result::project}; -use serde_json::{json, Value}; - -fn ledger() -> Ledger { - Ledger::new( - serde_json::from_value(json!({ - "version":1,"sessionId":"s","accountId":"a","baseCurrency":"USD", - "reserveOwnerId":"reserve","ownerIds":["A","B"],"initialCapital":"10000", - "riskSession":{"calendarId":"c","calendarRevision":"1","sessionId":"d","startsAt":0} - })) - .unwrap(), - ) - .unwrap() -} -fn apply(ledger: &mut Ledger, id: &str, at: i64, body: Value) -> EngineFinancialCommand { - let command = serde_json::from_value(json!({"version":1,"sessionId":"s","accountId":"a", - "commandId":id,"eventTime":at,"body":body})) - .unwrap(); - ledger.apply(&command).unwrap(); - command -} -fn fill( - owner: &str, - order: &str, - fill: &str, - side: &str, - quantity: &str, - price: &str, - fee: &str, -) -> Value { - json!({"kind":"applyFill","decision":{"ownerId":owner,"decisionId":order,"sequence":0}, - "orderId":order,"fillId":fill,"instrumentId":"X","side":side,"quantity":quantity, - "price":price,"fee":{"feeId":format!("fee-{fill}"),"amount":fee}}) -} -fn output(ledger: &Ledger) -> Value { - serde_json::to_value(project(ledger).unwrap()).unwrap() -} - -#[test] -fn projection_aliases_once_and_is_read_only_after_restore() { - let mut ledger = ledger(); - apply( - &mut ledger, - "mark", - 0, - json!({"kind":"mark","instrumentId":"X","price":"12"}), - ); - let command = apply( - &mut ledger, - "fill", - 1, - fill("A", "buy", "f1", "buy", "2", "12", "0.24"), - ); - assert!(ledger.apply(&command).unwrap().replayed); - let mut alias = command; - alias.command_id = serde_json::from_value(json!("alias")).unwrap(); - assert!(ledger.apply(&alias).unwrap().replayed); - assert_eq!(ledger.receipts().len(), 3); - let before = ledger.checkpoint(); - let projection = output(&ledger); - assert_eq!(projection["fills"].as_array().unwrap().len(), 1); - assert_eq!(projection["fills"][0]["commandId"], "fill"); - assert_eq!(projection["fills"][0]["fee"]["amount"], "0.24000000"); - // cashDelta is gross; fee remains a distinct canonical posting. - assert_eq!(projection["fills"][0]["cashDelta"], "-24.00000000"); - assert_eq!(projection["valuation"]["cash"], "9975.76000000"); - assert_eq!(projection["valuation"]["equity"], "9999.76000000"); - assert_eq!(output(&ledger), projection); - assert_eq!(ledger.checkpoint(), before); - assert_eq!(output(&Ledger::restore(before).unwrap()), projection); -} - -#[test] -fn partial_fill_projection_retains_final_basis_residual_and_actual_fees() { - let mut ledger = ledger(); - apply( - &mut ledger, - "mark", - 0, - json!({"kind":"mark","instrumentId":"X","price":"3"}), - ); - for (index, body) in [ - fill("A", "buy", "b1", "buy", "1", "1", "0.01"), - fill("A", "buy", "b2", "buy", "2", "2", "0.04"), - fill("A", "sell", "s1", "sell", "1", "3", "0.03"), - fill("A", "sell", "s2", "sell", "1", "3", "0.03"), - fill("A", "sell", "s3", "sell", "1", "3", "0.03"), - ] - .into_iter() - .enumerate() - { - apply( - &mut ledger, - &format!("command-{index}"), - index as i64 + 1, - body, - ); - } - let projection = output(&ledger); - let fills = projection["fills"].as_array().unwrap(); - assert_eq!(fills.len(), 5); - assert_eq!(fills[2]["releasedBasis"], "1.66666667"); - assert_eq!(fills[3]["releasedBasis"], "1.66666667"); - assert_eq!(fills[4]["releasedBasis"], "1.66666666"); - assert_eq!(projection["valuation"]["remainingCost"], "0.00000000"); - assert_eq!(projection["valuation"]["realizedGrossPnl"], "4.00000000"); - assert_eq!(projection["valuation"]["fees"], "0.14000000"); - assert_eq!(projection["valuation"]["equity"], "10003.86000000"); -} - -#[test] -fn two_owner_projection_retains_negative_contribution_and_empty_results() { - let mut ledger = ledger(); - let empty = output(&ledger); - assert_eq!(empty["fills"], json!([])); - assert_eq!(empty["valuation"]["equity"], "10000.00000000"); - apply( - &mut ledger, - "mark", - 0, - json!({"kind":"mark","instrumentId":"X","price":"10"}), - ); - apply( - &mut ledger, - "a", - 1, - fill("A", "a-buy", "a-fill", "buy", "1", "10", "1"), - ); - apply( - &mut ledger, - "b", - 2, - fill("B", "b-buy", "b-fill", "buy", "2", "8", "0.5"), - ); - let projection = output(&ledger); - let owners = projection["valuation"]["owners"].as_array().unwrap(); - assert_eq!(owners[0]["ownerId"], "A"); - assert_eq!(owners[0]["equityContribution"], "-1.00000000"); - assert_eq!(owners[1]["ownerId"], "B"); - assert_eq!(owners[1]["equityContribution"], "3.50000000"); - assert_eq!(owners[2]["ownerId"], "reserve"); - assert_eq!(owners[2]["equityContribution"], "10000.00000000"); - assert_eq!(projection["valuation"]["equity"], "10002.50000000"); - assert_eq!(projection["fills"][0]["ownerId"], "A"); - assert_eq!(projection["fills"][1]["decision"]["ownerId"], "B"); -} diff --git a/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts b/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts index 261dd7c8..bd446af6 100644 --- a/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts +++ b/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts @@ -1,17 +1,10 @@ import { fork, type ChildProcess } from 'node:child_process'; import { fileURLToPath } from 'node:url'; import { - parseReplayProjectionResult, - parseReplayReportResult, parseReplayResult, replayConfigSchema, replayIdentitySchema, - replayResultFormatSchema, } from '../contracts/native-replay'; -import { - parseStrategyReplayResult, - strategyReplayRequestSchema, -} from '../contracts/strategy-replay'; import { nativeWorkerMessageSchema, type NativeWorkerRequest } from './native-worker-protocol'; import { BacktestConflictError } from './run-repository'; @@ -35,25 +28,17 @@ export class NativeBacktestWorker { if (this.active) { throw new BacktestConflictError('A native backtest worker is already running'); } - // Detach the entire normalized strategy request, including the frozen-data - // payload. The caller must not mutate what is sent or what counts as success. - const strategyRequest = - request.type === 'runStrategyReplay' - ? structuredClone(strategyReplayRequestSchema.parse(request)) - : undefined; - const submitted = strategyRequest ?? request; // Capture expected identity/policy before asynchronous execution. A caller // mutating its request cannot change which completed child result is valid. const expectedReplay = - submitted.type === 'runReplayTrace' || submitted.type === 'runStrategyReplay' + request.type === 'runReplayTrace' ? { identity: replayIdentitySchema.parse({ version: 1, - sessionId: submitted.config.matching.risk.ledger.sessionId, - datasetHash: (submitted.dataset as { manifest?: { hash?: unknown } })?.manifest?.hash, + sessionId: request.config.matching.risk.ledger.sessionId, + datasetHash: (request.dataset as { manifest?: { hash?: unknown } })?.manifest?.hash, }), - policy: replayConfigSchema.parse(submitted.config), - format: replayResultFormatSchema.parse(submitted.resultFormat ?? 'trace'), + policy: replayConfigSchema.parse(request.config), } : undefined; const child = fork(fileURLToPath(this.workerUrl), [], { @@ -96,20 +81,7 @@ export class NativeBacktestWorker { } else if (message.type === 'result') { if (expectedReplay) { try { - if (strategyRequest) { - parseStrategyReplayResult(message.result, { - ...expectedReplay, - strategies: strategyRequest.strategies, - }); - } else { - const parse = - expectedReplay.format === 'report' - ? parseReplayReportResult - : expectedReplay.format === 'projection' - ? parseReplayProjectionResult - : parseReplayResult; - parse(message.result, expectedReplay.identity, expectedReplay.policy); - } + parseReplayResult(message.result, expectedReplay.identity, expectedReplay.policy); } catch (error) { terminate(error instanceof Error ? error : new Error(String(error))); return; @@ -162,7 +134,7 @@ export class NativeBacktestWorker { return; } try { - child.send(submitted, error => { + child.send(request, error => { if (error) { terminate(error); } diff --git a/apps/stock/orchestrator/src/backtest/canonical-result.ts b/apps/stock/orchestrator/src/backtest/canonical-result.ts deleted file mode 100644 index 4e50d271..00000000 --- a/apps/stock/orchestrator/src/backtest/canonical-result.ts +++ /dev/null @@ -1,195 +0,0 @@ -import { z } from 'zod'; -import { - dayMs, - drawdownAnalysis, - nullable, - ratio, - returnStatistics, -} from '@stock-bot/calculations/analytics'; -import { cagr, simpleReturn } from '@stock-bot/calculations/returns'; -import type { - CanonicalBacktestAnalytics, - CanonicalMetrics, - CanonicalMetricsInput, - CanonicalMetricUnavailableReason, - CanonicalSessionReturn, -} from '@stock-bot/types'; -import type { ReplayReportResult } from '../contracts/native-replay'; - -const metricsInput = z - .object({ - version: z.literal(1), - periodsPerYear: z.number().finite().positive(), - annualRiskFreeRate: z.number().finite().nullable(), - benchmark: z.null(), - }) - .strict(); - -export interface CanonicalBacktestReport { - /** Exact validated Rust facts; never converted through the legacy DTO. */ - financial: ReplayReportResult; - analytics: CanonicalBacktestAnalytics; -} - -/** Consume a validated report from the native protocol parser. Financial facts - * stay untouched; only statistical reporting converts decimal equity to numbers. - * Persistence/public-result migration belongs to the separately gated R05 path. */ -export function buildCanonicalBacktestReport( - financial: ReplayReportResult, - input: CanonicalMetricsInput -): CanonicalBacktestReport { - const policy = metricsInput.parse(input); - const reporting = financial.reporting; - const initial = Number(reporting.initialEquity); - const terminal = Number(financial.projection.valuation.equity); - const elapsedMs = Number(reporting.elapsedMs); - let previous = initial; - const sessionReturns: CanonicalSessionReturn[] = reporting.sessions.map(session => { - const current = Number(session.equity); - const value = previous > 0 ? nullable(simpleReturn(previous, current)) : null; - const reason = - value === null - ? previous <= 0 - ? ('nonpositive-baseline' as const) - : ('nonfinite-result' as const) - : undefined; - previous = current; - return { - sessionId: session.session.sessionId, - periodStart: session.periodStart, - periodEnd: session.periodEnd, - partialStart: session.partialStart, - partialEnd: session.partialEnd, - value, - eligible: !session.partialStart && !session.partialEnd && value !== null, - ...(reason ? { reason } : {}), - }; - }); - const complete = sessionReturns.filter(session => !session.partialStart && !session.partialEnd); - // One undefined complete return invalidates this statistical sequence. A later - // positive baseline must not silently turn it into a shorter, different sample. - const periodicReturns = complete.every( - (session): session is CanonicalSessionReturn & { value: number } => session.value !== null - ) - ? complete.map(session => session.value) - : null; - const statistics = - periodicReturns === null - ? null - : returnStatistics(periodicReturns, policy.annualRiskFreeRate, policy.periodsPerYear); - const points = [ - { timestamp: reporting.tradeStart, value: initial }, - ...reporting.sessions.map(session => ({ - timestamp: session.periodEnd, - value: Number(session.equity), - })), - ]; - const metrics: CanonicalMetrics = { - totalReturn: initial > 0 ? nullable(simpleReturn(initial, terminal)) : null, - cagr: initial > 0 ? cagr(initial, terminal, elapsedMs / dayMs / 365) : null, - maxDrawdown: initial > 0 ? drawdownAnalysis(points, initial).maxDrawdown : null, - exposureTime: ratio(Number(reporting.occupiedMs), elapsedMs), - volatility: statistics?.volatility ?? null, - downsideDeviation: statistics?.downsideDeviation ?? null, - sharpeRatio: statistics?.sharpeRatio ?? null, - sortinoRatio: statistics?.sortinoRatio ?? null, - var95: statistics?.var95 ?? null, - cvar95: statistics?.cvar95 ?? null, - var99: statistics?.var99 ?? null, - alpha: null, - beta: null, - informationRatio: null, - roundTripCount: null, - winRate: null, - profitFactor: null, - avgWin: null, - avgLoss: null, - }; - const unavailable: CanonicalBacktestAnalytics['unavailable'] = { - alpha: 'missing-benchmark', - beta: 'missing-benchmark', - informationRatio: 'missing-benchmark', - roundTripCount: 'unsupported-round-trips', - winRate: 'unsupported-round-trips', - profitFactor: 'unsupported-round-trips', - avgWin: 'unsupported-round-trips', - avgLoss: 'unsupported-round-trips', - }; - if (metrics.totalReturn === null) { - unavailable.totalReturn = initial <= 0 ? 'nonpositive-baseline' : 'nonfinite-result'; - } - if (metrics.maxDrawdown === null) { - unavailable.maxDrawdown = 'nonpositive-baseline'; - } - if (metrics.exposureTime === null) { - unavailable.exposureTime = elapsedMs === 0 ? 'zero-duration' : 'nonfinite-result'; - } - if (metrics.cagr === null) { - unavailable.cagr = - initial <= 0 - ? 'nonpositive-baseline' - : elapsedMs === 0 - ? 'zero-duration' - : terminal < 0 - ? 'negative-terminal-equity' - : 'nonfinite-result'; - } - const minimumPeriods = { - volatility: 2, - downsideDeviation: 2, - sharpeRatio: 2, - sortinoRatio: 2, - var95: 20, - cvar95: 20, - var99: 100, - }; - for (const key of Object.keys(minimumPeriods) as (keyof typeof minimumPeriods)[]) { - if (metrics[key] !== null) { - continue; - } - let reason: CanonicalMetricUnavailableReason = 'nonfinite-result'; - if (periodicReturns === null) { - reason = 'undefined-period-return'; - } else if ( - ['downsideDeviation', 'sharpeRatio', 'sortinoRatio'].includes(key) && - policy.annualRiskFreeRate === null - ) { - reason = 'missing-risk-free'; - } else if (periodicReturns.length < minimumPeriods[key]) { - reason = 'insufficient-periods'; - } else if (key === 'sharpeRatio' && statistics?.volatility === 0) { - reason = 'zero-variance'; - } else if (key === 'sortinoRatio' && statistics?.downsideDeviation === 0) { - reason = 'zero-downside-deviation'; - } - unavailable[key] = reason; - } - return { - financial, - analytics: { - version: 1, - policy: { - ...policy, - calendarId: reporting.calendarId, - calendarRevision: reporting.calendarRevision, - sampling: reporting.sampling, - marks: 'last-available-no-per-session-freshness-certification', - returnUnit: 'fraction', - variance: 'sample-n-minus-one', - riskFreeConversion: 'annual-rate-divided-by-periods-per-year', - downside: 'full-series-rms-relative-to-risk-free', - partialPeriods: 'visible-excluded-from-periodic-statistics', - drawdown: 'session-end-and-terminal-sampled', - exposureBasis: reporting.exposureBasis, - cagrBasis: 'elapsed-calendar-days-365', - zeroTerminalCagr: 'negative-one-for-positive-elapsed-time', - }, - sessionReturns, - completePeriodCount: complete.length, - periodicSampleCount: periodicReturns?.length ?? 0, - fillCount: financial.projection.fills.length, - metrics, - unavailable, - }, - }; -} diff --git a/apps/stock/orchestrator/src/backtest/native-replay.ts b/apps/stock/orchestrator/src/backtest/native-replay.ts index 8a99f198..b96e3457 100644 --- a/apps/stock/orchestrator/src/backtest/native-replay.ts +++ b/apps/stock/orchestrator/src/backtest/native-replay.ts @@ -7,9 +7,7 @@ import { type FinancialStrategyIntent, } from '@stock-bot/types'; import { - parseReplayProjectionValue, - parseReplayReportValue, - parseReplayResultValue, + parseReplayResult, replayConfigSchema, replayTraceSchema, sameIdentity, @@ -19,13 +17,8 @@ import { type PublishedObservation, type ReplayConfig, type ReplayIdentity, - type ReplayOutput, - type ReplayProjectionResult, - type ReplayReportResult, type ReplayResult, - type ReplayResultFormat, type ReplayStep, - type ReplaySubmissionOutcome, type ReplayTraceRequest, } from '../contracts/native-replay'; import { validateDatasetV2 } from '../data/historical-dataset-v2'; @@ -35,10 +28,6 @@ export type { ReplayIdentity, ReplayStep, ReplayResult, - ReplayProjectionResult, - ReplayReportResult, - ReplayOutput, - ReplayResultFormat, DecisionContext, PublishedObservation, ReplayTraceRequest, @@ -155,7 +144,6 @@ export class NativeReplaySession { submitResponseBytes: 0, resultBytes: 0, }; - readonly finalization = { nativeMs: 0, decodeMs: 0, validationMs: 0 }; constructor(load: ReturnType) { this.identity = freeze({ ...load.identity }); this.native = new FinancialReplaySession(JSON.stringify(load)); @@ -188,38 +176,9 @@ export class NativeReplaySession { return freeze(result.outcome); } finalize(): ReplayResult { - const identity = JSON.stringify(this.identity); - return this.finish( - () => this.native.finalize(identity), - input => parseReplayResultValue(input, this.identity) - ); - } - project(): ReplayProjectionResult { - const identity = JSON.stringify(this.identity); - return this.finish( - () => this.native.project(identity), - input => parseReplayProjectionValue(input, this.identity) - ); - } - report(): ReplayReportResult { - const identity = JSON.stringify(this.identity); - return this.finish( - () => this.native.report(identity), - input => parseReplayReportValue(input, this.identity) - ); - } - private finish(native: () => string, validate: (input: unknown) => T): T { - let start = performance.now(); - const raw = native(); - this.finalization.nativeMs += performance.now() - start; + const raw = this.native.finalize(JSON.stringify(this.identity)); this.transport.resultBytes += Buffer.byteLength(raw); - start = performance.now(); - const decoded: unknown = JSON.parse(raw); - this.finalization.decodeMs += performance.now() - start; - start = performance.now(); - const result = validate(decoded); - this.finalization.validationMs += performance.now() - start; - return result; + return parseReplayResult(raw, this.identity); } dispose(): void { this.native.dispose(); @@ -237,97 +196,21 @@ export interface ReplayMetrics { submitMs: number; decisionMs: number; finalizeMs: number; - finalizeNativeMs: number; - finalizeDecodeMs: number; - finalizeValidationMs: number; - disposeMs: number; } -type Decide = ( - ownerId: string, - context: DecisionContext, - observations: readonly PublishedObservation[] -) => FinancialStrategyIntent; -export interface ReplayOptions { - eventBudget?: number; - reverseCallbacks?: boolean; - onProgress?: (step: ReplayStep) => void; - resultFormat?: ReplayResultFormat; -} -/** Internal trusted-host seam. All due decisions are staged before one native - * submission. A controller never receives the native handle. */ -export interface ReplayController { - stage( - context: DecisionContext, - observations: readonly PublishedObservation[] - ): FinancialStrategyDecision[]; - committed?(outcome: ReplaySubmissionOutcome): void; -} -/* eslint-disable no-redeclare -- TypeScript overloads preserve the existing trace result type. */ -export function runReplayConformance( - session: NativeReplaySession, - decide: Decide, - options: ReplayOptions & { resultFormat: 'report' } -): { result: ReplayReportResult; metrics: ReplayMetrics }; -export function runReplayConformance( - session: NativeReplaySession, - decide: Decide, - options: ReplayOptions & { resultFormat: 'projection' } -): { result: ReplayProjectionResult; metrics: ReplayMetrics }; -export function runReplayConformance( - session: NativeReplaySession, - decide: Decide, - options?: ReplayOptions & { resultFormat?: 'trace' } -): { result: ReplayResult; metrics: ReplayMetrics }; -export function runReplayConformance( - session: NativeReplaySession, - decide: Decide, - options: ReplayOptions -): { result: ReplayOutput; metrics: ReplayMetrics }; /** Conformance driver only. No persisted strategy states/RNG, dynamic code, or * production strategy framework. Shared view is frozen before any fixture runs. */ export function runReplayConformance( session: NativeReplaySession, - decide: Decide, - options: ReplayOptions = {} -) { - /* eslint-enable no-redeclare */ - let sequence = 0; - return runReplaySession( - session, - { - stage(context, observations) { - const owners = [...context.barrier.owner_ids]; - if (options.reverseCallbacks) { - owners.reverse(); - } - const decisions = owners.map(ownerId => - parseFinancialStrategyDecision({ - version: 1, - sessionId: session.identity.sessionId, - barrierId: context.barrier.barrier_id, - revision: context.barrier.revision, - decision: { - ownerId, - decisionId: JSON.stringify(['trace', sequence, ownerId]), - sequence, - }, - intent: decide(ownerId, context, observations), - }) - ); - sequence++; - return decisions; - }, - }, - options - ); -} - -/** One pull loop for conformance and stateful programs. Always disposes the - * attempt, including ambiguous submissions or failures in host callbacks. */ -export function runReplaySession( - session: NativeReplaySession, - controller: ReplayController, - options: ReplayOptions = {} + decide: ( + ownerId: string, + context: DecisionContext, + observations: readonly PublishedObservation[] + ) => FinancialStrategyIntent, + options: { + eventBudget?: number; + reverseCallbacks?: boolean; + onProgress?: (step: ReplayStep) => void; + } = {} ) { const metrics: ReplayMetrics = { advanceCalls: 0, @@ -340,12 +223,9 @@ export function runReplaySession( submitMs: 0, decisionMs: 0, finalizeMs: 0, - finalizeNativeMs: 0, - finalizeDecodeMs: 0, - finalizeValidationMs: 0, - disposeMs: 0, }; let observations: PublishedObservation[] = []; + let sequence = 0; try { for (;;) { const start = performance.now(), @@ -363,16 +243,8 @@ export function runReplaySession( throw new Error(step.step.diagnostic); case 'complete': { const start = performance.now(), - result = - options.resultFormat === 'report' - ? session.report() - : options.resultFormat === 'projection' - ? session.project() - : session.finalize(); + result = session.finalize(); metrics.finalizeMs = performance.now() - start; - metrics.finalizeNativeMs = session.finalization.nativeMs; - metrics.finalizeDecodeMs = session.finalization.decodeMs; - metrics.finalizeValidationMs = session.finalization.validationMs; metrics.contextBytes = session.transport.advanceResponseBytes; metrics.submissionBytes = session.transport.submitRequestBytes; metrics.outcomeBytes = session.transport.submitResponseBytes; @@ -382,12 +254,30 @@ export function runReplaySession( 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 = controller.stage(context, publishedDelta); + 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; @@ -395,45 +285,20 @@ export function runReplaySession( if (typeof outcome.status === 'object') { throw new Error(outcome.status.Failed.diagnostic); } - if (controller.committed) { - const commitStart = performance.now(); - controller.committed(outcome); - metrics.decisionMs += performance.now() - commitStart; - } break; } } } } finally { - const start = performance.now(); session.dispose(); - metrics.disposeMs = performance.now() - start; } } /** Bounded fixed intent trace for conformance/debug, not a declarative strategy DSL. */ -/* eslint-disable no-redeclare -- TypeScript overloads narrow the selected result format. */ -export function executeReplayTrace( - input: ReplayTraceRequest & { resultFormat: 'report' }, - onProgress?: (step: ReplayStep) => void -): { result: ReplayReportResult; metrics: ReplayMetrics }; -export function executeReplayTrace( - input: ReplayTraceRequest & { resultFormat: 'projection' }, - onProgress?: (step: ReplayStep) => void -): { result: ReplayProjectionResult; metrics: ReplayMetrics }; -export function executeReplayTrace( - input: ReplayTraceRequest & { resultFormat?: 'trace' }, - onProgress?: (step: ReplayStep) => void -): { result: ReplayResult; metrics: ReplayMetrics }; -export function executeReplayTrace( - input: ReplayTraceRequest, - onProgress?: (step: ReplayStep) => void -): { result: ReplayOutput; metrics: ReplayMetrics }; export function executeReplayTrace( input: ReplayTraceRequest, onProgress: (step: ReplayStep) => void = () => {} ) { - /* eslint-enable no-redeclare */ const request = replayTraceSchema.parse(input), load = prepareReplayLoad(request.dataset, request.config); const trace = new Map(); @@ -457,7 +322,6 @@ export function executeReplayTrace( }, { eventBudget: request.eventBudget, - resultFormat: request.resultFormat, onProgress: step => { if (step.step.type === 'complete' && trace.size) { throw new Error('Unused trace decisions'); diff --git a/apps/stock/orchestrator/src/backtest/native-worker-protocol.ts b/apps/stock/orchestrator/src/backtest/native-worker-protocol.ts index 27a891d9..2ac401a0 100644 --- a/apps/stock/orchestrator/src/backtest/native-worker-protocol.ts +++ b/apps/stock/orchestrator/src/backtest/native-worker-protocol.ts @@ -1,6 +1,5 @@ import { z } from 'zod'; import { replayTraceSchema } from '../contracts/native-replay'; -import { strategyReplayRequestSchema } from '../contracts/strategy-replay'; import { BacktestConfigSchema } from '../types'; const finite = z.number().finite(); @@ -22,11 +21,7 @@ const legacyRequestSchema = z.object({ ), }); -export const nativeWorkerRequestSchema = z.union([ - legacyRequestSchema, - replayTraceSchema, - strategyReplayRequestSchema, -]); +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() }), @@ -34,5 +29,5 @@ export const nativeWorkerMessageSchema = z.discriminatedUnion('type', [ z.object({ type: z.literal('error'), message: z.string() }), ]); -export type NativeWorkerRequest = z.input; +export type NativeWorkerRequest = z.infer; export type NativeWorkerMessage = z.infer; diff --git a/apps/stock/orchestrator/src/backtest/native-worker.ts b/apps/stock/orchestrator/src/backtest/native-worker.ts index a0a8bf8a..ad6cdf0a 100644 --- a/apps/stock/orchestrator/src/backtest/native-worker.ts +++ b/apps/stock/orchestrator/src/backtest/native-worker.ts @@ -1,13 +1,7 @@ import { BacktestEngine } from '@stock-bot/engine'; -import type { StrategyReplayResult } from '../contracts/strategy-replay'; -import { - createBuiltinStrategy, - validateBuiltinStrategyBindings, -} from '../strategies/canonical-sma'; -import { executeReplayTrace, prepareReplayLoad } from './native-replay'; +import { executeReplayTrace } from './native-replay'; import { resolveNativeStrategies } from './native-strategies'; import { nativeWorkerRequestSchema, type NativeWorkerMessage } from './native-worker-protocol'; -import { runStrategyReplay } from './strategy-runtime'; /** One process, one native engine, one request. No database or service-container access. */ function send(message: NativeWorkerMessage): Promise { @@ -23,36 +17,6 @@ function send(message: NativeWorkerMessage): Promise { process.once('message', async (input: unknown) => { try { const request = nativeWorkerRequestSchema.parse(input); - if (request.type === 'runStrategyReplay') { - const load = prepareReplayLoad(request.dataset, request.config); - validateBuiltinStrategyBindings(request.strategies, load); - const programs = request.strategies.map(selection => { - const program = createBuiltinStrategy(selection); - if ( - program.ownerId !== selection.ownerId || - program.strategyId !== selection.strategyId || - program.strategyVersion !== selection.strategyVersion || - program.seed !== selection.seed || - program.mode !== 'target' - ) { - throw new Error('Trusted strategy constructor identity mismatch'); - } - return program; - }); - await send({ type: 'progress', progress: 0, message: 'Canonical strategy replay started' }); - const { result } = runStrategyReplay(load, programs, { - eventBudget: request.eventBudget, - resultFormat: request.resultFormat, - }); - const envelope: StrategyReplayResult = { - type: 'strategyReplayResult', - version: 1, - strategies: request.strategies, - result, - }; - await send({ type: 'result', result: JSON.stringify(envelope) }); - return; - } 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 diff --git a/apps/stock/orchestrator/src/backtest/strategy-runtime.ts b/apps/stock/orchestrator/src/backtest/strategy-runtime.ts deleted file mode 100644 index 57aaf90d..00000000 --- a/apps/stock/orchestrator/src/backtest/strategy-runtime.ts +++ /dev/null @@ -1,415 +0,0 @@ -/** Trusted synchronous programs on the canonical financial engine. Fresh - * attempts recompute from original inputs; diagnostics are not resume tokens. */ -import { types } from 'node:util'; -import { z } from 'zod'; -import { parseFinancialStrategyDecision, type FinancialStrategyDecision } from '@stock-bot/types'; -import type { - DeepReadonly, - StrategyAdmissionFeedback, - StrategyDiagnostic, - StrategyDiagnosticSnapshot, - StrategyProgram, -} from '../contracts/canonical-strategy'; -import { - nativeAdmissionOrders, - replayConfigSchema, - replayIdentitySchema, - type DecisionContext, - type PublishedObservation, - type ReplayIdentity, - type ReplayOutput, - type ReplayProjectionResult, - type ReplayReportResult, - type ReplayResult, - type ReplaySubmissionOutcome, -} from '../contracts/native-replay'; -import { - NativeReplaySession, - runReplaySession, - type prepareReplayLoad, - type ReplayController, - type ReplayMetrics, - type ReplayOptions, -} from './native-replay'; - -export type { StrategyProgram } from '../contracts/canonical-strategy'; -export type StrategyReplayOptions = Omit; -type StrategyRun = { - result: Result; - /** decisionMs includes state staging, validation and admission feedback. */ - metrics: ReplayMetrics; - diagnostics: DeepReadonly; -}; - -export class StrategyReplayError extends Error { - constructor( - cause: unknown, - readonly diagnostics: DeepReadonly - ) { - super(cause instanceof Error ? cause.message : String(cause), { cause }); - this.name = 'StrategyReplayError'; - } -} - -function freeze(value: T): DeepReadonly { - if (value && typeof value === 'object' && !Object.isFrozen(value)) { - for (const child of Object.values(value)) { - freeze(child); - } - Object.freeze(value); - } - return value as DeepReadonly; -} - -/** Check descriptors before reading values: JSON.stringify would silently lose - * symbols/custom array keys, invoke accessors, or rewrite non-JSON objects. */ -function stateCopy(input: unknown, ancestors = new Set()): unknown { - if (input === null || typeof input === 'string' || typeof input === 'boolean') { - return input; - } - if (typeof input === 'number' && Number.isFinite(input)) { - if (Object.is(input, -0)) { - throw new Error('Strategy state cannot contain negative zero'); - } - return input; - } - const invalid = () => new Error('Strategy state requires finite plain JSON data properties'); - if (!input || typeof input !== 'object' || ancestors.has(input)) { - throw invalid(); - } - const array = Array.isArray(input); - if (Object.getPrototypeOf(input) !== (array ? Array.prototype : Object.prototype)) { - throw invalid(); - } - const descriptors = Object.getOwnPropertyDescriptors(input); - const keys = Reflect.ownKeys(input); - if (keys.some(key => typeof key !== 'string')) { - throw invalid(); - } - ancestors.add(input); - try { - const data = (key: string): unknown => { - const descriptor = descriptors[key]; - if (!descriptor?.enumerable || !('value' in descriptor)) { - throw invalid(); - } - return stateCopy(descriptor.value, ancestors); - }; - if (array) { - if (keys.length !== input.length + 1) { - throw invalid(); - } - return Array.from({ length: input.length }, (_, index) => data(String(index))); - } - // fromEntries preserves an own '__proto__' key without changing prototype. - return Object.fromEntries((keys as string[]).sort().map(key => [key, data(key)])); - } finally { - ancestors.delete(input); - } -} - -const id = z - .string() - .min(1) - .refine(value => - [...value].every(char => char.charCodeAt(0) >= 32 && char.charCodeAt(0) !== 127) - ); -const metadataSchema = z - .object({ - ownerId: id, - strategyId: id, - strategyVersion: id, - mode: z.enum(['target', 'orders']), - seed: z.number().int().min(0).max(0xffff_ffff), - }) - .strict(); -type Metadata = z.infer; -interface Slot { - program: Metadata & { decide: StrategyProgram['decide'] }; - diagnostic: DeepReadonly; - pendingObservations: PublishedObservation[]; -} -function increment(value: number, amount = 1): number { - const next = value + amount; - if (!Number.isSafeInteger(next) || next < 0) { - throw new Error('Strategy counter exhausted'); - } - return next; -} - -class StrategyController implements ReplayController { - private slots: Map; - private committedBarriers = 0; - private lastBarrierId: string | null = null; - private observed = 0; - private staged: { - barrierId: string; - expectedRevision: number; - owners: { - ownerId: string; - diagnostic: StrategyDiagnostic; - decision: FinancialStrategyDecision; - }[]; - } | null = null; - - constructor( - private readonly identity: ReplayIdentity, - programs: readonly StrategyProgram[], - config: ReturnType - ) { - this.slots = new Map( - programs.map(program => { - const { ownerId, strategyId, strategyVersion, mode, seed } = program; - const metadata = metadataSchema.parse({ ownerId, strategyId, strategyVersion, mode, seed }); - const decide = program.decide; - if (typeof decide !== 'function') { - throw new Error('Strategy decide must be synchronous callable code'); - } - const diagnostic = freeze({ - ownerId, - strategyId, - strategyVersion, - nextDecisionSequence: 0, - state: stateCopy(program.initialState), - rng: { algorithm: 'lcg32-v1' as const, seed, state: seed, draws: 0 }, - observationCount: 0, - previousAdmission: null, - }); - return [ownerId, { program: { ...metadata, decide }, diagnostic, pendingObservations: [] }]; - }) - ); - const owners = config.matching.owners; - if ( - this.slots.size !== programs.length || - this.slots.size !== owners.length || - owners.some(owner => this.slots.get(owner.ownerId)?.program.mode !== owner.mode.toLowerCase()) - ) { - throw new Error('Programs must exactly match configured owners and modes'); - } - } - - snapshot(): DeepReadonly { - return freeze({ - version: 1, - identity: this.identity, - committedBarriers: this.committedBarriers, - lastBarrierId: this.lastBarrierId, - strategies: [...this.slots.values()] - .sort((a, b) => - a.program.ownerId < b.program.ownerId ? -1 : a.program.ownerId > b.program.ownerId ? 1 : 0 - ) - .map(slot => slot.diagnostic), - }); - } - - stage(context: DecisionContext, observations: readonly PublishedObservation[]) { - if (this.staged) { - throw new Error('Previous strategy barrier has not committed'); - } - this.observed = increment(this.observed, observations.length); - const due = new Set(context.barrier.owner_ids); - if ( - this.observed !== context.barrier.observation_count || - due.size !== context.barrier.owner_ids.length || - [...due].some(owner => !this.slots.has(owner)) || - observations.some(observation => observation.available_at > context.barrier.at) - ) { - throw new Error('Strategy barrier observation or owner mismatch'); - } - const staged: NonNullable = { - barrierId: context.barrier.barrier_id, - expectedRevision: increment(context.barrier.revision), - owners: [], - }; - for (const slot of this.slots.values()) { - // Other owners may have slower cadence. Do not discard their warmup/prefix. - for (const observation of observations) { - slot.pendingObservations.push(observation); - } - if (!due.has(slot.program.ownerId)) { - continue; - } - const { program, diagnostic } = slot; - let active = true, - rngState = diagnostic.rng.state, - draws = diagnostic.rng.draws; - const random = () => { - if (!active) { - throw new Error('Strategy random is only valid during its decision'); - } - draws = increment(draws); - rngState = (Math.imul(rngState, 1664525) + 1013904223) >>> 0; - return rngState / 4294967296; - }; - let output: ReturnType; - try { - const decide = program.decide; - output = decide( - Object.freeze({ - ownerId: program.ownerId, - strategyId: program.strategyId, - strategyVersion: program.strategyVersion, - decisionSequence: diagnostic.nextDecisionSequence, - now: context.barrier.at, - barrier: context.barrier, - portfolio: context.view, - positions: Object.freeze( - context.view.portfolio.positions.filter( - position => position.ownerId === program.ownerId - ) - ), - observations: Object.freeze([...slot.pendingObservations]), - previousAdmission: diagnostic.previousAdmission, - state: diagnostic.state, - random, - }) - ); - } finally { - active = false; - } - if (types.isPromise(output)) { - // Reject async strategies synchronously, but observe their actual - // Promise rejection so failed attempts cannot leak unhandled errors. - // Do not await it or call arbitrary thenable methods. - Promise.prototype.then.call(output, undefined, () => {}); - throw new Error('Strategy decide must synchronously return nextState and intent'); - } - if (!output || typeof output !== 'object' || 'then' in output) { - throw new Error('Strategy decide must synchronously return nextState and intent'); - } - const state = freeze(stateCopy(output.nextState)); - const decision = parseFinancialStrategyDecision({ - version: 1, - sessionId: this.identity.sessionId, - barrierId: context.barrier.barrier_id, - revision: context.barrier.revision, - decision: { - ownerId: program.ownerId, - decisionId: JSON.stringify([ - 'strategy', - program.ownerId, - program.strategyId, - program.strategyVersion, - diagnostic.nextDecisionSequence, - ]), - sequence: diagnostic.nextDecisionSequence, - }, - intent: output.intent, - }); - if (decision.intent.mode !== program.mode) { - throw new Error('Strategy intent mode differs from its configured mode'); - } - staged.owners.push({ - ownerId: program.ownerId, - decision, - diagnostic: { - ownerId: program.ownerId, - strategyId: program.strategyId, - strategyVersion: program.strategyVersion, - state, - nextDecisionSequence: increment(diagnostic.nextDecisionSequence), - rng: { algorithm: 'lcg32-v1', seed: program.seed, state: rngState, draws }, - observationCount: increment(diagnostic.observationCount, slot.pendingObservations.length), - previousAdmission: null, - }, - }); - } - this.staged = staged; - return staged.owners.map(owner => owner.decision); - } - - committed(outcome: ReplaySubmissionOutcome): void { - const staged = this.staged; - if ( - !staged || - outcome.replayed || - outcome.status !== 'Running' || - outcome.revision !== staged.expectedRevision - ) { - throw new Error('Unexpected strategy admission acknowledgement'); - } - const orders = nativeAdmissionOrders(outcome.effects); - if ( - orders.some( - order => !staged.owners.some(owner => owner.ownerId === order.order.decision.ownerId) - ) - ) { - throw new Error('Admission feedback belongs to an owner outside the barrier'); - } - const nextCount = increment(this.committedBarriers); - const next = new Map(this.slots); - // Parse/detach ALL feedback before swapping any committed slot. Even an - // ambiguous/malformed acknowledgement leaves diagnostics at the old barrier. - for (const owner of staged.owners) { - const slot = this.slots.get(owner.ownerId); - if (!slot) { - throw new Error('Staged strategy owner is missing'); - } - const previousAdmission: StrategyAdmissionFeedback = { - decision: owner.decision.decision, - revision: outcome.revision, - orders: orders - .filter(order => order.order.decision.ownerId === owner.ownerId) - .map(order => ({ - orderId: order.order.orderId, - instrumentId: order.order.instrumentId, - decision: order.order.decision, - status: order.status, - })), - }; - next.set(owner.ownerId, { - program: slot.program, - diagnostic: freeze({ ...owner.diagnostic, previousAdmission }), - pendingObservations: [], - }); - } - this.slots = next; - this.committedBarriers = nextCount; - this.lastBarrierId = staged.barrierId; - this.staged = null; - } -} - -/* eslint-disable no-redeclare -- Keep selected native result formats precise. */ -export function runStrategyReplay( - load: ReturnType, - programs: readonly StrategyProgram[], - options: StrategyReplayOptions & { resultFormat: 'report' } -): StrategyRun; -export function runStrategyReplay( - load: ReturnType, - programs: readonly StrategyProgram[], - options: StrategyReplayOptions & { resultFormat: 'projection' } -): StrategyRun; -export function runStrategyReplay( - load: ReturnType, - programs: readonly StrategyProgram[], - options?: StrategyReplayOptions & { resultFormat?: 'trace' } -): StrategyRun; -export function runStrategyReplay( - load: ReturnType, - programs: readonly StrategyProgram[], - options: StrategyReplayOptions -): StrategyRun; -export function runStrategyReplay( - load: ReturnType, - programs: readonly StrategyProgram[], - options: StrategyReplayOptions = {} -): StrategyRun { - /* eslint-enable no-redeclare */ - const identity = freeze(replayIdentitySchema.parse(load.identity)); - const config = replayConfigSchema.parse(load.config); - const controller = new StrategyController(identity, programs, config); - try { - // Native construction synchronously detaches prepared data/config into Rust. - // Caller mutations during later callbacks cannot rewrite that loaded input. - const output = runReplaySession( - new NativeReplaySession({ ...load, identity, config }), - controller, - { ...options } - ); - return { ...output, diagnostics: controller.snapshot() }; - } catch (cause) { - throw new StrategyReplayError(cause, controller.snapshot()); - } -} diff --git a/apps/stock/orchestrator/src/contracts/builtin-strategy.ts b/apps/stock/orchestrator/src/contracts/builtin-strategy.ts deleted file mode 100644 index 6802780b..00000000 --- a/apps/stock/orchestrator/src/contracts/builtin-strategy.ts +++ /dev/null @@ -1,51 +0,0 @@ -/** Trusted built-in selection only. No callbacks, code paths or checkpoint transport. */ -import { z } from 'zod'; -import { parseFinancialDecimal } from '@stock-bot/types'; -import { maxStrategyPeriod } from './strategies'; -import { builtinStrategy } from './strategy-names'; - -const identity = z - .string() - .min(1) - .refine(value => - [...value].every(character => { - const code = character.charCodeAt(0); - return ( - code >= 32 && code !== 127 && !(character.length === 1 && code >= 0xd800 && code <= 0xdfff) - ); - }) - ); -const period = z.number().int().min(1).max(maxStrategyPeriod); - -export const builtinStrategySelectionSchema = z - .object({ - ownerId: identity, - strategyId: z - .string() - .refine(value => builtinStrategy(value) === 'sma_crossover', 'Unsupported canonical strategy') - .transform(() => 'sma_crossover' as const), - strategyVersion: z.literal('sma-crossover-long-only/v1'), - seed: z.number().int().min(0).max(0xffffffff), - instrumentId: identity, - seriesId: identity, - ownerBudget: z - .string() - .transform(value => parseFinancialDecimal(value)) - .refine( - value => !value.startsWith('-') && value !== '0.00000000', - 'Owner budget must be positive' - ), - parameters: z - .object({ - fastPeriod: period.default(5), - slowPeriod: period.min(2).default(15), - }) - .strict() - .refine( - value => value.fastPeriod < value.slowPeriod, - 'SMA fastPeriod must be below slowPeriod' - ), - }) - .strict(); - -export type BuiltinStrategySelection = z.infer; diff --git a/apps/stock/orchestrator/src/contracts/canonical-strategy.ts b/apps/stock/orchestrator/src/contracts/canonical-strategy.ts deleted file mode 100644 index ff678701..00000000 --- a/apps/stock/orchestrator/src/contracts/canonical-strategy.ts +++ /dev/null @@ -1,78 +0,0 @@ -/** Trusted synchronous strategy author contract. No execution or native capabilities. */ -import type { DecisionIdentity, FinancialStrategyIntent } from '@stock-bot/types'; -import type { - DecisionContext, - NativeOrderStatus, - PublishedObservation, - ReplayIdentity, -} from './native-replay'; - -export type DeepReadonly = T extends string | number | boolean | null | undefined - ? T - : T extends object - ? { readonly [Key in keyof T]: DeepReadonly } - : T; - -/** Copied native admission outcomes, not a later fill-event stream. */ -export interface StrategyAdmissionFeedback { - decision: DecisionIdentity; - revision: number; - orders: { - orderId: string; - instrumentId: string; - decision: DecisionIdentity; - status: NativeOrderStatus; - }[]; -} - -export interface StrategyContext { - readonly ownerId: string; - readonly strategyId: string; - readonly strategyVersion: string; - readonly decisionSequence: number; - readonly now: number; - readonly barrier: DeepReadonly; - /** The exact same read-only account view is shared by all due callbacks. */ - readonly portfolio: DeepReadonly; - readonly positions: DeepReadonly; - readonly observations: readonly DeepReadonly[]; - readonly previousAdmission: DeepReadonly | null; - readonly state: DeepReadonly; - /** Valid only during this synchronous callback; never use Math.random for decisions. */ - readonly random: () => number; -} - -export interface StrategyProgram { - readonly ownerId: string; - readonly strategyId: string; - readonly strategyVersion: string; - readonly mode: 'target' | 'orders'; - readonly seed: number; - /** Finite plain JSON, checked and detached before the native attempt starts. */ - readonly initialState: State; - decide(context: StrategyContext): { - nextState: State; - intent: FinancialStrategyIntent; - }; -} - -export interface StrategyDiagnostic { - ownerId: string; - strategyId: string; - strategyVersion: string; - nextDecisionSequence: number; - state: unknown; - rng: { algorithm: 'lcg32-v1'; seed: number; state: number; draws: number }; - observationCount: number; - previousAdmission: StrategyAdmissionFeedback | null; -} - -/** Last confirmed strategy transitions only. This cannot restore financial state. - * Retry always starts a fresh native session and recomputes from original inputs. */ -export interface StrategyDiagnosticSnapshot { - version: 1; - identity: ReplayIdentity; - committedBarriers: number; - lastBarrierId: string | null; - strategies: StrategyDiagnostic[]; -} diff --git a/apps/stock/orchestrator/src/contracts/native-replay.ts b/apps/stock/orchestrator/src/contracts/native-replay.ts index 421042e8..13b39568 100644 --- a/apps/stock/orchestrator/src/contracts/native-replay.ts +++ b/apps/stock/orchestrator/src/contracts/native-replay.ts @@ -162,7 +162,6 @@ const outcomeSchema = z export const submissionSchema = z .object({ identity: replayIdentitySchema, outcome: outcomeSchema }) .strict(); -export type ReplaySubmissionOutcome = z.infer; const resultSchema = z .object({ identity: replayIdentitySchema, @@ -177,171 +176,6 @@ const resultSchema = z .strict(); export type ReplayStep = z.infer; export type ReplayResult = z.infer; -const nonnegative = decimal.refine(value => !value.startsWith('-')); -const positive = nonnegative.refine(value => value !== '0.00000000'); -const nativeOrderStatusSchema = z.union([ - z.enum(['Open', 'Filled', 'Cancelled', 'Expired']), - z - .object({ - Rejected: z.enum([ - 'OrderSize', - 'PositionSize', - 'SymbolExposure', - 'GrossExposure', - 'InsufficientCash', - 'InsufficientInventory', - 'MissingMark', - 'StaleMark', - 'DailyLoss', - 'Drawdown', - 'InactiveOrder', - ]), - }) - .strict(), -]); -export type NativeOrderStatus = z.infer; -const managedOrderSchema = z - .object({ - order: z - .object({ - orderId: id, - decision: z.object({ ownerId: id, decisionId: id, sequence: counter }).strict(), - instrumentId: id, - side: z.enum(['buy', 'sell']), - quantity: positive, - limitPrice: positive.nullable(), - origin: z.enum(['Explicit', 'Target']), - }) - .strict(), - timeInForce: z.enum(['DAY', 'GTC', 'IOC', 'FOK']), - submittedAt: z - .object({ - at: time, - phase: z.enum(['Observation', 'Decision', 'Execution', 'SessionClose']), - instrumentId: id, - sourceSequence: counter, - }) - .strict(), - readyAt: time, - venueSession: id.nullable(), - remaining: nonnegative, - filled: nonnegative, - status: nativeOrderStatusSchema, - admissionSequence: counter, - }) - .strict(); -const admissionEffectSchema = z.union([ - z.object({ Order: managedOrderSchema }).strict(), - z.object({ Risk: z.record(z.unknown()) }).strict(), - z.object({ Operator: z.record(z.unknown()) }).strict(), -]); -/** Decode only the existing native facts needed for strategy admission feedback. - * Other nested risk/ledger diagnostics are never interpreted as TS accounting. */ -export function nativeAdmissionOrders(effects: ReplaySubmissionOutcome['effects']) { - return effects.flatMap(effect => { - const parsed = admissionEffectSchema.parse(effect); - return 'Order' in parsed ? [parsed.Order] : []; - }); -} -const ownerValuationSchema = z - .object({ - ownerId: id, - initialCapital: nonnegative, - markedHoldings: nonnegative, - remainingCost: nonnegative, - realizedGrossPnl: decimal, - unrealizedPnl: decimal, - fees: nonnegative, - equityContribution: decimal, - }) - .strict(); -export const financialProjectionSchema = z - .object({ - valuation: z - .object({ - cash: nonnegative, - markedHoldings: nonnegative, - equity: nonnegative, - remainingCost: nonnegative, - realizedGrossPnl: decimal, - unrealizedPnl: decimal, - fees: nonnegative, - owners: z.array(ownerValuationSchema), - }) - .strict(), - fills: z.array( - z - .object({ - commandId: id, - eventTime: time, - ownerId: id, - decision: z.object({ ownerId: id, decisionId: id, sequence: counter }).strict(), - orderId: id, - fillId: id, - instrumentId: id, - side: z.enum(['buy', 'sell']), - quantity: positive, - price: positive, - fee: z.object({ feeId: id, amount: nonnegative }).strict(), - // Gross notional cash movement; the separate fee posting is not included. - cashDelta: decimal, - quantityDelta: decimal, - releasedBasis: nonnegative, - realizedGrossPnl: decimal, - }) - .strict() - .refine(fill => fill.ownerId === fill.decision.ownerId, 'Fill ownership mismatch') - ), - }) - .strict(); -const projectionResultSchema = resultSchema - .omit({ receipts: true }) - .extend({ - format: z.literal('projection'), - projectionVersion: z.literal(1), - financialVersion: z.literal(1), - projection: financialProjectionSchema, - }) - .strict(); -export type ReplayProjectionResult = z.infer; -export const replayReportingSchema = z - .object({ - calendarId: id, - calendarRevision: id, - tradeStart: time, - tradeEnd: time, - initialEquity: nonnegative, - sampling: z.literal('account-boundary-after-observations-v1'), - exposureBasis: z.literal('elapsed-calendar-time'), - sessions: z.array( - z - .object({ - session: riskSession, - periodStart: time, - periodEnd: time, - partialStart: z.boolean(), - partialEnd: z.boolean(), - equity: nonnegative, - }) - .strict() - ), - occupiedIntervals: z.array(z.object({ start: time, end: time }).strict()), - occupiedMs: z.string().regex(/^(0|[1-9][0-9]*)$/), - elapsedMs: z.string().regex(/^(0|[1-9][0-9]*)$/), - }) - .strict(); -const reportResultSchema = projectionResultSchema - .extend({ - format: z.literal('report'), - reportingVersion: z.literal(1), - reporting: replayReportingSchema, - }) - .strict(); -export type ReplayReporting = z.infer; -export type ReplayReportResult = z.infer; -export const replayResultFormatSchema = z.enum(['trace', 'projection', 'report']); -export type ReplayResultFormat = z.infer; -export type ReplayOutput = ReplayResult | ReplayProjectionResult | ReplayReportResult; export type DecisionContext = Extract; export type PublishedObservation = z.infer; @@ -359,14 +193,7 @@ export function parseReplayResult( identity: ReplayIdentity, expectedPolicy?: ReplayConfig ): ReplayResult { - return parseReplayResultValue(JSON.parse(input), identity, expectedPolicy); -} - -function checkResultIdentity( - result: ReplayOutput, - identity: ReplayIdentity, - expectedPolicy?: ReplayConfig -): void { + const result = resultSchema.parse(JSON.parse(input)); sameIdentity(result.identity, identity); const ledger = result.policy.matching.risk.ledger, portfolio = result.view.portfolio; @@ -383,137 +210,8 @@ function checkResultIdentity( ) { throw new Error('Native replay result identity mismatch'); } -} - -export function parseReplayResultValue( - input: unknown, - identity: ReplayIdentity, - expectedPolicy?: ReplayConfig -): ReplayResult { - const result = resultSchema.parse(input); - checkResultIdentity(result, identity, expectedPolicy); return result; } -export function parseReplayProjectionValue( - input: unknown, - identity: ReplayIdentity, - expectedPolicy?: ReplayConfig -): ReplayProjectionResult { - const result = projectionResultSchema.parse(input); - checkResultIdentity(result, identity, expectedPolicy); - checkProjection(result); - return result; -} -function checkProjection(result: ReplayProjectionResult | ReplayReportResult): void { - if ( - result.projection.valuation.cash !== result.view.portfolio.cash || - result.projection.valuation.equity !== result.view.equity - ) { - throw new Error('Native replay projection does not match terminal view'); - } -} -export function parseReplayProjectionResult( - input: string, - identity: ReplayIdentity, - expectedPolicy?: ReplayConfig -): ReplayProjectionResult { - return parseReplayProjectionValue(JSON.parse(input), identity, expectedPolicy); -} - -export function parseReplayReportValue( - input: unknown, - identity: ReplayIdentity, - expectedPolicy?: ReplayConfig -): ReplayReportResult { - const result = reportResultSchema.parse(input); - checkResultIdentity(result, identity, expectedPolicy); - checkProjection(result); - const report = result.reporting; - const bounds = z.object({ tradeStart: time, tradeEnd: time }).parse(result.manifest.bounds); - const initial = result.policy.matching.risk.ledger; - if ( - report.tradeStart !== bounds.tradeStart || - report.tradeEnd !== bounds.tradeEnd || - report.tradeStart >= report.tradeEnd || - report.calendarId !== initial.riskSession.calendarId || - report.calendarRevision !== initial.riskSession.calendarRevision || - report.initialEquity !== initial.initialCapital || - report.sessions.at(-1)?.equity !== result.view.equity - ) { - throw new Error('Native replay reporting identity or terminal value mismatch'); - } - // Check calendar partition/labels, not equity arithmetic or financial accounting. - const boundaries = [...result.policy.risk_boundaries].sort((a, b) => a.startsAt - b.startsAt); - let session = initial.riskSession; - let start = report.tradeStart, - index = 0; - for (const boundary of boundaries) { - if (boundary.startsAt <= report.tradeStart) { - session = boundary; - continue; - } - if (boundary.startsAt > report.tradeEnd) { - break; - } - const actual = report.sessions[index++]; - if ( - !actual || - JSON.stringify(actual.session) !== JSON.stringify(session) || - actual.periodStart !== start || - actual.periodEnd !== boundary.startsAt || - actual.partialStart !== (start !== session.startsAt) || - actual.partialEnd - ) { - throw new Error('Native replay reporting session partition mismatch'); - } - start = boundary.startsAt; - session = boundary; - } - if (start < report.tradeEnd) { - const actual = report.sessions[index++]; - if ( - !actual || - JSON.stringify(actual.session) !== JSON.stringify(session) || - actual.periodStart !== start || - actual.periodEnd !== report.tradeEnd || - actual.partialStart !== (start !== session.startsAt) || - !actual.partialEnd - ) { - throw new Error('Native replay reporting final session mismatch'); - } - } - if (index !== report.sessions.length) { - throw new Error('Native replay reporting has extra sessions'); - } - let occupied = 0n, - previousEnd: number | undefined; - for (const interval of report.occupiedIntervals) { - if ( - interval.start < report.tradeStart || - interval.end > report.tradeEnd || - interval.start >= interval.end || - (previousEnd !== undefined && interval.start <= previousEnd) - ) { - throw new Error('Native replay reporting intervals are not a clipped union'); - } - occupied += BigInt(interval.end) - BigInt(interval.start); - previousEnd = interval.end; - } - if ( - report.occupiedMs !== String(occupied) || - report.elapsedMs !== String(BigInt(report.tradeEnd) - BigInt(report.tradeStart)) - ) { - throw new Error('Native replay reporting duration mismatch'); - } - return result; -} -export function parseReplayReportResult( - input: string, - identity: ReplayIdentity, - expectedPolicy?: ReplayConfig -): ReplayReportResult { - return parseReplayReportValue(JSON.parse(input), identity, expectedPolicy); -} export const replayTraceSchema = z .object({ @@ -522,7 +220,6 @@ export const replayTraceSchema = z dataset: z.unknown(), config: replayConfigSchema, eventBudget: counter.positive(), - resultFormat: replayResultFormatSchema.optional(), trace: z.array( z .object({ diff --git a/apps/stock/orchestrator/src/contracts/strategy-replay.ts b/apps/stock/orchestrator/src/contracts/strategy-replay.ts deleted file mode 100644 index 872fce7b..00000000 --- a/apps/stock/orchestrator/src/contracts/strategy-replay.ts +++ /dev/null @@ -1,72 +0,0 @@ -/** Data-only trusted built-in execution protocol; no strategy code or native imports. */ -import { z } from 'zod'; -import { builtinStrategySelectionSchema, type BuiltinStrategySelection } from './builtin-strategy'; -import { - parseReplayProjectionValue, - parseReplayReportValue, - parseReplayResultValue, - replayConfigSchema, - replayResultFormatSchema, - type ReplayConfig, - type ReplayIdentity, - type ReplayOutput, - type ReplayResultFormat, -} from './native-replay'; - -export const strategyReplayRequestSchema = z - .object({ - type: z.literal('runStrategyReplay'), - version: z.literal(1), - dataset: z.unknown(), - config: replayConfigSchema, - eventBudget: z.number().int().positive().max(Number.MAX_SAFE_INTEGER), - resultFormat: replayResultFormatSchema.optional(), - strategies: z.array(builtinStrategySelectionSchema).min(1), - }) - .strict(); - -export type StrategyReplayRequest = z.input; - -const strategyReplayResultSchema = z - .object({ - type: z.literal('strategyReplayResult'), - version: z.literal(1), - strategies: z.array(builtinStrategySelectionSchema).min(1), - result: z.unknown(), - }) - .strict(); - -export interface StrategyReplayResult { - type: 'strategyReplayResult'; - version: 1; - strategies: BuiltinStrategySelection[]; - result: ReplayOutput; -} - -export interface StrategyReplayExpectation { - strategies: readonly BuiltinStrategySelection[]; - identity: ReplayIdentity; - policy: ReplayConfig; - format: ReplayResultFormat; -} - -/** Strategy selection is additional provenance; Rust remains the only result authority. */ -export function parseStrategyReplayResult( - input: string, - expected: StrategyReplayExpectation -): StrategyReplayResult { - const envelope = strategyReplayResultSchema.parse(JSON.parse(input)); - if (JSON.stringify(envelope.strategies) !== JSON.stringify(expected.strategies)) { - throw new Error('Native strategy replay selection mismatch'); - } - const parse = - expected.format === 'report' - ? parseReplayReportValue - : expected.format === 'projection' - ? parseReplayProjectionValue - : parseReplayResultValue; - return { - ...envelope, - result: parse(envelope.result, expected.identity, expected.policy), - }; -} diff --git a/apps/stock/orchestrator/src/strategies/canonical-sma.ts b/apps/stock/orchestrator/src/strategies/canonical-sma.ts deleted file mode 100644 index aa262f8a..00000000 --- a/apps/stock/orchestrator/src/strategies/canonical-sma.ts +++ /dev/null @@ -1,200 +0,0 @@ -import { z } from 'zod'; -import { movingAverageCrossover } from '@stock-bot/calculations/indicators'; -import { - parseFinancialDecimal, - type FinancialDecimal, - type HistoricalDatasetManifestV2, -} from '@stock-bot/types'; -import { - builtinStrategySelectionSchema, - type BuiltinStrategySelection, -} from '../contracts/builtin-strategy'; -import type { StrategyProgram } from '../contracts/canonical-strategy'; -import type { ReplayConfig } from '../contracts/native-replay'; - -const time = z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER); -const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER); -const decimal = z.string().transform(value => parseFinancialDecimal(value)); -const nonnegative = decimal.refine(value => !value.startsWith('-')); -const positive = nonnegative.refine(value => value !== '0.00000000'); - -export interface SmaStrategyState { - version: 1; - selectionKey: string; - closes: number[]; - lastObservation: { - eventTime: number; - availableAt: number; - sourceSequence: number; - close: FinancialDecimal; - } | null; - lastCrossover: 'golden' | 'death' | null; - targetQuantity: FinancialDecimal | null; -} - -/** Validate dataset/cadence membership before opening the native session. */ -export function validateBuiltinStrategyBindings( - selections: readonly BuiltinStrategySelection[], - load: { config: ReplayConfig; manifest: Pick } -): void { - const parsed = selections.map(selection => builtinStrategySelectionSchema.parse(selection)); - const owners = load.config.matching.owners; - if ( - new Set(parsed.map(selection => selection.ownerId)).size !== parsed.length || - parsed.length !== owners.length || - owners.some(owner => owner.mode !== 'Target' || !parsed.some(s => s.ownerId === owner.ownerId)) - ) { - throw new Error('Canonical built-ins must exactly match target-mode owners'); - } - for (const selection of parsed) { - const series = load.manifest.series.find(item => item.id === selection.seriesId); - const cadence = load.config.cadence.filter(item => item.owner_id === selection.ownerId); - if ( - series?.instrumentId !== selection.instrumentId || - !load.config.matching.series.some(item => item.instrumentId === selection.instrumentId) || - cadence.length !== 1 || - !cadence[0]?.series_ids.includes(selection.seriesId) - ) { - throw new Error('Canonical SMA requires its instrument/series in its owner cadence'); - } - } -} - -/** Whole-share intent sizing only. Rust remains authoritative for all financial effects. */ -function desiredShares(budget: FinancialDecimal, price: FinancialDecimal): FinancialDecimal { - const units = (value: FinancialDecimal) => BigInt(value.replace('.', '')); - return parseFinancialDecimal((units(budget) / units(price)).toString()); -} - -/** One explicitly versioned long-only program; legacy factories remain unchanged. */ -export function createBuiltinStrategy( - selectionInput: BuiltinStrategySelection -): StrategyProgram { - const selection = builtinStrategySelectionSchema.parse(selectionInput); - const { fastPeriod, slowPeriod } = selection.parameters; - const selectionKey = JSON.stringify(selection); - const stateSchema = z - .object({ - version: z.literal(1), - selectionKey: z.literal(selectionKey), - closes: z.array(z.number().finite().positive()).max(slowPeriod + 1), - lastObservation: z - .object({ - eventTime: time, - availableAt: time, - sourceSequence: counter, - close: positive, - }) - .strict() - .refine(value => value.availableAt >= value.eventTime) - .nullable(), - lastCrossover: z.enum(['golden', 'death']).nullable(), - targetQuantity: nonnegative.refine(value => value.endsWith('.00000000')).nullable(), - }) - .strict() - .refine(state => { - if (!state.lastObservation) { - return ( - state.closes.length === 0 && state.lastCrossover === null && state.targetQuantity === null - ); - } - if (state.closes.at(-1) !== Number(state.lastObservation.close)) { - return false; - } - if (state.lastCrossover === null) { - return state.targetQuantity === null; - } - if (state.closes.length !== slowPeriod + 1) { - return false; - } - return state.lastCrossover !== 'death' || state.targetQuantity === '0.00000000'; - }, 'Inconsistent SMA checkpoint'); - - return { - ownerId: selection.ownerId, - strategyId: selection.strategyId, - strategyVersion: selection.strategyVersion, - seed: selection.seed, - mode: 'target', - initialState: { - version: 1, - selectionKey, - closes: [], - lastObservation: null, - lastCrossover: null, - targetQuantity: null, - }, - decide(context) { - const nextState = stateSchema.parse(context.state); - let advanced = false; - for (const observation of context.observations) { - if (observation.series_id !== selection.seriesId) { - continue; - } - if ( - observation.instrument_id !== selection.instrumentId || - observation.available_at > context.now - ) { - throw new Error('Canonical SMA observation binding or availability mismatch'); - } - const previous = nextState.lastObservation; - // Arrival order is authoritative. A delayed older event cannot rewrite evaluated history. - if ( - previous && - (observation.event_time < previous.eventTime || - (observation.event_time === previous.eventTime && - observation.source_sequence <= previous.sourceSequence)) - ) { - continue; - } - const close = positive.parse(observation.close); - nextState.closes.push(Number(close)); - if (nextState.closes.length > slowPeriod + 1) { - nextState.closes.shift(); - } - nextState.lastObservation = { - eventTime: observation.event_time, - availableAt: observation.available_at, - sourceSequence: observation.source_sequence, - close, - }; - advanced = true; - const cross = movingAverageCrossover(nextState.closes, fastPeriod, slowPeriod); - if (cross?.goldenCross && nextState.lastCrossover !== 'golden') { - nextState.lastCrossover = 'golden'; - nextState.targetQuantity = null; - } else if (cross?.deathCross) { - nextState.lastCrossover = 'death'; - nextState.targetQuantity = parseFinancialDecimal('0'); - } - } - const input = context.barrier.inputs.find(item => item.series_id === selection.seriesId); - const availability = input?.availability; - const last = nextState.lastObservation; - const fresh = - typeof availability === 'object' && 'Fresh' in availability ? availability.Fresh : null; - if ( - !advanced || - !last || - !fresh || - fresh.event_time !== last.eventTime || - fresh.available_at !== last.availableAt - ) { - return { nextState, intent: { mode: 'target', targets: [] } }; - } - if (nextState.lastCrossover === 'golden' && nextState.targetQuantity === null) { - nextState.targetQuantity = desiredShares(selection.ownerBudget, last.close); - } - return { - nextState, - intent: { - mode: 'target', - targets: - nextState.targetQuantity === null - ? [] - : [{ instrumentId: selection.instrumentId, quantity: nextState.targetQuantity }], - }, - }; - }, - }; -} diff --git a/docs/development/ROADMAP.md b/docs/development/ROADMAP.md index 626cdfc6..4d564af2 100644 --- a/docs/development/ROADMAP.md +++ b/docs/development/ROADMAP.md @@ -1,14 +1,14 @@ # Revised development roadmap -Baseline `b7aeca4` · execution 2026-10-23 · **F08 committed; S01 validated, uncommitted** +Baseline `b7aeca4` · handoff 2026-10-23 · **F07 reviewed, validated and committed** -Authorization update: the owner accepted F08 and requested “commit all of it and continue” after the handoff named S01 and linked ADR-005. F08 is committed as `3838295`; S01 is authorized under ADR-004/005. Other pending ADRs and the multi-asset mark policy are unchanged. New S01 implementation commits, pushes, PRs and trading/default-engine operations remain outside this continuation's scope. +Authorization update: the owner accepted and committed the reviewed F07 changes as `e3635f2` on 2026-10-23. The accompanying performance question requests assessment, not optimization implementation. 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 Use TypeScript for strategies, research and the web product; one Rust kernel owns money, risk, matching and replay. Preserve durable decisions/checkpoints, transactional execution, frozen datasets, reviewed calculations and failure-oriented tests. -The skeptical review established 43 scheduled tasks, 5 conditional tasks and 4 merged redirects. The measured F09/P07/P08 additions bring the current plan to **46 scheduled + 5 conditional + 4 merged = 55 retained IDs**. See [review findings and dispositions](REVIEW.md), [complete index](backlog/README.md) and [canonical manifest](backlog/manifest.json). +The skeptical review consolidates **52 separate task definitions into 43 scheduled tasks plus 5 conditional tasks**. Four old IDs remain merged redirects, not extra work. This is a smaller delivery plan, not a smaller correctness standard. See [review findings and dispositions](REVIEW.md), [complete index](backlog/README.md) and [canonical manifest](backlog/manifest.json). The existing web workbench improves during engine migration. Legacy results remain labelled; fixing controls or terminal valuation does not make same-bar economics trustworthy. C06 blocks shared-runtime legacy research rather than building another soon-to-be-retired simulator runtime. @@ -20,7 +20,7 @@ The existing web workbench improves during engine migration. Legacy results rema | [ADR-002](architecture/decisions/002-financial-policy.md) | Maintained checked decimal; 8-place half-up postings; authoritative remaining cost; owner books from day one; initial cash-funded long-only account | Approved by owner, 2026-10-22 | | [ADR-003](architecture/decisions/003-time-and-datasets.md) | Availability/event phases; open-only next-interval matching; explicit zero-latency convention; mark-open terminal policy; account risk-session clock | Approved by owner, 2026-10-22 | | [ADR-004](architecture/decisions/004-strategy-boundary.md) | NAPI pull sessions in existing workers; tagged decision barriers; IPC for untrusted code; no embedded JS | Approved by owner, 2026-10-22 | -| [ADR-005](architecture/decisions/005-durable-cutover.md) | One Rust transition kernel; resident research state; private staged paper state under existing SQL transactions | Approved by owner continuation, 2026-10-23; paper activation separately gated | +| [ADR-005](architecture/decisions/005-durable-cutover.md) | One Rust transition kernel; resident research state; private staged paper state under existing SQL transactions | Plan approval | | [ADR-006](architecture/decisions/006-research-product.md) | Existing API/queue/database; immutable versions, provenance and evidence retention; no laboratory framework | Plan approval | | [ADR-007](architecture/decisions/007-ai-boundary.md) | Isolated untrusted code, research-only permissions/budgets; human-only paper promotion; live disabled | Explicit trust-model approval | | [ADR-008](architecture/decisions/008-performance.md) | Measure actual paths; cursor replay and bounded trials; caching/DSL only when measured | Plan approval; later optimization go/no-go | @@ -35,7 +35,7 @@ Long-only is the approved first canonical model, not deletion of short history o | --- | --- | --- | | M0: safe interim behavior | C01/C02/C03/C04/C06; O01; P01 | Scoped terminal/funding/input fixes; failed init cleans up; shared-runtime research rejected; migration lock and honest baseline measurements | | M1: usable current workbench | W01–W04 | Save, submit, cancel, inspect and reopen tested in browser; unsupported controls hidden; legacy economic limitations visible | -| M2: canonical Rust/TS research | F01/F02/F04–F09, D01, S01/S02; R01/R10/W03/C06 then R05; P07 measurements | Owner-aware finance, deterministic replay, compact results, one TS strategy and retained input provenance work through durable runs | +| M2: canonical Rust/TS research | F01/F02/F04–F08, D01, S01/S02; R01/R10/W03/C06 then R05 | Owner-aware finance, deterministic replay, one TS strategy and retained input provenance work through durable runs | | M3: useful research product | R02/R03/R04/R11/R12 | Catalog/workspace/dataset selection and original reproduction; metadata/UI proceed alongside engine work | | M4: batch research and validation | R06–R09, P04; S05 when ready | Bounded sweeps, summary comparisons, OOS/reset-segment walk-forward and measured worker scaling; regime panels only with S05 | | M5: paper parity and AI research | S03/S04, A01–A04 | Recovery parity, operator readiness, isolated bounded AI experiments and evidence-linked human paper promotion | @@ -52,8 +52,6 @@ flowchart LR D01[Availability-aware eligible datasets] --> F06 P01[Existing-path measurements] --> F06 F06 --> F07[Bounded NAPI sessions] --> S01[TS decisions] --> S02[One SMA] - F07 --> F09[Compact financial projections] --> F08 - F07 --> P07[Representative replay profiling] C02[Boundary integrity] --> F07 F06 --> F08[Canonical projections + reviewed TS statistics] S02 --> R05[Durable canonical runs] @@ -273,135 +271,6 @@ Limits remain explicit: trusted host interface, not an untrusted-code sandbox; n 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 is committed. 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. -## Twelfth-wave handoff — 2026-10-23 - -Two focused performance stories replace a broad optimization request: [F09](backlog/tasks/F09.md) emits compact authoritative terminal values/owned fills with optional complete diagnostics; [P07](backlog/tasks/P07.md) profiles no-trade, sparse and high-turnover workloads using the existing harness. F08 consumes F09 and later adds explicit session sampling/exposure/statistical policies. No session-close values are inferred from risk baselines, and fills are not relabelled completed trades. - -Base `19e9dad`; isolated worktrees under `/tmp/stock-bot-wave12.F9Rlh4/`. One native/result contract owner, one disjoint benchmark owner, root planning/integration and independent review. Baseline profiling was measured on F07; compact comparisons used the accepted F09 contract. Internal journals/recovery, legacy/default paths and all mark-policy release gates remain. No framework, DSL, cache, worker-pool or web-pagination expansion. - -Both stories are independently reviewed and `review` / `validated_uncommitted`. Root integrated 14 source/test files with exact reviewed hashes. F09's accepted contract was overlaid into P07's isolated worktree before compact comparison work; neither owner independently changed the other's contract. - -- **F09:** native `project()` returns the existing authoritative ledger valuation and actual owned fills copied from committed commands/effects. It skips replay aliases and retains separate gross cash movement and fee postings, signed owner contributions and residual cost basis. Typed serialization borrows journal facts; no checkpoint copying, financial replay or TypeScript accounting is introduced. Complete-state/identity/format/cancellation guards cover the compact path. Full `finalize()` output, defaults, internal journals and recovery are preserved. -- **P07:** the existing harness now selects no-trade, sparse and turnover profiles with identical callback cadence, plus trace/projection/both output. It records native-finalization, decoding, validation and disposal separately. Comparisons require the same dataset, policy, strategy, artifact, terminal view and actual fill facts. Full per-format hashes remain independent; no TypeScript valuation is fabricated to compare formats. A 200,000-fill regression prevents a benchmark-only JavaScript argument-limit failure. - -Validation: full `CARGO_BUILD_JOBS=2 bun run check` passed build/types/contracts/lint/audit, 63 tooling, 43 utility, 35 calculation, 359 integration and **136 Rust tests**, zero failures; four existing manual benchmarks remain intentionally ignored. After the final benchmark files were integrated, all **72 tooling tests / 10,184 assertions** passed. Extra strict test/script TypeScript, scoped ESLint, rustfmt and diff checks passed. Disposable PostgreSQL/Redis suites passed **58 tests / 345 assertions** before and after integration. Independent debug and integrated release native/worker checks each passed **23 tests / 198 assertions**. These focused tests overlap larger suites. No browser/Python rerun was needed for unchanged boundaries. - -Paired release results below use identical frozen source and addon `d98308d0…`, two fresh processes with two fresh native sessions each, including reversed callback order. Numbers are median **replay/decision/finalization/disposal time**, excluding native construction and benchmark-only oracle/hash work. Bars are total across assets. Preparation/imports, whole-trial time, all phase timings, RSS, hashes and raw report paths are recorded in the manifest. This is synthetic component conformance throughput on a shared host, not durable-job latency or an isolated-host SLA. - -| Total bars | Profile | Assets / owners | Full trace | Compact | Reduction | -| --- | --- | --- | ---: | ---: | ---: | -| 10,000 | No trade | 1 / 1 | 1.142s | 0.744s | 34.9% | -| 10,000 | No trade | 10 / 2 | 0.599s | 0.296s | 50.7% | -| 10,000 | Sparse | 1 / 1 | 1.184s | 0.835s | 29.5% | -| 10,000 | Sparse | 10 / 2 | 0.720s | 0.419s | 41.8% | -| 10,000 | Turnover | 1 / 1 | 2.105s | 1.467s | 30.3% | -| 10,000 | Turnover | 10 / 2 | 2.598s | 1.804s | 30.6% | -| 100,000 | Sparse | 1 / 1 | 11.918s | 8.097s | 32.1% | -| 100,000 | Sparse | 10 / 2 | 7.312s | 4.245s | 41.9% | -| 100,000 | Turnover | 1 / 1 | 21.027s | 14.821s | 29.5% | -| 100,000 | Turnover | 10 / 2 | 26.501s | 18.743s | 29.3% | - -Every selected comparison passed independent economic oracles, complete result repeatability and common financial equality. All six 10k diagnostic hashes also match the historical F07 baseline. That intermediate extended harness's source bodies were not retained, only their hashes, so historical timings are contextual; speedup claims use the final paired source, which is archived with all 21 changed files as measured. Final planning edits follow the measurements; application source remains identical. No 100k no-trade run is claimed. - -At 10k turnover, output falls from **66.7MB to 9.8MB** single and **103.6MB to 19.4MB** multi. At 100k turnover it falls from 672MB/1.044GB to 98.6MB/195.8MB. Full diagnostics remain available; this is an export reduction, not deletion of retained history. Compact 10k advance/submit accounts for 70–88% of run time. Those mixed timers should be profiled before selecting another optimization. Fixture TS decisions take only 0.9–3.5%; these results do not justify a DSL. Compact schema validation and disposal remain measured costs; removing checks or recovery history is not the next step. - -Only the two exact disposable fixture containers and their synthetic data were removed; development services were untouched. Worktrees, logs and measured-source archive remain available. No commits, pushes, PRs, default cutover or trading operation occurred. **Next after acceptance: F08 historical equity/session/exposure and versioned statistics**, with explicit sampling conventions. S01 and product/AI work retain their pending ADR gates; the equal-time multi-asset risk-mark restriction remains unresolved. - -## Thirteenth-wave execution — 2026-10-23 - -F09/P07 were accepted and committed as `e3bd722`, superseding their uncommitted handoff above. [F08](backlog/tasks/F08.md#execution-contract--2026-10-23) is the next code/ADR-ready story. Isolated worktrees start at that commit under `/tmp/stock-bot-wave13.KfvceG/`. - -Root pinned the reporting contract after Rust and quantitative review. One owner implements the native reporting accumulator/wire; a disjoint owner implements reviewed statistics and the additive analytics adapter. The accepted native schema is passed to the consumer before integration. An independent reviewer checks sampling, financial invariants and undefined-statistic handling. - -Account-session samples follow all equal-time observations without changing the earlier risk reset or financial event indexes. Partial session returns remain visible but are excluded from full-period annualized ratios. Exposure counts the union of actual occupied intervals over elapsed calendar time, including open positions through termination. Statistical policy explicitly records annualization/risk-free conventions and unavailable benchmark/round-trip metrics; no hidden 2%/252 defaults are introduced for canonical reports. - -F08 adds a canonical analytics DTO beside the existing result contract. It does not fabricate the legacy DTO's per-position mark/average/P&L fields or infer round trips from fills. R05 retains persisted/public-result migration and default cutover. Existing readers/UI remain compatibility gates. No new financial policy, cache/DSL, journal deletion or unrelated per-step performance change is included. - -**Validated handoff:** F08 is `review` / `validated_uncommitted`. Root integrated all 22 owner files with exact independently reviewed hashes and added a real native → worker → analytics composition test. The planning commit is `1e16445`; no F08 implementation commit has been made. - -- Rust records account-session equity after equal-time observations and unions actual occupied intervals, including open positions at termination. Restore reconstructs the same facts without changing financial event IDs, checkpoints or existing trace/projection output. -- Native `report()` and the existing worker transport expose the versioned facts. The additive TypeScript adapter reuses reviewed calculations with explicit annualization/risk-free policy, partial-period exclusion and nullable unsupported metrics. Shared calculations retain old defaults for old callers; exactly constant returns and zero terminal-equity CAGR now have pinned edge-case tests. -- Repository build, typecheck, contract, audit and lint gates passed, with 72 tooling, 43 utility, 44 calculation and 144 Rust tests. Four existing manual Rust benchmarks remain ignored. The initial integration run exposed missing explicit hold decisions in the new composition fixture; after that test-only correction, **375 integration tests / 3,345 assertions passed**. Strict test TypeScript, scoped ESLint/Prettier/rustfmt and diff checks passed. Disposable PostgreSQL/Redis recovery suites passed **58 tests / 345 assertions** before and after integration. The release addon passed **39 focused native/worker/analytics tests / 703 assertions**. Counts overlap; browser/Python boundaries did not change and those suites were not rerun. - -Release measurements used six synthetic workloads with **10,000 total bars**, one asset/owner or ten assets/two owners, and no-trade/sparse/turnover strategies. The first candidate appeared 33–44% slower than the early baseline, including unchanged TypeScript callback/JSON phases. Shared host load varied materially. A contemporaneous rerun of the exact unchanged F09 release reproduced that slowdown; 128 relevant control source files match `e3bd722`. All complete result and financial hashes agree. Retain both sets of evidence; this is not a speedup claim. - -| Workload | Early F09 median | Contemporaneous F09 control | F08 median | F08 vs control | -| --- | ---: | ---: | ---: | ---: | -| No trade, 1 asset / 1 owner | 722 ms | 1,050 ms | 1,037 ms | −1.2% | -| No trade, 10 assets / 2 owners | 301 ms | 422 ms | 413 ms | −2.2% | -| Sparse, 1 asset / 1 owner | 788 ms | 1,137 ms | 1,125 ms | −1.0% | -| Sparse, 10 assets / 2 owners | 425 ms | 589 ms | 582 ms | −1.3% | -| Turnover, 1 asset / 1 owner | 1,425 ms | 1,994 ms | 2,009 ms | +0.7% | -| Turnover, 10 assets / 2 owners | 1,820 ms | 2,432 ms | 2,426 ms | −0.3% | - -Each median has four fresh-session samples across two processes. A separate counterbalanced comparison of projection/report output passed all **48 sessions**, exact repeated report/analytics hashes and an independent integer-cent oracle. Removing reporting fields and normalizing the format discriminator to `projection` yields the identical complete projection. Report finalization medians were 0.24–6.77 ms higher; analytics took 0.50–1.28 ms. These fixtures have only one partial account period: they measure export/occupancy and minimal analytics, not long histories of session statistics, durable research throughput or empty NAPI cost. There is no demonstrated material replay regression on these workloads, and no stable-host SLA is claimed. - -Raw samples, source/artifact hashes, commands and review evidence are in `manifest.json` → `thirteenth_wave_validation`, with retained files under `/tmp/stock-bot-wave13.KfvceG/`. Only the two exact disposable test containers were stopped; development services were untouched. Source worktrees and logs remain. - -Limits: sampled drawdown is not intraday maximum; marks are last available without per-session freshness certification; benchmark-dependent and round-trip statistics remain null with reasons. Sequential equal-time marks can still latch intermediate risk halts. R05 retains its owner policy gate and public/persisted result cutover. **Next after acceptance: S01 stateful TypeScript strategy decisions**, requiring ADR-005 approval; R01/R11 require ADR-006. No pending decision, default cutover, push, PR or trading operation was implicitly approved. - -## Fourteenth-wave execution — 2026-10-23 - -F08 was accepted and committed as `3838295`, superseding its uncommitted handoff above. S01 is the next satisfied task under ADR-004/005. Isolated runtime and verification worktrees start at that commit under `/tmp/stock-bot-wave14.JYfazy/`; root owns planning/integration and a separate reviewer checks the result. - -[S01's execution contract](backlog/tasks/S01.md#execution-contract--2026-10-23) pins one shared pull loop, typed synchronous state-in/state-out strategy programs, per-owner observation/decision/RNG cursors, atomic staging around native submission and truthful admission feedback. Different strategy cadences must not lose another owner's observations. Rust remains the only financial authority. - -Recovery deliberately follows the current research job boundary: restart the whole attempt from frozen inputs and original initial states/seeds. TS snapshots are diagnostic; no incomplete mid-run resume or new native checkpoint transport. S02 owns the first real strategy and trusted worker composition; S03 preserves durable paper integration, R05 the default/public-result cutover. The active legacy registry, SQL/paper state and web runner remain unchanged. - -**Validated handoff:** S01 is `review` / `validated_uncommitted`. Eight author/verification files were integrated with exact independently reviewed hashes. Root added the permanent author type-test gate. The source bundle and raw logs remain under `/tmp/stock-bot-wave14.JYfazy/`; the manifest owns the precise validation record. - -Callbacks now receive frozen prefix observations, isolated typed state/positions and scoped per-owner randomness. Every due callback uses the same native portfolio view; all next states/intents are staged before admission and all feedback is validated before one committed-state swap. Rejections advance state and carry actual Rust order status. Late callback failures, ambiguous native submissions and malformed feedback dispose the attempt and retain the last confirmed diagnostic state. The original conformance driver uses the same extracted pull loop with unchanged IDs and financial hashes. - -Review caught two boundary defects before integration: unhandled Promise rejections from invalid async callbacks, and empty feedback envelopes accepted by `z.unknown()` fields. Narrow fixes observe actual Promise rejection without awaiting/invoking arbitrary thenables and require present object-valued feedback tags. Regression tests cover both, including foreign-realm Promises and failure after real native admission. No Rust semantics, worker protocol, SQL or legacy registry implementation changed. - -Full `CARGO_BUILD_JOBS=2 bun run check` passed build/typecheck/contracts/audit/lint plus **78 tooling, 43 utility, 44 calculation, 390 integration and 144 Rust tests**, with four existing manual Rust measurements ignored. Extra strict test TypeScript, scoped ESLint/Prettier and diff checks passed. The initial temporary strict config lacked its root-relative Bun type lookup; fixing that external config resolved it without source changes. Disposable PostgreSQL/Redis suites passed **58 tests / 345 assertions**; final release tests passed **43 tests / 568 assertions**. Independent native verification contributed 15 scenarios / 249 assertions, overlapping the integrated totals. Browser and Python boundaries did not change and those suites were not rerun. - -The unchanged conformance CLI passed all six 10k workloads with identical complete result/economic hashes and the same release native artifact as F08. Historical wall-time changes track shared-host load; they are not an extraction speedup claim. A separate counterbalanced benchmark compared stateful programs with **replay of their exact captured decisions**, including IDs. This avoids treating different identity/payload sizes as callback cost. - -| 10,000 total bars | Recorded decisions | Stateful programs | Added wall time | -| --- | ---: | ---: | ---: | -| No trade, 1 asset / 1 owner | 861 ms | 949 ms | 88 ms / 10.3% | -| No trade, 10 assets / 2 owners | 357 ms | 372 ms | 14 ms / 4.0% | -| Sparse, 1 asset / 1 owner | 908 ms | 1,050 ms | 143 ms / 15.7% | -| Sparse, 10 assets / 2 owners | 511 ms | 527 ms | 16 ms / 3.1% | -| Turnover, 1 asset / 1 owner | 1,569 ms | 1,881 ms | 313 ms / 19.9% | -| Turnover, 10 assets / 2 owners | 1,925 ms | 2,212 ms | 287 ms / 14.9% | - -All **48 timed sessions** match complete financial hashes; repeated/reversed program order preserves diagnostic state/RNG hashes. Each fresh child first captures a reference trace, so timed sessions are in a warmed process. Medians have four samples per mode. Wall time includes construction, state validation/staging, callbacks, admission feedback, finalization and disposal; post-run oracle/hash work is separate. Each callback updates four scalar fields and draws once. This is neither pure callback overhead nor complex-strategy, database/queue or cold-start throughput. The measured 3.1–19.9% overhead is retained as a profiling baseline, without removing correctness checks or introducing a DSL/cache. - -Only the two exact disposable fixture containers were stopped; development services were untouched. Worktrees, archives and measurements remain. **Next after acceptance: S02**, port one SMA strategy and wire its explicit trusted version into the existing worker. Its handoff distinguishes indicator state reconstruction from unsupported native mid-run resume. R05 still owns durable/public-result activation; paper migration and other pending decisions remain separately gated. No S01 commit, push, PR or trading operation occurred. - -## Fifteenth-wave execution — 2026-10-23 - -S01 is accepted and committed as `2bcadbd`, superseding its uncommitted handoff above. S02 now has satisfied prerequisites. Isolated strategy and worker worktrees start at that commit under `/tmp/stock-bot-wave15.zi3GmP/`; root owns integration and a separate reviewer checks both changes. - -[S02's pinned contract](backlog/tasks/S02.md#execution-contract--2026-10-23) defines an explicit long-only SMA version with reviewed crossover arithmetic, owner-budget whole-share sizing, prefix-safe history and native freshness checks. The existing worker accepts only reviewed built-in selections and binds returned strategy provenance to the captured request. Legacy readers/factories, financial Rust semantics and active web/paper paths stay intact. No generic registry, source-code transport, feature framework or incomplete checkpoint resume is introduced. - -S03 is code/ADR-ready but outside this wave. R05 retains durable canonical/default activation and its multi-asset policy gate; R01/R11 require ADR-006. No pending policy was implicitly approved. - -**Validated handoff:** S02 is `review` / `validated_uncommitted`. Ten integrated source/test files match the independently reviewed hashes. `sma-crossover-long-only/v1` uses the existing aliases and reviewed crossover helper, exact whole-share budget sizing, bounded JSON state and explicit availability/freshness rules. The legacy long/short strategy stays intact. The existing child worker locally runs trusted programs over the canonical Rust session; the parent detaches input and checks exact effective selections plus native identity/policy/format. No callback source, module path, TS financial engine or default/paper activation was added. - -The independent next-open fixture buys ten shares at5 and sells at2, with0.7 total fees and9969.3 terminal equity from10000. Further tests cover warmup entry sizing, delayed older bars, equality, stale inputs, unaffordable fees/gaps, same-order partial fills, owner attribution, JSON reconstruction and full retry. Worker tests reject altered provenance/economics, malformed/duplicate output and crashes, and preserve hard cancellation even after a result arrives before child close. - -`CARGO_BUILD_JOBS=2 bun run check` passed build/types/contracts/audit/lint plus **78 tooling, 43 utility, 44 calculation, 432 integration and 144 Rust tests**; four existing manual Rust measurements remain ignored. Dedicated test/fixture strict TypeScript and scoped lint/format/diff checks passed. Disposable PostgreSQL/Redis: **58 tests /345 assertions**. Final release tests: **48 /175**. Built `dist/native-worker.js` matches direct execution in trace, projection and report formats. Browser/Python boundaries did not change and were not rerun. - -The worker owner's second elevated test run waited for approval and was aborted; root took over final validation after an explicit handoff. Root's restricted IPC run also stalled and was stopped, then passed unrestricted. Fixture correction uses a mutable detached dataset for the mutation test; schema `.min(1)` retains runtime nonempty validation without requiring a tuple input type. No economic failure was hidden by those environment/type corrections. Only the two exact disposable test containers were stopped. - -The unchanged release addon is `6fe9dae…`. A paired benchmark compares actual SMA programs with replay of their **exact captured decisions**, including IDs. All **48 timed sessions** preserve complete financial hashes; repeated/reversed program order preserves diagnostics. - -| 10,000 total bars | Recorded decisions | SMA callbacks | Added wall time | -| --- | ---: | ---: | ---: | -| SMA5/15, 1 asset /1 owner | 1,091 ms | 1,467 ms | 376 ms /34.5% | -| SMA5/15, 10 assets /2 owners | 410 ms | 478 ms | 69 ms /16.8% | -| SMA5/15, 10 assets /10 owners | 624 ms | 916 ms | 292 ms /46.8% | -| SMA15/252, 1 asset /1 owner | 1,018 ms | 2,351 ms | 1,333 ms /130.9% | -| SMA15/252, 10 assets /2 owners | 409 ms | 636 ms | 227 ms /55.5% | -| SMA15/252, 10 assets /10 owners | 594 ms | 1,681 ms | 1,087 ms /183.1% | - -Each median has four samples across two processes, after an untimed reference capture. Imports/preparation are separate. Ten-assets/two-owners trades only two assets; the other eight still replay. Single-asset runs have9999 decisions and10000 advance calls; ten-assets/two-owners has1998 decisions/1000 calls, and ten-owners has9990 decisions/1000 calls. Warmup proportions and fills also differ. Cross-shape ratios do not isolate scaling. This is warmed direct-runtime throughput, not durable jobs, worker IPC, pure callbacks or NAPI cost; no speedup is claimed for S02. - -The long-window decision/state phase accounts for roughly51–62% of wall time in the owner-dense cases, but cloning, freezing, schema validation, trailing calculation and allocation costs are not yet separated. [P08](backlog/tasks/P08.md) is the recommended next task **after S02 acceptance**, to profile and reduce that measured cost while preserving all strict-state and financial invariants. It is planned, not started. Immutable code artifacts remain R01/R05 work; no label-only reproduction guarantee is claimed. All raw evidence, exact commands, source archive and hashes are in `manifest.json` → `fifteenth_wave_validation` and `/tmp/stock-bot-wave15.zi3GmP/`. No new implementation commit, push, PR 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. diff --git a/docs/development/architecture/decisions/005-durable-cutover.md b/docs/development/architecture/decisions/005-durable-cutover.md index 2762c2ec..f26dee7a 100644 --- a/docs/development/architecture/decisions/005-durable-cutover.md +++ b/docs/development/architecture/decisions/005-durable-cutover.md @@ -1,6 +1,6 @@ # ADR-005 — Shared kernel, distinct persistence boundaries -Status: **approved by owner continuation, 2026-10-23**. After the handoff named S01 and linked this pending decision, the owner instructed “commit all of it and continue.” This approves the documented direction for the next task; paper migration/default activation remain separately gated. Preservation of existing recovery is required. +Status: proposed for approval; preservation of existing recovery is required. ## One implementation @@ -23,7 +23,3 @@ All currently supported paper order policies must be preserved or a migration ex C06 contains unsafe legacy research/paper composition; it does not build a temporary second worker framework. F02 builds owner accounting once. S03 adopts the kernel and durable recovery without waiting for Sharpe/Sortino or web pages. S04 verifies paper feed/readiness. S06 retires competing active execution after those gates, retaining result readers/research algorithms. Compare financial transitions for the **same event and intent trace**. Research and paper receive different real-world prices/availability; identical P&L is not promised for different inputs. Broker fills remain future external facts to reconcile, not simulated orders that can be rejected after occurrence. - -## S01 retry scope - -The existing durable research runner retries whole attempts. S01 follows that boundary: create a fresh native session from frozen data/configuration, clone original strategy states and restore original per-owner seeds, then recompute observations, decisions and RNG cursors. Per-barrier TypeScript diagnostic snapshots are not independently resumable financial checkpoints. Do not add a native checkpoint wire or accept a TS-only mid-run resume merely for S01. Existing Rust checkpoint reconstruction and paper SQL checkpoints remain preserved; S03 owns their durable integration. diff --git a/docs/development/backlog/README.md b/docs/development/backlog/README.md index 0534a708..57080d2f 100644 --- a/docs/development/backlog/README.md +++ b/docs/development/backlog/README.md @@ -1,12 +1,12 @@ # Canonical development backlog -**First fourteen waves committed; S02 is validated and awaiting acceptance.** S01 is accepted as `2bcadbd`; `4f6e44a` records acceptance and the S02 contract. S02 adds one explicit long-only SMA version and trusted selection through the existing native worker. Consult manifest execution_scope and [current wave](../ROADMAP.md#fifteenth-wave-execution--2026-10-23). ADR-002/003/004/005 are approved; other policies/default cutovers remain gated. +**First eleven waves reviewed, validated and committed.** F07 was accepted and committed as `e3635f2`. Consult manifest execution_scope, [ROADMAP](../ROADMAP.md), [skeptical review](../REVIEW.md) and [first-wave handoff](../FIRST-WAVE.md). ADR-002/003/004 are approved. Other tasks/policies remain gated; the latest performance question does not authorize implementation. ## One source of truth [manifest.json](manifest.json) owns scheduling metadata: status, priorities, dependencies, ADR approvals, assignments and write locks. Task Markdown owns implementation scope/evidence/acceptance. This index and the [graph](dependencies.mmd) are derived views. Only the planning/integration owner updates scheduling state. -**46 scheduled + 5 deferred + 4 merged IDs = 55 retained IDs.** F09/P07 add projection/profiling work; P08 follows measured TypeScript strategy overhead. Merged records preserve traceability; never execute them separately. Deferred work requires its stated trigger and explicit activation. +**43 scheduled + 5 deferred + 4 merged IDs = 52 retained IDs.** Merged records preserve traceability; never execute them separately. Deferred work requires its stated trigger and explicit activation. States: ready, claimed, in_progress, review, done, blocked, deferred, merged. “Ready” means no code/ADR prerequisite, not execution authority. Implementation dependencies require accepted integration. `release_gates` govern enabling an end-to-end feature, not component coding or integration; conditional gates apply only to the named capability. F05 may integrate before F06, but its replay behavior is not released until F06 proves it. @@ -36,8 +36,7 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr | [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 / done | F05, D01, P01, ADR-003 | — | Rust deterministic replay / M | | [F07 Expose bounded Rust step sessions through existing NAPI workers](tasks/F07.md) | P0 / done | F06, C02, ADR-004 | — | Rust/TypeScript integration / M | -| [F08 Publish canonical metrics and versioned result projections](tasks/F08.md) | P1 / done | F06, F09, ADR-002, ADR-003 | — | Quant analytics/Rust integration / M | -| [F09 Return compact canonical replay projections](tasks/F09.md) | P1 / done | F07, ADR-002, ADR-003, ADR-004 | — | Rust/TypeScript financial 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 @@ -52,9 +51,9 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr | Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size | | --- | --- | --- | --- | --- | -| [S01 Run deterministic TypeScript decisions on Rust sessions](tasks/S01.md) | P0 / done | F07, ADR-004, ADR-005 | — | TypeScript trading infrastructure / M | -| [S02 Adapt one SMA strategy for the first canonical path](tasks/S02.md) | P1 / review | S01 | — | TypeScript strategy/quant engineering / M | -| [S03 Adapt durable paper transactions to Rust financial reducers](tasks/S03.md) | P0 / ready | S01, C06, ADR-005 | — | Durable execution/Rust integration / L | +| [S01 Run deterministic TypeScript decisions on Rust sessions](tasks/S01.md) | P0 / blocked | F07, ADR-004, ADR-005 | — | TypeScript trading infrastructure / M | +| [S02 Adapt one SMA strategy for the first canonical path](tasks/S02.md) | P1 / blocked | S01 | — | TypeScript strategy/quant engineering / M | +| [S03 Adapt durable paper transactions to Rust financial reducers](tasks/S03.md) | P0 / blocked | S01, C06, ADR-005 | — | Durable execution/Rust integration / L | | [S04 Establish a verified paper feed and operator safety gate](tasks/S04.md) | P1 / blocked | S02, S03 | — | TypeScript trading infrastructure / M | | [S05 Add a small composable multi-signal regime example](tasks/S05.md) | P2 / blocked | S02, F08 | R08 | Quant strategy research / M | | [S06 Retire duplicate simulator paths after cutover proof](tasks/S06.md) | P2 / blocked | S03, S04, R05 | — | TypeScript trading infrastructure / M | @@ -95,8 +94,6 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr | [P04 Schedule deterministic batches across a bounded worker pool](tasks/P04.md) | P2 / blocked | F07, R06, C06, P01, ADR-008 | — | Performance/infrastructure engineering / M | | [P05 Separate result summaries from paged detail payloads](tasks/P05.md) | P2 / deferred | R06, P01 | — | Performance/infrastructure engineering / M | | [P06 Conditionally add a minimal Rust-executed strategy plan](tasks/P06.md) | P2 / deferred | P04, S01, ADR-008 | — | Rust/TS performance compiler boundary / M | -| [P07 Profile representative canonical replay workloads](tasks/P07.md) | P1 / done | F07, P01 | F09 for compact comparisons | Performance/test infrastructure / M | -| [P08 Reduce measured TypeScript strategy decision overhead](tasks/P08.md) | P1 / blocked | S02, P07 | — | TypeScript performance/runtime engineering / M | ### E8 — Authorized, isolated AI research @@ -118,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 fourteen waves are committed. **S02 is independently reviewed and validated, with new implementation changes uncommitted.** Recommended next after acceptance: P08, profile and reduce the measured TypeScript strategy decision/state overhead. S03 is also code/ADR-ready. R01/R11 still need ADR-006; the multi-asset mark-policy gate still blocks default activation. No P08 implementation, new S02 commit, push, PR or trading operation is included in this continuation. +The first eleven waves are independently reviewed, validated and committed with owner approval; see the [eleventh-wave handoff](../ROADMAP.md#eleventh-wave-handoff--2026-10-23) and manifest evidence. Next recommended: **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. diff --git a/docs/development/backlog/dependencies.mmd b/docs/development/backlog/dependencies.mmd index 168e6013..dffb7091 100644 --- a/docs/development/backlog/dependencies.mmd +++ b/docs/development/backlog/dependencies.mmd @@ -15,7 +15,6 @@ flowchart TD F06["F06: Implement deterministic replay once, with linear historical traversal"] F07["F07: Expose bounded Rust step sessions through existing NAPI workers"] F08["F08: Publish canonical metrics and versioned result projections"] - F09["F09: Return compact canonical replay projections"] end subgraph E3["E3: Point-in-time datasets and features"] D01["D01: Introduce availability-aware dataset v2"] @@ -56,8 +55,6 @@ flowchart TD P04["P04: Schedule deterministic batches across a bounded worker pool"] P05["P05: Separate result summaries from paged detail payloads (conditional)"] P06["P06: Conditionally add a minimal Rust-executed strategy plan (conditional)"] - P07["P07: Profile representative canonical replay workloads"] - P08["P08: Reduce measured TypeScript strategy decision overhead"] end subgraph E8["E8: Authorized, isolated AI research"] A01["A01: Add research-only principals and durable job budgets"] @@ -89,13 +86,8 @@ flowchart TD C02 --> F07 ADR004 --> F07 F06 --> F08 - F09 --> F08 ADR002 --> F08 ADR003 --> F08 - F07 --> F09 - ADR002 --> F09 - ADR003 --> F09 - ADR004 --> F09 ADR003 --> D01 D01 --> D02 S01 --> D04 @@ -177,11 +169,6 @@ flowchart TD P04 --> P06 S01 --> P06 ADR008 --> P06 - F07 --> P07 - P01 --> P07 - F09 -. compact comparisons only .-> P07 - S02 --> P08 - P07 --> P08 R06 --> A01 O01 --> A01 ADR007 --> A01 diff --git a/docs/development/backlog/manifest.json b/docs/development/backlog/manifest.json index 101306e2..abc5ae05 100644 --- a/docs/development/backlog/manifest.json +++ b/docs/development/backlog/manifest.json @@ -1,16 +1,15 @@ { "schema_version": 1, - "plan_revision": "2026-10-23.34", + "plan_revision": "2026-10-23.26", "repository_base": "b7aeca4", - "plan_status": "fifteenth_wave_in_review", + "plan_status": "eleventh_wave_committed", "execution_authorized": true, "execution_scope": { - "authorized_by": "User: commit and continue (2026-10-23), after S01 validated handoff named S02. S01 accepted and committed as 2bcadbd. Continue only S02 under approved ADR-002/003/004/005.", + "authorized_by": "User: commit and continue (2026-10-22), authorizing the F06 commit and proposed F07 continuation", "tasks": [ - "S02" + "F07" ], "permissions": [ - "accepted_wave14_commits", "isolated_implementation", "local_tests", "local_integration_review", @@ -21,10 +20,10 @@ "push", "pull_requests", "live_or_paper_operations", - "default_engine_cutover", "other_backlog_tasks" ], "pending_policy_decisions": [ + "ADR-005", "ADR-006", "ADR-007", "ADR-008" @@ -61,9 +60,7 @@ { "id": "ADR-005", "file": "architecture/decisions/005-durable-cutover.md", - "status": "approved", - "approved_by": "Owner instructed commit all of it and continue after handoff explicitly named S01 and linked pending ADR-005; direction approved, paper migration/default activation remain separate.", - "approved_on": "2026-10-23" + "status": "proposed_for_plan_approval" }, { "id": "ADR-006", @@ -641,11 +638,7 @@ "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" - ], + "reviewed_by": ["/root/wave11_boundary_review", "/root/wave11_data_review", "/root"], "verification_reference": "ROADMAP.md#eleventh-wave-handoff--2026-10-23", "accepted_by": "Owner: commit everything (2026-10-23). Performance assessment requested; no optimization implementation authorized." }, @@ -655,10 +648,9 @@ "epic": "E2", "priority": "P1", "severity": "High", - "status": "done", + "status": "ready", "dependencies": [ - "F06", - "F09" + "F06" ], "decision_dependencies": [ "ADR-002", @@ -672,98 +664,15 @@ "complexity": "M", "specialization": "Quant analytics/Rust integration", "write_locks": [ - "result-contract", - "native-public-api", - "replay-reporting", - "canonical-analytics", - "calculation-statistics" - ], - "parallel_policy": "One native/reporting-wire owner; disjoint analytics/calculation owner consumes root-accepted frozen wire schema. No independent financial contract reinterpretation. Root owns integration/planning.", - "assignment": "/root/f08_contract_review", - "branch": "wave13/f08-reporting", - "pull_request": null, - "completed_commit": "3838295eec8e84a46115462ca6c5d5c8c7fab66b", - "blocker": null, - "release_gates": [], - "worktree": "/tmp/stock-bot-wave13.KfvceG/f08", - "integration_base": "e3bd722e31a4e14519df543d87affd90a8103fa2", - "integration_state": "validated_committed", - "implementation_slices": [ - { - "owner": "/root/f08_contract_review", - "scope": "Rust reporting accumulator, replay hooks, native API, strict TS native/worker contract and focused tests", - "worktree": "/tmp/stock-bot-wave13.KfvceG/f08", - "branch": "wave13/f08-reporting" - }, - { - "owner": "/root/f08_benchmark_plan", - "scope": "Additive shared canonical analytics types, reviewed statistics policy extension, pure report adapter and focused tests", - "worktree": "/tmp/stock-bot-wave13.KfvceG/f08-analytics", - "branch": "wave13/f08-analytics" - } - ], - "review_notes": "Independent reviews accepted native/reporting and analytics slices. 22 owner files integrated with exact hashes plus root native/worker/analytics composition tests. Repository gates, disposable recovery and release comparisons pass; shared-host drift checked against unchanged release control. Financial event IDs/checkpoints/trace/projection and legacy paths retained. See thirteenth_wave_validation; R05 owns persisted/public-result cutover.", - "reviewed_by": [ - "/root/wave12_review", - "/root" - ], - "verification_reference": "ROADMAP.md#thirteenth-wave-execution--2026-10-23", - "accepted_by": "Owner: commit all of it and continue (2026-10-23). Accepted source hashes reverified before commit 3838295." - }, - { - "id": "F09", - "title": "Return compact canonical replay projections", - "epic": "E2", - "priority": "P1", - "severity": "High", - "status": "done", - "dependencies": [ - "F07" - ], - "decision_dependencies": [ - "ADR-002", - "ADR-003", - "ADR-004" - ], - "task_file": "backlog/tasks/F09.md", - "findings": [ - "PER-01", - "FIN-05", - "KEEP-02" - ], - "complexity": "M", - "specialization": "Rust/TypeScript financial integration", - "write_locks": [ - "financial-projection", - "native-public-api", - "worker-protocol", "result-contract" ], - "parallel_policy": "One owner of financial/result/native/TS contract. P07 benchmark-only files are disjoint. No independent interpretation of reporting/financial semantics.", - "assignment": "/root/f08_contract_review", - "branch": "wave12/f09-compact-results", - "worktree": "/tmp/stock-bot-wave12.F9Rlh4/f09", - "integration_base": "19e9dad", - "integration_state": "validated_committed", + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, "pull_request": null, - "completed_commit": "e3bd722e31a4e14519df543d87affd90a8103fa2", + "completed_commit": null, "blocker": null, - "release_gates": [], - "concrete_write_scope": [ - "apps/stock/engine/src/financial/result.rs and result_tests.rs", - "apps/stock/engine/src/financial/ledger.rs (read-only receipts/valuation serialization only)", - "apps/stock/engine/src/financial/mod.rs", - "apps/stock/engine/src/api/replay.rs", - "apps/stock/orchestrator/src/contracts/native-replay.ts", - "apps/stock/orchestrator/src/backtest/native-replay.ts", - "apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts", - "apps/stock/orchestrator/src/backtest/native-worker.ts and native-worker-protocol.ts if needed", - "test/integration/native-replay*.test.ts", - "test/fixtures/native-replay*", - "scripts/test/native-bindings.test.ts" - ], - "review_notes": "Independent frozen-artifact review, exact root integration, full checks, disposable recovery tests and paired release comparisons passed. Optional compact projection preserves financial semantics/full diagnostic hashes; no default cutover or journal deletion. See twelfth_wave_validation. Owner accepted and authorized commit e3bd722 on 2026-10-23.", - "verification_reference": "ROADMAP.md#twelfth-wave-handoff--2026-10-23" + "release_gates": [] }, { "id": "D01", @@ -911,7 +820,7 @@ "epic": "E4", "priority": "P0", "severity": "Critical", - "status": "done", + "status": "blocked", "dependencies": [ "F07" ], @@ -929,39 +838,15 @@ "specialization": "TypeScript trading infrastructure", "write_locks": [ "strategy-contract", - "replay-driver", - "native-admission-feedback" + "worker-protocol" ], - "parallel_policy": "One runtime/native-feedback contract owner; disjoint verification owner consumes the pinned contract. Root owns metadata/integration; independent reviewer is read-only. No worker request or financial-engine change.", - "assignment": "/root/s01_contract", - "branch": "wave14/s01-runtime", + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, "pull_request": null, - "completed_commit": "2bcadbd117c288577a26615e6d132cf49ea074e4", + "completed_commit": null, "blocker": null, - "release_gates": [], - "worktree": "/tmp/stock-bot-wave14.JYfazy/s01", - "integration_base": "3838295eec8e84a46115462ca6c5d5c8c7fab66b", - "integration_state": "validated_committed", - "implementation_slices": [ - { - "owner": "/root/s01_contract", - "scope": "Typed strategy contract, shared pull driver, staged per-owner runtime, native admission-feedback parser and focused tests", - "worktree": "/tmp/stock-bot-wave14.JYfazy/s01", - "branch": "wave14/s01-runtime" - }, - { - "owner": "/root/s01_test_review", - "scope": "Disjoint real-native multi-owner failure/retry/integrity tests and measured strategy fixture after pinned API handoff", - "worktree": "/tmp/stock-bot-wave14.JYfazy/verification", - "branch": "wave14/s01-verification" - } - ], - "review_notes": "Exact eight-file integration independently reviewed; root added permanent author type gate. Full repository, disposable recovery and release checks passed. Whole-attempt retry, mixed cadence, staged owner state/RNG and native admission feedback verified. Rejected Promise cleanup and missing envelope tags fixed before acceptance. Paired 48-session measurement preserves exact economic identities; see fourteenth_wave_validation. Trusted direct programs only; S02/S03/R05 own later worker/paper/default integration. Owner accepted and authorized commit on 2026-10-23.", - "reviewed_by": [ - "/root/s01_final_review", - "/root" - ], - "verification_reference": "ROADMAP.md#fourteenth-wave-execution--2026-10-23" + "release_gates": [] }, { "id": "S02", @@ -969,7 +854,7 @@ "epic": "E4", "priority": "P1", "severity": "High", - "status": "review", + "status": "blocked", "dependencies": [ "S01" ], @@ -982,52 +867,15 @@ "complexity": "M", "specialization": "TypeScript strategy/quant engineering", "write_locks": [ - "strategy-builtins", - "worker-protocol" + "strategy-builtins" ], - "parallel_policy": "Disjoint strategy/schema and worker owners; worker consumes root-accepted selection overlay. Root owns planning/integration; independent review controls acceptance.", - "assignment": "/root/s02_strategy", - "branch": "wave15/s02-strategy", + "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", + "assignment": null, + "branch": null, "pull_request": null, "completed_commit": null, "blocker": null, - "release_gates": [], - "worktree": "/tmp/stock-bot-wave15.zi3GmP/strategy", - "integration_base": "2bcadbd117c288577a26615e6d132cf49ea074e4", - "integration_state": "validated_uncommitted", - "implementation_slices": [ - { - "owner": "/root/s02_strategy", - "scope": "Strict trusted selection and versioned long-only SMA with dedicated tests", - "worktree": "/tmp/stock-bot-wave15.zi3GmP/strategy", - "branch": "wave15/s02-strategy" - }, - { - "owner": "/root/s02_worker", - "scope": "Additive trusted worker request/result supervision with dedicated tests", - "worktree": "/tmp/stock-bot-wave15.zi3GmP/worker", - "branch": "wave15/s02-worker", - "integration_handoff": "Root imported six-file draft after explicit takeover authorization, corrected nonempty-array input typing and readonly expected test arrays, and completed all validation. Worker owner made no concurrent edits." - } - ], - "reviewed_by": [ - "/root/s02_review", - "/root" - ], - "verification_reference": "ROADMAP.md#fifteenth-wave-execution--2026-10-23", - "review_notes": "All ten source/test files independently approved with exact hashes. Full repository, strict test types/lint/format, disposable recovery, release and built-worker parity gates passed. Long-only policy differs explicitly from legacy; R01/R05 retain artifact and durable/public cutover. Paired 48-session exact-decision benchmark identifies aggregate strategy/state overhead; P08 planned only. Root finished worker validation after owner tool approval stalled; no new source semantics changed during takeover.", - "concrete_write_scope": [ - "apps/stock/orchestrator/src/contracts/builtin-strategy.ts", - "apps/stock/orchestrator/src/strategies/canonical-sma.ts", - "apps/stock/orchestrator/src/contracts/strategy-replay.ts", - "apps/stock/orchestrator/src/backtest/native-worker-protocol.ts", - "apps/stock/orchestrator/src/backtest/native-worker.ts", - "apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts", - "test/fixtures/canonical-sma.ts", - "test/integration/canonical-sma.test.ts", - "test/integration/canonical-strategy-worker.test.ts", - "test/fixtures/canonical-strategy-worker.ts" - ] + "release_gates": [] }, { "id": "S03", @@ -1035,7 +883,7 @@ "epic": "E4", "priority": "P0", "severity": "Critical", - "status": "ready", + "status": "blocked", "dependencies": [ "S01", "C06" @@ -1944,84 +1792,6 @@ "blocker": "Owner go/no-go after representative profiling and explicit prototype budget; no fixed 20%/1.5x magic thresholds.", "release_gates": [] }, - { - "id": "P07", - "title": "Profile representative canonical replay workloads", - "epic": "E7", - "priority": "P1", - "severity": "High", - "status": "done", - "dependencies": [ - "F07", - "P01" - ], - "decision_dependencies": [], - "task_file": "backlog/tasks/P07.md", - "findings": [ - "PER-01" - ], - "complexity": "M", - "specialization": "Performance/test infrastructure", - "write_locks": [ - "benchmark-harness" - ], - "parallel_policy": "Baseline profiles compile against committed F07 and can run independently of F09. Compact-mode consumption waits for root-accepted F09 contract overlay; do not edit adapter/native/schema files.", - "assignment": "/root/f08_benchmark_plan", - "branch": "wave12/p07-replay-profiling", - "worktree": "/tmp/stock-bot-wave12.F9Rlh4/p07", - "integration_base": "19e9dad", - "integration_state": "validated_committed", - "pull_request": null, - "completed_commit": "e3bd722e31a4e14519df543d87affd90a8103fa2", - "blocker": null, - "release_gates": [], - "conditional_release_gates": [ - { - "when": "Paired compact/diagnostic measurements are enabled", - "tasks": [ - "F09" - ] - } - ], - "concrete_write_scope": [ - "scripts/benchmark-replay.ts", - "scripts/benchmark-research.ts", - "scripts/test/benchmark-replay.test.ts" - ], - "review_notes": "Independent financial-normalizer and measurement/provenance reviews passed; final 72-tooling gate and strict test types/lint passed. Paired final-source release benchmarks cover all three 10k profiles and sparse/turnover at 100k. Historical baseline source-retention limitation is explicit; measured final source is archived. Owner accepted and authorized commit e3bd722 on 2026-10-23.", - "verification_reference": "ROADMAP.md#twelfth-wave-handoff--2026-10-23" - }, - { - "id": "P08", - "title": "Reduce measured TypeScript strategy decision overhead", - "epic": "E7", - "priority": "P1", - "severity": "High", - "status": "blocked", - "dependencies": [ - "S02", - "P07" - ], - "decision_dependencies": [], - "task_file": "backlog/tasks/P08.md", - "findings": [ - "PER-02" - ], - "complexity": "M", - "specialization": "TypeScript performance/deterministic runtime engineering", - "write_locks": [ - "strategy-contract", - "strategy-builtins", - "benchmark-harness" - ], - "parallel_policy": "One runtime/strategy optimization owner. Disjoint review may proceed; actual file overlap with S03/S05 or benchmark work blocks concurrency. Scope exact files before edits.", - "assignment": null, - "branch": null, - "pull_request": null, - "completed_commit": null, - "blocker": "Requires S02 acceptance/commit and explicit next-wave authorization. Profile subphase costs before choosing a local optimization; preserve current contracts and all invariants.", - "release_gates": [] - }, { "id": "A01", "title": "Add research-only principals and durable job budgets", @@ -3742,7 +3512,7 @@ "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 \u00d72fresh 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.", + "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": [ @@ -4084,1786 +3854,5 @@ ], "cleanup": "Stopped/removed only disposable containers4843a8d42953aefac9c323ff0a8913f0d5e0c39dd862273f149c1ba9cfc3bf63 and4a518cf5400aef08eae49e029d1ddd6649d3af152e051f17bc5fbc082e2a9915, deleting recreatable synthetic fixture state. Development services untouched; worktree/logs retained.", "handoff": "F06 committed417a7bd. Owner accepted and committed reviewed F07 as e3635f2 on2026-10-23. F08 remains ready by existing code/approved ADR prerequisites, not authorized yet. S01 needs ADR005. Latest performance question authorizes assessment, not optimization implementation. No push, PR, default-engine activation or paper/live operation." - }, - "twelfth_wave": [ - "F09", - "P07" - ], - "twelfth_wave_base": "19e9dad68be9a06d1e9cd86cc27112c5dc8a4aa2", - "twelfth_wave_notes": [ - "Two focused stories created and implemented: F09 read-only terminal valuation/actual owned fills, and P07 representative profiling. F08 retains historical equity/session/exposure/statistical policy work.", - "Exact frozen financial source accepted after independent review, then overlaid into the isolated benchmark worktree. Two disjoint implementation owners; coordinated native/worker/result authority.", - "Full diagnostic finalize/defaults unchanged; optional project uses existing ledger valuation and committed effects, skips aliases, preserves gross cashDelta with separate fee and signed owner contributions. Internal journals/idempotency/restore unchanged.", - "Independent reviews covered failure-state proof, repeated byte-identical projection, format/cancellation guards, shared financial hashing, all alias levels and 200k-fill argument-limit regression. All code integrated with matching reviewed hashes.", - "All selected 10k and 100k paired release measurements passed. Result comparisons use shared terminal state/actual fills without synthesizing LedgerValuation in TypeScript.", - "F09/P07 await owner acceptance/commit. F08 follows after acceptance; S01/product work retain pending ADR gates. No default-engine switch, new financial/risk policy, paper/live operation, commit, push or PR." - ], - "twelfth_wave_validation": { - "base": "19e9dad", - "worktreeRoot": "/tmp/stock-bot-wave12.F9Rlh4", - "check": { - "status": "passed", - "tooling": 63, - "utility": 43, - "calculations": 35, - "integration": 359, - "rust": 136, - "rustIgnoredManual": 4, - "log": "/tmp/stock-bot-wave12.F9Rlh4/integration-check.log" - }, - "database": { - "baseline": { - "tests": 58, - "assertions": 345, - "log": "/tmp/stock-bot-wave12.F9Rlh4/baseline-postgres.log" - }, - "integrated": { - "tests": 58, - "assertions": 345, - "log": "/tmp/stock-bot-wave12.F9Rlh4/integration-postgres.log" - }, - "cleanup": "Stopped exact two disposable container IDs after success; --rm removes only recreated fixture data. Development services untouched." - }, - "release": { - "sha256": "d98308d0af80c225f2ee631d5e68065fa762073619a8b5cf6f3681ba0f1d5dd6", - "addonMatchesLibrary": true, - "tests": 23, - "assertions": 198, - "log": "/tmp/stock-bot-wave12.F9Rlh4/integration-release-focused.log" - }, - "independentReview": { - "agent": "/root/wave12_review", - "tests": 23, - "assertions": 198, - "artifact": "edabf1a0410df3bec29bc0d8e3a9301e4adb77b61b7bf6bc7363b9090d8308c0", - "notes": "Exact owner debug artifact; worker IPC required escalated rerun, then all passed. No source blocker." - }, - "final_tooling": { - "tests": 72, - "assertions": 10184, - "log": "/tmp/stock-bot-wave12.F9Rlh4/integration-tooling-final.log", - "notes": "After final benchmark integration; the preceding full check used 63 tooling cases. No financial/source rebuild or edits occurred during measurements." - }, - "extra_checks": { - "strict_types": "/tmp/stock-bot-wave12.F9Rlh4/integration-extra-types-final.log", - "lint": "/tmp/stock-bot-wave12.F9Rlh4/integration-benchmark-lint.log", - "f09_lint": "/tmp/stock-bot-wave12.F9Rlh4/integration-extra-lint.log", - "scoped_rustfmt": "passed", - "diff_check": "passed" - }, - "reviewed_source_sha256": { - "apps/stock/engine/src/api/replay.rs": "ae5866616773726e0151525f45c5f1ee20a73b1544c7e4f79681727d435602b6", - "apps/stock/engine/src/financial/ledger.rs": "52b46bdedd90f81f3bbf642ff395268dfeb2dcd65906587738e9026649f046e9", - "apps/stock/engine/src/financial/mod.rs": "c849a85703370bc72a1861a9a2497be4635e972d76cb949aff1980240fa7feb1", - "apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts": "8c339ac2b70074b7c4f0627b325f94b1346c697f13ffa8c47988252e97e7d9ce", - "apps/stock/orchestrator/src/backtest/native-replay.ts": "b6b4284904fd6d40185a8b6e8e42804d1e0360ebfdc9544db7bd0d0960ef7eaf", - "apps/stock/orchestrator/src/contracts/native-replay.ts": "1d79c3a582b59f94d07f883e30f1cfb6433123e3e74701dc31e50925367ff43d", - "scripts/test/native-bindings.test.ts": "8e6427a9c9b560b38c660330d10a09ddd36aefdf6cdd611d5b4480593eeff4ba", - "test/fixtures/native-replay-worker.ts": "f1f011c876c8b1fa4b1b871d46a3ba8dbea25899e0dea71d4c3e54b2b0202279", - "apps/stock/engine/src/financial/result.rs": "a876fe44ed78efbad775ef1c0c4fb0463b895a671d94b47863b6b2a6430cb2b1", - "apps/stock/engine/src/financial/result_tests.rs": "98fa81ee8ae0e4e04886cc1e3f9c0e24e7ec0e3e2511a1b9a4bd634c9bb279b3", - "test/integration/native-replay-projection.test.ts": "2a3e6de8c75f4a7c9b506c5f877e7e0022082f58a1db8b5dd2d75eff590b2573", - "scripts/benchmark-replay.ts": "569214767fc203c496e09a87d81d6e98b0af94f86c7447b5aadd00663dfc7101", - "scripts/benchmark-research.ts": "402196947f32135e669058d2e74e721a7a5b04700b9b9b1f4880b55c8ce37d69", - "scripts/test/benchmark-replay.test.ts": "1e97126da385c5c16b7984dfe4eebd19d2ee6c5555e22608ed7226de007e54f9" - }, - "source_archive": { - "file": "/tmp/stock-bot-wave12.F9Rlh4/integration-measured-source.tar", - "sha256": "fbb0b0b5d5dbc7480528d03eb5b65ce96104dc1058fdbbbca7bd266559557858", - "scope": "All 21 changed source/test/planning files as measured, layered on integration_base. Final handoff edits only change planning files afterward." - }, - "benchmark": { - "source": { - "commit": "19e9dad68be9a06d1e9cd86cc27112c5dc8a4aa2", - "dirty": true, - "contentSha256": "d0b8666d2aa2d0ebdc0abdb76ca2a087bbedb0bc54954345b8b1b18dc20c2e02", - "files": 1158, - "scope": "Tracked and nonignored untracked file paths/content, including dirty changes; generated ignored artifacts excluded." - }, - "runtime": { - "bun": "1.2.17", - "nodeCompatibility": "v22.6.0", - "executableSha256": "6cd2f181c30d3cb1497b0b9d4bc9d63eb1ec4a9142f809183fed18fcc4e1051b", - "rustc": "rustc 1.88.0 (6b00bc388 2025-06-23)", - "lockSha256": "1a2b653bbaaeb5075785b860487557b8fc379f0c50cbe8f2554c90e4a3ac4514", - "cargoLockSha256": "8f2ecaa4f1790f14e1650326f78fbf246f454dad6139dc4cb0d61383b9e301e8" - }, - "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" - }, - "native_sha256": "d98308d0af80c225f2ee631d5e68065fa762073619a8b5cf6f3681ba0f1d5dd6", - "build_profile": "release", - "command": "bun run scripts/benchmark-research.ts --session --measure --profile=all --format=both --bars=10000; separately --profile=sparse and --profile=turnover with --bars=100000", - "method": "Sequential workloads, 2 fresh processes x 2 fresh native sessions per format; second session reverses callback order. 10k means total bars, not bars per asset. Identical final source/artifact across all three paired reports. No concurrent task builds/tests during measured runs; shared host, no CPU isolation or OS-cache flush.", - "timing": "runWallMs includes replay, decisions, finalization and disposal; excludes native construction and independent fixture oracle/hash work. wallMs includes those extras, excluding per-child setup/imports and parent aggregation. FinalizeNative includes Rust projection/serialization/boundary, not pure crossing cost. Raw reports separate decode/validation/disposal. Peak RSS includes JS verification and retained allocator memory, not native-only usage.", - "historical_baseline": { - "file": "/tmp/stock-bot-wave12.F9Rlh4/p07-baseline-10k-trace.json", - "sha256": "6f53ff55f3974eacb584c71db22e398639e37f83263a64f64101ba7b8e185b33", - "native_sha256": "b62e85283325020de09d44dccb27ae5ec5da97cc514ccd92c9b510c0fd814aad", - "result": "All six diagnostic result hashes match all four historical and final trials.", - "limitation": "Intermediate pre-F09 benchmark source bodies were not retained, only their hashes. Historical timing is context, not the basis of speedup claims. Final paired source is archived and is the reproducible comparison." - }, - "reports": [ - { - "file": "/tmp/stock-bot-wave12.F9Rlh4/integration-paired-10k.json", - "sha256": "c69666755e6884d9c4414f588f8d1e03e7e9765d55564584c9c2e1f7175524ef", - "workloads": [ - { - "profile": "none", - "total_bars": 10000, - "assets": 1, - "owners": 1, - "dataset_hash": "3cca7ed706f28a56a9ea463df1a310bb72dae8c52366ad631330ea439f2b7396", - "policy_hash": "54d87634729bbcd61e02a72c9cadba0bc9a225d7ced5525b25c3c83fdf4a3b5b", - "strategy_hash": "0350ffc58432cd23d7b080358474734d74dbd3bf9ec8aeb2a7de583b988649f5", - "common_financial_sha256": "a4642b181216b0485a4ba6b098c17cd1f24188ed676180778301b81b5db9d43a", - "formats": [ - { - "format": "trace", - "result_hash": "daf474508b191971d99f7c307e191f8525aaf8ed7f8bfebcf55f84bf09b12bc6", - "result_bytes": 24885467, - "median_ms": { - "nativeCreateMs": 72.399, - "advance": 524.412, - "submit": 129.843, - "decisions": 26.321, - "finalize": 393.913, - "finalizeNative": 298.731, - "finalizeDecode": 42.583, - "finalizeValidation": 51.937, - "dispose": 64.798, - "unattributedLoop": 3.119, - "runWallMs": 1141.971, - "validationAndHashMs": 59.877, - "wallMs": 1272.342 - }, - "peak_rss_bytes": 985526272, - "trial_run_ms": [ - 1208.158, - 1116.707, - 1165.671, - 1118.27 - ], - "trial_wall_ms": [ - 1340.524, - 1250.286, - 1294.187, - 1250.498 - ] - }, - { - "format": "projection", - "result_hash": "ba38c860ec1ea215118f3cee4ffbb214d4d22c00e6b5f59fcc041570e6595d39", - "result_bytes": 5414, - "median_ms": { - "nativeCreateMs": 66.086, - "advance": 521.075, - "submit": 129.527, - "decisions": 25.867, - "finalize": 0.58, - "finalizeNative": 0.133, - "finalizeDecode": 0.044, - "finalizeValidation": 0.301, - "dispose": 64.429, - "unattributedLoop": 3.066, - "runWallMs": 743.889, - "validationAndHashMs": 0.47, - "wallMs": 810.475 - }, - "peak_rss_bytes": 322838528, - "trial_run_ms": [ - 767.036, - 716.171, - 744.246, - 743.532 - ], - "trial_wall_ms": [ - 836.651, - 774.65, - 809.654, - 811.295 - ] - } - ] - }, - { - "profile": "none", - "total_bars": 10000, - "assets": 10, - "owners": 2, - "dataset_hash": "ebaf4f6908d3897539ab7c52bb5003d81a10e099d66aa3ab3e60c43c97bc93ef", - "policy_hash": "c672a5fcc2a61129e86de006d6435dcc5ea409c244d254a7569a0bfaa6c5e65f", - "strategy_hash": "0350ffc58432cd23d7b080358474734d74dbd3bf9ec8aeb2a7de583b988649f5", - "common_financial_sha256": "9ef78491580ee2b0a8fa62aa6d1eaf7f60d6410c0830abe2bb1d4631ce2e39a7", - "formats": [ - { - "format": "trace", - "result_hash": "b4054bfc5c2bfaef4c7f67b65e6c1ca3edc29c07d96be6c159d0cf0c703b021e", - "result_bytes": 20441628, - "median_ms": { - "nativeCreateMs": 63.902, - "advance": 224.433, - "submit": 20.844, - "decisions": 6.843, - "finalize": 304.768, - "finalizeNative": 229.617, - "finalizeDecode": 34.494, - "finalizeValidation": 40.107, - "dispose": 39.673, - "unattributedLoop": 0.91, - "runWallMs": 599.095, - "validationAndHashMs": 46.112, - "wallMs": 709.125 - }, - "peak_rss_bytes": 862060544, - "trial_run_ms": [ - 646.657, - 566.9, - 631.29, - 556.297 - ], - "trial_wall_ms": [ - 764.845, - 676.094, - 742.157, - 658.522 - ] - }, - { - "format": "projection", - "result_hash": "c9d2f8c913394fa37b3a4e057567ffa1463413ec5dbcda9c2c26109078b27103", - "result_bytes": 9198, - "median_ms": { - "nativeCreateMs": 62.698, - "advance": 225.131, - "submit": 20.264, - "decisions": 6.191, - "finalize": 0.602, - "finalizeNative": 0.144, - "finalizeDecode": 0.049, - "finalizeValidation": 0.295, - "dispose": 42.307, - "unattributedLoop": 0.899, - "runWallMs": 295.608, - "validationAndHashMs": 0.453, - "wallMs": 358.811 - }, - "peak_rss_bytes": 329752576, - "trial_run_ms": [ - 307.53, - 292.32, - 298.896, - 277.266 - ], - "trial_wall_ms": [ - 375.3, - 355.424, - 362.197, - 337.733 - ] - } - ] - }, - { - "profile": "sparse", - "total_bars": 10000, - "assets": 1, - "owners": 1, - "dataset_hash": "3cca7ed706f28a56a9ea463df1a310bb72dae8c52366ad631330ea439f2b7396", - "policy_hash": "0bf67f24b77aefcc4aab10085770bf193801901f229464ac5cc4596c64000994", - "strategy_hash": "2d4d42ddb82459313b11e5dedb8166b81cbeaf9351692da3eb0684ad3f784da1", - "common_financial_sha256": "a280278886deac4a160d8bb0f3263c764f0ba0844150f7d1c2e8d8dc617c24e4", - "formats": [ - { - "format": "trace", - "result_hash": "5489b1b458b0df734b2c4b93595032b72cc4170089fae2ea72b0bca81089ca2d", - "result_bytes": 24893875, - "median_ms": { - "nativeCreateMs": 63.866, - "advance": 584.118, - "submit": 131.543, - "decisions": 25.456, - "finalize": 379.709, - "finalizeNative": 284.818, - "finalizeDecode": 44.217, - "finalizeValidation": 50.568, - "dispose": 63.949, - "unattributedLoop": 3.061, - "runWallMs": 1184.069, - "validationAndHashMs": 58.533, - "wallMs": 1303.617 - }, - "peak_rss_bytes": 999903232, - "trial_run_ms": [ - 1212.542, - 1127.82, - 1240.286, - 1155.596 - ], - "trial_wall_ms": [ - 1333.809, - 1253.839, - 1369.169, - 1273.426 - ] - }, - { - "format": "projection", - "result_hash": "7bba2bd2b3183d3c73d7d0e52e8e9eefd995704d5b3ad3b19d1a0467ff07ac0a", - "result_bytes": 7480, - "median_ms": { - "nativeCreateMs": 64.395, - "advance": 601.172, - "submit": 135.083, - "decisions": 27.974, - "finalize": 0.644, - "finalizeNative": 0.151, - "finalizeDecode": 0.063, - "finalizeValidation": 0.339, - "dispose": 70.165, - "unattributedLoop": 3.133, - "runWallMs": 834.776, - "validationAndHashMs": 0.458, - "wallMs": 901.387 - }, - "peak_rss_bytes": 322781184, - "trial_run_ms": [ - 831.475, - 838.077, - 851.289, - 829.918 - ], - "trial_wall_ms": [ - 895.489, - 907.285, - 917.518, - 890.667 - ] - } - ] - }, - { - "profile": "sparse", - "total_bars": 10000, - "assets": 10, - "owners": 2, - "dataset_hash": "ebaf4f6908d3897539ab7c52bb5003d81a10e099d66aa3ab3e60c43c97bc93ef", - "policy_hash": "4e122c3175f2fc01e1fe595432d619ea70948d311bd4441fd401d0aa72d328d1", - "strategy_hash": "2d4d42ddb82459313b11e5dedb8166b81cbeaf9351692da3eb0684ad3f784da1", - "common_financial_sha256": "2acceddabdeb61d3334caad7bb4700b1fde79969102a4460fb010eb8c82ce297", - "formats": [ - { - "format": "trace", - "result_hash": "5d210d1bc52c4668c5114f18f5d8348b7d27ad7ac8f8cce5aa264ae29ad06f9b", - "result_bytes": 20609553, - "median_ms": { - "nativeCreateMs": 62.93, - "advance": 337.192, - "submit": 22.564, - "decisions": 5.98, - "finalize": 307.415, - "finalizeNative": 232.283, - "finalizeDecode": 35.646, - "finalizeValidation": 37.748, - "dispose": 42.024, - "unattributedLoop": 1.075, - "runWallMs": 719.632, - "validationAndHashMs": 47.215, - "wallMs": 832.807 - }, - "peak_rss_bytes": 884621312, - "trial_run_ms": [ - 770.328, - 688.561, - 750.704, - 671.168 - ], - "trial_wall_ms": [ - 882.713, - 803.956, - 861.658, - 776.748 - ] - }, - { - "format": "projection", - "result_hash": "16d8bc7f63fcfbbb17a2ec949959e2976332c90a3b66f88764434bd74a1f870a", - "result_bytes": 50387, - "median_ms": { - "nativeCreateMs": 64.872, - "advance": 345.535, - "submit": 22.943, - "decisions": 5.966, - "finalize": 1.326, - "finalizeNative": 0.233, - "finalizeDecode": 0.149, - "finalizeValidation": 0.869, - "dispose": 43.538, - "unattributedLoop": 0.978, - "runWallMs": 418.864, - "validationAndHashMs": 0.626, - "wallMs": 489.721 - }, - "peak_rss_bytes": 321789952, - "trial_run_ms": [ - 421.876, - 414.497, - 441.383, - 415.851 - ], - "trial_wall_ms": [ - 487.036, - 492.405, - 507.794, - 477.373 - ] - } - ] - }, - { - "profile": "turnover", - "total_bars": 10000, - "assets": 1, - "owners": 1, - "dataset_hash": "3cca7ed706f28a56a9ea463df1a310bb72dae8c52366ad631330ea439f2b7396", - "policy_hash": "5033c5bc74a54e41bc443bb7a0c9159a0c6e863a9f8a81514fc81deaf9753712", - "strategy_hash": "0a293e08ffc6cc42b4573b5b5bd33512f786bf78aa9b0ea111ceb836bfb9a6d3", - "common_financial_sha256": "d85e6133ea043b20d01634c456ecf36c694d0b25915b717757ea5626bfebba5f", - "formats": [ - { - "format": "trace", - "result_hash": "492467b561adb8792f6b75a6d8754e10fc5361772218bd7bcdbb1984748953bd", - "result_bytes": 66707481, - "median_ms": { - "nativeCreateMs": 64.111, - "advance": 730.06, - "submit": 336.168, - "decisions": 34.621, - "finalize": 802.789, - "finalizeNative": 617.302, - "finalizeDecode": 123.887, - "finalizeValidation": 59.798, - "dispose": 171.988, - "unattributedLoop": 3.974, - "runWallMs": 2105.478, - "validationAndHashMs": 158.625, - "wallMs": 2327.538 - }, - "peak_rss_bytes": 1895075840, - "trial_run_ms": [ - 2175.759, - 1940.376, - 2192.556, - 2035.197 - ], - "trial_wall_ms": [ - 2397.705, - 2188.435, - 2416.187, - 2257.372 - ] - }, - { - "format": "projection", - "result_hash": "84449a90550ae61b1ed7ac038a21420ed0347f7e9130d84fe960ca2d2dc7590c", - "result_bytes": 9784124, - "median_ms": { - "nativeCreateMs": 65.417, - "advance": 744.849, - "submit": 337.228, - "decisions": 35.569, - "finalize": 141.273, - "finalizeNative": 19.147, - "finalizeDecode": 15.794, - "finalizeValidation": 105.936, - "dispose": 190.762, - "unattributedLoop": 3.744, - "runWallMs": 1467.315, - "validationAndHashMs": 42.532, - "wallMs": 1575.591 - }, - "peak_rss_bytes": 616632320, - "trial_run_ms": [ - 1529.686, - 1414.974, - 1519.656, - 1379.613 - ], - "trial_wall_ms": [ - 1640.146, - 1516.634, - 1634.548, - 1482.195 - ] - } - ] - }, - { - "profile": "turnover", - "total_bars": 10000, - "assets": 10, - "owners": 2, - "dataset_hash": "ebaf4f6908d3897539ab7c52bb5003d81a10e099d66aa3ab3e60c43c97bc93ef", - "policy_hash": "2e55eb1dcae65f847ab53914a7a11afaa46b0c9a199b20565dafe08cc1b94c95", - "strategy_hash": "0a293e08ffc6cc42b4573b5b5bd33512f786bf78aa9b0ea111ceb836bfb9a6d3", - "common_financial_sha256": "b5622787cf1f7a23713c0d4366958c39ead889c5f240ea21b32b958efd31404b", - "formats": [ - { - "format": "trace", - "result_hash": "b065da3a8ff7c0a341bf8d4326c455fac0a029027446f9734d13ac117ea13e4c", - "result_bytes": 103598570, - "median_ms": { - "nativeCreateMs": 80.633, - "advance": 747.085, - "submit": 476.238, - "decisions": 16.15, - "finalize": 1120.544, - "finalizeNative": 877.465, - "finalizeDecode": 179.543, - "finalizeValidation": 61.841, - "dispose": 237.852, - "unattributedLoop": 1.428, - "runWallMs": 2598.202, - "validationAndHashMs": 229.475, - "wallMs": 2911.615 - }, - "peak_rss_bytes": 2642341888, - "trial_run_ms": [ - 2642.449, - 2553.955, - 2660.854, - 2551.372 - ], - "trial_wall_ms": [ - 2942.804, - 2873.862, - 2960.667, - 2880.425 - ] - }, - { - "format": "projection", - "result_hash": "aa8405f705705c9153b18b00965ddca11271a3a2e9bf61787985a68cb8df620f", - "result_bytes": 19408576, - "median_ms": { - "nativeCreateMs": 69.605, - "advance": 777.851, - "submit": 487.186, - "decisions": 16.501, - "finalize": 280.961, - "finalizeNative": 40.631, - "finalizeDecode": 33.149, - "finalizeValidation": 207.406, - "dispose": 234.904, - "unattributedLoop": 1.634, - "runWallMs": 1803.833, - "validationAndHashMs": 80.124, - "wallMs": 1953.275 - }, - "peak_rss_bytes": 901554176, - "trial_run_ms": [ - 1833.138, - 1786.199, - 1821.467, - 1726.482 - ], - "trial_wall_ms": [ - 1981.66, - 1938.343, - 1968.206, - 1889.177 - ] - } - ] - } - ] - }, - { - "file": "/tmp/stock-bot-wave12.F9Rlh4/integration-paired-100k-sparse.json", - "sha256": "cece6e52dd671e712e05e5c0608af29947e213aec542afc64e3cf705d8e934b6", - "workloads": [ - { - "profile": "sparse", - "total_bars": 100000, - "assets": 1, - "owners": 1, - "dataset_hash": "e4af6863bb868f706216f0196f111c4396fe140829470dad1c855f4fcb496b89", - "policy_hash": "0bf67f24b77aefcc4aab10085770bf193801901f229464ac5cc4596c64000994", - "strategy_hash": "2d4d42ddb82459313b11e5dedb8166b81cbeaf9351692da3eb0684ad3f784da1", - "common_financial_sha256": "a47f812924fc873be84916e1158aa902b963f7eb666abbffdeb730efa6a541ad", - "formats": [ - { - "format": "trace", - "result_hash": "1073108a8adf3f7e1eb6b8d52baf4a3d706e67eff6a2904833fc0f48dca68567", - "result_bytes": 250743592, - "median_ms": { - "nativeCreateMs": 724.544, - "advance": 5617.265, - "submit": 1273.372, - "decisions": 235.39, - "finalize": 3929.677, - "finalizeNative": 2939.941, - "finalizeDecode": 443.902, - "finalizeValidation": 539.635, - "dispose": 835.954, - "unattributedLoop": 26.992, - "runWallMs": 11918.35, - "validationAndHashMs": 627.338, - "wallMs": 13270.767 - }, - "peak_rss_bytes": 9127473152, - "trial_run_ms": [ - 12334.067, - 11524.568, - 12312.131, - 11521.608 - ], - "trial_wall_ms": [ - 13644.69, - 12915.376, - 13626.158, - 12879.641 - ] - }, - { - "format": "projection", - "result_hash": "45ce5c8c0484f82387e37a647a538777350600ba1bc3e1a36a8768f4eb2c4d91", - "result_bytes": 17241, - "median_ms": { - "nativeCreateMs": 696.54, - "advance": 5701.783, - "submit": 1294.866, - "decisions": 233.676, - "finalize": 1.477, - "finalizeNative": 0.882, - "finalizeDecode": 0.111, - "finalizeValidation": 0.403, - "dispose": 864.986, - "unattributedLoop": 27.86, - "runWallMs": 8096.545, - "validationAndHashMs": 0.635, - "wallMs": 8818.836 - }, - "peak_rss_bytes": 1828900864, - "trial_run_ms": [ - 7871.941, - 7905.888, - 8355.872, - 8287.202 - ], - "trial_wall_ms": [ - 8568.299, - 8652.421, - 9035.656, - 8985.251 - ] - } - ] - }, - { - "profile": "sparse", - "total_bars": 100000, - "assets": 10, - "owners": 2, - "dataset_hash": "ef6ae4668c49048457c591d58e1a1273a89af5e787fe7f8a38bcf79e9d20e4f9", - "policy_hash": "4e122c3175f2fc01e1fe595432d619ea70948d311bd4441fd401d0aa72d328d1", - "strategy_hash": "2d4d42ddb82459313b11e5dedb8166b81cbeaf9351692da3eb0684ad3f784da1", - "common_financial_sha256": "19603df92d922ee7c30c9baf4378c505e2dcb14f9c648c937f3fb508dd6c03ac", - "formats": [ - { - "format": "trace", - "result_hash": "de9aeeb0add3649f1947a1bb829fe211e7c00d2e6d2812625d4f3c0d605e520a", - "result_bytes": 206015626, - "median_ms": { - "nativeCreateMs": 737.344, - "advance": 3366.303, - "submit": 211.153, - "decisions": 55.017, - "finalize": 3115.84, - "finalizeNative": 2404.412, - "finalizeDecode": 346.546, - "finalizeValidation": 360.799, - "dispose": 577.556, - "unattributedLoop": 7.938, - "runWallMs": 7312.064, - "validationAndHashMs": 448.802, - "wallMs": 8490.684 - }, - "peak_rss_bytes": 7150276608, - "trial_run_ms": [ - 7548.873, - 7075.254, - 7731.073, - 7003.793 - ], - "trial_wall_ms": [ - 8789.492, - 8191.877, - 8972.451, - 8157.448 - ] - }, - { - "format": "projection", - "result_hash": "17f3e1e6fd4b3e0bf2bfbf5261ab63c0c57a87bf5a11e393deddf36d6f5fdedc", - "result_bytes": 51525, - "median_ms": { - "nativeCreateMs": 730.576, - "advance": 3365.649, - "submit": 204.066, - "decisions": 51.301, - "finalize": 2.138, - "finalizeNative": 0.982, - "finalizeDecode": 0.155, - "finalizeValidation": 0.906, - "dispose": 618.382, - "unattributedLoop": 8.076, - "runWallMs": 4245.126, - "validationAndHashMs": 0.776, - "wallMs": 4972.624 - }, - "peak_rss_bytes": 1652928512, - "trial_run_ms": [ - 4360.771, - 4233.099, - 4257.154, - 4208.83 - ], - "trial_wall_ms": [ - 5112.064, - 4931.674, - 5013.574, - 4920.282 - ] - } - ] - } - ] - }, - { - "file": "/tmp/stock-bot-wave12.F9Rlh4/integration-paired-100k-turnover.json", - "sha256": "04f810aa6cfd359c1243f31aa9b34314148e807df2efa79c03bc81c581e36a77", - "workloads": [ - { - "profile": "turnover", - "total_bars": 100000, - "assets": 1, - "owners": 1, - "dataset_hash": "e4af6863bb868f706216f0196f111c4396fe140829470dad1c855f4fcb496b89", - "policy_hash": "5033c5bc74a54e41bc443bb7a0c9159a0c6e863a9f8a81514fc81deaf9753712", - "strategy_hash": "0a293e08ffc6cc42b4573b5b5bd33512f786bf78aa9b0ea111ceb836bfb9a6d3", - "common_financial_sha256": "d421fc880af8752604452580777210836897443f5c9962291c84aa75126535e8", - "formats": [ - { - "format": "trace", - "result_hash": "7985aaca59dc38d5552a353e912ea1b90423e3f439dfb4f8bd4820b4fd4e5ed5", - "result_bytes": 672191254, - "median_ms": { - "nativeCreateMs": 682.227, - "advance": 7277.258, - "submit": 3373.902, - "decisions": 331.129, - "finalize": 7945.507, - "finalizeNative": 6083.605, - "finalizeDecode": 1230.656, - "finalizeValidation": 663.809, - "dispose": 2087.562, - "unattributedLoop": 36.328, - "runWallMs": 21027.189, - "validationAndHashMs": 1756.218, - "wallMs": 23491.526 - }, - "peak_rss_bytes": 18088566784, - "trial_run_ms": [ - 21737.623, - 20316.756, - 21968.344, - 20151.726 - ], - "trial_wall_ms": [ - 24210.651, - 22772.401, - 24474.82, - 22555.669 - ] - }, - { - "format": "projection", - "result_hash": "8d5662a18c9f33dd23c5f2da2fde5634cb0d73674e6f8f160784b285526c5a19", - "result_bytes": 98609582, - "median_ms": { - "nativeCreateMs": 668.535, - "advance": 7501.108, - "submit": 3507.3, - "decisions": 337.349, - "finalize": 1389.409, - "finalizeNative": 191.359, - "finalizeDecode": 165.427, - "finalizeValidation": 1030.594, - "dispose": 2063.713, - "unattributedLoop": 37.177, - "runWallMs": 14820.723, - "validationAndHashMs": 410.452, - "wallMs": 15887.464 - }, - "peak_rss_bytes": 5057183744, - "trial_run_ms": [ - 14930.103, - 14711.343, - 15013.435, - 14604.524 - ], - "trial_wall_ms": [ - 16026.827, - 15748.101, - 16172.813, - 15657.574 - ] - } - ] - }, - { - "profile": "turnover", - "total_bars": 100000, - "assets": 10, - "owners": 2, - "dataset_hash": "ef6ae4668c49048457c591d58e1a1273a89af5e787fe7f8a38bcf79e9d20e4f9", - "policy_hash": "2e55eb1dcae65f847ab53914a7a11afaa46b0c9a199b20565dafe08cc1b94c95", - "strategy_hash": "0a293e08ffc6cc42b4573b5b5bd33512f786bf78aa9b0ea111ceb836bfb9a6d3", - "common_financial_sha256": "1a8c025bfe2e957b0e8582baa86734e9882bd621c25a584d15cf9bab99c0552a", - "formats": [ - { - "format": "trace", - "result_hash": "3a7823aececa30e0a0b8d9f05d4e6ad0d62ccbce3874e015e8dbd380d94564d1", - "result_bytes": 1044534187, - "median_ms": { - "nativeCreateMs": 719.113, - "advance": 7885.628, - "submit": 4949.83, - "decisions": 179.319, - "finalize": 10706.091, - "finalizeNative": 8300.15, - "finalizeDecode": 1822.651, - "finalizeValidation": 555.375, - "dispose": 2777.094, - "unattributedLoop": 14.367, - "runWallMs": 26500.96, - "validationAndHashMs": 2325.053, - "wallMs": 29509.002 - }, - "peak_rss_bytes": 20508598272, - "trial_run_ms": [ - 27009.292, - 25375.892, - 27608.379, - 25992.629 - ], - "trial_wall_ms": [ - 30036.597, - 28454.937, - 30713.282, - 28981.406 - ] - }, - { - "format": "projection", - "result_hash": "c8dab7c03012529f4d26f5a9c7c82cc0dc172ff470d33202c762bc7196907b06", - "result_bytes": 195752374, - "median_ms": { - "nativeCreateMs": 724.751, - "advance": 8011.898, - "submit": 5007.651, - "decisions": 184.578, - "finalize": 2783.424, - "finalizeNative": 394.154, - "finalizeDecode": 333.951, - "finalizeValidation": 2050.37, - "dispose": 2799.035, - "unattributedLoop": 14.323, - "runWallMs": 18743.039, - "validationAndHashMs": 808.522, - "wallMs": 20265.147 - }, - "peak_rss_bytes": 7780823040, - "trial_run_ms": [ - 18775.157, - 18710.92, - 19152.908, - 18433.932 - ], - "trial_wall_ms": [ - 20354.488, - 20175.806, - 20740.79, - 19922.356 - ] - } - ] - } - ] - } - ], - "conclusions": [ - "10k high-turnover median run time: 2.105s to 1.467s single and 2.598s to 1.804s multi, 30.3%/30.6% lower; bytes 66.7MB to 9.8MB and 103.6MB to 19.4MB.", - "100k sparse medians: 11.918s to 8.097s single, 7.312s to 4.245s multi. 100k turnover: 21.027s to 14.821s and 26.501s to 18.743s. All repetitions, reversed callbacks and shared financial projections match.", - "10k compact advance plus submit takes 70-88% of run time; current timers mix native work, encoding, validation and freezing. Split/profile these before selecting another optimization. TS fixture decisions take 0.9-3.5%; no DSL evidence.", - "10k turnover compact validation costs 106/207ms, native finalization only 19/41ms, disposal 191/235ms. Do not remove validation or journal/recovery history to chase timings.", - "Synthetic conformance workloads, not arbitrary production strategies, database/queue throughput, empty NAPI cost, parallel speedup or an isolated-host SLA. No 100k no-trade measurement is claimed." - ] - } - }, - "thirteenth_wave": [ - "F08" - ], - "thirteenth_wave_base": "e3bd722e31a4e14519df543d87affd90a8103fa2", - "thirteenth_wave_notes": [ - "Owner accepted F09/P07 and requested commit plus continuation. Feature commit e3bd722 contains the reviewed wave12 source/tests/planning; F08 is the next satisfied code/ADR task.", - "Reporting conventions pinned in F08 Execution contract after independent Rust/quant design inspection. Separate accumulator; existing financial events/checkpoints/config/outputs retained; account-session reporting and elapsed occupancy are explicit.", - "Two isolated source owners: native/reporting wire and disjoint shared analytics/statistics adapter. Exact accepted schema is handed off before consumer integration. Independent reviewer is read-only.", - "Legacy positions and round-trip DTOs cannot truthfully represent the new facts without further work. F08 publishes an additive canonical analytics DTO; R05 retains persisted/public-result/default cutover with existing approval gates." - ], - "thirteenth_wave_validation": { - "state": "validated_committed", - "accepted_commit": "3838295eec8e84a46115462ca6c5d5c8c7fab66b", - "work_root": "/tmp/stock-bot-wave13.KfvceG", - "committed_before_implementation": [ - "e3bd722e31a4e14519df543d87affd90a8103fa2", - "1e164450c3f7a16c1838b3318842f49a5ff3cf28" - ], - "scope": "F08 only. Additive reporting/analytics; financial events/checkpoints/trace/projection and active legacy/web/paper paths unchanged. R05 owns persisted/public-result cutover.", - "source_integration": { - "reviewed_owner_files": 22, - "all_owner_hashes_match": true, - "root_additions": [ - "test/integration/canonical-native-report.test.ts", - "libs/calculations/README.md" - ], - "source_archive": "/tmp/stock-bot-wave13.KfvceG/integrated-source.tar", - "source_archive_sha256": "1b72060dd11f4f7577d5078798188b0e024a34c951d316b3a29cfde193eb3a04", - "measured_source": { - "commit": "1e164450c3f7a16c1838b3318842f49a5ff3cf28", - "dirty": true, - "contentSha256": "4f60ad86bf2ef9afbc2630563d3ae2c8c5a54e60f4a57c82de798edc1a497a00", - "files": 1167 - }, - "owner_hashes_file": "/tmp/stock-bot-wave13.KfvceG/f08-sources.sha256 and /tmp/stock-bot-wave13.KfvceG/analytics-final.sha256" - }, - "gates": { - "repository": { - "command": "CARGO_BUILD_JOBS=2 bun run check", - "log": "/tmp/stock-bot-wave13.KfvceG/integration-check.log", - "outcome": "Build/typecheck/contracts/audit/lint passed; 72 tooling, 43 utility, 44 calculation and 144 Rust tests passed (4 existing manual benchmarks ignored). Initial integration failed only new composition fixtures missing explicit hold decisions; fixed test only. Required integration rerun below passed; no production changes after passing gates." - }, - "integration": { - "command": "bun run test:integration", - "log": "/tmp/stock-bot-wave13.KfvceG/integration-tests-final.log", - "passed": 375, - "assertions": 3345 - }, - "strict_test_types": { - "command": "bunx tsc --project /tmp/stock-bot-wave13.KfvceG/tsconfig.integration.json --noEmit", - "log": "/tmp/stock-bot-wave13.KfvceG/integration-extra-types-final.log", - "passed": true - }, - "disposable_recovery": { - "command": "PIPELINE_TEST_DATABASE_URL=postgres://fixture:fixture@127.0.0.1:32809/stock_bot_safety BACKTEST_TEST_REDIS_URL=redis://127.0.0.1:32810/15 bun run test:postgres", - "baseline_log": "/tmp/stock-bot-wave13.KfvceG/baseline-postgres.log", - "integrated_log": "/tmp/stock-bot-wave13.KfvceG/integration-postgres.log", - "passed_each": 58, - "assertions_each": 345 - }, - "release_focused": { - "command": "bun test test/integration/native-replay.test.ts test/integration/native-replay-projection.test.ts test/integration/native-replay-report.test.ts test/integration/canonical-result.test.ts test/integration/canonical-native-report.test.ts scripts/test/native-bindings.test.ts", - "log": "/tmp/stock-bot-wave13.KfvceG/integration-release-focused.log", - "passed": 39, - "assertions": 703 - }, - "formatting": "Scoped test ESLint with --no-ignore --max-warnings 0; scoped Prettier and Rust rustfmt; git diff --check passed.", - "review": "Independent frozen native/wire and analytics review; real native/worker/analytics composition reviewed after corrected exact-trace fixtures. No blockers. Focused counts overlap full suites.", - "not_run": "Browser/Python unchanged; no browser or Python rerun. No default cutover, paper account migration or live operation." - }, - "native": { - "release_sha256": "6fe9dae546b4fc1d50b064b2ad50b0a3d08a0208ede3c568bf0f95e549c57b9e", - "artifact_matches": "apps/stock/engine/dist/engine.node == target/release/libengine.so", - "generated_types_sha256": "4ab02314df3b64ae698942d5ba69260430f4488dc8ad64d1ef825d86db71da5d" - }, - "performance": { - "methodology": "Release; six workloads of 10000 TOTAL bars, one asset/owner or ten assets/two owners, none/sparse/turnover; two fresh processes x two fresh sessions each. Shared host; no timing assertions.", - "projection_command": "bun run scripts/benchmark-research.ts --session --measure --profile=all --format=projection --bars=10000", - "raw_files": { - "baseline": { - "path": "/tmp/stock-bot-wave13.KfvceG/baseline-10k-projection.json", - "sha256": "3fd571b271d7ebdacd078315ab8c7102bb4d26edbeb31d9d15ce97e0b1efa6dc" - }, - "candidate": { - "path": "/tmp/stock-bot-wave13.KfvceG/candidate-10k-projection.json", - "sha256": "e122cdd57d9126eeecf5d85203485dfaded47cbede24a61ce726e0cc8c548b2d" - }, - "control": { - "path": "/tmp/stock-bot-wave13.KfvceG/control-10k-projection.json", - "sha256": "99940d4dc6debf22e98c1cda45d79f7ae3bfad4890625b22c6f490ad5fd243d4" - }, - "comparison": { - "path": "/tmp/stock-bot-wave13.KfvceG/projection-comparison.json", - "sha256": "b11ae6348eaf944c7ec0b24abb65d0c931654e572bfa1c831c2fb2414ea3d158" - } - }, - "baseline_addon": "d98308d0af80c225f2ee631d5e68065fa762073619a8b5cf6f3681ba0f1d5dd6", - "control_source": { - "commit": "19e9dad68be9a06d1e9cd86cc27112c5dc8a4aa2", - "dirty": true, - "contentSha256": "8c181e664dfcd14951da1730918efd7817cc64c24409d12a1dbfbc65a4f3cd68", - "files": 1156, - "scope": "Tracked and nonignored untracked file paths/content, including dirty changes; generated ignored artifacts excluded." - }, - "projection_rows": [ - [ - "none", - 1, - 1, - 722.1379744999999, - 1036.9407385, - 1049.7488, - -1.2201072770933519, - "ba38c860ec1ea215118f3cee4ffbb214d4d22c00e6b5f59fcc041570e6595d39" - ], - [ - "none", - 10, - 2, - 301.1164395, - 412.87483849999995, - 422.0579295, - -2.1757892360603215, - "c9d2f8c913394fa37b3a4e057567ffa1463413ec5dbcda9c2c26109078b27103" - ], - [ - "sparse", - 1, - 1, - 788.4738159999999, - 1125.431942, - 1136.793305, - -0.9994220541261867, - "7bba2bd2b3183d3c73d7d0e52e8e9eefd995704d5b3ad3b19d1a0467ff07ac0a" - ], - [ - "sparse", - 10, - 2, - 425.1541205, - 581.5226849999999, - 589.4312225, - -1.3417235460410404, - "16d8bc7f63fcfbbb17a2ec949959e2976332c90a3b66f88764434bd74a1f870a" - ], - [ - "turnover", - 1, - 1, - 1425.262843, - 2008.9278365000002, - 1994.4425904999998, - 0.7262804188497007, - "84449a90550ae61b1ed7ac038a21420ed0347f7e9130d84fe960ca2d2dc7590c" - ], - [ - "turnover", - 10, - 2, - 1820.0325200000002, - 2425.662255, - 2432.1380289999997, - -0.2662584903810772, - "aa8405f705705c9153b18b00965ddca11271a3a2e9bf61787985a68cb8df620f" - ] - ], - "interpretation": "Initial candidate was 33-44% slower than early baseline, including unchanged TS callback/JSON phases. Host load varied 9-26. Contemporaneous unchanged exact F09 addon reproduced slowdown; 128 relevant source/lock files verified equal e3bd722. Candidate/control -2.18% to +0.73%; no material regression demonstrated, no speedup or SLA claim. All complete result/economic hashes identical; retain unfavorable initial samples.", - "report_comparison": { - "command": "bun run /tmp/stock-bot-wave13.KfvceG/report-benchmark.ts", - "harness": { - "path": "/tmp/stock-bot-wave13.KfvceG/report-benchmark.ts", - "sha256": "d37f63aadd9b1849a57347c27991027e31fd03121edb3c7d6fb40575af2d00a5" - }, - "smoke": "--smoke passed all tiny 8/16-total-bar pairs", - "path": "/tmp/stock-bot-wave13.KfvceG/report-comparison.json", - "sha256": "3969ca227d46655933395a744bd16a95cf6a90ca28dfe27556c6c2d66169524b", - "trials": 48, - "rows": [ - [ - "none", - 1, - 1, - 1038.244792, - 1038.0855645000001, - 0.7150815000001103, - 0.9550145000000612, - 0.5035165000000461, - 5414, - 5972 - ], - [ - "none", - 10, - 2, - 419.2966825, - 415.5477985, - 0.6127834999999777, - 1.0950445000000286, - 0.638200500000039, - 9198, - 9755 - ], - [ - "sparse", - 1, - 1, - 1140.11128, - 1122.99876, - 0.9735344999999143, - 1.2432044999999334, - 1.2845025000000305, - 7480, - 8090 - ], - [ - "sparse", - 10, - 2, - 579.425198, - 585.6239385000001, - 1.435258000000033, - 1.9801919999999882, - 0.5092425000000276, - 50387, - 50995 - ], - [ - "turnover", - 1, - 1, - 1965.9803270000002, - 2002.67703, - 197.7599379999998, - 201.9273004999999, - 0.6505395000001499, - 9784124, - 10004689 - ], - [ - "turnover", - 10, - 2, - 2466.477757, - 2465.8275665, - 431.99900449999996, - 438.7678484999997, - 0.8527414999998655, - 19408576, - 19431138 - ] - ], - "validation": "Counterbalanced format order; removing reporting fields and normalizing format to projection yields the identical complete projection, including valuation/all fill fields; matches initial baseline. Repeated full report/analytics hashes and integer-cent oracle pass. Independent final audit verified recorded raw/harness hashes, all 48 trials, medians and limitations.", - "scope": "Both formats collect reporting. Additional export median 0.24-6.77ms; adapter 0.50-1.28ms. Fixture has one partial session, zero complete periodic samples; not long-session-history statistics, storage/queue throughput, arbitrary strategies or pure NAPI costs.", - "rows_columns": [ - "profile", - "assets", - "owners", - "projection_run_ms", - "report_run_ms", - "projection_finalize_ms", - "report_finalize_ms", - "analytics_ms", - "projection_bytes", - "report_bytes" - ] - }, - "projection_rows_columns": [ - "profile", - "assets", - "owners", - "initial_baseline_ms", - "candidate_ms", - "contemporaneous_control_ms", - "candidate_vs_control_percent", - "full_result_hash" - ] - }, - "limitations": [ - "Session-end/terminal sampled drawdown, not intraday maximum; partial periods visible/excluded from periodic ratios.", - "Marks are last available; per-session freshness not certified. Sequential equal-time risk halt limitation unchanged; R05 owner policy gate unresolved.", - "Benchmark-dependent and round-trip metrics unsupported/null with reasons. Fills are not round trips; no invented legacy position financial fields.", - "Legacy financial paths/results/UI remain active until separately gated migration. No DSL/cache/journal deletion or unrelated hot-loop rewrite." - ], - "cleanup": "Stopped only exact --rm fixture containers a4edf7d7b61f944d9b42f93fe2fb77c9be565efabfa9292aeb8d34de3d1c8c85 and 604c940db286ab408bd60963116355428f0efa216725ca2e269639e1572fc1dd. Development services untouched; isolated worktrees/logs retained.", - "next": "At handoff S01 required ADR-005; the next owner instruction accepted F08 and continued the explicitly named S01/ADR-005 direction. See fourteenth_wave_notes. R01/R11 remain gated by ADR-006." - }, - "fourteenth_wave": [ - "S01" - ], - "fourteenth_wave_base": "3838295eec8e84a46115462ca6c5d5c8c7fab66b", - "fourteenth_wave_notes": [ - "Owner: commit all of it and continue, after the handoff named S01 and linked pending ADR-005. F08 committed after exact accepted-source hash verification; S01 is now authorized under ADR-004/005.", - "Root pinned S01 whole-attempt restart and per-owner state/RNG/observation semantics after independent runtime/recovery inspection. Existing native API has no checkpoint wire; do not introduce a partial TS-only resume.", - "One implementation owner controls strategy contract/shared driver/native admission feedback. Disjoint verification owner waits for pinned API. Root owns metadata/integration; independent review checks both slices.", - "Trusted direct programs only. S02 owns real-strategy/worker composition, S03 paper migration, R05 durable canonical/default cutover. Other ADRs, untrusted-code isolation, financial policy and existing active runtimes remain unchanged." - ], - "fourteenth_wave_validation": { - "state": "validated_uncommitted", - "work_root": "/tmp/stock-bot-wave14.JYfazy", - "committed_before_implementation": [ - "3838295eec8e84a46115462ca6c5d5c8c7fab66b", - "0870b5583045b98d7f02598e61d772c489af5441" - ], - "scope": "S01 trusted host runtime only. No Rust financial semantics, worker request, SQL/paper, active legacy registry, user strategy loading or default cutover changes. S02 owns one real strategy and trusted worker composition.", - "source_integration": { - "owner_files": 8, - "exact_hashes": { - "apps/stock/orchestrator/src/backtest/strategy-runtime.ts": "c46bd8704ecbbb0a0d70fa60ff7d062a2398614ad0d5d8c6f23540f5b4e1b56e", - "apps/stock/orchestrator/src/backtest/native-replay.ts": "61e296f6cff7b441612872742d60379087f7661557bbb52db7b039128e425232", - "apps/stock/orchestrator/src/contracts/canonical-strategy.ts": "479347248ef19077ef7d4802a2023911c37c6cb7d14d2a6857133d24bd219bea", - "apps/stock/orchestrator/src/contracts/native-replay.ts": "bc7d98d735e453c78d174d80aba2a94637193c77bcfe14f65ffd12f305221789", - "scripts/test/architecture.test.ts": "afc718d1b157d6d501508bb9be6e0f204cdaaa822a8e15c9dbaec1b4ba562716", - "scripts/test/strategy-runtime.test.ts": "1da6beaf983e4a391610d32efa93b7435ae3ce9cce849ea07692742bd9b732d4", - "test/integration/strategy-runtime.test.ts": "6c95437b2bf2c7c6c42a70f8d16aa4b046cb81453bd0fb45556f256853dadd99", - "test/contracts/strategy-runtime.type-test.ts": "9017fd3eba72b3628e77ac79e884af2bb1251b1b9d06ca29df71b23b923c73f6" - }, - "root_gate": "tsconfig.contracts.json permanently includes test/contracts/strategy-runtime.type-test.ts", - "root_gate_sha256": "eab2122e8741b7e129e8fefbe62441460df5dfcab80c5eaec1c105db46bd07e9", - "source_archive": "/tmp/stock-bot-wave14.JYfazy/integrated-source.tar", - "source_archive_sha256": "aa568bf216b111fc161ff1ade7962f6aa773c6117eb202c0a29ace4cbaa3a86f", - "measured_source": { - "root": "/home/boki/repos/stock-bot", - "commit": "0870b5583045b98d7f02598e61d772c489af5441", - "dirty": true, - "sha256": "29d0b55e68aa31f0005a1dc81b4b2bd5ac24716148884549fc16159360c9932b", - "files": 1172 - }, - "note": "Only planning records changed after measurement; source hashes remain those independently reviewed and validated." - }, - "review": { - "reviewer": "/root/s01_final_review", - "disposition": "Accepted exact eight-file integration and final performance methodology/results; no remaining blocker. Reviewer read code/logs, did not execute builds/tests.", - "fixed_findings": [ - "Invalid async callbacks could leave unhandled Promise rejections; intrinsic rejection observation now covers immediate, delayed and foreign-realm Promises without awaiting or invoking arbitrary thenables.", - "Zod unknown fields accepted missing Risk/Operator tags; decoder now requires object-valued tags while leaving nested financial diagnostics opaque." - ], - "independent_tests": "15 real-native scenarios /249 assertions; trace-format determinism includes all no-op decisions; owner unit tests also verify malformed post-submit feedback cannot partially advance TS state." - }, - "gates": { - "full": { - "command": "CARGO_BUILD_JOBS=2 bun run check", - "log": "/tmp/stock-bot-wave14.JYfazy/integration-check.log", - "passed": true, - "tests": { - "tooling": 78, - "utilities": 43, - "calculations": 44, - "integration": 390, - "rust": 144 - }, - "existing_manual_rust_ignored": 4, - "other": "Build/typecheck/permanent contracts/audit/lint passed." - }, - "extra_strict_types": { - "command": "bunx tsc --project /tmp/stock-bot-wave14.JYfazy/tsconfig.integration.json --noEmit", - "log": "/tmp/stock-bot-wave14.JYfazy/integration-extra-types-final.log", - "passed": true, - "note": "Initial temporary config lacked root Bun typeRoots; corrected external config only. Production and permanent contract gates passed." - }, - "disposable_recovery": { - "command": "PIPELINE_TEST_DATABASE_URL=postgres://fixture:fixture@127.0.0.1:32811/stock_bot_safety BACKTEST_TEST_REDIS_URL=redis://127.0.0.1:32812/15 bun run test:postgres", - "log": "/tmp/stock-bot-wave14.JYfazy/integration-postgres.log", - "passed": 58, - "assertions": 345 - }, - "release_focused": { - "command": "bun test scripts/test/strategy-runtime.test.ts test/integration/strategy-runtime.test.ts test/integration/native-replay.test.ts test/integration/native-replay-projection.test.ts test/integration/native-replay-report.test.ts", - "log": "/tmp/stock-bot-wave14.JYfazy/integration-release-focused.log", - "passed": 43, - "assertions": 568 - }, - "scoped": "Explicit ESLint --no-ignore --max-warnings 0 for new unit/integration/type fixtures, scoped Prettier and git diff --check passed. Existing architecture script curly findings were not expanded or rewritten.", - "not_run": "Browser/Python boundaries unchanged; not rerun. Counts overlap. No paper/default activation." - }, - "native": { - "release_sha256": "6fe9dae546b4fc1d50b064b2ad50b0a3d08a0208ede3c568bf0f95e549c57b9e", - "matches": "apps/stock/engine/dist/engine.node == target/release/libengine.so; same financial artifact as F08", - "owner_debug_sha256": "ee43d8aeba4de5f1bd6d076348f7336f732411222036fec2f47f8442deb2537a", - "verifier_debug_sha256": "24e8c31995a752bc8915c737ce34564698bb5b518e5cf4ac5dffcd039593e4eb", - "isolation": "Root verified owner/verifier engine, types and calculations workspace links resolve within their respective worktrees; each addon matches its own local debug library." - }, - "performance": { - "conformance": { - "command": "bun run scripts/benchmark-research.ts --session --measure --profile=all --format=projection --bars=10000", - "raw": "/tmp/stock-bot-wave14.JYfazy/conformance-10k-projection.json", - "raw_sha256": "39925fd1742df32ddd356bef0b03889d72ea18e2d11027c64ee0cb5448105ddc", - "comparison": "/tmp/stock-bot-wave14.JYfazy/conformance-comparison.json", - "comparison_sha256": "e897c7fb9e7dad710014d23db4b812631396caf69da0c98212386ddd387a5240", - "assertion": "Six workloads, four samples each; same dataset/policy/strategy hashes and exact complete-result/common-financial hashes as accepted F08. Same native artifact. Historical wall-time changes reflect different shared-host load; no speedup attribution." - }, - "stateful": { - "command": "bun run /tmp/stock-bot-wave14.JYfazy/strategy-benchmark.ts", - "harness": { - "path": "/tmp/stock-bot-wave14.JYfazy/strategy-benchmark.ts", - "sha256": "0d9f6ac8c9a073b2661dc4fb41cab1a5f3b6d2934fb36a19d42bef49ed9e59c3" - }, - "smoke": "--smoke passed all six tiny workload pairs before full execution", - "raw": "/tmp/stock-bot-wave14.JYfazy/strategy-comparison.json", - "raw_sha256": "57a1d12fb6ff92b84dca0593b3d95eb52c0e5b3b9135ebceca819ef57a3da76c", - "summary": "/tmp/stock-bot-wave14.JYfazy/strategy-summary.json", - "summary_sha256": "a324e580dcf562567041082338ab4e35a5455289a50cc6d6a5eb497843bed285", - "timed_sessions": 48, - "untimed_reference_captures": 24, - "total_bars_per_workload": 10000, - "rows": [ - { - "profile": "none", - "assets": 1, - "owners": 1, - "decisions": 9999, - "recorded_ms": 860.6842254999999, - "stateful_ms": 948.9492395000002, - "added_ms": 88.26501400000029, - "added_percent": 10.255214558942827, - "recorded_decision_ms": 11.100141499980168, - "stateful_decision_ms": 94.17082600002038, - "full_result_hash": "ba38c860ec1ea215118f3cee4ffbb214d4d22c00e6b5f59fcc041570e6595d39" - }, - { - "profile": "none", - "assets": 10, - "owners": 2, - "decisions": 1998, - "recorded_ms": 357.3840935, - "stateful_ms": 371.74131, - "added_ms": 14.357216499999993, - "added_percent": 4.0173070825268775, - "recorded_decision_ms": 2.3033820000006813, - "stateful_decision_ms": 19.935226999995734, - "full_result_hash": "c9d2f8c913394fa37b3a4e057567ffa1463413ec5dbcda9c2c26109078b27103" - }, - { - "profile": "sparse", - "assets": 1, - "owners": 1, - "decisions": 9999, - "recorded_ms": 907.9061945000001, - "stateful_ms": 1050.4517705, - "added_ms": 142.54557599999998, - "added_percent": 15.700473998693475, - "recorded_decision_ms": 10.62779800000419, - "stateful_decision_ms": 100.2197030000076, - "full_result_hash": "96cd34df8ef15c5dfb50607035ea3ddd038e66e248fd5e2cbf85c6255e487ff2" - }, - { - "profile": "sparse", - "assets": 10, - "owners": 2, - "decisions": 1998, - "recorded_ms": 511.2353980000001, - "stateful_ms": 527.2819215, - "added_ms": 16.046523499999864, - "added_percent": 3.1387739508600854, - "recorded_decision_ms": 2.3143130000000838, - "stateful_decision_ms": 26.409344500000202, - "full_result_hash": "35cbb5cabda1716a87ae54442f214f4030ddadf9e894271a90d6852590ea8211" - }, - { - "profile": "turnover", - "assets": 1, - "owners": 1, - "decisions": 9999, - "recorded_ms": 1568.5752975, - "stateful_ms": 1881.493087, - "added_ms": 312.9177895, - "added_percent": 19.94917234759015, - "recorded_decision_ms": 12.920671999951082, - "stateful_decision_ms": 267.69706899998255, - "full_result_hash": "f6f92431d08c1f52d4b5ceea4860b9607750da2d0c07ce68e57c92d23a1e948d" - }, - { - "profile": "turnover", - "assets": 10, - "owners": 2, - "decisions": 1998, - "recorded_ms": 1924.771716, - "stateful_ms": 2211.8719705, - "added_ms": 287.1002544999999, - "added_percent": 14.9160678179874, - "recorded_decision_ms": 3.2020279999999275, - "stateful_decision_ms": 279.2468269999845, - "full_result_hash": "ecf3f66cc98da3a6813c6a33f31ecb9f26ede7d6f1ac57eb6375c95a11279263" - } - ], - "assertion": "Exact captured decision replay preserves every financial ID and complete projection hash. Repeated/reversed program order preserves diagnostic/RNG hashes. Integer-cent oracle verifies this fixed fixture.", - "interpretation": "Stateful wall overhead 14-313 ms /3.1-19.9%, including construction, state validation/staging, RNG, callbacks and admission feedback. This is a profiling baseline, not pure callback cost or justification for a DSL/cache.", - "limitations": [ - "Timed sessions are in a warmed process after an untimed reference capture; four samples per mode in counterbalanced separate processes.", - "Each callback updates four scalar fields and draws once; no complex models/large state/shared features are measured.", - "Both modes retain a decision tape; peak RSS includes it and reference activity. Oracle/hash verification excluded from executionWallMs.", - "10000 total bars, not per asset. No queue/storage/durable job, cold-start SLA, allocation attribution or isolated-host confidence interval.", - "S01 decision IDs enlarge payloads compared with F08 conformance. Only the exact-decision paired control measures stateful overhead without that confound." - ] - } - }, - "limitations": [ - "Trusted synchronous author contract, not an untrusted-code sandbox or proof of arbitrary JS determinism.", - "Diagnostic snapshots cannot resume financial state. Retry reconstructs the whole attempt from frozen data/config, initial states and original seeds.", - "Feedback represents native admission effects, not a complete later fill-event stream; current holdings/orders remain native views.", - "Existing financial/time/risk/model limitations remain; multi-asset default mark-policy gate unresolved." - ], - "cleanup": "Stopped only disposable --rm fixtures 0547b8ad5629caea34a7191d44c09beba2f58770dcc2d57e938526a39118864f and a6b5721f9cce058e341abbba8f33234bda1cef318ae3d438fa4e95181f4feeac. Development services untouched; worktrees/logs/archives retained.", - "next": "After acceptance: S02 one SMA program and explicit trusted worker composition; no additional economic-policy approval needed for its scoped task. R01/R11 await ADR-006; S03/R05 retain paper/default activation gates." - }, - "fifteenth_wave": [ - "S02" - ], - "fifteenth_wave_base": "2bcadbd117c288577a26615e6d132cf49ea074e4", - "fifteenth_wave_notes": [ - "S01 accepted after frozen-hash and diff verification. No new-wave implementation commit yet.", - "Pinned S02 explicit long-only version, reviewed crossover arithmetic, exact owner-budget whole-share sizing, monotonic available observations and native Fresh gating; legacy semantics unchanged.", - "Minimal trusted worker selection/result envelope binds exact strategy provenance and native identity/policy/format. No callback/source/path or checkpoint transport.", - "S03 is code/ADR-ready but not authorized in this wave. R05 owns durable/default/public result cutover; ADR-006/007/008 remain pending.", - "Paired S02 benchmark demonstrates aggregate TS strategy/state overhead, especially 252-bar windows. P08 is a narrow planned follow-up, recommended after S02 acceptance; no optimization or extra task implementation in this wave." - ], - "fifteenth_wave_validation": { - "state": "validated_uncommitted", - "work_root": "/tmp/stock-bot-wave15.zi3GmP", - "committed_before_implementation": [ - "2bcadbd117c288577a26615e6d132cf49ea074e4", - "4f6e44a85395929a16a0d7ba622f7ae7986e4afe" - ], - "scope": "One explicitly versioned long-only SMA and strict trusted selection through existing native worker. No Rust financial semantics, legacy registry, SQL, web/default or paper migration.", - "source_integration": { - "owner_files": 10, - "exact_hashes": { - "apps/stock/orchestrator/src/contracts/builtin-strategy.ts": "bd648e863f00419a7210b17ccc796ab72ba4e72edf5c04cd61af9e61527bc4d2", - "apps/stock/orchestrator/src/strategies/canonical-sma.ts": "d76ba01e40f3eed073bcada2b40078bba6f0f1702fb9e7fcdca0278775d4b01b", - "apps/stock/orchestrator/src/contracts/strategy-replay.ts": "fccba629266524c4e2a79dc95d5a89f4eea3e64b5790ea7a1c38c8121360528b", - "apps/stock/orchestrator/src/backtest/native-worker-protocol.ts": "43b0e01fd59cb6bbd483e4858555e0cdc4666c3e4835786d01442ab86520f1e5", - "apps/stock/orchestrator/src/backtest/native-worker.ts": "0f5583d72aad6841962d017565fadcecb6be775ff6b8abacbb54da9a5e0f95e1", - "apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts": "fdfa65d61b22c959ec83c83a19e6e9acbaee7d8d855b950ab30306b65b65565c", - "test/fixtures/canonical-sma.ts": "138aa061225a8d6340c788c1e914fc6eb9649234718eb273ffe5139cc6f3acb1", - "test/integration/canonical-sma.test.ts": "18d523784e5f7b3ad81729cc04de0c2af27e804e8cb0b30cda0b94551403c15b", - "test/integration/canonical-strategy-worker.test.ts": "5b0410932e96d5091e19761fba7cc3d6a2e3944cad796f55fe369fd4d0553942", - "test/fixtures/canonical-strategy-worker.ts": "546a6fc502a53260ece4361177bc4e784e97ec3f2423f65193d231eba06149bc" - }, - "reviewed_hash_list_sha256": "44780f2b0f276e74c4e1b28b7297ac37a51537942e97e9595686b77ab46bb662", - "source_archive": "/tmp/stock-bot-wave15.zi3GmP/integrated-source.tar", - "source_archive_sha256": "660604296a75dc148e82622e92d8459e7d795b672ff8d4644dc6ae9a408ae948", - "measured_source": { - "root": "/home/boki/repos/stock-bot", - "commit": "4f6e44a85395929a16a0d7ba622f7ae7986e4afe", - "dirty": true, - "sha256": "8c5cd9d17e3870ebe21e95f2013b39ef00d7aa981245471f6a801fa162c42696", - "files": 1179 - }, - "note": "Only planning records changed after measurement; all ten source hashes remain independently reviewed and validated. Reconstruct measured source from planning commit4f6e44a plus the ten-file archive." - }, - "review": { - "reviewer": "/root/s02_review", - "disposition": "Approved frozen strategy and worker integration, no blocking findings; read-only review. Reviewed measurements and supports narrow P08 follow-up; no reviewer tests/builds.", - "root_takeover": "Worker owner approval request stalled about415s and aborted with no test session; explicit ownership handoff permitted root final corrections/validation.", - "corrections": [ - "Mutation test now starts with a detached mutable dataset rather than mutating the intentionally frozen fixture.", - "Schema min(1) preserves nonempty arrays without unnecessary input tuples; request author type uses schema input; readonly expectations copied for Bun strict types." - ] - }, - "checks": [ - { - "command": "CARGO_BUILD_JOBS=2 bun run check", - "result": "passed", - "counts": { - "tooling": 78, - "utilities": 43, - "calculations": 44, - "integration": 432, - "rust": 144, - "rust_manual_ignored": 4 - }, - "log": "/tmp/stock-bot-wave15.zi3GmP/integration-check.log" - }, - { - "command": "bunx tsc --project /tmp/stock-bot-wave15.zi3GmP/tsconfig.integration.json --noEmit", - "result": "passed", - "log": "/tmp/stock-bot-wave15.zi3GmP/integration-test-types.log" - }, - { - "command": "Scoped ESLint --no-ignore --max-warnings 0 and Prettier --check over all ten integrated TypeScript files; git diff --check", - "result": "passed" - }, - { - "command": "PIPELINE_TEST_DATABASE_URL=postgres://fixture:fixture@127.0.0.1:32814/stock_bot_safety BACKTEST_TEST_REDIS_URL=redis://127.0.0.1:32813/15 bun run test:postgres", - "result": "passed", - "tests": 58, - "assertions": 345, - "log": "/tmp/stock-bot-wave15.zi3GmP/integration-postgres.log" - }, - { - "command": "CARGO_BUILD_JOBS=2 bun run --cwd apps/stock/engine build:release", - "result": "passed", - "log": "/tmp/stock-bot-wave15.zi3GmP/integration-native-release.log" - }, - { - "command": "bun test test/integration/canonical-sma.test.ts test/integration/canonical-strategy-worker.test.ts scripts/test/native-bindings.test.ts", - "result": "passed against release addon", - "tests": 48, - "assertions": 175, - "log": "/tmp/stock-bot-wave15.zi3GmP/integration-release-focused.log" - }, - { - "command": "bun /tmp/stock-bot-wave15.zi3GmP/packaged-worker-smoke.ts", - "result": "built dist/native-worker.js matches direct native trace/projection/report", - "evidence": { - "verified": true, - "summaries": [ - { - "resultFormat": "trace", - "sha256": "73bc6b6c195547ad32df76613e25195c806e66d4f81e7e4ee4034d4200561055" - }, - { - "resultFormat": "projection", - "sha256": "1ea0bc7ceb82d7cf70ab40a597cea9963e65303a92fead25ef04f69f313009e0" - }, - { - "resultFormat": "report", - "sha256": "643a06a8824134f7cbf2a1c1b981c7bebfabe3ce86ba0ac3312ac0ad02a6a00e" - } - ] - }, - "harness_sha256": "fef64af8f6f38870a8470a168c19e0b9d9ee5bad59371f0a7aed00ae9927c2de" - } - ], - "environment_notes": [ - "Root restricted IPC test stalled and was interrupted, then unrestricted focused tests passed42/160; full/release gates used required subprocess permissions.", - "Dedicated worker test typing initially exposed array-tuple/readonly expectation issues; corrected before final strict pass.", - "Browser and Python boundaries unchanged; those suites not rerun." - ], - "financial_fixture": { - "fast": 2, - "slow": 3, - "closes": [ - 3, - 2, - 1, - 4, - 5, - 1, - 1 - ], - "ownerBudget": "40", - "initialCapital": "10000", - "quantity": "10", - "entryNextOpen": "5", - "exitNextOpen": "2", - "feeRate": "0.01", - "totalFees": "0.7", - "terminalEquity": "9969.3" - }, - "native": { - "path": "/home/boki/repos/stock-bot/apps/stock/engine/dist/engine.node", - "sha256": "6fe9dae546b4fc1d50b064b2ad50b0a3d08a0208ede3c568bf0f95e549c57b9e", - "artifact": "/home/boki/repos/stock-bot/target/release/libengine.so", - "buildProfile": "release", - "generated_types_sha256": "62c0338e9909e6bfe3feb713949fb3b063bf2b5831044763bdbdb9cf87f9f703", - "note": "Same native release artifact as S01/F08; no Rust change." - }, - "performance": { - "command": "bun /tmp/stock-bot-wave15.zi3GmP/sma-benchmark.ts", - "harness": { - "path": "/tmp/stock-bot-wave15.zi3GmP/sma-benchmark.ts", - "sha256": "f0f6ec1957c752635597d6c91c725ae1ab55287fb1b445bc6095f93cde106b0c" - }, - "raw_file": "/tmp/stock-bot-wave15.zi3GmP/sma-release.json", - "raw_sha256": "0e0231722401933564e4ea390146c71615a6e96241f4472c3d801d96f7923485", - "log": "/tmp/stock-bot-wave15.zi3GmP/sma-release.log", - "host": { - "platform": "linux", - "arch": "x64", - "kernel": "6.8.0-146-generic", - "cpu": "AMD Ryzen 9 9950X3D 16-Core Processor", - "logicalCpus": 32, - "memoryBytes": 98683457536, - "loadAverage": [ - 1.24, - 2.03, - 3.06 - ] - }, - "host_load_at_finish": [ - 2.8, - 2.38, - 3.09 - ], - "runtime": { - "bun": "1.2.17", - "nodeCompatibility": "v22.6.0", - "executableSha256": "6cd2f181c30d3cb1497b0b9d4bc9d63eb1ec4a9142f809183fed18fcc4e1051b", - "rustc": "rustc 1.88.0 (6b00bc388 2025-06-23)", - "bunLockSha256": "1a2b653bbaaeb5075785b860487557b8fc379f0c50cbe8f2554c90e4a3ac4514", - "cargoLockSha256": "8f2ecaa4f1790f14e1650326f78fbf246f454dad6139dc4cb0d61383b9e301e8" - }, - "timed_sessions": 48, - "untimed_reference_sessions": 24, - "smoke": "passed all three short-period shapes; raw sma-smoke.json retained", - "summary": [ - { - "workload": { - "totalBars": 10000, - "assets": 1, - "owners": 1, - "fastPeriod": 5, - "slowPeriod": 15, - "untradedAssets": 0 - }, - "verified": true, - "samples_per_mode": 4, - "recorded_ms": 1091.0554985, - "sma_ms": 1466.9523095, - "added_ms": 375.89681099999984, - "added_percent": 34.45258389850825, - "sma_decision_phase_ms": 326.81869449997794, - "sma_bars_per_second": 6816.854191673367, - "decisions": 9999, - "fills": 997, - "full_financial_hash": "25fadb03424da2ab9c7e405358332ae89de492a83c71882e8bbef04b1d7f318e" - }, - { - "workload": { - "totalBars": 10000, - "assets": 10, - "owners": 2, - "fastPeriod": 5, - "slowPeriod": 15, - "untradedAssets": 8 - }, - "verified": true, - "samples_per_mode": 4, - "recorded_ms": 409.59593200000006, - "sma_ms": 478.2034970000001, - "added_ms": 68.60756500000002, - "added_percent": 16.750060154406032, - "sma_decision_phase_ms": 66.50624600000037, - "sma_bars_per_second": 20911.599481674217, - "decisions": 1998, - "fills": 194, - "full_financial_hash": "02afdf4e00a589bdae0c66ab4416a6d8cbb130543deb4ff5b4a8e18421a7250e" - }, - { - "workload": { - "totalBars": 10000, - "assets": 10, - "owners": 10, - "fastPeriod": 5, - "slowPeriod": 15, - "untradedAssets": 0 - }, - "verified": true, - "samples_per_mode": 4, - "recorded_ms": 624.1090814999999, - "sma_ms": 916.3397714999999, - "added_ms": 292.23069, - "added_percent": 46.82365609832904, - "sma_decision_phase_ms": 275.0971249999985, - "sma_bars_per_second": 10912.982619569733, - "decisions": 9990, - "fills": 970, - "full_financial_hash": "3616bfd9c6061abb217bd5b8451650c68e0167c9830b3b8cf0143323c6513526" - }, - { - "workload": { - "totalBars": 10000, - "assets": 1, - "owners": 1, - "fastPeriod": 15, - "slowPeriod": 252, - "untradedAssets": 0 - }, - "verified": true, - "samples_per_mode": 4, - "recorded_ms": 1018.2021005000001, - "sma_ms": 2350.8183565, - "added_ms": 1332.6162559999998, - "added_percent": 130.87934658017332, - "sma_decision_phase_ms": 1201.672781500027, - "sma_bars_per_second": 4253.837806034675, - "decisions": 9999, - "fills": 975, - "full_financial_hash": "056f9253b2b2c9ce00aab6fa6776534e931e87273b7c1ea75e345ff57e999971" - }, - { - "workload": { - "totalBars": 10000, - "assets": 10, - "owners": 2, - "fastPeriod": 15, - "slowPeriod": 252, - "untradedAssets": 8 - }, - "verified": true, - "samples_per_mode": 4, - "recorded_ms": 409.37107850000007, - "sma_ms": 636.4676205, - "added_ms": 227.09654199999989, - "added_percent": 55.47449586133864, - "sma_decision_phase_ms": 223.09511149999656, - "sma_bars_per_second": 15711.718362269776, - "decisions": 1998, - "fills": 150, - "full_financial_hash": "99f624549deb03d41a9ca47030ef5f39bdb98f497063af6c4bf8adc5fee013af" - }, - { - "workload": { - "totalBars": 10000, - "assets": 10, - "owners": 10, - "fastPeriod": 15, - "slowPeriod": 252, - "untradedAssets": 0 - }, - "verified": true, - "samples_per_mode": 4, - "recorded_ms": 593.9949515000001, - "sma_ms": 1681.4738735, - "added_ms": 1087.478922, - "added_percent": 183.07881561178553, - "sma_decision_phase_ms": 1042.1618619999977, - "sma_bars_per_second": 5947.163472236965, - "decisions": 9990, - "fills": 750, - "full_financial_hash": "fb8024de3c4a710d5e7773575d59ad4904a4955ef14a15d6122bf7284526e98c" - } - ], - "limitations": [ - "10,000 TOTAL bars in full workloads, not per asset. Synthetic sawtooth fixture unchanged; one owner per selected asset. Ten-assets/two-owners explicitly leaves eight assets untraded while all ten replay/mark.", - "No database, durable queue, public-result mapping, real native-worker IPC, or production wall-clock throughput measurement. Each child imports modules and directly executes the canonical runtime.", - "Each fresh child first runs an untimed SMA reference to capture exact submitted financial identities. Timed fresh sessions therefore run in warmed processes; imports, preparation, reference capture and process wall time are separate.", - "Actual versioned SMA code uses bounded slow+1 JSON history and reviewed trailing calculations. Both 5/15 and 15/252 are measured; large-period copying/scanning costs remain included.", - "Recorded control replays exact captured decisions through the same Rust/native pull loop. Complete financial projection hashes including all IDs must match; there is no TypeScript accounting oracle or financial normalization.", - "executionWallMs includes native-session construction, replay, state copying/strategy/staging/feedback where applicable, finalization and disposal. Benchmark verification/hashing is measured separately.", - "decisionMs includes host validation/state copying/strategy execution/admission feedback for SMA and tape lookup/checks for recorded control. Difference is not pure callback or NAPI crossing cost.", - "Both modes retain reference decision tapes; RSS includes reference activity and tape memory. No allocation attribution or resident-dataset caching claim.", - "Two separate processes per mode, two fresh timed sessions each, counterbalanced mode order. Second SMA session reverses owner callback order and must preserve financial and diagnostic hashes. This checks fresh whole-attempt recomputation, not native checkpoint resume.", - "Shared host, no timing assertion, confidence interval, cold-start SLA, or cross-artifact performance attribution. Root must freeze source and use the matching release addon before execution." - ], - "interpretation": "Verified aggregate host/strategy/state overhead, not per-function attribution. Long-window decision phase is about51\u201362%of total owner-dense wall. Profiles in P08 must distinguish schema parsing, copying/freezing, trailing calculations and allocation before optimization. No cross-shape scaling or S02 speedup claim." - }, - "cleanup": { - "stopped_exact_containers": [ - "d42bc73629ccfc7d816ad6d603a0131b3cd95fe53be0cc68d0bafadbf0bf2407", - "6333a832a853e86a35b7a646e96ede511e9a22fcc90ff58643f70ad702dd8db2" - ], - "development_resources_touched": false, - "worktrees_and_evidence_retained": true - }, - "next": "Accept/commit S02; recommended next P08 measured local TS decision/state optimization. S03 also code/ADR-ready; R01/R11 still require ADR-006. No extra task/default/paper approval inferred." } } diff --git a/docs/development/backlog/tasks/F08.md b/docs/development/backlog/tasks/F08.md index fa376813..3188cf47 100644 --- a/docs/development/backlog/tasks/F08.md +++ b/docs/development/backlog/tasks/F08.md @@ -13,34 +13,30 @@ Scheduling source of truth: [manifest entry F08](../manifest.json). No task is a ## Intended behavior and implementation scope -F09 now supplies the independently deliverable compact terminal/owned-fill projection. F08 consumes it and adds historical sampling/statistical reporting; do not duplicate its native transport work. F09 is not completion of this story. - Use canonical Rust ledger postings, owned fills, occupied intervals and session-ending marks as the sole financial inputs. Reuse reviewed TypeScript statistical functions in `libs/calculations/src/analytics/` for return ratios and reports; do not port them to Rust merely for language uniformity. Add a small adapter for the engine-declared session calendar rather than blindly regrouping every venue by UTC date. -Version economics and metrics independently. Define sampling, annualization, benchmark and risk-free conventions in the result policy. Missing benchmark/risk-free inputs must not silently become invented measurements. Undefined or unsupported metrics are null with reasons. Add a reusable canonical analytics DTO alongside the existing result types; R05 owns persisted/public-result cutover. Do not coerce owned financial facts into incompatible legacy position/round-trip fields or rewrite old rows. +Version economics and metrics independently. Define sampling, annualization, benchmark and risk-free conventions in the result policy. Missing benchmark/risk-free inputs must not silently become invented measurements. Undefined or unsupported metrics are null with reasons. Adapt existing result DTOs without rewriting old rows. Measurable benefit: comparable, independently checked rankings without a second ledger or a needless analytics rewrite. -Before implementation, pin reporting-only conventions in the handoff: account boundaries currently execute before equal-time observations and are not automatically close-equity samples; partial final sessions must be explicit; exposure needs a declared elapsed/venue-time denominator; the reviewed statistics currently assume 252 periods and default to 2% risk-free, so the adapter must pass a supported explicit policy and diagnose omitted inputs. These choices must not alter financial event ordering or risk semantics. Fills are not round trips. - ## Exclusions No accounting/fill recomputation in TypeScript, statistical library rewrite, forced native port, new service, or silent reinterpretation of historical results. Native analytics remain an option only if measured as a bottleneck. ## Likely files and ownership -- apps/stock/engine/src/financial/result.rs and replay reporting hooks (canonical outputs; legacy simple_results.rs remains separate) +- apps/stock/engine/src/backtest/simple_results.rs (authoritative projections, not new statistical formulas) - apps/stock/orchestrator/src/backtest/native-result.ts - apps/stock/orchestrator/src/backtest/BacktestReport.ts - libs/calculations/src/analytics/return-statistics.ts - libs/calculations/src/analytics/equity.ts (review existing UTC grouping; use explicit session marks) - libs/core/types/src/backtest-run.ts -Write locks: result-contract, native-public-api, replay-reporting, canonical-analytics, calculation-statistics. One owner controls the Rust/native reporting contract. A separate analytics owner may implement disjoint shared types/calculations/adapter files after root pins the contract; consume the exact accepted schema before integration. Lock names do not override actual overlapping files. +Write locks: result-contract. One agent owns this change. Lock names do not override actual overlapping files. ## Dependencies and blockers -Implementation requires [F06](F06.md) and [F09](F09.md) integrated. +Implementation requires [F06](F06.md) integrated. Architecture decisions: ADR-002, ADR-003. Agents may not independently amend their policies. @@ -52,7 +48,6 @@ Parallel eligibility: only with disjoint actual files and reserved write locks; - Sharpe uses periodic excess-return mean/std; Sortino uses downside deviation relative to the declared target; zero-variance/undefined cases are null with reasons. - Exposure uses the union of occupied intervals; open positions count; attribution distinguishes fills and round trips. - Reviewed calculation functions are reused where their conventions match. Any deliberate difference has a versioned policy and independent arithmetic fixture, not an unexplained second formula. -- The additive canonical analytics DTO preserves nullable/unsupported metrics and fill ownership without invoking legacy percentage conversion. Existing result mapping and frontend fixtures remain unchanged and pass. Persisted canonical rows/public DTO conversion remain R05; this story does not enable canonical web runs. - Preserve the sequential equal-time marking policy and its material risk limitation in result provenance: intermediate valuations may latch halts despite a recovered synchronized value. Do not report such traces as atomically marked portfolio risk. Before canonical multi-asset default cutover, apply R05's explicit owner policy-review gate; component F06 acceptance does not satisfy it. ## Mandatory tests @@ -70,66 +65,3 @@ Keep migrations additive and previous results readable. Do not add a switch that ## Handoff Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done. - -## Execution contract — 2026-10-23 - -Owner instruction: commit accepted F09/P07 and continue the backlog. F09/P07 are committed in `e3bd722`; F08 is the next code/ADR-ready story. These are reporting conventions, not changes to approved financial/risk policy. - -### Native financial reporting owner - -- Keep `Replay.events`, event indexes/IDs, `ReplayConfig`, `ReplayCheckpoint`, all financial receipts and existing trace/projection wire output unchanged. Add a small private reporting accumulator; restore already replays the retained decisions and must rebuild identical reporting facts without a new checkpoint schema. -- Periods follow the initial account risk session plus declared risk boundaries. Clip to `[tradeStart, tradeEnd]`; never infer UTC or asset venue days. At each boundary, sample the preceding period after **all** equal-time Observation events, before Decision/Execution. Risk reset still occurs in its existing earlier phase. Initial equity comes from Rust, and terminal equity is always retained. -- First periods clipped by tradeStart have `partialStart`; final periods without a declared closing boundary at tradeEnd have `partialEnd`. An exact terminal boundary emits one preceding period, not a zero-length new period. Retain partial returns/history but exclude them from full-period statistics. Last available marks remain explicit; do not claim freshness or atomic portfolio risk. -- Exposure is the union of account occupancy intervals over elapsed calendar time, including overnight/weekends. Observe actual non-replayed committed fills, then use existing `Ledger::owned_quantities().next().is_some()`; no quantity reconstruction. Merge adjacent intervals, omit zero-length intervals, and clip open holdings at tradeEnd for measurement only. No synthetic closing fill. Encode `occupiedMs`/`elapsedMs` as canonical nonnegative integer strings to preserve durations spanning the supported timestamp domain. -- Sampling failures must not reorder or mutate financial transitions or overwrite a financial failure. Report access rejects incomplete/failed/disposed or unavailable reporting state. -- Add native `report(identityJson)` beside unchanged `finalize()`/`project()`. Wire output is `format: "report"`, `reportingVersion: 1`, `projectionVersion: 1`, `financialVersion: 1`, the existing provenance/view/limitations and financial `projection`, plus `reporting` below. Keep reporting outside strategy contexts. - -```ts -reporting: { - calendarId: string; - calendarRevision: string; - tradeStart: number; - tradeEnd: number; - initialEquity: FinancialDecimal; - sampling: 'account-boundary-after-observations-v1'; - exposureBasis: 'elapsed-calendar-time'; - sessions: { - session: RiskSessionIdentity; - periodStart: number; - periodEnd: number; - partialStart: boolean; - partialEnd: boolean; - equity: FinancialDecimal; - }[]; - occupiedIntervals: { start: number; end: number }[]; - occupiedMs: string; - elapsedMs: string; -} -``` - -- Extend the same TS native session/conformance/worker path with explicit `resultFormat: "report"`, strict parsing and captured format/identity/policy guards. Old omitted/trace/projection behavior and hashes stay stable. Root accepts the schema before the analytics consumer integrates it. - -### TypeScript analytics owner - -- Add application-independent `CanonicalBacktestAnalytics`/policy types adjacent to `BacktestRunResult`, without widening/reinterpreting the legacy DTO. One orchestrator adapter composes `{ financial: ReplayReportResult, analytics: CanonicalBacktestAnalytics }`. -- Adapter input requires policy version 1, positive finite `periodsPerYear`, explicit finite `annualRiskFreeRate` or `null`, and `benchmark: null`. Benchmark-dependent metrics are unavailable in v1; reject unsupported benchmark input. Output policy also records the fixed conventions, calendar identity and units. These are recorded conventions, not new configurable switches. -- Compute ratios from authoritative equity samples only. Include every session return, including partial terminal periods, with eligibility flags. Use only complete periods with defined positive baselines for periodic statistics; do not silently discard undefined full-period returns to create a different sequence. -- Reuse reviewed `returnStatistics`, equity/drawdown helpers and primitives. Extend `returnStatistics` minimally with explicit periods/year and nullable risk-free input, preserving old defaults for existing callers. Missing risk-free input leaves volatility/tail statistics available but target-dependent ratios/downside deviation null. Sample standard deviation uses n−1; downside RMS uses all n observations relative to annualRiskFreeRate/periodsPerYear. Exactly constant finite input has zero deviation; no arbitrary epsilon. -- Drawdown is explicitly session-end/terminal-sampled, not maximum intraday drawdown. Total return uses initial-to-terminal equity; CAGR may use actual elapsed calendar time with the fixed 365-day-year convention, including partial endpoints. This does not treat a partial period as a complete session. Zero/nonpositive baselines and nonfinite/undefined results produce null with reasons. -- Reuse a narrowly extracted drawdown-only helper instead of invoking unused UTC Date grouping, since native safe-integer timestamps exceed JavaScript Date's range. Positive initial equity and elapsed time with terminal equity zero has CAGR −1; negative terminal equity remains unsupported. Pin both edge cases with independent tests. Policy must state that marks are last available and per-session freshness is not certified. -- Report `fillCount` separately. Round-trip count/win rate/profit factor/average win/loss are unsupported/null; no inferred trade grouping, position marks, average cost or financial postings. Preserve exact Rust financial facts in the composed report. -- Keep legacy `BacktestReport`, normalization, stored-row mapping and UI unchanged. R05 will consume this additive contract during its separately gated persistence/public-result migration. Existing compatibility tests must pass. - -### Required additional validation - -- Rust: boundary sample after observations versus unchanged earlier risk reset; equal-time sequential risk halt still latched; first/final partial periods and exact terminal-boundary deduplication; exposure overlap/open positions/same-time owner handoff; no trade/stale marks; restore after every event including within observation groups; unchanged financial checkpoint/trace/project results. -- TS/native: report format/identity/calendar/terminal-value validation; worker format/cancellation/failure guards; two sessions 100 → 110 → 99 yield +10%/−10%; partial returns retained but not annualized as full sessions; missing rates/benchmark; constant negative and nonbinary constant returns; unsupported round trips remain null; genuine zero exposure survives the additive adapter. -- Run existing calculation, mapping and frontend metric/provenance fixtures, full repository checks and scoped strict test TypeScript. Worker changes require disposable PostgreSQL/Redis recovery gates. Measure reporting overhead against the accepted compact path with identical economic hashes; no timing assertions, new cache/DSL, journal deletion, or unrelated hot-loop optimization. - -## Reviewed implementation handoff — 2026-10-23 - -Implemented in `financial/reporting.rs` and replay hooks, native `FinancialReplaySession.report()`, the existing TS native/worker contract, additive `CanonicalBacktestAnalytics` types and `backtest/canonical-result.ts`. Existing reviewed calculations supply statistical reporting; no legacy DTO or default runner cutover. - -Independent review, exact owner-source integration, repository gates, disposable recovery and release-format comparisons passed. Full check initially found an incomplete decision trace in the new integration fixture; the corrected test explicitly submits every due hold and passes. See [wave handoff](../../ROADMAP.md#thirteenth-wave-execution--2026-10-23) and the canonical manifest validation record for commands, counts, hashes, initial unfavorable timings and the unchanged-artifact control. New implementation remains uncommitted. - -R05 must consume the additive contract without filling unsupported round-trip/benchmark statistics or legacy position fields with invented values. S01 does not need another reporting contract. Long-session statistical throughput remains unmeasured; the six benchmark fixtures each contain one partial account period. diff --git a/docs/development/backlog/tasks/F09.md b/docs/development/backlog/tasks/F09.md deleted file mode 100644 index 0dc602af..00000000 --- a/docs/development/backlog/tasks/F09.md +++ /dev/null @@ -1,48 +0,0 @@ -# F09 — Return compact canonical replay projections - -Parent epic: E2. Priority/severity: P1 / High. Complexity: M. Specialist: Rust/TypeScript financial integration. - -Story: As a researcher, I can obtain authoritative terminal holdings, P&L and actual fills without serializing the complete nested execution journal, while retaining full diagnostics when needed. - -Scheduling and ownership: [manifest F09](../manifest.json). This is the independently deliverable projection portion of F08, not a replacement for its historical metrics. - -## Evidence and root cause - -- **PER-01 / KEEP-02 — Verified:** [full native finalization](../../../../apps/stock/engine/src/api/replay.rs#L165) exports every nested matching receipt through a JSON value tree. The recorded F07 release workload emits 66.7MB/103.6MB at 10k total bars; finalization averages 0.963s/1.377s, approximately 35–39% of trial time. This is conformance output, not useful minimal research output. -- **FIN-05 — Verified:** [Ledger::valuation](../../../../apps/stock/engine/src/financial/ledger.rs#L674), [FinancialEffect](../../../../apps/stock/engine/src/financial/contract.rs#L327) and existing ledger receipts already contain authoritative terminal values, realized basis/P&L, actual fees and ownership. Recomputing these in TypeScript would create competing financial authority. - -## Scope and pinned contract - -- Add a small Rust projection module. Emit the existing terminal snapshot/view, checked Ledger valuation and owner contributions, plus flattened actual fills copied from committed commands/effects in authoritative order. Retain IDs, event time, owner/decision/order/fill, side/quantity/price, fee, cash/quantity deltas, released basis and realized gross P&L. Fills are not completed round trips. -- `cashDelta` preserves the ledger effect's gross notional movement; the fee is a separate posting, not an additional fee already included in that delta. Valuation owner contributions include reserve capital and can be negative. Schema coherence checks compare the returned cash/equity strings with the existing view without reproducing accounting arithmetic. -- Iterate borrowed ledger receipts once, skipping replay-labelled aliases. A read-only ledger receipt accessor and serialization derives for existing valuation types are allowed. No checkpoint cloning, ledger reconstruction, replay or financial arithmetic duplication to produce output. Preserve internal receipts, idempotency indexes and restore behavior. -- Add native `project(identityJson)` beside the unchanged full diagnostic `finalize(identityJson)`. Compact output has `format: "projection"`, `projectionVersion: 1`, `financialVersion: 1`, the same identity/status/manifest/policy/view/limitations, and `projection: { valuation, fills }`; it has no nested `receipts`. Use typed serialization with borrowed metadata where practical. -- TS adds a strict projection parser and typed `NativeReplaySession.project()`. The existing conformance loop may select `resultFormat: "projection" | "trace"`; old omitted-format calls and the existing diagnostic parser retain their trace behavior. No second loop. New compact consumers explicitly select projection; active legacy/durable defaults do not change. -- The existing fixed-trace worker request may carry the optional format; the parent captures expected format with identity/policy and rejects mismatched responses. Both formats share completion, failure, disposal and cancellation guards. -- Extend observational metrics with finalization native-call time (including Rust work/serialization), JSON decode time, schema-validation time and disposal time. Keep these outside economic outputs and deterministic hashes; do not call them pure crossing measurements. Expose unavailable internal Rust/GC splits honestly. - -## Exclusions - -No session-close equity curve, return ratios, Sharpe/Sortino, exposure percentage, round-trip win rate, invented defaults or legacy DTO coercion: these remain F08. No journal deletion/compaction, new accounting, risk/timing changes, new persistence/service, pagination, DSL, cache or default engine/paper/live cutover. - -## Files and ownership - -- `apps/stock/engine/src/financial/result.rs` and tests; `ledger.rs` read-only accessor/valuation serialization; module registration. -- `apps/stock/engine/src/api/replay.rs` and generated binding verification. -- `apps/stock/orchestrator/src/contracts/native-replay.ts`, `backtest/native-replay.ts`, existing worker supervisor/dispatch as needed. -- Focused native/projection/worker fixtures and tests. Benchmark files belong to P07; root coordinates final paired comparisons. - -Write locks: financial-projection, native-public-api, worker-protocol, result-contract. One owner. Dependencies: F07; approved ADR-002/003/004. P07 baseline work is independent; benchmark integration uses the frozen projection contract, not concurrent reinterpretation. - -## Acceptance and mandatory tests - -1. `compact_full_financial_parity`: terminal snapshot/valuation/flattened fills agree with the retained full trace and independent hand-calculated fixtures; all amounts remain canonical decimal strings. -2. `projection_aliases_once`, `partial_fill_projection`, `two_owner_projection`: duplicate command/fill aliases do not duplicate output, partial fills remain distinct, owner attribution and fees reconcile, including final residual basis. No-trade output has zero fills and honest terminal values. -3. `projection_is_read_only`: repeated project/finalize calls preserve state/checkpoints and original diagnostic output; restored sessions produce the same projection. Full-trace fixture hashes remain unchanged. -4. `projection_terminal_guard`, `projection_identity_policy_format`: incomplete/failed/disposed sessions cannot return successful compact output; malformed identities, policies and requested formats reject, including worker races/cancellation and post-result abort. -5. Strict TS/schema/architecture/native gates pass. No receipt/future-data leakage into strategy contexts; no broadening of worker-only native reachability. -6. Paired release measurements on the same frozen dataset/config/decisions show identical financial projection hashes and reduced output bytes/finalization cost. Preserve full trace as an explicit diagnostic oracle. Record actual before/after; no timing threshold in CI and no promised speedup. P07 supplies representative workload variants. - -Regression risk: alias double counting, effect-to-fee mispairing, silently changed output semantics or a successful result from failed state. Review G1/G2 independently; retain existing F07 regressions and disposable worker/runner durability gates. Rollback is additive API deployment, not weaker financial policies. - -Definition of done: reviewed source, exact integrated test/benchmark evidence and canonical manifest handoff. No commit/push/PR without separate authorization. diff --git a/docs/development/backlog/tasks/P07.md b/docs/development/backlog/tasks/P07.md deleted file mode 100644 index 4bed2b39..00000000 --- a/docs/development/backlog/tasks/P07.md +++ /dev/null @@ -1,42 +0,0 @@ -# P07 — Profile representative canonical replay workloads - -Parent epic: E7. Priority/severity: P1 / High. Complexity: M. Specialist: performance/test infrastructure. - -Story: As a platform developer, I can distinguish replay, financial turnover, result transport and diagnostic overhead before choosing the next optimization. - -Scheduling and ownership: [manifest P07](../manifest.json). Extend P01's existing harness; do not create another benchmark framework. - -## Evidence and root cause - -- **PER-01 — Verified:** the F07 [turnover profile](../../../../scripts/benchmark-replay.ts#L100) alternates positions at every barrier. At 10k total bars it creates 9,999/19,980 fills; 2.65–3.61s is not the cost of merely reading bars. -- In the original F07 measurement, finalization consumed approximately 35–39%; fixture decisions less than 2%; native creation approximately 3%. Before F09, the [adapter](../../../../apps/stock/orchestrator/src/backtest/native-replay.ts#L184) combined native work and JSON validation, without a separate disposal timer. These measurements did not establish a pure NAPI overhead, Rust bottleneck, or need for a DSL. - -## Scope - -- Extend `scripts/benchmark-replay.ts`, `scripts/benchmark-research.ts` and their tests only. Reuse frozen fixture generation, source/addon/host/runtime hashes and cold-process/fresh-session structure. -- Add `none` (same callbacks/cadence, no targets), `sparse` (one opening and one closing fill per owner/asset), and `turnover` (existing alternating unit targets) profiles. Preserve existing invocation behavior; expose explicit CLI profile/format selection and an opt-in 100k size. No new application input limits. -- Measure verified dataset preparation, native load, actual advance/submit/decision/finalization/disposal phases, emitted bytes, observed fills/decisions/calls, wall time and process RSS. Consume optional finalization subphase metrics only after the contract owner publishes them. Do not infer internal Rust/GC time from an unexplained residual. -- Independent integer-based fixture oracles remain test/benchmark-only. Repeated runs/reversed callback evaluation must preserve economic output. Full trace keeps exact normalized-result hash validation; compact/full comparisons use the same canonical financial projection, not unlike wire-envelope hashes. -- Baseline profiles work against committed F07 independently. Paired compact runs are enabled only after F09's contract is frozen/accepted by root; do not edit adapter/schema/native files to make the benchmark fit. Record the exact source/artifact for each baseline/candidate. -- Run selected 10k and explicitly requested 100k workloads sequentially. Report unavailable measurements/resource failures honestly rather than silently trimming data/traces. Full-history 100k diagnostic output can be large; no throughput claim for cases not run. - -## Exclusions - -No financial semantic change, arbitrary hot-loop refactor, native dataset cache, shared feature framework, worker pool, DSL, new service, web paging or journal deletion. Select a concrete next optimization from evidence; implementation beyond F09 requires a scoped follow-up. - -## Dependencies, locks and parallelism - -Code prerequisites: F07 and P01. No new economic policy or ADR-008 approval is needed for measurements alone. P03/P04/P06 remain gated. Write lock: benchmark-harness, with the three explicit files above. Safe parallel work with F09's separate core/adapter files. Compact comparison is a conditional integration gate requiring F09; baseline compilation/tests must not depend on unmerged native APIs. - -## Acceptance and mandatory tests - -1. `profile_none`, `profile_sparse`, `profile_turnover` pin deterministic call/fill/fee/basis/terminal-equity expectations, including multiple owners/assets and retained session gaps. -2. `benchmark_profile_arguments` rejects unsupported flags/combinations; existing P01/F07 invocation and tiny tests still work. -3. `profile_identity_mismatch` rejects changed dataset/policy/strategy/native result identity; profile/result format is included in provenance. Different profiles are never compared as equivalent economics. -4. `compact_trace_projection_parity` and reversed callback order agree on authoritative projection; diagnostics remain complete and independently testable. -5. No fake zero/unavailable timings, no timing-flaky assertions. Print raw repeated rows and a concise breakdown with timing boundaries/build profile. Distinguish first process/setup from reused prepared JS inputs and fresh native sessions. -6. Integrated evidence documents measured candidate effects, remaining unattributed costs and the smallest justified next action. No unsupported 10x/100x claim. - -Regression risk: benchmark oracle mistakes, comparing different policies/profiles, or profiling work inside a purported engine-only timer. Mandatory focused tooling/native fixtures, strict TypeScript and scoped lint; financial/result owner reviews oracle/parity independently. No native rebuild concurrent with another agent's artifact review. - -Definition of done: reproducible script/tests, baseline and accepted-candidate measurements, independent review and root manifest handoff. Missing resource-dependent large runs must be explicit; not a pass. No commits/pushes/PRs without authorization. diff --git a/docs/development/backlog/tasks/P08.md b/docs/development/backlog/tasks/P08.md deleted file mode 100644 index 8801b32c..00000000 --- a/docs/development/backlog/tasks/P08.md +++ /dev/null @@ -1,38 +0,0 @@ -# P08 — Reduce measured TypeScript strategy decision overhead - -Parent epic: E7. Priority/severity: P1 / High. Complexity: M. Specialist: TypeScript performance and deterministic runtime engineering. - -Story: As a researcher, I can run realistic window-based TypeScript strategies without repeatedly paying avoidable state-validation or copying costs. - -Scheduling source of truth: [manifest P08](../manifest.json). This story is planned, not authorized for implementation in S02's wave. - -## Evidence and root cause - -**PER-02 — Verified aggregate cost; individual causes need profiling.** S02's release comparison replays exactly the same financial decisions and IDs. For 10,000 total bars, recorded decisions versus SMA callbacks took 1,091→1,467 ms (5/15, one owner) and 1,018→2,351 ms (15/252, one owner). With ten assets/ten owners, 15/252 took 594→1,681 ms. All 48 timed sessions preserve complete financial hashes; repeat/reversed-owner runs preserve diagnostics. These are warmed synthetic workloads, not durable-job throughput or pure callback/NAPI measurements. - -Potential contributors are the [host staging boundary](../../../../apps/stock/orchestrator/src/backtest/strategy-runtime.ts#L205), strict JSON copying/freezing, [per-callback SMA state parsing](../../../../apps/stock/orchestrator/src/strategies/canonical-sma.ts#L128), bounded history and [reviewed trailing calculations](../../../../libs/calculations/src/indicators/window-statistics.ts#L50). The aggregate difference does not attribute cost among them. Larger windows also change decisions and fills; compare each strategy with its own exact recorded control, not the two periods as identical economics. - -Raw evidence/harness/source identity: `manifest.json` → `fifteenth_wave_validation.performance`; [roadmap](../../ROADMAP.md#fifteenth-wave-execution--2026-10-23). Retained local harness: `/tmp/stock-bot-wave15.zi3GmP/sma-benchmark.ts`. - -## Scope and exclusions - -1. Extend the existing research benchmark entrypoint with the S02 paired strategy/recorded workload; incorporate the useful temporary harness logic into existing tooling, not another benchmark framework. Preserve cold import/preparation versus warmed-session boundaries, source/addon hashes, raw samples, counts and exact comparisons. -2. Profile actual calculation, schema parsing, state copy/freezing, host admission feedback and allocations. Measure instrumentation separately; a residual is not a named subsystem cost. -3. Implement the smallest evidenced local optimization in `backtest/strategy-runtime.ts`, `strategies/canonical-sma.ts` or their private helpers. Avoid changing public contracts. Publish a proposed exact file scope before editing shared runtime/strategy files. -4. Preserve strict JSON state validation, detached immutable contexts, per-owner isolation, staged commit-after-native-ack, failure diagnostics, scoped RNG, whole-attempt retry, reviewed crossover arithmetic, financial decisions and result provenance. Do not special-case away validation for trusted built-ins or change strategy semantics to make the benchmark faster. - -No Rust financial changes, DSL, worker pool, resident dataset/feature framework, shared mutable checkpoints, public/default cutover, weakened validation, arbitrary input limits or general cleanup. Incremental indicator arithmetic or a new state contract needs a separately reviewed proposal; neither is assumed necessary. - -## Dependencies, ownership and parallelism - -Code prerequisites: S02 accepted/integrated, P07 complete. No additional policy approval for profiling/local semantics-preserving optimization. One owner holds strategy-contract, strategy-builtins and benchmark-harness locks for the minimal patch; disjoint review may run in parallel. Do not overlap S03/S05 or another worker using those actual files. Root alone updates task state. No native rebuild during measurements or artifact review. - -## Acceptance and mandatory tests - -- `sma_benchmark_modes` validates selection/period/topology arguments, labels ten-assets/two-owners as eight untraded assets, and reports actual decisions/fills rather than inferring equal work from bar count. -- `sma_recorded_decision_parity` compares identical captured decision IDs and complete financial outputs for 5/15 and 15/252, with 1/1, 10/2 and 10/10 asset/owner shapes. Fresh retries and reversed program order preserve diagnostic/RNG/state hashes. Retain raw repeated measurements and the exact baseline/candidate artifacts. -- Profile identifies the removed cost. Counterbalance baseline/candidate runs on the same host/release addon and configurations; show repeatable end-to-end improvement larger than observed run-to-run variation on both 15/252 owner-dense workloads, with the smaller workloads checked for regression. Do not claim an optimization from changed economics, instrumentation overhead or host drift. If no safe local improvement is demonstrated, hand off the blocker/proposal rather than mark implementation complete. -- Preserve all `canonical-sma`, `strategy-runtime`, `native-replay`, worker and runtime tooling regression tests. Add a focused regression for each changed state/validation path, including retained mutable references, malformed JSON, callback failure after prior owners staged, native rejection and malformed/ambiguous admission feedback as relevant. Accessors must not execute; prototype/cycle/symbol/sparse/non-finite/negative-zero rejection and future-information isolation remain intact. No unstable wall-time assertions in unit tests. -- Strict TypeScript for new test/tooling sources, scoped lint/format, full `bun run check`, final release verification and G2 recovery if worker/durable boundaries change. Independent reviewer signs off both invariants and measurement methodology. - -Risks: accidental mutable aliasing, skipped validation, changed floating-point crossover arithmetic, committing partial owner state, misleading benchmark attribution. Revert a failed optimization without weakening economic policy or deleting reviewed helpers. Definition of done: focused reviewed patch, passing gates and repeatable exact-economics measurements; root acceptance and explicit commit authorization remain separate. diff --git a/docs/development/backlog/tasks/R05.md b/docs/development/backlog/tasks/R05.md index e775ad3e..c86e5e2d 100644 --- a/docs/development/backlog/tasks/R05.md +++ b/docs/development/backlog/tasks/R05.md @@ -14,8 +14,6 @@ Scheduling source of truth: [manifest entry R05](../manifest.json). No task is a Freeze strategy/model artifact IDs, parameters, seed, code/lockfile/build hashes and execution policies at submission. For a selected frozen dataset, pin its hash immediately; for a source request, retain the immutable query and atomically attach the first prepared dataset/hash before replay begins. Expose preparing versus reproducibility-finalized state. Wire the canonical Rust session with existing registered TS strategies into the durable runner and versioned result DTO. Exact reproduction API/UI is R12. -Consume F08's additive canonical analytics/report contract here. Version the persisted/public projection so canonical fractions, genuine zero exposure and null reasons bypass legacy percentage conversion/placeholder suppression. Preserve owner books and distinguish fills from round trips. Additional position valuations needed by the UI must come from Rust or be explicitly unavailable; do not invent marks, average-price basis or unrealized P&L in TypeScript merely to satisfy the old DTO. Keep historical readers unchanged and prove reopen/render compatibility during this cutover. - Measurable benefit: Creates reproducible, project-gated runs usable by humans and AI. ## Exclusions @@ -50,7 +48,6 @@ Parallel eligibility: only with disjoint actual files and reserved write locks; - mutate_template_after_submit, freeze_before_first_decision, frozen_seed_replay, provider_change_after_dataset_bind. - Full durable runner restart/lease/cancel suite and result contract compatibility. -- Canonical reporting fractions/zero/null reasons, owner attribution and fill-versus-round-trip semantics survive persistence/reopen/UI rendering; existing legacy rows retain their prior interpretation. - Multi-asset default activation rejects while the mark-policy disposition is absent; accepted policy/version/limitations are frozen in provenance, with offsetting-mark regression evidence. Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist. diff --git a/docs/development/backlog/tasks/S01.md b/docs/development/backlog/tasks/S01.md index da92ec5e..2d39cc76 100644 --- a/docs/development/backlog/tasks/S01.md +++ b/docs/development/backlog/tasks/S01.md @@ -57,27 +57,3 @@ Keep migrations additive and previous results readable. Do not add a switch that ## Handoff Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done. - -## Execution contract — 2026-10-23 - -The owner accepted F08 and requested continuation after the handoff explicitly named S01 and linked ADR-005. Base `3838295`; manifest revision `2026-10-23.31`. Root reserves the strategy contract/shared pull driver/native feedback parser to one owner; independent test author owns disjoint test/measurement files after the API is pinned. No Rust financial semantics, worker request protocol, active legacy registry, SQL/paper operation or default cutover changes. - -- Add `runStrategyReplay(load, programs, options)` as a trusted host primitive. Programs have owner ID, strategy ID/version, fixed target/orders mode, explicit uint32 seed, initial JSON state and a synchronous `decide(context) -> {nextState, intent}`. Owner IDs are unique and exactly match native configuration; strategy IDs/versions may repeat for independent instances. Capture/detach inputs at attempt creation. Do not pass execution services, native handles, future data or state belonging to other owners into author callbacks. -- Context contains the engine time/barrier, the same frozen portfolio view for every due callback, owned positions, newly available observations since that owner's prior decision, previous admission feedback, readonly typed state and a scoped `random()`. Cadence controls scheduling; it must not discard another owner's pending observations. Warmup is consumed through the same prefix. Account information remains visible for portfolio-aware strategies; isolated state/feedback belongs only to its owner. -- Extract one internal pull loop used by the existing conformance wrapper and the new runtime. Keep existing trace IDs, output hashes, observation delivery and format defaults stable for conformance. The runtime stages all due decisions/states before one native batch; only a validated successful response commits all prepared state/RNG/observation/sequence slots. A native risk rejection is a valid state transition; a failed/ambiguous submit disposes the attempt. -- Per-owner RNG uses versioned `lcg32-v1`, the existing unsigned 32-bit `Math.imul(state,1664525)+1013904223` recurrence, divided by 2^32. Track state/draw count and safe decision counters. Invalidate the scoped RNG function immediately after the synchronous callback, including exceptions. This is reproducible fixture randomness, not a cryptographic or statistical-independence claim. -- Reject non-JSON, lossy/nonfinite state, async outputs, invalid intents and wrong modes before admission. Detach/freeze input and returned state; do not let caller mutation or retained callback references rewrite a committed snapshot. Copying small strategy state is acceptable; never clone native financial history per observation. -- Admission feedback copies validated native `Order` effects for the owner, including native rejection reasons and cancellation of that owner's earlier decisions. `Running` is not proof of order acceptance. Feedback is available at that owner's next decision and retained in terminal diagnostics. This is not a complete fill-event stream: subsequent fills appear in authoritative positions/open orders; S01 does not invent execution events or accounting. -- Return `{result, metrics, diagnostics}`. Versioned diagnostic snapshots contain identity, committed barrier count/last ID, sorted owner records with state, next decision sequence, RNG state/draw count, consumed observation count and previous admission feedback. `StrategyReplayError` carries the last confirmed committed diagnostics and cause, never a successful financial result. Fault tests may spy on the native host submit method; no generic session factory is needed. -- Retry means an entirely fresh native session with the original frozen inputs, detached initial states and per-owner seeds. Recompute every cursor and decision. Diagnostic TS snapshots are **not resumable financial checkpoints**. Do not expose a TS-only restore API or add native checkpoint transport for this task. Existing Rust reconstruction and paper checkpoints remain intact. -- Direct trusted program objects suffice here. S02 supplies the first real SMA strategy and trusted worker composition; R01/A02 own immutable/untrusted artifacts and isolation. Keep the existing legacy `StrategyRegistry` instead of broadening its execution-service factory into the canonical author API. - -Required regression scenarios include mixed owner cadence/warmup, reversed callback order and independent RNG draws, prefix/future-suffix integrity, late callback failure after a committed barrier, ambiguous post-native-submit failure, risk-rejection feedback with state advancement, repeated/partial targets, owned cancellation feedback, frozen/retained-reference isolation, invalid state/Promise/mode rejection, and compile-time absence of financial mutation services. Fresh retries must equal uninterrupted decision/state/RNG/economic results. Preserve existing conformance/result hashes and paper recovery tests. Measure deterministic strategy staging on representative release workloads without a DSL/cache or an unrelated hot-loop optimization. - -## Reviewed implementation handoff — 2026-10-23 - -Implemented the pinned contract in `contracts/canonical-strategy.ts`, `backtest/strategy-runtime.ts`, the shared native replay loop and a narrow native order-feedback decoder. The exact architecture allowlist adds only the new trusted host runtime; direct native entry points remain unchanged. `tsconfig.contracts.json` permanently includes the author type tests. - -Independent review found and fixed two issues before acceptance: rejected async callbacks could leave unhandled rejections, and optional-looking Zod unknown fields accepted an empty feedback tag. Actual Promises are now observed without awaiting; arbitrary thenables remain invalid and uninvoked. Feedback tags require object payloads while nested financial diagnostics stay opaque. Subprocess regressions cover immediate, delayed and foreign-realm rejection; native failure tests prove all-owner atomic diagnostic state. - -Full repository checks passed (78 tooling, 43 utility, 44 calculation, 390 integration, 144 Rust tests), plus 58 disposable recovery tests, 43 focused release tests and extra strict test TypeScript/lint/formatting. The 48-session paired benchmark preserves every financial ID/hash; measured stateful overhead is 14–313 ms across six 10,000-total-bar workloads. This includes validation/staging/feedback, not pure callback cost. See the [wave handoff](../../ROADMAP.md#fourteenth-wave-execution--2026-10-23) and canonical manifest for exact commands, hashes and measurement limitations. New S01 implementation remains uncommitted. diff --git a/docs/development/backlog/tasks/S02.md b/docs/development/backlog/tasks/S02.md index 44fe15f4..8b17a2a9 100644 --- a/docs/development/backlog/tasks/S02.md +++ b/docs/development/backlog/tasks/S02.md @@ -19,11 +19,12 @@ No unrelated refactor, new service or broker activation. ## Likely files and ownership -- `apps/stock/orchestrator/src/contracts/builtin-strategy.ts` and `strategies/canonical-sma.ts`: one strategy/schema owner. -- `apps/stock/orchestrator/src/contracts/strategy-replay.ts` and the existing native worker protocol/child/supervisor: a disjoint worker owner consumes the pinned selection schema. -- Dedicated strategy and worker integration tests/fixtures follow those owners. Root owns planning/integration; review is independent. +- apps/stock/orchestrator/src/strategies/StrategyRegistry.ts +- apps/stock/orchestrator/src/strategies/BaseStrategy.ts +- apps/stock/orchestrator/src/strategies/builtin/SmaCrossoverStrategy.ts +- apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy.ts -Preserve the legacy registry, BaseStrategy and built-ins unchanged; reuse their alias mapping. No generic registry rewrite. Actual overlapping files override symbolic locks. +Write locks: strategy-builtins. One agent owns this change. Lock names do not override actual overlapping files. ## Dependencies and blockers @@ -54,29 +55,3 @@ Keep migrations additive and previous results readable. Do not add a switch that ## Handoff Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done. - -## S01 integration handoff — 2026-10-23 - -Consume `contracts/canonical-strategy.ts` and `backtest/strategy-runtime.ts`: typed synchronous programs return JSON next state and financial intent; the host owns per-instance seeds/cursors and Rust owns admission/accounting. Reuse reviewed calculation semantics. Preserve the current legacy factory contract; add only the small trusted built-in resolver/composition needed to select the canonical SMA version deliberately. - -Wire that reviewed built-in through the existing native worker with explicit strategy/version/parameters and retained dataset/config inputs. Never serialize callback functions/source or accept arbitrary module paths. Keep legacy and conformance requests intact; unknown canonical strategies/versions reject explicitly. R05 still owns durable default and public-result migration. No browser/default activation or paper migration is implied here. - -S01 retries whole attempts from frozen inputs and original state/seeds. Its snapshots are diagnostic, not native resume tokens. `sma_checkpoint_restore` should verify indicator state serialization/recomputation and full retry equivalence without introducing TS-only mid-run financial resume. Admission feedback is not a complete fill-event feed; positions/open orders remain authoritative native views. - -## Execution contract — 2026-10-23 - -S01 is accepted as `2bcadbd`. The trusted selection is `{ownerId, strategyId, strategyVersion, seed, instrumentId, seriesId, ownerBudget, parameters: {fastPeriod, slowPeriod}}`. Existing SMA aliases normalize to `sma_crossover`; the explicit new version is `sma-crossover-long-only/v1`. Reject legacy quantity/fraction/holding-period parameters and unknown fields on this version. It deliberately differs from legacy short entries and account-wide sizing. - -One instance consumes one declared instrument/series included in its native cadence. Use the reviewed `movingAverageCrossover` with a bounded `slowPeriod + 1` close window, including warmup and its existing equality rules. Process availability-order observations only if their `(event_time, source_sequence)` advances; delayed older observations do not rewrite history. A real golden cross establishes a whole-share target `floor(ownerBudget / close)` using exact decimal inputs; no minimum-one purchase. Hold that target through the bullish phase, including ties; a death cross establishes zero. Repeat the same target on fresh selected input so native target reconciliation preserves or retries commitments. Missing, stale or no-new selected input emits sparse empty targets, preserving existing GTC intent. Match the last accepted observation to the native Fresh input before emitting a target. Budget is desired gross notional, not a new hard risk allocation; Rust alone handles fees, gaps, funding and risk. - -Keep finite plain JSON indicator state; validate reconstruction without exposing initial-state injection over IPC. Whole-attempt retries start from original inputs. No rolling-sum arithmetic rewrite or feature-cache framework. - -Add strict `runStrategyReplay` version1 requests with existing dataset/config/eventBudget/resultFormat and trusted selections only. Return a versioned `strategyReplayResult` envelope containing normalized selections actually executed and the unchanged native result. The parent captures detached normalized inputs before fork and binds selections, native identity, policy and format on return. No callbacks, source, arbitrary paths, checkpoint transport or second worker infrastructure. Existing legacy/conformance requests remain supported. - -Required additions: warmup/tie/delayed-bar/freshness cases; exact budget and native fee/gap rejection; separate owners; whole retry and JSON reconstruction; real worker/direct equality in all formats; malformed/tampered responses, crashes and cancellation (including result-before-close); legacy worker regressions. Full repository and disposable recovery gates follow integration. Measure representative release SMA replay without calling it pure callback cost or claiming a performance improvement. - -## Validated handoff — 2026-10-23 - -The new schema and `createBuiltinStrategy`/`validateBuiltinStrategyBindings` implement the pinned contract; the legacy registry and built-ins are unchanged. `runStrategyReplay` requests carry only trusted selections. `parseStrategyReplayResult` validates the versioned envelope and all native result formats. New tests and existing gates pass; exact source hashes, commands and measurements are in the manifest's fifteenth-wave validation and roadmap handoff. Implementation remains uncommitted pending acceptance. - -Worker provenance identifies the reviewed built-in/version/configuration. R01/R05 still own immutable code-artifact retention, durable/public results and default activation. Whole-attempt retry remains the recovery model. [P08](P08.md) records the measured state/decision overhead; optimization and financial-policy changes are outside S02. diff --git a/libs/calculations/README.md b/libs/calculations/README.md index d50a1ef8..07ec1140 100644 --- a/libs/calculations/README.md +++ b/libs/calculations/README.md @@ -20,10 +20,9 @@ const risk = returnStatistics(returns); - `./returns`: simple/log returns, explicit percentage-point conversion, CAGR and annualization. Inputs must be finite. Invalid price baselines throw, not return zero. - CAGR is `null` for zero elapsed time, negative ending capital or unrepresentable - output. With positive initial capital and elapsed time, zero terminal capital has - CAGR −1. Other nonrepresentable outputs throw. Annualization requires an explicit - positive number of periods/year. + CAGR is `null` for zero elapsed time, nonpositive ending capital or unrepresentable + output. Other nonrepresentable outputs throw. Annualization requires an explicit + positive number of periods/year; return statistics below intentionally use daily data. - `./indicators`: O(n) batch SMA plus trailing mean, population deviation and crossover helpers shared with the supported TypeScript strategies. SMA output index 0 belongs to source index `period - 1`; incomplete batch warm-up is `[]`, scalar warm-up is @@ -43,13 +42,8 @@ const risk = returnStatistics(returns); identity: partition qualified venue/instrument IDs before calculating any feature. - `./analytics`: the existing tested fraction-based equity/drawdown, observed daily return/factor, closed-trade and performance calculations, moved from the orchestrator. - `returnStatistics(returns, annualRiskFree, periodsPerYear)` supports an explicit - frequency and nullable risk-free input; omitted arguments retain the legacy 2%/252 - defaults. Null risk-free leaves target-dependent metrics unavailable while preserving - independently defined volatility/tail statistics. `drawdownAnalysis` uses numeric - timestamps without UTC grouping; `equityAnalysis` and legacy performance reporting - retain their UTC grouping. Undefined ratios are `null`, sample deviation uses n−1, - and downside deviation uses full-series RMS. Trade holding periods are minutes. Persisted strategy + Daily statistics use 252 periods/year, UTC grouping, sample volatility and explicit + `null` for undefined ratios. Trade holding periods are minutes. Persisted strategy versions and execution/checkpoint behavior are unchanged. The legacy Kelly/leverage fields in `performanceAnalysis` remain compatibility heuristics, not optimizers. diff --git a/libs/calculations/src/analytics/equity.ts b/libs/calculations/src/analytics/equity.ts index 3da1b89f..6f48a585 100644 --- a/libs/calculations/src/analytics/equity.ts +++ b/libs/calculations/src/analytics/equity.ts @@ -27,8 +27,7 @@ export function ratio(numerator: number, denominator: number): number | null { : nullable(numerator / denominator); } -/** Sampled drawdowns only; no UTC grouping or JavaScript Date range restriction. */ -export function drawdownAnalysis(points: readonly EquityPoint[], initialCapital: number) { +export function equityAnalysis(points: readonly EquityPoint[], initialCapital: number) { if (finite(initialCapital) <= 0) { throw new Error('Initial capital must be positive'); } @@ -38,6 +37,8 @@ export function drawdownAnalysis(points: readonly EquityPoint[], initialCapital: let maxDrawdown = 0; const periods: DrawdownPeriod[] = []; const underwater: EquityPoint[] = []; + const daily = new Map(); + const monthly = new Map(); for (const [index, point] of points.entries()) { finite(point.timestamp); finite(point.value); @@ -45,6 +46,9 @@ export function drawdownAnalysis(points: readonly EquityPoint[], initialCapital: throw new Error('Equity observations must be ordered'); } previousTimestamp = point.timestamp; + const iso = new Date(point.timestamp).toISOString(); + daily.set(iso.slice(0, 10), point.value); + monthly.set(iso.slice(0, 7), point.value); if (point.value >= peak) { if (active) { periods.push({ @@ -76,24 +80,6 @@ export function drawdownAnalysis(points: readonly EquityPoint[], initialCapital: if (active) { periods.push(active); } - return { - maxDrawdown, - currentDrawdown: Math.abs(underwater[underwater.length - 1]?.value ?? 0), - maxDrawdownDuration: periods.reduce((max, period) => Math.max(max, period.duration), 0), - periods, - underwater, - }; -} - -export function equityAnalysis(points: readonly EquityPoint[], initialCapital: number) { - const drawdown = drawdownAnalysis(points, initialCapital); - const daily = new Map(); - const monthly = new Map(); - for (const point of points) { - const iso = new Date(point.timestamp).toISOString(); - daily.set(iso.slice(0, 10), point.value); - monthly.set(iso.slice(0, 7), point.value); - } const first = points[0]; const last = points[points.length - 1]; const elapsedDays = first && last ? (last.timestamp - first.timestamp) / dayMs : 0; @@ -107,11 +93,11 @@ export function equityAnalysis(points: readonly EquityPoint[], initialCapital: n totalReturn, annualizedReturn, elapsedDays, - maxDrawdown: drawdown.maxDrawdown, - currentDrawdown: drawdown.currentDrawdown, - maxDrawdownDuration: drawdown.maxDrawdownDuration, - periods: drawdown.periods, - underwater: drawdown.underwater, + maxDrawdown, + currentDrawdown: Math.abs(underwater[underwater.length - 1]?.value ?? 0), + maxDrawdownDuration: periods.reduce((max, period) => Math.max(max, period.duration), 0), + periods, + underwater, // First observed period uses starting capital; no first-day loss/gain is discarded. dailyReturns: [...periodReturns(daily, initialCapital).values()], monthlyReturns: Object.fromEntries(periodReturns(monthly, initialCapital)), diff --git a/libs/calculations/src/analytics/index.ts b/libs/calculations/src/analytics/index.ts index 06e16349..736bd17b 100644 --- a/libs/calculations/src/analytics/index.ts +++ b/libs/calculations/src/analytics/index.ts @@ -1,4 +1,4 @@ -export { dayMs, drawdownAnalysis, equityAnalysis, finite, nullable, ratio } from './equity'; +export { dayMs, equityAnalysis, finite, nullable, ratio } from './equity'; export type { DrawdownPeriod, EquityPoint } from './equity'; export { factorStatistics, mean, returnStatistics, sampleDeviation } from './return-statistics'; export { tradeStatistics } from './trade-statistics'; diff --git a/libs/calculations/src/analytics/return-statistics.ts b/libs/calculations/src/analytics/return-statistics.ts index a6fdb072..3d0694ed 100644 --- a/libs/calculations/src/analytics/return-statistics.ts +++ b/libs/calculations/src/analytics/return-statistics.ts @@ -12,15 +12,7 @@ export function mean(values: readonly number[]): number | null { } export function sampleDeviation(values: readonly number[]): number | null { const average = mean(values); - if (values.length < 2) { - return null; - } - // Summing identical nonbinary fractions can perturb their mean. An exactly - // constant finite series has zero variance, without an arbitrary epsilon. - if (values.every(value => value === values[0])) { - return 0; - } - if (average === null) { + if (values.length < 2 || average === null) { return null; } return nullable( @@ -28,40 +20,26 @@ export function sampleDeviation(values: readonly number[]): number | null { ); } -/** Periodic fractions, arithmetic excess returns and full-series downside RMS. - * Existing callers retain 252 periods/year and 2% annual risk-free defaults. - * Explicit null means the target is unavailable, not an assumed zero rate. */ -export function returnStatistics( - returns: readonly number[], - annualRiskFree: number | null = 0.02, - periodsPerYear = 252 -) { - if (annualRiskFree !== null) { - finite(annualRiskFree); - } - if (finite(periodsPerYear) <= 0) { - throw new RangeError('Periods per year must be positive'); - } +/** Observed daily fractions; 252 periods/year, arithmetic excess returns, full-series downside RMS. */ +export function returnStatistics(returns: readonly number[], annualRiskFree = 0.02) { + finite(annualRiskFree); for (const value of returns) { finite(value); } const average = mean(returns); const deviation = sampleDeviation(returns); - const annualExcess = - average === null || annualRiskFree === null - ? null - : nullable(average * periodsPerYear - annualRiskFree); - const volatility = deviation === null ? null : nullable(deviation * Math.sqrt(periodsPerYear)); + const annualExcess = average === null ? null : nullable(average * 252 - annualRiskFree); + const volatility = deviation === null ? null : nullable(deviation * Math.sqrt(252)); const downsideDeviation = - returns.length < 2 || annualRiskFree === null + returns.length < 2 ? null : nullable( Math.sqrt( returns.reduce( - (sum, value) => sum + Math.min(value - annualRiskFree / periodsPerYear, 0) ** 2, + (sum, value) => sum + Math.min(value - annualRiskFree / 252, 0) ** 2, 0 ) / returns.length - ) * Math.sqrt(periodsPerYear) + ) * Math.sqrt(252) ); const sorted = [...returns].sort((a, b) => a - b); const tail = (confidence: number) => { diff --git a/libs/calculations/src/returns.ts b/libs/calculations/src/returns.ts index 70a21a1b..fcbf056a 100644 --- a/libs/calculations/src/returns.ts +++ b/libs/calculations/src/returns.ts @@ -54,11 +54,9 @@ export function cagr(start: number, end: number, years: number): number | null { if (finite(years) < 0) { throw new RangeError('Years must be nonnegative'); } - return years === 0 || end < 0 + return years === 0 || end <= 0 ? null - : end === 0 - ? -1 - : nullable(Math.expm1((Math.log(end) - Math.log(start)) / years)); + : nullable(Math.expm1((Math.log(end) - Math.log(start)) / years)); } export function annualizeReturn(periodicReturn: number, periodsPerYear: number): number { diff --git a/libs/calculations/test/core.test.ts b/libs/calculations/test/core.test.ts index e79871e1..7b3fa779 100644 --- a/libs/calculations/test/core.test.ts +++ b/libs/calculations/test/core.test.ts @@ -51,7 +51,7 @@ describe('reviewed shared calculation contracts', () => { test('annualization has explicit undefined CAGR and validates sampling units', () => { expect(cagr(100, 121, 2)).toBeCloseTo(0.1); expect(cagr(100, 110, 0)).toBeNull(); - expect(cagr(100, 0, 1)).toBe(-1); + expect(cagr(100, 0, 1)).toBeNull(); expect(cagr(100, -10, 1)).toBeNull(); expect(cagr(1, 2, Number.MIN_VALUE)).toBeNull(); expect(() => cagr(0, 10, 1)).toThrow(); @@ -85,7 +85,7 @@ describe('reviewed shared calculation contracts', () => { for (let end = 1; end <= prices.length; end++) { const prefix = prices.slice(0, end); expect(sma(prices, 3).slice(0, Math.max(0, end - 2))).toEqual(sma(prefix, 3)); - expect(trailingMean(prefix, 3)).toBe(sma(prefix, 3).at(-1)); + expect(trailingMean(prefix, 3)).toBe(sma(prefix, 3).at(-1)); } expect(movingAverageCrossover([3, 2, 1, 4], 2, 3)?.goldenCross).toBe(true); expect(() => sma([1, 2], 0)).toThrow(); diff --git a/libs/calculations/test/reporting-primitives.test.ts b/libs/calculations/test/reporting-primitives.test.ts deleted file mode 100644 index de7f1592..00000000 --- a/libs/calculations/test/reporting-primitives.test.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { expect, test } from 'bun:test'; -import { drawdownAnalysis, equityAnalysis } from '../src/analytics/equity'; -import { cagr } from '../src/returns'; - -test('sampled drawdown handles safe-integer timestamps beyond JavaScript Date range', () => { - const points = [ - { timestamp: -Number.MAX_SAFE_INTEGER, value: 100 }, - { timestamp: 0, value: 80 }, - { timestamp: Number.MAX_SAFE_INTEGER, value: 90 }, - ]; - expect(drawdownAnalysis(points, 100).maxDrawdown).toBeCloseTo(0.2); - expect(drawdownAnalysis(points, 100).currentDrawdown).toBeCloseTo(0.1); - expect(() => drawdownAnalysis([...points].reverse(), 100)).toThrow('ordered'); - expect(() => drawdownAnalysis(points, 0)).toThrow('positive'); -}); - -test('extracted drawdowns preserve the legacy equity analysis values and recovery periods', () => { - const points = [100, 110, 80, 90, 120, 100].map((value, i) => ({ - timestamp: i * 86400000, - value, - })); - const sampled = drawdownAnalysis(points, 100); - const legacy = equityAnalysis(points, 100); - expect(legacy).toMatchObject(sampled); - expect(sampled.periods).toHaveLength(2); - expect(sampled.periods[0]?.recovery).toBe(4); - expect(sampled.periods[1]?.recovery).toBeNull(); -}); - -test('CAGR zero terminal is total loss for positive elapsed time while negative terminal is unsupported', () => { - expect(cagr(100, 0, 0.5)).toBe(-1); - expect(cagr(100, 0, 0)).toBeNull(); - expect(cagr(100, -1, 1)).toBeNull(); - expect(cagr(100, 121, 2)).toBeCloseTo(0.1); - // Legacy UTC equity reporting retains its historical zero-terminal convention. - expect( - equityAnalysis( - [ - { timestamp: 0, value: 100 }, - { timestamp: 86400000, value: 0 }, - ], - 100 - ).annualizedReturn - ).toBeNull(); -}); diff --git a/libs/calculations/test/return-statistics.test.ts b/libs/calculations/test/return-statistics.test.ts deleted file mode 100644 index 9b3d5525..00000000 --- a/libs/calculations/test/return-statistics.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { returnStatistics, sampleDeviation } from '../src/analytics/return-statistics'; - -describe('explicit periodic return policy', () => { - test('legacy defaults remain equivalent to explicit 252 periods and 2% annual risk-free', () => { - const returns = [-0.02, 0.01, 0.03, -0.01]; - expect(returnStatistics(returns)).toEqual(returnStatistics(returns, 0.02, 252)); - }); - - test('arithmetic excess and full-series downside RMS use the declared period count', () => { - // Mean=.01, sample variance=.0008; periodic target=.12/12=.01. - // Full-series downside variance=(.02^2+0)/2=.0002. - const result = returnStatistics([-0.01, 0.03], 0.12, 12); - expect(result.volatility).toBeCloseTo(Math.sqrt(0.0008 * 12)); - expect(result.downsideDeviation).toBeCloseTo(Math.sqrt(0.0002 * 12)); - expect(result.sharpeRatio).toBeCloseTo(0); - expect(result.sortinoRatio).toBeCloseTo(0); - expect(returnStatistics([-0.01, 0.03], 0, 4).sharpeRatio).toBeCloseTo( - 0.04 / Math.sqrt(0.0008 * 4) - ); - }); - - test('constant_negative_returns have zero variance but nonzero downside and negative Sortino', () => { - for (const value of [-0.01, -0.1]) { - const result = returnStatistics([value, value, value], 0, 252); - expect(sampleDeviation([value, value, value])).toBe(0); - expect(result.volatility).toBe(0); - expect(result.sharpeRatio).toBeNull(); - expect(result.downsideDeviation).toBeCloseTo(-value * Math.sqrt(252)); - expect(result.sortinoRatio).toBeCloseTo(-Math.sqrt(252)); - } - }); - - test('zero_variance is exact without treating a small genuine deviation as zero', () => { - expect(sampleDeviation([0.1, 0.1, 0.1])).toBe(0); - expect(sampleDeviation([Number.MAX_VALUE, Number.MAX_VALUE])).toBe(0); - expect(sampleDeviation([0.1, 0.1 + Number.EPSILON])).toBeGreaterThan(0); - expect(returnStatistics([0, 0], 0)).toMatchObject({ - volatility: 0, - downsideDeviation: 0, - sharpeRatio: null, - sortinoRatio: null, - }); - expect(returnStatistics([0.01, 0.02], 0).sortinoRatio).toBeNull(); - expect(returnStatistics([0.01], 0).volatility).toBeNull(); - expect(sampleDeviation([])).toBeNull(); - expect(() => sampleDeviation([NaN, NaN])).toThrow('finite'); - }); - - test('missing risk-free leaves independent volatility and tail statistics available', () => { - const returns = Array.from({ length: 100 }, (_, i) => i / 1000 - 0.05); - const missing = returnStatistics(returns, null, 365); - const explicitZero = returnStatistics(returns, 0, 365); - expect(missing).toMatchObject({ - sharpeRatio: null, - sortinoRatio: null, - downsideDeviation: null, - }); - for (const key of [ - 'volatility', - 'var95', - 'cvar95', - 'var99', - 'skewness', - 'kurtosis', - 'tailRatio', - ] as const) { - expect(missing[key]).toEqual(explicitZero[key]); - } - expect(explicitZero.sharpeRatio).not.toBeNull(); - }); - - test('invalid rates, period counts and observations reject', () => { - for (const periods of [0, -1, NaN, Infinity]) { - expect(() => returnStatistics([], 0, periods)).toThrow(); - } - for (const rate of [NaN, Infinity, -Infinity]) { - expect(() => returnStatistics([], rate, 252)).toThrow(); - } - expect(() => returnStatistics([Infinity], null, 252)).toThrow(); - expect(() => returnStatistics(Array(2), null, 252)).toThrow(); - }); -}); diff --git a/libs/core/types/src/canonical-analytics.ts b/libs/core/types/src/canonical-analytics.ts deleted file mode 100644 index 195b6d04..00000000 --- a/libs/core/types/src/canonical-analytics.ts +++ /dev/null @@ -1,85 +0,0 @@ -/** Explicit reporting inputs, independent from financial/execution policy. */ -export interface CanonicalMetricsInput { - version: 1; - periodsPerYear: number; - annualRiskFreeRate: number | null; - /** Benchmark-dependent reporting is unsupported in version 1. */ - benchmark: null; -} - -export interface CanonicalMetricsPolicy extends CanonicalMetricsInput { - calendarId: string; - calendarRevision: string; - sampling: 'account-boundary-after-observations-v1'; - marks: 'last-available-no-per-session-freshness-certification'; - returnUnit: 'fraction'; - variance: 'sample-n-minus-one'; - riskFreeConversion: 'annual-rate-divided-by-periods-per-year'; - downside: 'full-series-rms-relative-to-risk-free'; - partialPeriods: 'visible-excluded-from-periodic-statistics'; - drawdown: 'session-end-and-terminal-sampled'; - exposureBasis: 'elapsed-calendar-time'; - cagrBasis: 'elapsed-calendar-days-365'; - zeroTerminalCagr: 'negative-one-for-positive-elapsed-time'; -} - -export type CanonicalMetricUnavailableReason = - | 'nonpositive-baseline' - | 'negative-terminal-equity' - | 'zero-duration' - | 'nonfinite-result' - | 'undefined-period-return' - | 'insufficient-periods' - | 'missing-risk-free' - | 'missing-benchmark' - | 'zero-variance' - | 'zero-downside-deviation' - | 'unsupported-round-trips'; - -export interface CanonicalSessionReturn { - sessionId: string; - periodStart: number; - periodEnd: number; - partialStart: boolean; - partialEnd: boolean; - value: number | null; - /** Complete period with a defined return; an undefined complete period invalidates - * the entire periodic-statistics sequence, not just this individual sample. */ - eligible: boolean; - reason?: 'nonpositive-baseline' | 'nonfinite-result'; -} - -/** Statistical numbers are approximate reporting values, never ledger postings. */ -export interface CanonicalMetrics { - totalReturn: number | null; - cagr: number | null; - maxDrawdown: number | null; - exposureTime: number | null; - volatility: number | null; - downsideDeviation: number | null; - sharpeRatio: number | null; - sortinoRatio: number | null; - var95: number | null; - cvar95: number | null; - var99: number | null; - alpha: null; - beta: null; - informationRatio: null; - roundTripCount: null; - winRate: null; - profitFactor: null; - avgWin: null; - avgLoss: null; -} - -export interface CanonicalBacktestAnalytics { - version: 1; - policy: CanonicalMetricsPolicy; - sessionReturns: CanonicalSessionReturn[]; - completePeriodCount: number; - /** Zero if any complete-period return is undefined; do not shorten the sequence. */ - periodicSampleCount: number; - fillCount: number; - metrics: CanonicalMetrics; - unavailable: Partial>; -} diff --git a/libs/core/types/src/index.ts b/libs/core/types/src/index.ts index 70040217..629fa12f 100644 --- a/libs/core/types/src/index.ts +++ b/libs/core/types/src/index.ts @@ -51,14 +51,6 @@ export type { BacktestRunTrade, BacktestRunResult, } from './backtest-run'; -export type { - CanonicalMetricsInput, - CanonicalMetricsPolicy, - CanonicalMetricUnavailableReason, - CanonicalSessionReturn, - CanonicalMetrics, - CanonicalBacktestAnalytics, -} from './canonical-analytics'; // Export helper types export type { HasClose, HasOHLC, HasTimestamp, HasVolume } from './helpers'; diff --git a/scripts/benchmark-replay.ts b/scripts/benchmark-replay.ts index 04a579cf..320e5597 100644 --- a/scripts/benchmark-replay.ts +++ b/scripts/benchmark-replay.ts @@ -1,35 +1,11 @@ /** F07 extension of P01, invoked only through benchmark-research.ts --session. */ import { createHash } from 'node:crypto'; import { readFileSync } from 'node:fs'; -import type { FinancialEffects } from '@stock-bot/types'; -import type { - ReplayOutput, - ReplayProjectionResult, - ReplayResultFormat, -} from '../apps/stock/orchestrator/src/contracts/native-replay'; +import type { ReplayResult } from '../apps/stock/orchestrator/src/contracts/native-replay'; -export const replayProfiles = ['none', 'sparse', 'turnover'] as const; -export type ReplayProfile = (typeof replayProfiles)[number]; -export type SessionOptions = { - profiles: ReplayProfile[]; - resultFormat: ReplayResultFormat | 'both'; - totalBars?: number; -}; -type SessionWorkload = { - totalBars: number; - assets: number; - owners: number; - eventBudget: number; - profile: ReplayProfile; - resultFormat: ReplayResultFormat; -}; +type SessionWorkload = { totalBars: number; assets: number; owners: number; eventBudget: number }; const hash = (value: string) => createHash('sha256').update(value).digest('hex'); const capital = '1000000.00000000'; -const profileDefinitions: Record = { - none: 'no-targets-v1', - sparse: 'first-last-unit-target-v1', - turnover: 'alternating-unit-target-v1', -}; function cents(value: bigint): string { const magnitude = value < 0n ? -value : value; @@ -39,12 +15,7 @@ function cents(value: bigint): string { /** 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 profileOracle( - profile: ReplayProfile, - barsPerAsset: number, - assets: number, - owners: number -) { +export function turnoverOracle(barsPerAsset: number, assets: number, owners: number) { if ( ![barsPerAsset, assets, owners].every(Number.isSafeInteger) || barsPerAsset < 3 || @@ -54,26 +25,15 @@ export function profileOracle( throw new Error('Expected at least three bars and positive asset/owner counts'); } let cashDelta = 0n, - fee = 0n, - fillsPerBook = 0; - const lastOpen = BigInt(10 + ((barsPerAsset - 1) % 20) * 2); - if (profile === 'turnover') { - for (let step = 1; step < barsPerAsset; step++) { - const price = BigInt(10 + (step % 20) * 2); - cashDelta += (step % 2 ? -price : price) * 100n - price; - fee += price; - } - fillsPerBook = barsPerAsset - 1; - } else if (profile === 'sparse') { - // Exactly one unit bought at first eligible open12 and sold at last open. - cashDelta = (lastOpen - 12n) * 100n - 12n - lastOpen; - fee = 12n + lastOpen; - fillsPerBook = 2; - } else if (profile !== 'none') { - throw new Error('Unknown replay profile'); + 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 = profile === 'turnover' ? (barsPerAsset - 1) % 2 : 0; + holding = (barsPerAsset - 1) % 2; + const lastOpen = BigInt(10 + ((barsPerAsset - 1) % 20) * 2); const cash = 100_000_000n + cashDelta * books; return { cash: cents(cash), @@ -81,154 +41,13 @@ export function profileOracle( feePerOwner: cents(fee * BigInt(assets)), quantity: `${holding}.00000000`, remainingCost: cents(BigInt(holding) * lastOpen * 100n), - fills: fillsPerBook * assets * owners, + fills: (barsPerAsset - 1) * assets * owners, decisions: (barsPerAsset - 1) * owners, }; } -export function turnoverOracle(barsPerAsset: number, assets: number, owners: number) { - return profileOracle('turnover', barsPerAsset, assets, owners); -} - -/** A desired unit target only, not an accounting/fill model. null means hold. */ -export function profileTarget( - profile: ReplayProfile, - decision: number, - barsPerAsset: number -): 0 | 1 | null { - if (profile === 'none') { - return null; - } - if (profile === 'turnover') { - return decision % 2 ? 0 : 1; - } - if (decision === 0) { - return 1; - } - return decision === barsPerAsset - 2 ? 0 : null; -} - -type SharedFill = Pick< - ReplayProjectionResult['projection']['fills'][number], - | 'commandId' - | 'eventTime' - | 'ownerId' - | 'orderId' - | 'fillId' - | 'instrumentId' - | 'price' - | 'cashDelta' - | 'quantityDelta' - | 'releasedBasis' - | 'realizedGrossPnl' - | 'fee' ->; - -function sharedFill(fill: SharedFill): SharedFill { - return { - commandId: fill.commandId, - eventTime: fill.eventTime, - ownerId: fill.ownerId, - orderId: fill.orderId, - fillId: fill.fillId, - instrumentId: fill.instrumentId, - price: fill.price, - cashDelta: fill.cashDelta, - quantityDelta: fill.quantityDelta, - releasedBasis: fill.releasedBasis, - realizedGrossPnl: fill.realizedGrossPnl, - fee: { feeId: fill.fee.feeId, amount: fill.fee.amount }, - }; -} - -/** Benchmark-only copy of shared authoritative fields. No valuation, fee or P&L - * arithmetic. The trace has no LedgerValuation; that extra compact projection - * remains covered by Rust/independent fixtures, not synthesized in this hash. */ -export function commonFinancialProjection(result: ReplayOutput) { - const fills: SharedFill[] = []; - if ('projection' in result) { - for (const fill of result.projection.fills) { - fills.push(sharedFill(fill)); - } - } else { - for (const receipt of result.receipts) { - if (receipt.outcome.replayed) { - continue; - } - for (const effect of receipt.outcome.effects) { - if (!('Risk' in effect)) { - continue; - } - const risk = effect.Risk as { - outcome: { - replayed: boolean; - disposition: unknown; - financial: null | { replayed: boolean; effects: FinancialEffects }; - }; - }; - if (risk.outcome.replayed) { - continue; - } - if (risk.outcome.disposition !== 'Accepted') { - throw new Error('Unexpected benchmark risk rejection'); - } - const financial = risk.outcome.financial; - if (!financial || financial.replayed) { - continue; - } - const applied = financial.effects.effects.filter(e => e.kind === 'fillApplied'); - const fees = financial.effects.effects.filter(e => e.kind === 'feeApplied'); - if (!applied.length && !fees.length) { - continue; - } - const fill = applied[0], - fee = fees[0]; - if ( - applied.length !== 1 || - fees.length !== 1 || - !fill || - !fee || - fill.ownerId !== fee.ownerId || - fill.fillId !== fee.fillId - ) { - throw new Error('Malformed trace fill/fee pair'); - } - fills.push( - sharedFill({ - ...fill, - commandId: financial.effects.commandId, - eventTime: financial.effects.eventTime, - fee: { feeId: fee.feeId, amount: fee.amount }, - }) - ); - } - } - } - return { - identity: result.identity, - status: result.status, - manifest: result.manifest, - policy: result.policy, - view: result.view, - limitations: result.limitations, - modelLimitations: result.modelLimitations, - fills, - }; -} - -export function assertResultFormat(result: ReplayOutput, expected: ReplayResultFormat): void { - if (('projection' in result ? 'projection' : 'trace') !== expected) { - throw new Error('Benchmark result format mismatch'); - } -} - -function assertEconomics( - result: ReplayOutput, - workload: SessionWorkload, - fills: readonly SharedFill[] -) { - const expected = profileOracle( - workload.profile, +function assertEconomics(result: ReplayResult, workload: SessionWorkload) { + const expected = turnoverOracle( workload.totalBars / workload.assets, workload.assets, workload.owners @@ -237,8 +56,7 @@ function assertEconomics( if ( portfolio.cash !== expected.cash || result.view.equity !== expected.equity || - portfolio.positions.length !== - (workload.profile === 'none' ? 0 : workload.assets * workload.owners) || + portfolio.positions.length !== workload.assets * workload.owners || portfolio.positions.some( p => p.quantity !== expected.quantity || p.remainingCost !== expected.remainingCost ) || @@ -249,10 +67,42 @@ function assertEconomics( ) { throw new Error('Canonical benchmark failed independent cash/equity/owner/basis/fee oracle'); } - if (fills.length !== expected.fills) { + 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: fills.length }; + return { ...expected, fees }; } export async function sessionChild(workload: SessionWorkload) { @@ -271,10 +121,6 @@ export async function sessionChild(workload: SessionWorkload) { const { nativeReplayFixture } = await import('../test/fixtures/native-replay'); const { parseFinancialDecimal } = await import('@stock-bot/types'); const applicationImportMs = elapsed(); - const nativeSha256 = createHash('sha256') - .update(readFileSync(new URL('../apps/stock/engine/dist/engine.node', import.meta.url))) - .digest('hex'); - const artifactIdentityMs = elapsed(); await import('@stock-bot/engine'); const addonImportMs = elapsed(); const { prepareReplayLoad, NativeReplaySession, runReplayConformance } = await import( @@ -317,33 +163,19 @@ export async function sessionChild(workload: SessionWorkload) { owner => { const decision = counts.get(owner) ?? 0; counts.set(owner, decision + 1); - const quantity = profileTarget( - workload.profile, - decision, - workload.totalBars / workload.assets - ); return { mode: 'target', - targets: - quantity === null - ? [] - : fixture.instruments.map(instrumentId => ({ - instrumentId, - quantity: quantity === 0 ? zero : one, - })), + targets: fixture.instruments.map(instrumentId => ({ + instrumentId, + quantity: decision % 2 ? zero : one, + })), }; }, - { - eventBudget: workload.eventBudget, - reverseCallbacks: repeat === 1, - resultFormat: workload.resultFormat, - } + { eventBudget: workload.eventBudget, reverseCallbacks: repeat === 1 } ); const runWallMs = performance.now() - runStart; const validationStart = performance.now(); - assertResultFormat(result, workload.resultFormat); - const common = commonFinancialProjection(result); - const economic = assertEconomics(result, workload, common.fills); + 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'); @@ -351,14 +183,12 @@ export async function sessionChild(workload: SessionWorkload) { // 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 commonFinancialHash = hash(JSON.stringify(common)); const validationAndHashMs = performance.now() - validationStart; const wallMs = performance.now() - trialStart; trials.push({ repeat, reverseCallbacks: repeat === 1, resultHash, - commonFinancialHash, economic, calls: { create: 1, @@ -383,18 +213,6 @@ export async function sessionChild(workload: SessionWorkload) { submit: metrics.submitMs, decisions: metrics.decisionMs, finalize: metrics.finalizeMs, - finalizeNative: metrics.finalizeNativeMs, - finalizeDecode: metrics.finalizeDecodeMs, - finalizeValidation: metrics.finalizeValidationMs, - dispose: metrics.disposeMs, - // This is measured time outside the named phases, not an inferred GC cost. - unattributedLoop: - runWallMs - - metrics.advanceMs - - metrics.submitMs - - metrics.decisionMs - - metrics.finalizeMs - - metrics.disposeMs, runWallMs, validationAndHashMs, wallMs, @@ -418,20 +236,15 @@ export async function sessionChild(workload: SessionWorkload) { : null; return { workload, - nativeSha256, - profile: workload.profile, - resultFormat: workload.resultFormat, - strategyHash: hash(profileDefinitions[workload.profile]), datasetHash: dataset.manifest.hash, policyHash: hash( - JSON.stringify({ config: load.config, strategy: profileDefinitions[workload.profile] }) + JSON.stringify({ config: load.config, strategy: 'alternating-unit-target-v1' }) ), datasetBytes: Buffer.byteLength(wireDataset), policy: load.config, phasesMs: { entryUptimeMs, applicationImportMs, - artifactIdentityMs, addonImportMs, adapterImportMs, fixtureGenerationMs, @@ -448,121 +261,43 @@ export async function sessionChild(workload: SessionWorkload) { } export function verifySessionRepeats( - samples: { - datasetHash: string; - policyHash: string; - nativeSha256: string; - profile: ReplayProfile; - resultFormat: ReplayResultFormat; - strategyHash: string; - trials: { resultHash: string; commonFinancialHash: string }[]; - }[], - expectedNativeHash?: string + samples: { datasetHash: string; policyHash: string; trials: { resultHash: string }[] }[] ) { const first = samples[0], expected = first?.trials[0]?.resultHash; - if (!first || !expected || !first.trials[0]?.commonFinancialHash) { + 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.nativeSha256 !== first.nativeSha256 || - (expectedNativeHash !== undefined && sample.nativeSha256 !== expectedNativeHash) || - sample.profile !== first.profile || - sample.resultFormat !== first.resultFormat || - sample.strategyHash !== first.strategyHash || !sample.trials.length || - sample.trials.some( - trial => - trial.resultHash !== expected || - trial.commonFinancialHash !== first.trials[0]?.commonFinancialHash - ) + sample.trials.some(trial => trial.resultHash !== expected) ) { throw new Error('Canonical dataset/policy/result mismatch; no timing comparison is valid'); } } } -type SessionSample = Parameters[0][number]; -export function verifyProjectionParity( - trace: SessionSample[], - projection: SessionSample[] -): string { - verifySessionRepeats(trace); - verifySessionRepeats(projection); - const a = trace[0], - b = projection[0], - sharedHash = a?.trials[0]?.commonFinancialHash; - if ( - !a || - !b || - !sharedHash || - a.resultFormat !== 'trace' || - b.resultFormat !== 'projection' || - a.datasetHash !== b.datasetHash || - a.policyHash !== b.policyHash || - a.strategyHash !== b.strategyHash || - a.profile !== b.profile || - a.nativeSha256 !== b.nativeSha256 || - sharedHash !== b.trials[0]?.commonFinancialHash - ) { - throw new Error('Compact/trace financial projection or provenance mismatch'); - } - return sharedHash; -} - -function median(values: number[]): number { - const sorted = [...values].sort((a, b) => a - b), - middle = Math.floor(sorted.length / 2), - upper = sorted[middle], - lower = sorted[Math.max(0, middle - 1)]; - if (upper === undefined || lower === undefined) { - throw new Error('Missing measurement samples'); - } - return sorted.length % 2 ? upper : (lower + upper) / 2; -} - export async function sessionBenchmark( root: string, entry: string, - metadata: { native: { sha256: string } }, + metadata: object, measured: boolean, - large: boolean, - options: SessionOptions = { profiles: ['turnover'], resultFormat: 'trace' } + large: boolean ) { - const sizes = options.totalBars - ? [options.totalBars] - : measured - ? large - ? [1000, 10000, 100000] - : [1000, 10000] - : [8]; - const formats: ReplayResultFormat[] = - options.resultFormat === 'both' ? ['trace', 'projection'] : [options.resultFormat]; - const workloads = options.profiles - .flatMap(profile => - sizes.flatMap(bars => [ - { - totalBars: bars, - assets: 1, - owners: 1, - eventBudget: 64, - profile, - resultFormat: 'trace' as const, - }, - { - totalBars: measured ? bars : bars * 2, - assets: measured ? 10 : 2, - owners: 2, - eventBudget: 64, - profile, - resultFormat: 'trace' as const, - }, - ]) - ) - .flatMap(workload => formats.map(resultFormat => ({ ...workload, resultFormat }))); + 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 = []; @@ -596,59 +331,21 @@ export async function sessionBenchmark( processBarsPerSecond: (workload.totalBars * sample.trials.length) / (processWallMs / 1000), }); } - verifySessionRepeats(samples, metadata.native.sha256); - const trials = samples.flatMap(sample => sample.trials), - firstTrial = trials[0]; - if (!firstTrial) { - throw new Error('Missing measurement trials'); - } - const breakdown = { - samples: trials.length, - medianMs: Object.fromEntries( - Object.keys(firstTrial.timingsMs).map(key => [ - key, - median(trials.map(trial => trial.timingsMs[key as keyof typeof trial.timingsMs])), - ]) - ), - resultBytes: firstTrial.bytes.finalizeResponse, - }; - measurements.push({ workload, repeatedResultHashesMatch: true, breakdown, samples }); + verifySessionRepeats(samples); + measurements.push({ workload, repeatedResultHashesMatch: true, samples }); process.stderr.write( - `Verified canonical ${workload.profile}/${workload.resultFormat}: ${workload.totalBars} bars / ${workload.assets} assets / ${workload.owners} owners, 2 fresh processes × 2 fresh sessions\n` + `Verified canonical ${workload.totalBars} bars / ${workload.assets} assets / ${workload.owners} owners, 2 fresh processes × 2 fresh sessions\n` ); } - const comparisons = []; - if (options.resultFormat === 'both') { - for (let index = 0; index < measurements.length; index += 2) { - const trace = measurements[index], - projection = measurements[index + 1]; - if (!trace || !projection) { - throw new Error('Missing paired measurements'); - } - const commonFinancialHash = verifyProjectionParity(trace.samples, projection.samples); - comparisons.push({ - profile: trace.workload.profile, - totalBars: trace.workload.totalBars, - assets: trace.workload.assets, - owners: trace.workload.owners, - commonFinancialHash, - trace: trace.breakdown, - projection: projection.breakdown, - }); - } - } process.stdout.write( JSON.stringify( { - schemaVersion: 2, + schemaVersion: 1, path: 'canonical-pull-session', mode: measured ? 'measurement' : 'self-test', ...metadata, strategy: { - profiles: options.profiles.map(profile => ({ - profile, - definition: profileDefinitions[profile], - })), + definition: 'alternating-unit-target-v1', randomness: 'None; controlled deterministic fixture/decision counters', }, unavailable: { @@ -662,8 +359,6 @@ export async function sessionBenchmark( parallelism: 'Sequential trials; no parallel simulation.', perCallDistribution: 'Mean and total latency only; no latency histogram or cancellation wall-time claim.', - nativeInternals: - 'Native-call timers include Rust work/serialization and NAPI; no Rust compute/serialization/allocation split.', }, limitations: [ 'Component conformance throughput, not a production strategy or durable research run; no comparison/speedup against legacy economics.', @@ -671,14 +366,10 @@ export async function sessionBenchmark( '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.', - 'Trace returns full retained receipts; projection returns compact authoritative fields. Neither mode compacts internal journals. RSS is process-wide, not native residency.', - 'Source/parent metadata hashing and aggregation are outside child timings. The child addon hash is measured separately in artifactIdentityMs and included in childWallMs.', - 'Each format retains its own full normalized result hash. Cross-format comparison hashes shared provenance/view and copied fill/effect/fee fields; projection-only LedgerValuation is not recomputed in TypeScript.', - 'Whole-trial time includes benchmark oracle and both result/projection hashes. runWallMs excludes that benchmark-only validation and includes separately measured disposal. Unattributed loop time is not labelled native work or GC.', + '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, - comparisons, }, null, 2 diff --git a/scripts/benchmark-research.ts b/scripts/benchmark-research.ts index 9ae70ffa..f420b467 100644 --- a/scripts/benchmark-research.ts +++ b/scripts/benchmark-research.ts @@ -5,8 +5,6 @@ * 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 - * bun run scripts/benchmark-research.ts --session --measure --profile=sparse --bars=10000 - * bun run scripts/benchmark-research.ts --session --measure --profile=all --format=both --bars=10000 * Build workspace libraries/config and the local engine first. JSON stdout; diagnostics stderr. */ import { createHash } from 'node:crypto'; @@ -338,77 +336,6 @@ export function verifyRepeats( } } -/** Explicit benchmark selections, not application dataset/input limits. */ -export function parseBenchmarkArguments(args: string[]) { - const options = { - session: false, - measured: false, - large: false, - selfTest: false, - profile: 'turnover' as 'none' | 'sparse' | 'turnover' | 'all', - resultFormat: 'trace' as 'trace' | 'projection' | 'both', - totalBars: undefined as number | undefined, - }; - const seen = new Set(); - for (const argument of args) { - const [flag, value] = argument.split('='); - if (!flag || seen.has(flag)) { - throw new Error('Duplicate or invalid benchmark flag'); - } - seen.add(flag); - switch (flag) { - case '--session': - options.session = true; - break; - case '--measure': - options.measured = true; - break; - case '--large': - options.large = true; - break; - case '--self-test': - options.selfTest = true; - break; - case '--profile': - if (!['none', 'sparse', 'turnover', 'all'].includes(value ?? '')) { - throw new Error('Unknown benchmark profile'); - } - options.profile = value as typeof options.profile; - break; - case '--format': - if (!['trace', 'projection', 'both'].includes(value ?? '')) { - throw new Error('Unknown benchmark result format'); - } - options.resultFormat = value as typeof options.resultFormat; - break; - case '--bars': - if (!['1000', '10000', '100000'].includes(value ?? '')) { - throw new Error('Benchmark --bars must be1000,10000 or100000'); - } - options.totalBars = Number(value); - break; - default: - throw new Error('Unknown benchmark flag'); - } - if (!['--profile', '--format', '--bars'].includes(flag) && value !== undefined) { - throw new Error('Boolean benchmark flags do not accept values'); - } - if (argument.split('=').length > 2) { - throw new Error('Invalid benchmark flag value'); - } - } - if ((options.large && !options.measured) || (options.selfTest && options.measured)) { - throw new Error('Use no flags/--self-test, --measure, or --measure --large'); - } - if (!options.session && ['--profile', '--format', '--bars'].some(flag => seen.has(flag))) { - throw new Error('Profile, format and bar selections require --session'); - } - if (options.totalBars !== undefined && (!options.measured || options.large)) { - throw new Error('--bars requires --measure and cannot be combined with --large'); - } - return options; -} - async function main(args: string[]) { if (args[0] === '--session-child') { const { sessionChild } = await import('./benchmark-replay'); @@ -419,23 +346,25 @@ async function main(args: string[]) { process.stdout.write(JSON.stringify(await child(JSON.parse(args[1] ?? ''))) + '\n'); return; } - const selection = parseBenchmarkArguments(args); + if ( + 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; optionally --session' + ); + } const metadata = identity(); // Excluded from workload timings. - const measured = selection.measured; - if (selection.session) { + const measured = args.includes('--measure'); + if (args.includes('--session')) { const { sessionBenchmark } = await import('./benchmark-replay'); await sessionBenchmark( root, fileURLToPath(import.meta.url), metadata, measured, - selection.large, - { - profiles: - selection.profile === 'all' ? ['none', 'sparse', 'turnover'] : [selection.profile], - resultFormat: selection.resultFormat, - totalBars: selection.totalBars, - } + args.includes('--large') ); return; } diff --git a/scripts/test/architecture.test.ts b/scripts/test/architecture.test.ts index a6240a5a..deb04b44 100644 --- a/scripts/test/architecture.test.ts +++ b/scripts/test/architecture.test.ts @@ -190,11 +190,7 @@ describe('orchestrator architecture boundaries', () => { 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', - 'backtest/strategy-runtime.ts', - ]).toContain(path); + expect(['backtest/native-replay.ts', 'backtest/native-worker.ts']).toContain(path); } const source = ts.createSourceFile( file, diff --git a/scripts/test/benchmark-replay.test.ts b/scripts/test/benchmark-replay.test.ts index 9c4ffb47..abfd5687 100644 --- a/scripts/test/benchmark-replay.test.ts +++ b/scripts/test/benchmark-replay.test.ts @@ -1,100 +1,7 @@ import { expect, test } from 'bun:test'; -import { parseFinancialDecimal } from '@stock-bot/types'; -import { executeReplayTrace } from '../../apps/stock/orchestrator/src/backtest/native-replay'; -import { nativeReplayFixture } from '../../test/fixtures/native-replay'; -import { - assertResultFormat, - commonFinancialProjection, - profileOracle, - profileTarget, - turnoverOracle, - verifyProjectionParity, - verifySessionRepeats, -} from '../benchmark-replay'; -import { parseBenchmarkArguments } from '../benchmark-research'; +import { turnoverOracle, verifySessionRepeats } from '../benchmark-replay'; -test('profile_none invokes the same cadence without orders, fees or position books', () => { - expect(profileOracle('none', 602, 2, 2)).toEqual({ - cash: '1000000.00000000', - equity: '1000000.00000000', - feePerOwner: '0.00000000', - quantity: '0.00000000', - remainingCost: '0.00000000', - fills: 0, - decisions: 1202, - }); - for (let decision = 0; decision < 601; decision++) { - expect(profileTarget('none', decision, 602)).toBeNull(); - } -}); - -test('profile_sparse buys first and sells last across retained session gaps', () => { - expect(profileOracle('sparse', 602, 2, 2)).toEqual({ - cash: '999999.04000000', - equity: '999999.04000000', - feePerOwner: '0.48000000', - quantity: '0.00000000', - remainingCost: '0.00000000', - fills: 8, - decisions: 1202, - }); - expect(profileTarget('sparse', 0, 602)).toBe(1); - expect(profileTarget('sparse', 600, 602)).toBe(0); - for (let decision = 1; decision < 600; decision++) { - expect(profileTarget('sparse', decision, 602)).toBeNull(); - } - expect(profileOracle('sparse', 4, 1, 1).cash).toBe('1000003.72000000'); -}); - -test('benchmark_profile_arguments preserves defaults and rejects unsupported combinations', () => { - expect(parseBenchmarkArguments([])).toMatchObject({ - session: false, - measured: false, - profile: 'turnover', - resultFormat: 'trace', - }); - expect(parseBenchmarkArguments(['--session'])).toMatchObject({ - session: true, - profile: 'turnover', - }); - expect( - parseBenchmarkArguments([ - '--session', - '--measure', - '--profile=all', - '--format=trace', - '--bars=100000', - ]) - ).toMatchObject({ - session: true, - measured: true, - profile: 'all', - resultFormat: 'trace', - totalBars: 100000, - }); - for (const resultFormat of ['trace', 'projection', 'both'] as const) { - expect(parseBenchmarkArguments(['--session', `--format=${resultFormat}`]).resultFormat).toBe( - resultFormat - ); - } - for (const args of [ - ['--profile=none'], - ['--session', '--profile=unknown'], - ['--session', '--format=unknown'], - ['--session', '--bars=10000'], - ['--session', '--measure', '--bars=99'], - ['--large'], - ['--session', '--measure', '--large', '--bars=10000'], - ['--self-test', '--measure'], - ['--session=yes'], - ['--session', '--session'], - ['--session', '--profile=none=extra'], - ]) { - expect(() => parseBenchmarkArguments(args)).toThrow(); - } -}); - -test('profile_turnover integer-cent oracle includes fees and terminal marks', () => { +test('canonical benchmark integer-cent oracle includes fees and terminal marks', () => { expect(turnoverOracle(3, 1, 1)).toEqual({ cash: '1000001.74000000', equity: '1000001.74000000', @@ -120,261 +27,18 @@ test('canonical benchmark rejects any changed provenance or complete result hash const sample = { datasetHash: 'dataset', policyHash: 'policy', - nativeSha256: 'native', - profile: 'turnover' as const, - resultFormat: 'trace' as const, - strategyHash: 'strategy', - trials: [ - { resultHash: 'result', commonFinancialHash: 'common' }, - { resultHash: 'result', commonFinancialHash: 'common' }, - ], + trials: [{ resultHash: 'result' }, { resultHash: 'result' }], }; expect(() => verifySessionRepeats([sample, structuredClone(sample)])).not.toThrow(); for (const changed of [ { ...sample, datasetHash: 'changed' }, { ...sample, policyHash: 'changed' }, - { ...sample, nativeSha256: 'changed' }, - { ...sample, strategyHash: 'changed' }, - { ...sample, profile: 'none' as const }, - { ...sample, resultFormat: 'projection' as const }, - { ...sample, trials: [{ resultHash: 'changed', commonFinancialHash: 'common' }] }, - { ...sample, trials: [{ resultHash: 'result', commonFinancialHash: 'changed' }] }, + { ...sample, trials: [{ resultHash: 'changed' }] }, { ...sample, trials: [] }, ]) { expect(() => verifySessionRepeats([sample, changed])).toThrow('mismatch'); } expect(() => verifySessionRepeats([])).toThrow('Missing'); - expect(() => - verifySessionRepeats([ - { ...sample, trials: [{ resultHash: 'result', commonFinancialHash: '' }] }, - ]) - ).toThrow('Missing'); - expect(() => verifySessionRepeats([sample], 'different-artifact')).toThrow('mismatch'); -}); - -function normalizerFixture() { - const fixture = nativeReplayFixture(); - const input = { - type: 'runReplayTrace' as const, - version: 1 as const, - dataset: fixture.dataset, - config: fixture.config, - eventBudget: 1, - trace: [ - { - at: fixture.start + fixture.minute, - ownerId: 'A', - intent: { - mode: 'target' as const, - targets: [{ instrumentId: 'X0.US', quantity: parseFinancialDecimal('2') }], - }, - }, - { - at: fixture.start + 2 * fixture.minute, - ownerId: 'A', - intent: { mode: 'target' as const, targets: [] }, - }, - ], - }; - return { - trace: executeReplayTrace(input).result, - projection: executeReplayTrace({ ...input, resultFormat: 'projection' }).result, - }; -} - -test('common financial projection copies authoritative fill facts without valuing positions', () => { - const { trace, projection } = normalizerFixture(); - const common = commonFinancialProjection(trace); - expect(commonFinancialProjection(projection)).toEqual(common); - expect(common).not.toHaveProperty('valuation'); - expect(common.fills).toHaveLength(1); - expect(common.fills[0]).toMatchObject({ - cashDelta: '-24.00000000', - fee: { amount: '0.24000000' }, - }); - for (const field of [ - 'commandId', - 'eventTime', - 'ownerId', - 'orderId', - 'fillId', - 'instrumentId', - 'price', - 'cashDelta', - 'quantityDelta', - 'releasedBasis', - 'realizedGrossPnl', - ] as const) { - const changed = structuredClone(projection); - const fill = changed.projection.fills[0]!; - Object.assign(fill, { - [field]: typeof fill[field] === 'number' ? Number(fill[field]) + 1 : 'changed', - }); - expect(commonFinancialProjection(changed)).not.toEqual(common); - } - for (const field of ['feeId', 'amount'] as const) { - const changed = structuredClone(projection); - Object.assign(changed.projection.fills[0]!.fee, { [field]: 'changed' }); - expect(commonFinancialProjection(changed)).not.toEqual(common); - } - expect(() => assertResultFormat(trace, 'trace')).not.toThrow(); - expect(() => assertResultFormat(projection, 'projection')).not.toThrow(); - expect(() => assertResultFormat(trace, 'projection')).toThrow('format mismatch'); - expect(() => assertResultFormat(projection, 'trace')).toThrow('format mismatch'); -}); - -test('common projection skips matching, risk and financial replay aliases independently', () => { - const { trace } = normalizerFixture(); - const receipt = trace.receipts.find(r => - r.outcome.effects.some((effect: any) => - effect.Risk?.outcome.financial?.effects.effects.some((e: any) => e.kind === 'fillApplied') - ) - )!; - expect(receipt).toBeDefined(); - for (const level of ['matching', 'risk', 'financial']) { - const alias = structuredClone(receipt); - const risk: any = alias.outcome.effects.find((effect: any) => - effect.Risk?.outcome.financial?.effects.effects.some((e: any) => e.kind === 'fillApplied') - )!.Risk; - if (level === 'matching') { - alias.outcome.replayed = true; - } else if (level === 'risk') { - risk.outcome.replayed = true; - } else { - risk.outcome.financial.replayed = true; - } - expect(commonFinancialProjection({ ...trace, receipts: [receipt, alias] }).fills).toHaveLength( - 1 - ); - expect(commonFinancialProjection({ ...trace, receipts: [alias] }).fills).toHaveLength(0); - } -}); - -test('common projection handles 100k multi-owner turnover without argument spreading', () => { - const { projection } = normalizerFixture(); - projection.projection.fills = Array.from( - { length: 200000 }, - () => projection.projection.fills[0]! - ); - const common = commonFinancialProjection(projection); - expect(common.fills).toHaveLength(200000); - expect(common.fills.at(-1)).toEqual(common.fills[0]!); -}); - -test('common projection rejects missing, duplicate or mismatched financial fee pairs', () => { - const { trace } = normalizerFixture(); - for (const change of ['missing', 'extra', 'owner', 'fill', 'rejection']) { - const invalid = structuredClone(trace); - const risk: any = invalid.receipts - .flatMap(r => r.outcome.effects) - .map(effect => effect.Risk) - .find((r: any) => - r?.outcome.financial?.effects.effects.some((e: any) => e.kind === 'fillApplied') - ); - const effects = risk.outcome.financial.effects.effects; - const fee = effects.find((e: any) => e.kind === 'feeApplied'); - if (change === 'missing') { - effects.splice(effects.indexOf(fee), 1); - } else if (change === 'extra') { - effects.push(structuredClone(fee)); - } else if (change === 'owner') { - fee.ownerId = 'other'; - } else if (change === 'fill') { - fee.fillId = 'other'; - } else { - risk.outcome.disposition = { Rejected: 'fixture' }; - } - expect(() => commonFinancialProjection(invalid)).toThrow(); - } -}); - -test('paired comparison requires shared economics and provenance while retaining distinct full hashes', () => { - const trace = { - datasetHash: 'dataset', - policyHash: 'policy', - nativeSha256: 'native', - profile: 'sparse' as const, - resultFormat: 'trace' as const, - strategyHash: 'strategy', - trials: [{ resultHash: 'full-trace', commonFinancialHash: 'common' }], - }; - const projection = { - ...trace, - resultFormat: 'projection' as const, - trials: [{ resultHash: 'compact-projection', commonFinancialHash: 'common' }], - }; - expect(verifyProjectionParity([trace], [projection])).toBe('common'); - for (const changed of [ - { ...projection, datasetHash: 'changed' }, - { ...projection, policyHash: 'changed' }, - { ...projection, nativeSha256: 'changed' }, - { ...projection, strategyHash: 'changed' }, - { ...projection, profile: 'none' as const }, - { ...projection, resultFormat: 'trace' as const }, - { - ...projection, - trials: [{ resultHash: 'compact-projection', commonFinancialHash: 'changed' }], - }, - ]) { - expect(() => verifyProjectionParity([trace], [changed])).toThrow('mismatch'); - } -}); - -test('all tiny replay profiles pin financial expectations and distinct strategy identities', async () => { - const worker = Bun.spawn( - [ - process.execPath, - 'scripts/benchmark-research.ts', - '--session', - '--profile=all', - '--format=both', - ], - { - cwd: new URL('../..', import.meta.url).pathname, - stdout: 'pipe', - stderr: 'pipe', - } - ); - const [stdout, stderr, exit] = await Promise.all([ - new Response(worker.stdout).text(), - new Response(worker.stderr).text(), - worker.exited, - ]); - expect(exit, stderr).toBe(0); - const report = JSON.parse(stdout); - expect(report.measurements).toHaveLength(12); - expect(report.comparisons).toHaveLength(6); - for (const comparison of report.comparisons) { - expect(comparison.commonFinancialHash).toMatch(/^[a-f0-9]{64}$/); - expect(comparison.projection.resultBytes).toBeLessThan(comparison.trace.resultBytes); - } - expect(new Set(report.measurements.map((m: any) => m.samples[0].strategyHash)).size).toBe(3); - for (const measurement of report.measurements) { - verifySessionRepeats(measurement.samples, report.native.sha256); - const workload = measurement.workload; - const expected = profileOracle( - workload.profile, - workload.totalBars / workload.assets, - workload.assets, - workload.owners - ); - for (const sample of measurement.samples) { - expect(sample.profile).toBe(workload.profile); - expect(sample.resultFormat).toBe(workload.resultFormat); - for (const trial of sample.trials) { - expect(trial.economic).toEqual({ ...expected, fees: expected.fills }); - for (const value of Object.values(trial.timingsMs) as number[]) { - expect(Number.isFinite(value)).toBe(true); - expect(value).toBeGreaterThanOrEqual(0); - } - expect(trial.timingsMs.finalize).toBeGreaterThanOrEqual( - trial.timingsMs.finalizeNative + - trial.timingsMs.finalizeDecode + - trial.timingsMs.finalizeValidation - ); - } - } - } }); test('canonical self-test measures real sessions and verifies repeated full-result hashes', async () => { diff --git a/scripts/test/native-bindings.test.ts b/scripts/test/native-bindings.test.ts index 9ff1b29a..fa7c2b65 100644 --- a/scripts/test/native-bindings.test.ts +++ b/scripts/test/native-bindings.test.ts @@ -72,8 +72,6 @@ describe('generated native bindings', () => { expect(binding.TechnicalIndicators).toBe(TechnicalIndicators); expect(binding.IncrementalSMA).toBe(IncrementalSMA); expect(binding.FinancialReplaySession).toBe(FinancialReplaySession); - expect(typeof FinancialReplaySession.prototype.project).toBe('function'); - expect(typeof FinancialReplaySession.prototype.report).toBe('function'); }); it('MACD keeps full-length EMA series aligned without out-of-bounds access', () => { diff --git a/scripts/test/strategy-runtime.test.ts b/scripts/test/strategy-runtime.test.ts deleted file mode 100644 index ebb1fd2b..00000000 --- a/scripts/test/strategy-runtime.test.ts +++ /dev/null @@ -1,297 +0,0 @@ -import { describe, expect, spyOn, test } from 'bun:test'; -import { parseFinancialDecimal } from '@stock-bot/types'; -import { - NativeReplaySession, - prepareReplayLoad, -} from '../../apps/stock/orchestrator/src/backtest/native-replay'; -import { - runStrategyReplay, - StrategyReplayError, - type StrategyProgram, -} from '../../apps/stock/orchestrator/src/backtest/strategy-runtime'; -import { nativeAdmissionOrders } from '../../apps/stock/orchestrator/src/contracts/native-replay'; -import { nativeReplayFixture } from '../../test/fixtures/native-replay'; - -const hold = () => ({ mode: 'target' as const, targets: [] }); -function program(initialState: unknown): StrategyProgram { - return { - ownerId: 'A', - strategyId: 'state-test', - strategyVersion: '1', - mode: 'target', - seed: 1, - initialState, - decide: context => ({ nextState: context.state, intent: hold() }), - }; -} -function load(owners = ['A']) { - const fixture = nativeReplayFixture(4, 1, owners); - return prepareReplayLoad(fixture.dataset, fixture.config); -} -const managed = (status: unknown) => ({ - order: { - orderId: 'order', - decision: { ownerId: 'A', decisionId: 'old-decision', sequence: 0 }, - instrumentId: 'X0.US', - side: 'buy', - quantity: '1.00000000', - limitPrice: null, - origin: 'Target', - }, - timeInForce: 'GTC', - submittedAt: { at: 1, phase: 'Decision', instrumentId: 'X0.US', sourceSequence: 0 }, - readyAt: 1, - venueSession: null, - remaining: '1.00000000', - filled: '0.00000000', - status, - admissionSequence: 1, -}); - -describe('canonical strategy state and native admission boundary', () => { - test('native status facts validate all supported risk reasons without reinterpreting them', () => { - const reasons = [ - 'OrderSize', - 'PositionSize', - 'SymbolExposure', - 'GrossExposure', - 'InsufficientCash', - 'InsufficientInventory', - 'MissingMark', - 'StaleMark', - 'DailyLoss', - 'Drawdown', - 'InactiveOrder', - ]; - for (const status of [ - 'Open', - 'Filled', - 'Cancelled', - 'Expired', - ...reasons.map(Rejected => ({ Rejected })), - ]) { - const order = managed(status); - const parsed = nativeAdmissionOrders([{ Order: order }]); - expect(parsed[0]?.status).toEqual(status); - expect(parsed[0]?.order.decision.decisionId).toBe('old-decision'); - } - expect(nativeAdmissionOrders([{ Risk: {} }, { Operator: {} }])).toEqual([]); - for (const effect of [ - { Order: managed('Unknown') }, - { Order: managed({ Rejected: 'Invented' }) }, - { Order: { ...managed('Open'), extra: true } }, - { Order: managed('Open'), extra: true }, - { Unknown: {} }, - {}, - { Risk: null }, - { Risk: undefined }, - { Risk: 1 }, - { Operator: 'wrong' }, - ]) { - expect(() => nativeAdmissionOrders([effect])).toThrow(); - } - }); - - test('plain __proto__ and constructor state keys survive without mutating the prototype', () => { - const state = JSON.parse( - '{"__proto__":{"value":7},"constructor":"own","nested":[true,null,1]}' - ); - const output = runStrategyReplay(load(), [program(state)], { resultFormat: 'projection' }); - const saved = output.diagnostics.strategies[0]!.state; - expect(saved).toEqual(state); - expect(Object.getPrototypeOf(saved)).toBe(Object.prototype); - expect(Object.hasOwn(saved as object, '__proto__')).toBe(true); - expect(Object.isFrozen(saved)).toBe(true); - expect(({} as { value?: number }).value).toBeUndefined(); - }); - - test('lossy initial states reject before any admission and do not invoke getters', () => { - let getters = 0; - const hidden = Object.defineProperty({}, 'hidden', { value: 1, enumerable: false }); - const accessor = Object.defineProperty({}, 'value', { - get() { - getters++; - return 1; - }, - enumerable: true, - }); - const array = [1] as number[] & { extra?: number }; - array.extra = 2; - const cyclic: Record = {}; - cyclic.self = cyclic; - const sparse = Array(2); - sparse[1] = 1; - const bad = [ - undefined, - NaN, - Infinity, - -0, - 1n, - () => 1, - new Date(), - Object.create(null), - { [Symbol('hidden')]: 1 }, - hidden, - accessor, - sparse, - array, - cyclic, - ]; - const submit = spyOn(NativeReplaySession.prototype, 'submit'); - try { - for (const state of bad) { - expect(() => runStrategyReplay(load(), [program(state)])).toThrow(); - } - expect(submit).not.toHaveBeenCalled(); - expect(getters).toBe(0); - } finally { - submit.mockRestore(); - } - }); - - test('malformed later-owner feedback keeps every owner at the prior committed barrier', () => { - const programs = ['A', 'B'].map( - ownerId => - ({ - ownerId, - strategyId: 'counter', - strategyVersion: '1', - mode: 'target' as const, - seed: 2, - initialState: { count: 0 }, - decide(context) { - context.random(); - const count = context.state.count + 1; - return { - nextState: { count }, - intent: { - mode: 'target' as const, - targets: [ - { instrumentId: 'X0.US', quantity: parseFinancialDecimal(String(count)) }, - ], - }, - }; - }, - }) satisfies StrategyProgram<{ count: number }> - ); - const original = NativeReplaySession.prototype.submit; - let count = 0; - const submit = spyOn(NativeReplaySession.prototype, 'submit').mockImplementation(function ( - this: NativeReplaySession, - barrier, - decisions - ) { - const response = structuredClone(original.call(this, barrier, decisions)); - if (++count === 2) { - const effect = response.effects.find( - effect => (effect.Order as any)?.order.decision.ownerId === 'B' - ); - expect(effect).toBeDefined(); - (effect!.Order as any).status = { Rejected: 'Invented' }; - } - return response; - }); - try { - let failure: unknown; - try { - runStrategyReplay(load(['A', 'B']), programs); - } catch (error) { - failure = error; - } - expect(failure).toBeInstanceOf(StrategyReplayError); - const diagnostics = (failure as StrategyReplayError).diagnostics; - expect(diagnostics.committedBarriers).toBe(1); - expect(diagnostics.strategies.map(owner => owner.state)).toEqual([ - { count: 1 }, - { count: 1 }, - ]); - expect(diagnostics.strategies.map(owner => owner.rng.draws)).toEqual([1, 1]); - expect(diagnostics.strategies.map(owner => owner.nextDecisionSequence)).toEqual([1, 1]); - } finally { - submit.mockRestore(); - } - }); - - test('replayed and mismatched acknowledgement revisions cannot commit strategy state', () => { - for (const mismatch of ['replayed', 'revision']) { - const original = NativeReplaySession.prototype.submit; - const submit = spyOn(NativeReplaySession.prototype, 'submit').mockImplementation(function ( - this: NativeReplaySession, - barrier, - decisions - ) { - const response = structuredClone(original.call(this, barrier, decisions)); - if (mismatch === 'replayed') { - response.replayed = true; - } else { - response.revision++; - } - return response; - }); - try { - let failure: unknown; - try { - runStrategyReplay(load(), [program({ count: 0 })]); - } catch (error) { - failure = error; - } - expect(failure).toBeInstanceOf(StrategyReplayError); - expect((failure as StrategyReplayError).diagnostics.committedBarriers).toBe(0); - expect( - (failure as StrategyReplayError).diagnostics.strategies[0]?.nextDecisionSequence - ).toBe(0); - } finally { - submit.mockRestore(); - } - } - }); - - test('rejected async outputs fail synchronously without unhandled rejections', async () => { - const runtimePath = new URL( - '../../apps/stock/orchestrator/src/backtest/strategy-runtime.ts', - import.meta.url - ).pathname; - const replayPath = new URL( - '../../apps/stock/orchestrator/src/backtest/native-replay.ts', - import.meta.url - ).pathname; - const fixturePath = new URL('../../test/fixtures/native-replay.ts', import.meta.url).pathname; - for (const kind of ['immediate', 'after-await', 'foreign']) { - const script = ` - import { runInNewContext } from 'node:vm'; - import { runStrategyReplay, StrategyReplayError } from ${JSON.stringify(runtimePath)}; - import { NativeReplaySession, prepareReplayLoad } from ${JSON.stringify(replayPath)}; - import { nativeReplayFixture } from ${JSON.stringify(fixturePath)}; - let admissions=0, disposals=0; - const submit=NativeReplaySession.prototype.submit; - NativeReplaySession.prototype.submit=function(...args){admissions++;return submit.apply(this,args);}; - const dispose=NativeReplaySession.prototype.dispose; - NativeReplaySession.prototype.dispose=function(){disposals++;return dispose.call(this);}; - const fixture=nativeReplayFixture(); - let failure; - try { - runStrategyReplay(prepareReplayLoad(fixture.dataset,fixture.config), [{ - ownerId:'A',strategyId:'async-test',strategyVersion:'1',mode:'target',seed:1,initialState:null, - decide: ${ - kind === 'foreign' - ? `()=>runInNewContext("Promise.reject(new Error('async-rejected'))")` - : `async()=>{${kind === 'after-await' ? 'await Promise.resolve();' : ''}throw new Error('async-rejected');}` - } - }]); - } catch(error) {failure=error;} - if (!(failure instanceof StrategyReplayError) || failure.diagnostics.committedBarriers!==0) throw new Error('Missing synchronous strategy failure'); - await new Promise(resolve=>setTimeout(resolve,10)); - if(admissions!==0||disposals!==1)throw new Error('Async strategy was admitted or attempt leaked'); - process.stdout.write('async-contract-checked'); - `; - const child = Bun.spawn([process.execPath, '-e', script], { stdout: 'pipe', stderr: 'pipe' }); - const [stdout, stderr, exitCode] = await Promise.all([ - new Response(child.stdout).text(), - new Response(child.stderr).text(), - child.exited, - ]); - expect({ exitCode, stderr }).toEqual({ exitCode: 0, stderr: '' }); - expect(stdout).toBe('async-contract-checked'); - } - }); -}); diff --git a/test/contracts/strategy-runtime.type-test.ts b/test/contracts/strategy-runtime.type-test.ts deleted file mode 100644 index bdecf45a..00000000 --- a/test/contracts/strategy-runtime.type-test.ts +++ /dev/null @@ -1,63 +0,0 @@ -import type { FinancialDecimal, FinancialStrategyIntent } from '@stock-bot/types'; -import type { - StrategyContext, - StrategyProgram, -} from '../../apps/stock/orchestrator/src/contracts/canonical-strategy'; - -type State = { count: number; indicator: { values: number[] } }; - -function authorBoundary(context: StrategyContext): FinancialStrategyIntent { - const quantity: FinancialDecimal = context.positions[0]!.quantity; - const brandedString: boolean = quantity.startsWith('-'); - void brandedString; - const draw: number = context.random(); - void draw; - // @ts-expect-error Strategies cannot mutate their previous state. - context.state.count++; - // @ts-expect-error Nested indicator snapshots are readonly too. - context.state.indicator.values.push(5); - // @ts-expect-error Native owned positions are immutable inputs. - context.positions[0]!.quantity = quantity; - // @ts-expect-error The shared account view is immutable. - context.portfolio.portfolio.cash = quantity; - // @ts-expect-error Published observations cannot be changed by an author. - context.observations[0]!.close = quantity; - // @ts-expect-error A callback cannot submit directly to the financial engine. - context.submit([]); - // @ts-expect-error Broker services do not enter the author contract. - context.execution.placeOrder({}); - // @ts-expect-error Native handles do not enter the author contract. - context.native.advance(1); - // @ts-expect-error Strategies cannot reset native risk. - context.resetRisk(); - // @ts-expect-error Full future datasets are not an author input. - context.dataset.bars; - return { mode: 'target', targets: [{ instrumentId: 'X0.US', quantity }] }; -} - -const valid: StrategyProgram = { - ownerId: 'A', - strategyId: 'typed', - strategyVersion: '1', - mode: 'target', - seed: 0, - initialState: { count: 0, indicator: { values: [] } }, - decide: context => ({ - nextState: { - count: context.state.count + 1, - indicator: { values: [...context.state.indicator.values, context.random()] }, - }, - intent: authorBoundary(context), - }), -}; -void valid; - -const asynchronous: StrategyProgram = { - ...valid, - // @ts-expect-error The author boundary is deliberately synchronous. - decide: async context => ({ - nextState: { count: 1, indicator: { values: [] } }, - intent: authorBoundary(context), - }), -}; -void asynchronous; diff --git a/test/fixtures/canonical-sma.ts b/test/fixtures/canonical-sma.ts deleted file mode 100644 index 64a0a9e2..00000000 --- a/test/fixtures/canonical-sma.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { builtinStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy'; -import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2'; -import { nativeReplayFixture } from './native-replay'; - -/** Reviewed oracle: buy ten at next open 5, sell ten at next open 2; fees 0.70. */ -export function canonicalSmaFixture( - owners = ['A'], - options: { - tradeStartStep?: number; - volume?: number; - opens?: number[]; - closes?: number[]; - availabilitySteps?: number[]; - } = {} -) { - const fixture = nativeReplayFixture(7, 1, owners); - const { calendars, series, executionSeries, bounds, universe, corporateActions } = - fixture.dataset.manifest; - const closes = options.closes ?? [3, 2, 1, 4, 5, 1, 1]; - const opens = options.opens ?? [3, 3, 2, 1, 5, 5, 2]; - const dataset = createDatasetV2({ - metadata: { - calendars, - series, - executionSeries, - bounds: { - ...bounds, - tradeStart: fixture.start + (options.tradeStartStep ?? 1) * fixture.minute, - }, - universe, - corporateActions, - }, - bars: fixture.dataset.bars.map((bar, index) => { - const open = opens[index]!, - close = closes[index]!; - return { - seriesId: bar.seriesId, - timestamp: bar.intervalStart, - availableAt: - fixture.start + (options.availabilitySteps?.[index] ?? index + 1) * fixture.minute, - sourceSequence: bar.sourceSequence, - open, - close, - high: Math.max(open, close), - low: Math.min(open, close), - volume: options.volume ?? 1000, - }; - }), - }); - const selections = owners.map(ownerId => - builtinStrategySelectionSchema.parse({ - ownerId, - strategyId: 'sma', - strategyVersion: 'sma-crossover-long-only/v1', - seed: 42, - instrumentId: 'X0.US', - seriesId: 'X0.US:1m', - ownerBudget: '40', - parameters: { fastPeriod: 2, slowPeriod: 3 }, - }) - ); - return { ...fixture, dataset, selections }; -} diff --git a/test/fixtures/canonical-strategy-worker.ts b/test/fixtures/canonical-strategy-worker.ts deleted file mode 100644 index b1f70fc2..00000000 --- a/test/fixtures/canonical-strategy-worker.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay'; -import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime'; -import { strategyReplayRequestSchema } from '../../apps/stock/orchestrator/src/contracts/strategy-replay'; -import { - createBuiltinStrategy, - validateBuiltinStrategyBindings, -} from '../../apps/stock/orchestrator/src/strategies/canonical-sma'; - -function send(message: unknown): Promise { - return new Promise((resolve, reject) => - process.send!(message, (error: Error | null) => (error ? reject(error) : resolve())) - ); -} - -process.once('message', async (input: unknown) => { - const request = strategyReplayRequestSchema.parse(input); - const mode = request.config.matching.risk.ledger.accountId; - const load = prepareReplayLoad(request.dataset, request.config); - validateBuiltinStrategyBindings(request.strategies, load); - const { result } = runStrategyReplay(load, request.strategies.map(createBuiltinStrategy), { - eventBudget: request.eventBudget, - resultFormat: - mode === 'wrong-format' - ? request.resultFormat === 'projection' - ? 'trace' - : 'projection' - : request.resultFormat, - }); - const envelope = { - type: 'strategyReplayResult', - version: 1, - strategies: structuredClone(request.strategies), - result, - }; - const selection = envelope.strategies[0]!; - await send({ type: 'progress', progress: 0, message: 'Fixture ready' }); - switch (mode) { - case 'wrong-envelope-version': - envelope.version = 2; - break; - case 'wrong-envelope-type': - envelope.type = 'result'; - break; - case 'wrong-strategy': - Object.assign(selection, { strategyId: 'mean_reversion' }); - break; - case 'wrong-version': - Object.assign(selection, { strategyVersion: 'sma-crossover-long-only/v2' }); - break; - case 'wrong-owner': - selection.ownerId = 'other'; - break; - case 'wrong-seed': - selection.seed++; - break; - case 'wrong-parameters': - selection.parameters.slowPeriod++; - break; - case 'wrong-budget': - Object.assign(selection, { ownerBudget: '101.00000000' }); - break; - case 'wrong-series': - selection.seriesId = 'X0.US:5m'; - break; - case 'wrong-instrument': - selection.instrumentId = 'OTHER.US'; - break; - case 'reordered': - envelope.strategies.reverse(); - break; - case 'missing-selection': - envelope.strategies.pop(); - break; - case 'wrong-session': - result.identity.sessionId = 'other'; - break; - case 'wrong-dataset': - result.identity.datasetHash = '0'.repeat(64); - break; - case 'wrong-policy': - Object.assign(result.policy.matching.risk, { feeRate: '0.5' }); - break; - case 'invalid-result': - Object.assign(envelope, { result: {} }); - break; - case 'malformed': - await send({ nonsense: true }); - process.disconnect?.(); - return; - case 'reported-error': - await send({ type: 'error', message: 'Fixture strategy failure' }); - process.disconnect?.(); - return; - case 'crash': - process.kill(process.pid, 'SIGKILL'); - return; - case 'no-result': - process.disconnect?.(); - return; - } - await send({ type: 'result', result: JSON.stringify(envelope) }); - if (mode === 'duplicate') { - await send({ type: 'result', result: JSON.stringify(envelope) }); - } - if (mode === 'result-then-block') { - while (true) { - Math.sqrt(Math.random()); - } - } - process.disconnect?.(); -}); diff --git a/test/fixtures/native-replay-worker.ts b/test/fixtures/native-replay-worker.ts index 3c83b068..de39a458 100644 --- a/test/fixtures/native-replay-worker.ts +++ b/test/fixtures/native-replay-worker.ts @@ -7,16 +7,9 @@ function send(message: unknown): Promise { ); } process.once('message', async (input: unknown) => { - const request = replayTraceSchema.parse(input); + const request = replayTraceSchema.parse(input), + { result } = executeReplayTrace(request); const mode = request.config.matching.risk.ledger.accountId; - const { result } = executeReplayTrace( - mode === 'wrong-format' - ? { - ...request, - resultFormat: request.resultFormat === 'projection' ? 'trace' : 'projection', - } - : request - ); await send({ type: 'progress', progress: 0, message: 'Fixture ready' }); switch (mode) { case 'wrong-version': diff --git a/test/integration/canonical-native-report.test.ts b/test/integration/canonical-native-report.test.ts deleted file mode 100644 index d71b6afc..00000000 --- a/test/integration/canonical-native-report.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { expect, test } from 'bun:test'; -import { parseFinancialDecimal, type CanonicalMetricsInput } from '@stock-bot/types'; -import { buildCanonicalBacktestReport } from '../../apps/stock/orchestrator/src/backtest/canonical-result'; -import { executeReplayTrace } from '../../apps/stock/orchestrator/src/backtest/native-replay'; -import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker'; -import { - parseReplayReportResult, - replayConfigSchema, -} from '../../apps/stock/orchestrator/src/contracts/native-replay'; -import { nativeReplayFixture } from '../fixtures/native-replay'; - -const policy: CanonicalMetricsInput = { - version: 1, - periodsPerYear: 252, - annualRiskFreeRate: 0, - benchmark: null, -}; - -test('real native facts, worker transport and canonical analytics compose without changing finances', async () => { - const fixture = nativeReplayFixture(); - fixture.config.risk_boundaries = [1, 2, 3].map(index => ({ - ...fixture.config.matching.risk.ledger.riskSession, - sessionId: `report-session-${index}`, - startsAt: fixture.start + index * fixture.minute, - })); - const input = { - type: 'runReplayTrace' as const, - version: 1 as const, - dataset: fixture.dataset, - config: replayConfigSchema.parse(fixture.config), - eventBudget: 1, - trace: [ - { - at: fixture.start + fixture.minute, - ownerId: 'A', - intent: { - mode: 'target' as const, - targets: [{ instrumentId: 'X0.US', quantity: parseFinancialDecimal('2') }], - }, - }, - { - at: fixture.start + 2 * fixture.minute, - ownerId: 'A', - intent: { mode: 'target' as const, targets: [] }, - }, - ], - }; - const projection = executeReplayTrace({ ...input, resultFormat: 'projection' }).result; - const financial = executeReplayTrace({ ...input, resultFormat: 'report' }).result; - const before = JSON.stringify(financial); - const report = buildCanonicalBacktestReport(financial, policy); - expect(financial.projection).toEqual(projection.projection); - expect(financial.view).toEqual(projection.view); - expect(report.financial).toBe(financial); - expect(JSON.stringify(financial)).toBe(before); - expect(financial.projection.valuation.cash).toBe('9975.76000000'); - expect(financial.projection.valuation.equity).toBe('10005.76000000'); - expect(financial.projection.valuation.fees).toBe('0.24000000'); - expect(financial.reporting.sessions.map(session => session.equity)).toEqual([ - '10001.76000000', - '10005.76000000', - ]); - expect(report.analytics.sessionReturns.map(session => session.eligible)).toEqual([true, true]); - expect(report.analytics.sessionReturns[0]?.value).toBeCloseTo(1.76 / 10000, 12); - expect(report.analytics.sessionReturns[1]?.value).toBeCloseTo(4 / 10001.76, 12); - expect(report.analytics.metrics.totalReturn).toBeCloseTo(5.76 / 10000, 12); - expect(report.analytics.metrics.exposureTime).toBe(1); - expect(report.analytics.metrics.maxDrawdown).toBe(0); - expect(report.analytics.metrics.sharpeRatio).not.toBeNull(); - expect(report.analytics.metrics.sortinoRatio).toBeNull(); - expect(report.analytics.unavailable.sortinoRatio).toBe('zero-downside-deviation'); - expect(report.analytics.fillCount).toBe(1); - expect(report.analytics.metrics.roundTripCount).toBeNull(); - expect(report.analytics.unavailable.roundTripCount).toBe('unsupported-round-trips'); - expect(financial.view.portfolio.positions[0]?.quantity).toBe('2.00000000'); - - const worker = new NativeBacktestWorker(); - const raw = await worker.execute( - { ...input, resultFormat: 'report', eventBudget: 64 }, - new AbortController().signal, - () => {} - ); - const transported = parseReplayReportResult(raw, financial.identity, input.config); - expect(buildCanonicalBacktestReport(transported, policy)).toEqual(report); - - const missingRate = buildCanonicalBacktestReport(financial, { - ...policy, - annualRiskFreeRate: null, - }); - expect(missingRate.financial).toBe(financial); - expect(missingRate.analytics.metrics.sharpeRatio).toBeNull(); - expect(missingRate.analytics.unavailable.sharpeRatio).toBe('missing-risk-free'); - expect(missingRate.analytics.metrics.volatility).toBe(report.analytics.metrics.volatility); -}); - -test('real no-trade native reporting retains genuine zero metrics through the canonical adapter', () => { - const fixture = nativeReplayFixture(); - const financial = executeReplayTrace({ - type: 'runReplayTrace', - version: 1, - dataset: fixture.dataset, - config: fixture.config, - eventBudget: 64, - trace: [1, 2].map(index => ({ - at: fixture.start + index * fixture.minute, - ownerId: 'A', - intent: { mode: 'target' as const, targets: [] }, - })), - resultFormat: 'report', - }).result; - const report = buildCanonicalBacktestReport(financial, policy); - expect(report.analytics.metrics.totalReturn).toBe(0); - expect(report.analytics.metrics.exposureTime).toBe(0); - expect(report.analytics.metrics.cagr).toBe(0); - expect(report.analytics.fillCount).toBe(0); - expect(report.analytics.sessionReturns[0]?.value).toBe(0); - expect(report.analytics.sessionReturns[0]?.partialEnd).toBe(true); - expect(report.analytics.periodicSampleCount).toBe(0); - expect(report.analytics.metrics.volatility).toBeNull(); - expect(report.analytics.unavailable.volatility).toBe('insufficient-periods'); -}); diff --git a/test/integration/canonical-result.test.ts b/test/integration/canonical-result.test.ts deleted file mode 100644 index 54ca6560..00000000 --- a/test/integration/canonical-result.test.ts +++ /dev/null @@ -1,353 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { parseFinancialDecimal, type CanonicalMetricsInput } from '@stock-bot/types'; -import { buildCanonicalBacktestReport } from '../../apps/stock/orchestrator/src/backtest/canonical-result'; -import { - parseReplayReportValue, - type ReplayConfig, - type ReplayReportResult, -} from '../../apps/stock/orchestrator/src/contracts/native-replay'; - -const policy: CanonicalMetricsInput = { - version: 1, - periodsPerYear: 252, - annualRiskFreeRate: 0, - benchmark: null, -}; -const money = (value: number | string) => parseFinancialDecimal(String(value)); - -/** Hand-authored statistical input fixtures validated by the accepted wire schema. - * Native reporting tests, not these fixtures, establish financial transition validity. */ -function fixture( - equities = [110, 99], - options: { - initial?: number; - times?: number[]; - partialStart?: boolean; - partialEnd?: boolean; - occupiedIntervals?: { start: number; end: number }[]; - } = {} -): ReplayReportResult { - const initial = options.initial ?? 100; - // Two sessions can end on the same UTC date; UTC grouping would lose a return. - const start = Date.parse('2024-01-01T23:30:00Z'); - const times = - options.times ?? Array.from({ length: equities.length + 1 }, (_, i) => start + i * 3600000); - const tradeStart = times[0]!, - tradeEnd = times.at(-1)!; - const identity = { - version: 1 as const, - sessionId: 'analytics-fixture', - datasetHash: 'a'.repeat(64), - }; - const riskSession = (index: number) => ({ - calendarId: 'account-test', - calendarRevision: 'revision-7', - sessionId: `session-${index}`, - startsAt: index === 0 && options.partialStart ? tradeStart - 1000 : times[index]!, - }); - const config: ReplayConfig = { - matching: { - risk: { - ledger: { - version: 1, - sessionId: identity.sessionId, - accountId: 'account', - baseCurrency: 'USD', - reserveOwnerId: 'reserve', - ownerIds: ['A'], - initialCapital: money(initial), - riskSession: riskSession(0), - }, - feeRate: '0', - maxOrderQuantity: '1000', - maxPositionQuantity: '1000', - maxSymbolExposure: '1000000', - maxGrossExposure: '1000000', - maxDailyLoss: '1000000', - maxDrawdownAmount: '1000000', - maxMarkAgeMs: 86400000, - }, - owners: [{ ownerId: 'A', mode: 'Target' }], - series: [{ instrumentId: 'X.US', seriesId: 'X.US:1m', mode: 'Open' }], - halfSpreadRate: '0', - slippageRate: '0', - latencyMs: 0, - }, - participation_rate: '1', - cadence: [{ owner_id: 'A', series_ids: ['X.US:1m'] }], - allow_exploratory: false, - risk_boundaries: [], - }; - const ledger = config.matching.risk.ledger; - config.risk_boundaries = times - .slice(1, options.partialEnd ? -1 : undefined) - .map((_, index) => riskSession(index + 1)); - const final = money(equities.at(-1)!); - const occupiedIntervals = options.occupiedIntervals ?? []; - const lastRisk = config.risk_boundaries.at(-1) ?? ledger.riskSession; - return parseReplayReportValue( - { - identity, - status: 'complete', - format: 'report', - reportingVersion: 1, - projectionVersion: 1, - financialVersion: 1, - manifest: { version: 2, hash: identity.datasetHash, bounds: { tradeStart, tradeEnd } }, - policy: config, - view: { - admissionRevision: 0, - portfolio: { - version: 1, - sessionId: identity.sessionId, - accountId: ledger.accountId, - revision: 0, - baseCurrency: ledger.baseCurrency, - reserveOwnerId: ledger.reserveOwnerId, - cash: final, - positions: [], - fees: [], - riskSession: lastRisk, - }, - equity: final, - availableCash: final, - orders: [], - reservations: [], - risk: { - dailyBaseline: money(initial), - peakEquity: money(initial), - dailyHalted: false, - drawdownHalted: false, - riskSession: lastRisk, - lastEventTime: tradeEnd, - }, - }, - projection: { - valuation: { - cash: final, - markedHoldings: '0', - equity: final, - remainingCost: '0', - realizedGrossPnl: '0', - unrealizedPnl: '0', - fees: '0', - owners: [], - }, - fills: [], - }, - reporting: { - calendarId: ledger.riskSession.calendarId, - calendarRevision: ledger.riskSession.calendarRevision, - tradeStart, - tradeEnd, - initialEquity: money(initial), - sampling: 'account-boundary-after-observations-v1', - exposureBasis: 'elapsed-calendar-time', - sessions: equities.map((equity, index) => ({ - session: riskSession(index), - periodStart: times[index], - periodEnd: times[index + 1], - partialStart: index === 0 && !!options.partialStart, - partialEnd: index === equities.length - 1 && !!options.partialEnd, - equity: money(equity), - })), - occupiedIntervals, - occupiedMs: String( - occupiedIntervals.reduce((sum, i) => sum + BigInt(i.end) - BigInt(i.start), 0n) - ), - elapsedMs: String(BigInt(tradeEnd) - BigInt(tradeStart)), - }, - limitations: ['fixture availability'], - modelLimitations: ['Equal-time asset marks are sequential; portfolio risk is not atomic.'], - }, - identity - ); -} - -function analytics(financial = fixture(), selectedPolicy = policy) { - const output = buildCanonicalBacktestReport(financial, selectedPolicy).analytics; - for (const [key, value] of Object.entries(output.metrics)) { - if (value === null) { - expect(output.unavailable[key as keyof typeof output.metrics]).toBeDefined(); - } else { - expect(Number.isFinite(value)).toBe(true); - expect(output.unavailable[key as keyof typeof output.metrics]).toBeUndefined(); - } - } - return output; -} - -describe('canonical statistical reporting', () => { - test('two_session_marks retain final session, fractional units and explicit calendar conventions', () => { - const output = analytics(); - expect(output.sessionReturns).toHaveLength(2); - expect(output.sessionReturns[0]?.value).toBeCloseTo(0.1); - expect(output.sessionReturns[1]?.value).toBeCloseTo(-0.1); - expect(output.metrics.totalReturn).toBeCloseTo(-0.01); - expect(output.metrics.maxDrawdown).toBeCloseTo(0.1); - expect(output.metrics.volatility).toBeCloseTo(Math.sqrt(0.02 * 252)); - expect(output.metrics.downsideDeviation).toBeCloseTo(Math.sqrt(0.005 * 252)); - expect(output.metrics.sharpeRatio).toBeCloseTo(0); - expect(output.metrics.sortinoRatio).toBeCloseTo(0); - expect(output.periodicSampleCount).toBe(2); - expect(output.policy).toMatchObject({ - calendarId: 'account-test', - calendarRevision: 'revision-7', - sampling: 'account-boundary-after-observations-v1', - drawdown: 'session-end-and-terminal-sampled', - exposureBasis: 'elapsed-calendar-time', - cagrBasis: 'elapsed-calendar-days-365', - returnUnit: 'fraction', - marks: 'last-available-no-per-session-freshness-certification', - }); - }); - - test('partial initial and final returns remain visible but do not become complete statistical periods', () => { - const output = analytics(fixture([110, 99, 198, 99], { partialStart: true, partialEnd: true })); - expect(output.sessionReturns.map(s => s.eligible)).toEqual([false, true, true, false]); - expect(output.sessionReturns.map(s => s.partialStart)).toEqual([true, false, false, false]); - expect(output.sessionReturns.at(-1)?.value).toBeCloseTo(-0.5); - expect(output.completePeriodCount).toBe(2); - expect(output.periodicSampleCount).toBe(2); - // Only -.1 and +1: mean .45, sample variance .605. - expect(output.metrics.volatility).toBeCloseTo(Math.sqrt(0.605 * 252)); - expect(output.metrics.sharpeRatio).toBeCloseTo((0.45 * 252) / Math.sqrt(0.605 * 252)); - expect(output.metrics.totalReturn).toBeCloseTo(-0.01); - }); - - test('undefined complete return invalidates the entire periodic sequence without dropping history', () => { - const output = analytics(fixture([0, 0, 0])); - expect(output.sessionReturns.map(s => s.value)).toEqual([-1, null, null]); - expect(output.sessionReturns[1]?.reason).toBe('nonpositive-baseline'); - expect(output.completePeriodCount).toBe(3); - expect(output.periodicSampleCount).toBe(0); - for (const key of [ - 'volatility', - 'downsideDeviation', - 'sharpeRatio', - 'sortinoRatio', - 'var95', - 'cvar95', - 'var99', - ] as const) { - expect(output.metrics[key]).toBeNull(); - expect(output.unavailable[key]).toBe('undefined-period-return'); - } - expect(output.metrics.totalReturn).toBe(-1); - expect(output.metrics.cagr).toBe(-1); - }); - - test('constant_negative_returns and zero_variance distinguish Sharpe from Sortino', () => { - const negative = analytics(fixture([90, 81])); - expect(negative.metrics.volatility).toBe(0); - expect(negative.metrics.sharpeRatio).toBeNull(); - expect(negative.unavailable.sharpeRatio).toBe('zero-variance'); - expect(negative.metrics.sortinoRatio).toBeCloseTo(-Math.sqrt(252)); - const zero = analytics(fixture([100, 100])); - expect(zero.metrics.totalReturn).toBe(0); - expect(zero.metrics.volatility).toBe(0); - expect(zero.metrics.downsideDeviation).toBe(0); - expect(zero.metrics.sortinoRatio).toBeNull(); - expect(zero.unavailable.sortinoRatio).toBe('zero-downside-deviation'); - }); - - test('missing rate and benchmark remain unavailable; explicit zero is not missing', () => { - const missing = analytics(fixture(), { ...policy, annualRiskFreeRate: null }); - for (const key of ['sharpeRatio', 'sortinoRatio', 'downsideDeviation'] as const) { - expect(missing.metrics[key]).toBeNull(); - expect(missing.unavailable[key]).toBe('missing-risk-free'); - } - expect(missing.metrics.volatility).not.toBeNull(); - expect(missing.unavailable.beta).toBe('missing-benchmark'); - expect(analytics().metrics.sharpeRatio).not.toBeNull(); - for (const input of [ - { ...policy, benchmark: 'SPY' }, - { ...policy, annualRiskFreeRate: undefined }, - { ...policy, periodsPerYear: 0 }, - { ...policy, periodsPerYear: Infinity }, - { ...policy, version: 2 }, - { ...policy, extra: true }, - ]) { - expect(() => - buildCanonicalBacktestReport(fixture(), input as CanonicalMetricsInput) - ).toThrow(); - } - }); - - test('exposure consumes the canonical union and includes terminal open-position occupancy', () => { - // Rust supplies the union [1,7) of overlapping positions [1,5),[3,7). - const financial = fixture([100], { - times: [0, 10], - occupiedIntervals: [ - { start: 1, end: 7 }, - { start: 8, end: 10 }, - ], - }); - expect(analytics(financial).metrics.exposureTime).toBe(0.8); - expect(analytics(fixture([100], { times: [0, 10] })).metrics.exposureTime).toBe(0); - expect( - analytics(fixture([100], { times: [0, 10], occupiedIntervals: [{ start: 0, end: 10 }] })) - .metrics.exposureTime - ).toBe(1); - }); - - test('financial facts and limitations are preserved; fill count is not round-trip count', () => { - const financial = fixture(); - financial.projection.fills.push({ - commandId: 'command', - eventTime: financial.reporting.tradeStart, - ownerId: 'A', - decision: { ownerId: 'A', decisionId: 'decision', sequence: 0 }, - orderId: 'order', - fillId: 'fill', - instrumentId: 'X0.US', - side: 'buy', - quantity: money(1), - price: money(10), - fee: { feeId: 'fee', amount: money(1) }, - cashDelta: money(-10), - quantityDelta: money(1), - releasedBasis: money(0), - realizedGrossPnl: money(0), - }); - const before = structuredClone(financial); - const result = buildCanonicalBacktestReport(financial, policy); - expect(result.financial).toBe(financial); - expect(result.financial).toEqual(before); - expect(result.analytics.fillCount).toBe(1); - for (const key of ['roundTripCount', 'winRate', 'profitFactor', 'avgWin', 'avgLoss'] as const) { - expect(result.analytics.metrics[key]).toBeNull(); - expect(result.analytics.unavailable[key]).toBe('unsupported-round-trips'); - } - expect(result.analytics).not.toHaveProperty('positions'); - }); - - test('extreme supported timestamps preserve integer durations without Date coercion', () => { - const min = -Number.MAX_SAFE_INTEGER, - max = Number.MAX_SAFE_INTEGER; - const financial = fixture([110, 99], { - times: [min, 0, max], - occupiedIntervals: [{ start: min, end: max }], - }); - expect(financial.reporting.elapsedMs).toBe('18014398509481982'); - const output = analytics(financial); - expect(output.metrics.exposureTime).toBe(1); - expect(output.metrics.maxDrawdown).toBeCloseTo(0.1); - expect(output.metrics.cagr).not.toBeNull(); - }); - - test('insufficient complete periods and nonpositive initial baseline have explicit reasons', () => { - const partial = analytics(fixture([110], { partialEnd: true })); - expect(partial.sessionReturns[0]?.value).toBeCloseTo(0.1); - expect(partial.completePeriodCount).toBe(0); - expect(partial.unavailable.volatility).toBe('insufficient-periods'); - const zero = analytics(fixture([0], { initial: 0 })); - expect(zero.unavailable.totalReturn).toBe('nonpositive-baseline'); - expect(zero.unavailable.cagr).toBe('nonpositive-baseline'); - expect(zero.unavailable.maxDrawdown).toBe('nonpositive-baseline'); - const overflow = analytics(fixture([200], { times: [0, 1] })); - expect(overflow.metrics.totalReturn).toBe(1); - expect(overflow.metrics.cagr).toBeNull(); - expect(overflow.unavailable.cagr).toBe('nonfinite-result'); - }); -}); diff --git a/test/integration/canonical-sma.test.ts b/test/integration/canonical-sma.test.ts deleted file mode 100644 index e2fb6a8c..00000000 --- a/test/integration/canonical-sma.test.ts +++ /dev/null @@ -1,406 +0,0 @@ -import { expect, test } from 'bun:test'; -import { parseFinancialDecimal } from '@stock-bot/types'; -import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay'; -import { - runStrategyReplay, - StrategyReplayError, -} from '../../apps/stock/orchestrator/src/backtest/strategy-runtime'; -import { - builtinStrategySelectionSchema, - type BuiltinStrategySelection, -} from '../../apps/stock/orchestrator/src/contracts/builtin-strategy'; -import type { - StrategyContext, - StrategyProgram, -} from '../../apps/stock/orchestrator/src/contracts/canonical-strategy'; -import type { PublishedObservation } from '../../apps/stock/orchestrator/src/contracts/native-replay'; -import { strategyAliases } from '../../apps/stock/orchestrator/src/contracts/strategy-names'; -import { createBuiltinStrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/builtin-strategies'; -import { - createBuiltinStrategy, - validateBuiltinStrategyBindings, - type SmaStrategyState, -} from '../../apps/stock/orchestrator/src/strategies/canonical-sma'; -import { canonicalSmaFixture } from '../fixtures/canonical-sma'; - -const d = parseFinancialDecimal; -function selection(overrides: Partial = {}) { - return builtinStrategySelectionSchema.parse({ - ...canonicalSmaFixture().selections[0], - ...overrides, - }); -} -function observation( - close: string, - sequence: number, - overrides: Partial = {} -): PublishedObservation { - return { - series_id: 'X0.US:1m', - instrument_id: 'X0.US', - interval_start: sequence, - interval_end: sequence + 1, - event_time: sequence + 1, - available_at: sequence + 1, - source_sequence: sequence, - open: d(close), - high: d(close), - low: d(close), - close: d(close), - volume: d('1000'), - ...overrides, - }; -} -function context( - state: SmaStrategyState, - observations: PublishedObservation[], - now = observations.at(-1)?.available_at ?? 0 -): StrategyContext { - const last = observations.at(-1); - const riskSession = { calendarId: 'test', calendarRevision: '1', sessionId: 'test', startsAt: 0 }; - return { - ownerId: 'A', - strategyId: 'sma_crossover', - strategyVersion: 'sma-crossover-long-only/v1', - decisionSequence: 0, - now, - barrier: { - barrier_id: 'test', - at: now, - revision: 0, - owner_ids: ['A'], - observation_count: observations.length, - inputs: [ - { - series_id: 'X0.US:1m', - availability: last - ? { Fresh: { event_time: last.event_time, available_at: last.available_at } } - : 'Missing', - }, - ], - }, - portfolio: { - admissionRevision: 0, - equity: d('10000'), - availableCash: d('10000'), - orders: [], - reservations: [], - portfolio: { - version: 1, - sessionId: 'test', - accountId: 'test', - revision: 0, - baseCurrency: 'USD', - reserveOwnerId: 'reserve', - cash: d('10000'), - positions: [], - fees: [], - riskSession, - }, - risk: { - dailyBaseline: d('10000'), - peakEquity: d('10000'), - dailyHalted: false, - drawdownHalted: false, - riskSession, - lastEventTime: now, - }, - }, - positions: [], - observations, - previousAdmission: null, - state, - random: () => { - throw new Error('SMA must not consume random'); - }, - }; -} -function decide( - program: StrategyProgram, - closes: string[], - state = program.initialState, - offset = 0 -) { - return program.decide( - context( - state, - closes.map((close, i) => observation(close, offset + i)) - ) - ); -} - -test('sma_registry_alias selects only the explicit canonical version and leaves legacy factories available', () => { - for (const strategyId of [...strategyAliases.sma_crossover, 'sma_crossover', ' SMA Crossover ']) { - expect(builtinStrategySelectionSchema.parse({ ...selection(), strategyId }).strategyId).toBe( - 'sma_crossover' - ); - } - for (const patch of [ - { strategyId: 'momentum' }, - { strategyVersion: 'sma-crossover-fixed/v2' }, - { source: 'code' }, - { parameters: { fastPeriod: 2, slowPeriod: 3, quantity: 10 } }, - { parameters: { fastPeriod: 3, slowPeriod: 3 } }, - { ownerBudget: '0' }, - ]) { - expect(() => builtinStrategySelectionSchema.parse({ ...selection(), ...patch })).toThrow(); - } - expect(typeof createBuiltinStrategyRegistry().create).toBe('function'); -}); - -test('binding validation rejects wrong owners, mode, cadence, instrument and unknown series before replay', () => { - const fixture = canonicalSmaFixture(); - const load = prepareReplayLoad(fixture.dataset, fixture.config); - expect(() => validateBuiltinStrategyBindings(fixture.selections, load)).not.toThrow(); - for (const changed of [ - selection({ ownerId: 'B' }), - selection({ seriesId: 'missing' }), - selection({ instrumentId: 'X1.US' }), - ]) { - expect(() => validateBuiltinStrategyBindings([changed], load)).toThrow(); - } - expect(() => - validateBuiltinStrategyBindings([...fixture.selections, ...fixture.selections], load) - ).toThrow(); - const wrongMode = structuredClone(load); - wrongMode.config.matching.owners[0]!.mode = 'Orders'; - expect(() => validateBuiltinStrategyBindings(fixture.selections, wrongMode)).toThrow(); - const wrongCadence = structuredClone(load); - wrongCadence.config.cadence[0]!.series_ids = []; - expect(() => validateBuiltinStrategyBindings(fixture.selections, wrongCadence)).toThrow(); -}); - -test('owner_budget_sizing uses exact decimal whole shares, never account equity or a forced minimum', () => { - for (const [budget, prices, expected] of [ - ['0.3', ['0.2', '0.01', '0.1'], '3'], - ['0.09', ['0.2', '0.01', '0.1'], '0'], - ['9007199254740993', ['2', '0.5', '1'], '9007199254740993'], - ] as const) { - const program = createBuiltinStrategy( - selection({ ownerBudget: d(budget), parameters: { fastPeriod: 1, slowPeriod: 2 } }) - ); - const result = decide(program, [...prices]); - expect(result.intent).toEqual({ - mode: 'target', - targets: [{ instrumentId: 'X0.US', quantity: d(expected) }], - }); - expect(JSON.stringify(result.nextState)).not.toContain('BigInt'); - } -}); - -test('warmup requires a real crossover; target survives equality and a repeated golden cross until death', () => { - const program = createBuiltinStrategy( - selection({ parameters: { fastPeriod: 1, slowPeriod: 2 } }) - ); - expect(decide(program, ['1', '2']).intent).toEqual({ mode: 'target', targets: [] }); - expect(decide(program, ['1', '2', '3']).intent).toEqual({ mode: 'target', targets: [] }); - let result = decide(program, ['3', '1', '2']); - expect(result.nextState.targetQuantity).toBe(d('20')); - result = decide(program, ['2'], result.nextState, 3); // equality retains long - expect(result.nextState.targetQuantity).toBe(d('20')); - result = decide(program, ['4'], result.nextState, 4); // golden after equality must not resize to10 - expect(result.nextState.targetQuantity).toBe(d('20')); - result = decide(program, ['1'], result.nextState, 5); - expect(result.nextState.targetQuantity).toBe(d('0')); -}); - -test('stale, missing, mismatched freshness and no-new inputs preserve GTC intent without new targets', () => { - const program = createBuiltinStrategy(selection()); - const initial = decide(program, ['3', '2', '1', '4']); - for (const availability of [ - 'Missing', - { Stale: { event_time: 5, available_at: 5 } }, - { Fresh: { event_time: 4, available_at: 4 } }, - ] as const) { - const input = context(initial.nextState, [observation('5', 4)]); - const result = program.decide({ - ...input, - barrier: { ...input.barrier, inputs: [{ series_id: 'X0.US:1m', availability }] }, - }); - expect(result.intent).toEqual({ mode: 'target', targets: [] }); - expect(result.nextState.targetQuantity).toBe(d('10')); - } - expect(program.decide(context(initial.nextState, [])).intent).toEqual({ - mode: 'target', - targets: [], - }); - const delayed = observation('0.01', 1, { available_at: 10 }); - const input = context(initial.nextState, [delayed], 10); - const result = program.decide({ - ...input, - barrier: { - ...input.barrier, - inputs: [ - { series_id: 'X0.US:1m', availability: { Fresh: { event_time: 4, available_at: 4 } } }, - ], - }, - }); - expect(result.nextState).toEqual(initial.nextState); - expect(result.intent).toEqual({ mode: 'target', targets: [] }); - expect(() => program.decide(context(initial.nextState, [observation('5', 4)], 4))).toThrow( - 'availability' - ); -}); - -test('sma_checkpoint_restore validates JSON state and reconstructs identical indicator decisions', () => { - const selected = selection(); - const first = createBuiltinStrategy(selected); - const before = decide(first, ['3', '2', '1', '4']); - const restored = JSON.parse(JSON.stringify(before.nextState)) as SmaStrategyState; - expect(decide(createBuiltinStrategy(selected), ['5', '1'], restored, 4)).toEqual( - decide(first, ['5', '1'], before.nextState, 4) - ); - expect(() => decide(first, ['5'], { ...restored, closes: [] }, 4)).toThrow(); - expect(() => - decide(createBuiltinStrategy(selection({ ownerId: 'B' })), ['5'], restored, 4) - ).toThrow(); - expect(() => decide(first, ['5'], { ...restored, targetQuantity: d('1.5') }, 4)).toThrow(); -}); - -test('sma_next_open_trace buys and closes at eligible next opens with authoritative fees and exact equity', () => { - const fixture = canonicalSmaFixture(); - const load = prepareReplayLoad(fixture.dataset, fixture.config); - validateBuiltinStrategyBindings(fixture.selections, load); - const run = (eventBudget: number) => - runStrategyReplay(load, fixture.selections.map(createBuiltinStrategy), { - resultFormat: 'report', - eventBudget, - }); - const first = run(1); - expect(run(64)).toEqual({ ...first, metrics: expect.anything() }); - expect(first.result.projection.valuation.equity).toBe(d('9969.3')); - expect(first.result.projection.valuation.fees).toBe(d('0.7')); - expect( - first.result.projection.fills.map(fill => ({ - price: fill.price, - quantityDelta: fill.quantityDelta, - })) - ).toEqual([ - { price: d('5'), quantityDelta: d('10') }, - { price: d('2'), quantityDelta: d('-10') }, - ]); -}); - -test('warmup crossover sizes once at the first eligible fresh trading close and cannot fill during warmup', () => { - const fixture = canonicalSmaFixture(['A'], { tradeStartStep: 5 }); - const load = prepareReplayLoad(fixture.dataset, fixture.config); - const run = runStrategyReplay(load, fixture.selections.map(createBuiltinStrategy), { - resultFormat: 'report', - }); - expect(run.result.projection.fills.map(fill => [fill.eventTime, fill.quantityDelta])).toEqual([ - [fixture.start + 5 * fixture.minute, d('8')], - [fixture.start + 6 * fixture.minute, d('-8')], - ]); - expect(run.result.projection.valuation.equity).toBe(d('9975.44')); -}); - -test('canonical SMA cannot bypass native fee-inclusive funding or adverse-gap fill checks', () => { - for (const capital of ['40', '45']) { - const fixture = canonicalSmaFixture(); - fixture.config.matching.risk.ledger.initialCapital = capital; - const run = runStrategyReplay( - prepareReplayLoad(fixture.dataset, fixture.config), - fixture.selections.map(createBuiltinStrategy), - { resultFormat: 'report' } - ); - expect(run.result.projection.fills).toEqual([]); - expect(run.result.projection.valuation.cash).toBe(d(capital)); - const trace = runStrategyReplay( - prepareReplayLoad(fixture.dataset, fixture.config), - fixture.selections.map(createBuiltinStrategy), - { resultFormat: 'trace' } - ); - expect(JSON.stringify(trace.result.receipts)).toContain('InsufficientCash'); - expect(run.diagnostics.strategies[0]!.state).toMatchObject({ - lastCrossover: 'death', - targetQuantity: d('0'), - }); - } -}); - -test('late older native observations cannot rewrite SMA history or alter its targets', () => { - const run = (lateClose: number) => { - const fixture = canonicalSmaFixture(['A'], { - closes: [3, lateClose, 1, 4, 5, 1, 1], - availabilitySteps: [1, 6, 3, 4, 5, 6, 7], - }); - return runStrategyReplay( - prepareReplayLoad(fixture.dataset, fixture.config), - fixture.selections.map(createBuiltinStrategy), - { resultFormat: 'report', eventBudget: 1 } - ); - }; - const first = run(2), - changed = run(200); - expect(changed.result.projection).toEqual(first.result.projection); - expect(changed.diagnostics.strategies).toEqual(first.diagnostics.strategies); - expect(first.result.projection.fills.map(fill => fill.quantityDelta)).toEqual([d('8'), d('-8')]); -}); - -test('repeating the desired target preserves the partially filled native order before a death closes owned inventory', () => { - const fixture = canonicalSmaFixture(['A'], { volume: 3 }); - const run = runStrategyReplay( - prepareReplayLoad(fixture.dataset, fixture.config), - fixture.selections.map(createBuiltinStrategy), - { resultFormat: 'report' } - ); - const fills = run.result.projection.fills; - expect(fills.map(fill => fill.quantityDelta)).toEqual([d('3'), d('3'), d('-3')]); - expect(fills[0]!.orderId).toBe(fills[1]!.orderId); - expect(run.result.view.portfolio.positions[0]!.quantity).toBe(d('3')); - expect(run.result.projection.valuation.cash).toBe(d('9975.64')); - expect(run.result.projection.valuation.equity).toBe(d('9978.64')); -}); - -test('two owners sharing an asset keep independent targets, fills and P&L', () => { - const fixture = canonicalSmaFixture(['B', 'A']); - fixture.selections = fixture.selections.map(item => - selection({ ...item, ownerBudget: d(item.ownerId === 'A' ? '40' : '20') }) - ); - const load = prepareReplayLoad(fixture.dataset, fixture.config); - validateBuiltinStrategyBindings(fixture.selections, load); - const run = runStrategyReplay(load, fixture.selections.map(createBuiltinStrategy), { - resultFormat: 'report', - }); - expect(run.result.projection.fills.map(fill => [fill.ownerId, fill.quantityDelta])).toEqual([ - ['A', d('10')], - ['B', d('5')], - ['A', d('-10')], - ['B', d('-5')], - ]); - expect( - run.result.projection.valuation.owners - .filter(owner => owner.ownerId !== 'reserve') - .map(owner => [owner.ownerId, owner.realizedGrossPnl, owner.fees]) - ).toEqual([ - ['A', d('-30'), d('0.7')], - ['B', d('-15'), d('0.35')], - ]); - expect(run.result.projection.valuation.equity).toBe(d('9953.95')); -}); - -test('sma_checkpoint_restore whole-attempt retry after strategy failure recomputes identical decisions and economics', () => { - const fixture = canonicalSmaFixture(); - const load = prepareReplayLoad(fixture.dataset, fixture.config); - const original = createBuiltinStrategy(fixture.selections[0]!); - const failing: StrategyProgram = { - ...original, - decide(input) { - if (input.decisionSequence === 4) { - throw new Error('injected strategy failure'); - } - return original.decide(input); - }, - }; - expect(() => runStrategyReplay(load, [failing], { resultFormat: 'report' })).toThrow( - StrategyReplayError - ); - const baseline = runStrategyReplay(load, [createBuiltinStrategy(fixture.selections[0]!)], { - resultFormat: 'report', - eventBudget: 1, - }); - const retried = runStrategyReplay(load, [original], { resultFormat: 'report', eventBudget: 7 }); - expect(retried.result).toEqual(baseline.result); - expect(retried.diagnostics).toEqual(baseline.diagnostics); - expect(original.initialState.closes).toEqual([]); -}); diff --git a/test/integration/canonical-strategy-worker.test.ts b/test/integration/canonical-strategy-worker.test.ts deleted file mode 100644 index 9e94f567..00000000 --- a/test/integration/canonical-strategy-worker.test.ts +++ /dev/null @@ -1,238 +0,0 @@ -import type { ChildProcess } from 'node:child_process'; -import { describe, expect, test } from 'bun:test'; -import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay'; -import { nativeWorkerRequestSchema } from '../../apps/stock/orchestrator/src/backtest/native-worker-protocol'; -import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker'; -import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime'; -import { - replayIdentitySchema, - type ReplayResultFormat, -} from '../../apps/stock/orchestrator/src/contracts/native-replay'; -import { - parseStrategyReplayResult, - strategyReplayRequestSchema, - type StrategyReplayExpectation, - type StrategyReplayRequest, -} from '../../apps/stock/orchestrator/src/contracts/strategy-replay'; -import { - createBuiltinStrategy, - validateBuiltinStrategyBindings, -} from '../../apps/stock/orchestrator/src/strategies/canonical-sma'; -import { nativeReplayFixture } from '../fixtures/native-replay'; - -function request(resultFormat: ReplayResultFormat = 'trace', owners = ['A']) { - const { dataset, config } = nativeReplayFixture(24, 1, owners); - return { - type: 'runStrategyReplay' as const, - version: 1 as const, - dataset, - config, - eventBudget: 3, - resultFormat, - strategies: owners.map((ownerId, index) => ({ - ownerId, - strategyId: 'SMA', - strategyVersion: 'sma-crossover-long-only/v1' as const, - seed: index + 7, - instrumentId: 'X0.US', - seriesId: 'X0.US:1m', - ownerBudget: '100', - parameters: { fastPeriod: 1, slowPeriod: 2 }, - })), - } satisfies StrategyReplayRequest; -} - -function expected(input: StrategyReplayRequest): StrategyReplayExpectation { - const normalized = strategyReplayRequestSchema.parse(input); - return { - strategies: normalized.strategies, - identity: replayIdentitySchema.parse({ - version: 1, - sessionId: normalized.config.matching.risk.ledger.sessionId, - datasetHash: (normalized.dataset as { manifest: { hash: string } }).manifest.hash, - }), - policy: normalized.config, - format: normalized.resultFormat ?? 'trace', - }; -} - -function direct(input: StrategyReplayRequest) { - const normalized = strategyReplayRequestSchema.parse(input); - const load = prepareReplayLoad(normalized.dataset, normalized.config); - validateBuiltinStrategyBindings(normalized.strategies, load); - return runStrategyReplay(load, normalized.strategies.map(createBuiltinStrategy), { - eventBudget: normalized.eventBudget, - resultFormat: normalized.resultFormat, - }).result; -} - -describe('trusted built-in strategy worker', () => { - test.each(['trace', 'projection', 'report'] as const)( - '%s real child matches direct SMA replay and repeated frozen-input attempts', - async resultFormat => { - const input = request(resultFormat, ['B', 'A']); - const captured = expected(input); - const worker = new NativeBacktestWorker(); - const raw = await worker.execute(input, new AbortController().signal, () => {}); - const envelope = parseStrategyReplayResult(raw, captured); - expect(envelope.result).toEqual(direct(input)); - expect(envelope.strategies).toEqual([...captured.strategies]); - expect(envelope.strategies.map(selection => selection.strategyId)).toEqual([ - 'sma_crossover', - 'sma_crossover', - ]); - expect(envelope.result.view.portfolio.positions).toHaveLength(2); - expect(Object.keys(envelope).sort()).toEqual(['result', 'strategies', 'type', 'version']); - expect(await worker.execute(input, new AbortController().signal, () => {})).toBe(raw); - } - ); - - test('schema normalizes built-in aliases/defaults but rejects code and unsupported versions', () => { - const defaults = request(); - const parsed = strategyReplayRequestSchema.parse({ - ...defaults, - strategies: [{ ...defaults.strategies[0], parameters: {} }], - }); - expect(parsed.strategies[0]).toMatchObject({ - strategyId: 'sma_crossover', - ownerBudget: '100.00000000', - parameters: { fastPeriod: 5, slowPeriod: 15 }, - }); - for (const extra of [ - { source: 'return buy()' }, - { module: './candidate.ts' }, - { initialState: {} }, - { decide: () => ({}) }, - ]) { - expect(() => nativeWorkerRequestSchema.parse({ ...request(), ...extra })).toThrow(); - const input = request(); - expect(() => - nativeWorkerRequestSchema.parse({ - ...input, - strategies: [{ ...input.strategies[0], ...extra }], - }) - ).toThrow(); - } - for (const changes of [ - { strategyId: 'momentum' }, - { strategyVersion: 'legacy' }, - { parameters: { fastPeriod: 1, slowPeriod: 2, quantity: 10 } }, - ]) { - const input = request(); - expect(() => - nativeWorkerRequestSchema.parse({ - ...input, - strategies: [{ ...input.strategies[0], ...changes }], - }) - ).toThrow(); - } - }); - - test('captures the entire normalized request before caller mutation', async () => { - const input = structuredClone(request('report')); - const captured = expected(input); - const reference = direct(structuredClone(input)); - const worker = new NativeBacktestWorker(); - const running = worker.execute(input, new AbortController().signal, () => {}); - input.strategies[0]!.seed = 999; - input.strategies[0]!.parameters.slowPeriod = 20; - input.strategies[0]!.ownerBudget = '5000'; - input.strategies[0]!.ownerId = 'mutated'; - input.config.matching.risk.ledger.sessionId = 'mutated'; - (input.dataset.manifest as { hash: string }).hash = '0'.repeat(64); - (input.dataset.bars as unknown[]).length = 0; - input.resultFormat = 'projection'; - input.eventBudget = 0; - const envelope = parseStrategyReplayResult(await running, captured); - expect(envelope.result).toEqual(reference); - expect(envelope.strategies).toEqual([...captured.strategies]); - }); - - test('actual child rejects invalid owner, cadence and series bindings', async () => { - const worker = new NativeBacktestWorker(); - for (const change of ['owner', 'cadence', 'series', 'instrument'] as const) { - const input = request(); - if (change === 'owner') { - input.strategies[0]!.ownerId = 'unknown'; - } - if (change === 'cadence') { - input.config.cadence[0]!.series_ids = []; - } - if (change === 'series') { - input.strategies[0]!.seriesId = 'X0.US:unknown'; - } - if (change === 'instrument') { - input.strategies[0]!.instrumentId = 'OTHER.US'; - } - await expect(worker.execute(input, new AbortController().signal, () => {})).rejects.toThrow(); - } - expect( - JSON.parse(await worker.execute(request(), new AbortController().signal, () => {})).type - ).toBe('strategyReplayResult'); - }); - - test.each([ - 'wrong-envelope-version', - 'wrong-envelope-type', - 'wrong-strategy', - 'wrong-version', - 'wrong-owner', - 'wrong-seed', - 'wrong-parameters', - 'wrong-budget', - 'wrong-series', - 'wrong-instrument', - 'reordered', - 'missing-selection', - 'wrong-session', - 'wrong-dataset', - 'wrong-policy', - 'wrong-format', - 'invalid-result', - 'malformed', - 'reported-error', - 'crash', - 'no-result', - 'duplicate', - ])('%s child cannot publish a successful result', async mode => { - const worker = new NativeBacktestWorker( - new URL('../fixtures/canonical-strategy-worker.ts', import.meta.url) - ); - const input = request('trace', ['B', 'A']); - input.config.matching.risk.ledger.accountId = mode; - await expect(worker.execute(input, new AbortController().signal, () => {})).rejects.toThrow(); - expect( - JSON.parse(await worker.execute(request(), new AbortController().signal, () => {})).type - ).toBe('strategyReplayResult'); - }); - - test('hard cancellation discards pending success and releases the worker', async () => { - const actual = new NativeBacktestWorker(); - const beforeResult = new AbortController(); - await expect( - actual.execute(request(), beforeResult.signal, () => { - beforeResult.abort(new Error('cancel strategy work')); - }) - ).rejects.toThrow('cancel strategy work'); - const worker = new NativeBacktestWorker( - new URL('../fixtures/canonical-strategy-worker.ts', import.meta.url) - ); - const input = request(); - input.config.matching.risk.ledger.accountId = 'result-then-block'; - const afterResult = new AbortController(); - let observed = false; - const running = worker.execute(input, afterResult.signal, () => {}); - const child = (worker as unknown as { active: ChildProcess }).active; - child.on('message', (message: { type: string }) => { - if (message.type === 'result') { - observed = true; - afterResult.abort(new Error('cancel pending strategy success')); - } - }); - await expect(running).rejects.toThrow('cancel pending strategy success'); - expect(observed).toBe(true); - expect( - JSON.parse(await worker.execute(request(), new AbortController().signal, () => {})).type - ).toBe('strategyReplayResult'); - }); -}); diff --git a/test/integration/native-replay-projection.test.ts b/test/integration/native-replay-projection.test.ts deleted file mode 100644 index 5a5b48e6..00000000 --- a/test/integration/native-replay-projection.test.ts +++ /dev/null @@ -1,265 +0,0 @@ -import type { ChildProcess } from 'node:child_process'; -import { createHash } from 'node:crypto'; -import { describe, expect, test } from 'bun:test'; -import { FinancialReplaySession } from '@stock-bot/engine'; -import { parseFinancialDecimal } from '@stock-bot/types'; -import { - executeReplayTrace, - NativeReplaySession, - prepareReplayLoad, - runReplayConformance, -} from '../../apps/stock/orchestrator/src/backtest/native-replay'; -import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker'; -import { - parseReplayProjectionResult, - parseReplayResult, - replayConfigSchema, -} from '../../apps/stock/orchestrator/src/contracts/native-replay'; -import { nativeReplayFixture } from '../fixtures/native-replay'; - -const intent = (quantity = '2') => ({ - mode: 'target' as const, - targets: [{ instrumentId: 'X0.US', quantity: parseFinancialDecimal(quantity) }], -}); -const hold = () => ({ mode: 'target' as const, targets: [] }); -function request() { - const f = nativeReplayFixture(); - return { - type: 'runReplayTrace' as const, - version: 1 as const, - dataset: f.dataset, - config: replayConfigSchema.parse(f.config), - eventBudget: 1, - trace: [ - { at: f.start + f.minute, ownerId: 'A', intent: intent() }, - { at: f.start + 2 * f.minute, ownerId: 'A', intent: hold() }, - ], - }; -} -describe('compact canonical replay projection', () => { - test('compact_full_financial_parity and unchanged diagnostic hash', () => { - const input = request(), - trace = executeReplayTrace(input), - compact = executeReplayTrace({ ...input, resultFormat: 'projection' }); - // Captured from committed F07 before implementing this projection. - expect(createHash('sha256').update(JSON.stringify(trace.result)).digest('hex')).toBe( - 'bb46165ddfe2de122689bdc47d5b1cc4065d55fdfc58a991cb3a61a91f4ad880' - ); - expect(compact.result.view).toEqual(trace.result.view); - expect(compact.result.policy).toEqual(trace.result.policy); - expect(compact.result.manifest).toEqual(trace.result.manifest); - expect(compact.result.limitations).toEqual(trace.result.limitations); - expect(compact.result.modelLimitations).toEqual(trace.result.modelLimitations); - expect(compact.result).not.toHaveProperty('receipts'); - expect(compact.result.projection.valuation.cash).toBe('9975.76000000'); - expect(compact.result.projection.valuation.equity).toBe('10005.76000000'); - expect(compact.result.projection.valuation.fees).toBe('0.24000000'); - expect(compact.result.projection.fills).toHaveLength(1); - const fill = compact.result.projection.fills[0]!; - expect(fill.cashDelta).toBe('-24.00000000'); - expect(fill.fee.amount).toBe('0.24000000'); - expect(fill.releasedBasis).toBe('0.00000000'); - expect(fill.ownerId).toBe('A'); - expect(fill.decision.ownerId).toBe('A'); - const fullEffects = trace.result.receipts - .flatMap(r => (r.outcome.replayed ? [] : r.outcome.effects)) - .flatMap((effect: any) => - effect.Risk?.outcome.replayed || effect.Risk?.outcome.financial?.replayed - ? [] - : (effect.Risk?.outcome.financial?.effects.effects ?? []) - ); - const applied = fullEffects.filter((e: any) => e.kind === 'fillApplied'); - const fee = fullEffects.filter((e: any) => e.kind === 'feeApplied'); - expect(applied).toHaveLength(1); - expect(fee).toHaveLength(1); - for (const key of [ - 'ownerId', - 'orderId', - 'fillId', - 'instrumentId', - 'price', - 'cashDelta', - 'quantityDelta', - 'releasedBasis', - 'realizedGrossPnl', - ] as const) { - expect(fill[key]).toEqual(applied[0][key]); - } - expect(fill.fee.amount).toEqual(fee[0].amount); - expect(fill.fee.feeId).toEqual(fee[0].feeId); - expect(compact.metrics.resultBytes).toBeLessThan(trace.metrics.resultBytes); - for (const metrics of [compact.metrics, trace.metrics]) { - for (const value of [ - metrics.finalizeNativeMs, - metrics.finalizeDecodeMs, - metrics.finalizeValidationMs, - metrics.disposeMs, - ]) { - expect(Number.isFinite(value)).toBe(true); - expect(value).toBeGreaterThanOrEqual(0); - } - } - expect(JSON.stringify(compact.result)).not.toContain('finalizeNativeMs'); - }); - test('two owners share one financial projection and reverse callbacks preserve it', () => { - const f = nativeReplayFixture(3, 1, ['B', 'A']); - const run = (reverseCallbacks: boolean) => - runReplayConformance( - new NativeReplaySession(prepareReplayLoad(f.dataset, f.config)), - (_owner, c) => (c.barrier.at === f.start + f.minute ? intent('1') : hold()), - { resultFormat: 'projection', reverseCallbacks } - ).result; - const output = run(false); - expect(run(true)).toEqual(output); - expect(output.projection.fills.map(f => f.ownerId)).toEqual(['A', 'B']); - expect(output.projection.valuation.fees).toBe('0.24000000'); - expect(output.projection.valuation.equity).toBe('10005.76000000'); - }); - test('projection_is_read_only preserves native diagnostic bytes across repeated projections', () => { - const f = nativeReplayFixture(), - load = prepareReplayLoad(f.dataset, f.config); - const native = new FinancialReplaySession(JSON.stringify(load)), - identity = JSON.stringify(load.identity); - let sequence = 0; - try { - for (;;) { - const response = JSON.parse( - native.advance(JSON.stringify({ identity: load.identity, eventBudget: 100 })) - ); - if (response.step.type === 'complete') { - break; - } - if (response.step.type === 'failed') { - throw new Error(response.step.diagnostic); - } - if (response.step.type === 'decisionBatch') { - const barrier = response.step.barrier; - native.submit( - JSON.stringify({ - identity: load.identity, - barrierId: barrier.barrier_id, - decisions: [ - { - version: 1, - sessionId: load.identity.sessionId, - barrierId: barrier.barrier_id, - revision: barrier.revision, - decision: { - ownerId: 'A', - decisionId: `native-${sequence}`, - sequence: sequence++, - }, - intent: barrier.at === f.start + f.minute ? intent() : hold(), - }, - ], - }) - ); - } - } - const before = native.finalize(identity), - first = native.project(identity); - expect(native.project(identity)).toBe(first); - expect(native.finalize(identity)).toBe(before); - expect(JSON.parse(first).view).toEqual(JSON.parse(before).view); - expect(JSON.parse(first).projection.fills).toHaveLength(1); - } finally { - native.dispose(); - } - }); - test('projection_terminal_guard covers incomplete, failed, disposed and wrong identity', () => { - const f = nativeReplayFixture(), - load = prepareReplayLoad(f.dataset, f.config); - load.prepared.bars[0]!.high = '792281625142643375935.43950335'; - load.prepared.bars[0]!.close = '792281625142643375935.43950335'; - const native = new FinancialReplaySession(JSON.stringify(load)), - identity = JSON.stringify(load.identity); - expect(() => native.project(identity)).toThrow('complete'); - expect(() => native.project(JSON.stringify({ ...load.identity, version: 2 }))).toThrow(); - expect(() => native.project(JSON.stringify({ ...load.identity, sessionId: 'wrong' }))).toThrow( - 'identity' - ); - const step = JSON.parse( - native.advance(JSON.stringify({ identity: load.identity, eventBudget: 100 })) - ); - const submission = JSON.parse( - native.submit( - JSON.stringify({ - identity: load.identity, - barrierId: step.step.barrier.barrier_id, - decisions: [ - { - version: 1, - sessionId: load.identity.sessionId, - barrierId: step.step.barrier.barrier_id, - revision: step.step.barrier.revision, - decision: { ownerId: 'A', decisionId: 'overflow', sequence: 0 }, - intent: intent(), - }, - ], - }) - ) - ); - expect(submission.outcome.status).toHaveProperty('Failed'); - expect(() => native.project(identity)).toThrow('complete'); - native.dispose(); - expect(() => native.project(identity)).toThrow('disposed'); - }); - test('projection_identity_policy_format rejects incompatible and inconsistent payloads', () => { - const input = request(), - trace = executeReplayTrace(input).result, - output = executeReplayTrace({ ...input, resultFormat: 'projection' }).result; - expect(() => parseReplayProjectionResult(JSON.stringify(trace), output.identity)).toThrow(); - expect(() => parseReplayResult(JSON.stringify(output), output.identity)).toThrow(); - for (const mutate of [ - (r: any) => (r.projectionVersion = 2), - (r: any) => (r.financialVersion = 2), - (r: any) => (r.receipts = []), - (r: any) => (r.projection.valuation.cash = '1'), - (r: any) => (r.projection.valuation.equity = '1'), - (r: any) => (r.projection.fills[0].ownerId = 'B'), - (r: any) => (r.projection.fills[0].fee.amount = '-1'), - (r: any) => (r.policy.matching.risk.feeRate = '0.5'), - ]) { - const bad = structuredClone(output); - mutate(bad); - expect(() => - parseReplayProjectionResult(JSON.stringify(bad), output.identity, input.config) - ).toThrow(); - } - }); - test('worker captures projection format and preserves post-result cancellation', async () => { - const input = { ...request(), resultFormat: 'projection' as const }, - worker = new NativeBacktestWorker(); - const expected = executeReplayTrace(input).result; - const mutable: { resultFormat: 'projection' | 'trace' } & typeof input = { ...input }; - const raw = await worker.execute(mutable, new AbortController().signal, () => { - (mutable as { resultFormat: string }).resultFormat = 'trace'; - }); - expect(parseReplayProjectionResult(raw, expected.identity, input.config)).toEqual(expected); - const fixture = new NativeBacktestWorker( - new URL('../fixtures/native-replay-worker.ts', import.meta.url) - ); - for (const resultFormat of ['projection', 'trace'] as const) { - const bad = { ...request(), resultFormat }; - bad.config.matching.risk.ledger.accountId = 'wrong-format'; - await expect(fixture.execute(bad, new AbortController().signal, () => {})).rejects.toThrow(); - } - const blocked = { ...request(), resultFormat: 'projection' as const }; - blocked.config.matching.risk.ledger.accountId = 'result-then-block'; - const cancel = new AbortController(); - let observed = false; - const running = fixture.execute(blocked, cancel.signal, () => {}); - const child = (fixture as unknown as { active: ChildProcess }).active; - child.on('message', (message: any) => { - if (message.type === 'result') { - observed = true; - cancel.abort(new Error('compact result cancelled')); - } - }); - await expect(running).rejects.toThrow('compact result cancelled'); - expect(observed).toBe(true); - expect( - JSON.parse(await fixture.execute(input, new AbortController().signal, () => {})).format - ).toBe('projection'); - }); -}); diff --git a/test/integration/native-replay-report.test.ts b/test/integration/native-replay-report.test.ts deleted file mode 100644 index 60174d5e..00000000 --- a/test/integration/native-replay-report.test.ts +++ /dev/null @@ -1,311 +0,0 @@ -import type { ChildProcess } from 'node:child_process'; -import { describe, expect, test } from 'bun:test'; -import { FinancialReplaySession } from '@stock-bot/engine'; -import { parseFinancialDecimal } from '@stock-bot/types'; -import { - executeReplayTrace, - NativeReplaySession, - prepareReplayLoad, - runReplayConformance, -} from '../../apps/stock/orchestrator/src/backtest/native-replay'; -import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker'; -import { - parseReplayProjectionResult, - parseReplayReportResult, - parseReplayResult, - replayConfigSchema, -} from '../../apps/stock/orchestrator/src/contracts/native-replay'; -import { nativeReplayFixture } from '../fixtures/native-replay'; - -const hold = () => ({ mode: 'target' as const, targets: [] }); -const buy = () => ({ - mode: 'target' as const, - targets: [{ instrumentId: 'X0.US', quantity: parseFinancialDecimal('2') }], -}); -function request(twoSessions = false) { - const f = nativeReplayFixture(); - if (twoSessions) { - f.config.risk_boundaries = [2, 3].map(n => ({ - ...f.config.matching.risk.ledger.riskSession, - sessionId: `risk-${n}`, - startsAt: f.start + n * f.minute, - })); - } - 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: buy() }, - { at: f.start + 2 * f.minute, ownerId: 'A', intent: hold() }, - ], - }; -} - -describe('authoritative replay reporting', () => { - test('two_session_marks and occupancy preserve compact financial facts and earlier reset', () => { - const input = request(true), - f = nativeReplayFixture(); - const projected = executeReplayTrace({ ...input, resultFormat: 'projection' }).result; - let reset: string | undefined; - const output = runReplayConformance( - new NativeReplaySession(prepareReplayLoad(input.dataset, input.config)), - (_owner, context) => (context.barrier.at === f.start + f.minute ? buy() : hold()), - { - resultFormat: 'report', - eventBudget: 1, - onProgress: step => { - if ( - step.step.type === 'decisionBatch' && - step.step.barrier.at === f.start + 2 * f.minute - ) { - reset = step.step.view.risk.dailyBaseline; - } - }, - } - ).result; - expect(output.projection).toEqual(projected.projection); - expect(output.view).toEqual(projected.view); - expect(output.policy).toEqual(projected.policy); - expect(output.modelLimitations).toEqual(projected.modelLimitations); - expect(reset).toBe('9999.76000000'); - expect(output.reporting).toEqual({ - calendarId: 'account', - calendarRevision: '1', - tradeStart: f.start + f.minute, - tradeEnd: f.start + 3 * f.minute, - initialEquity: parseFinancialDecimal('10000.00000000'), - sampling: 'account-boundary-after-observations-v1', - exposureBasis: 'elapsed-calendar-time', - sessions: [ - { - session: input.config.matching.risk.ledger.riskSession, - periodStart: f.start + f.minute, - periodEnd: f.start + 2 * f.minute, - partialStart: true, - partialEnd: false, - equity: parseFinancialDecimal('10001.76000000'), - }, - { - session: input.config.risk_boundaries[0]!, - periodStart: f.start + 2 * f.minute, - periodEnd: f.start + 3 * f.minute, - partialStart: false, - partialEnd: false, - equity: parseFinancialDecimal('10005.76000000'), - }, - ], - occupiedIntervals: [{ start: f.start + f.minute, end: f.start + 3 * f.minute }], - occupiedMs: '120000', - elapsedMs: '120000', - }); - expect(output).not.toHaveProperty('receipts'); - expect(executeReplayTrace({ ...input, resultFormat: 'report' }).result).toEqual(output); - }); - - test('native report is read-only and rejects incomplete, failed, wrong identity and disposed states', () => { - const f = nativeReplayFixture(), - load = prepareReplayLoad(f.dataset, f.config); - const native = new FinancialReplaySession(JSON.stringify(load)), - identity = JSON.stringify(load.identity); - expect(() => native.report(identity)).toThrow('complete'); - expect(() => native.report(JSON.stringify({ ...load.identity, version: 2 }))).toThrow(); - expect(() => native.report(JSON.stringify({ ...load.identity, sessionId: 'wrong' }))).toThrow( - 'identity' - ); - let sequence = 0; - try { - for (;;) { - const step = JSON.parse( - native.advance(JSON.stringify({ identity: load.identity, eventBudget: 1 })) - ).step; - if (step.type === 'complete') { - break; - } - if (step.type === 'failed') { - throw new Error(step.diagnostic); - } - if (step.type === 'decisionBatch') { - native.submit( - JSON.stringify({ - identity: load.identity, - barrierId: step.barrier.barrier_id, - decisions: [ - { - version: 1, - sessionId: load.identity.sessionId, - barrierId: step.barrier.barrier_id, - revision: step.barrier.revision, - decision: { - ownerId: 'A', - decisionId: `direct-${sequence}`, - sequence: sequence++, - }, - intent: hold(), - }, - ], - }) - ); - } - } - const trace = native.finalize(identity), - projection = native.project(identity), - report = native.report(identity); - expect(native.report(identity)).toBe(report); - expect(native.finalize(identity)).toBe(trace); - expect(native.project(identity)).toBe(projection); - const parsed = parseReplayReportResult(report, load.identity); - expect(parsed.reporting.occupiedMs).toBe('0'); - expect(parsed.reporting.sessions).toHaveLength(1); - expect(parsed.reporting.sessions[0]?.partialEnd).toBe(true); - } finally { - native.dispose(); - } - expect(() => native.report(identity)).toThrow('disposed'); - load.prepared.bars[0]!.high = '792281625142643375935.43950335'; - load.prepared.bars[0]!.close = '792281625142643375935.43950335'; - const failed = new FinancialReplaySession(JSON.stringify(load)); - try { - const step = JSON.parse( - failed.advance(JSON.stringify({ identity: load.identity, eventBudget: 100 })) - ).step; - const submission = JSON.parse( - failed.submit( - JSON.stringify({ - identity: load.identity, - barrierId: step.barrier.barrier_id, - decisions: [ - { - version: 1, - sessionId: load.identity.sessionId, - barrierId: step.barrier.barrier_id, - revision: step.barrier.revision, - decision: { ownerId: 'A', decisionId: 'overflow', sequence: 0 }, - intent: buy(), - }, - ], - }) - ) - ); - expect(submission.outcome.status).toHaveProperty('Failed'); - expect(() => failed.report(identity)).toThrow('complete'); - } finally { - failed.dispose(); - } - }); - - test('strict reporting format, identity, calendar, partition, terminal and union validation', () => { - const input = request(true), - result = executeReplayTrace({ ...input, resultFormat: 'report' }).result; - expect(() => parseReplayProjectionResult(JSON.stringify(result), result.identity)).toThrow(); - expect(() => parseReplayResult(JSON.stringify(result), result.identity)).toThrow(); - for (const mutate of [ - (r: any) => (r.format = 'projection'), - (r: any) => (r.reportingVersion = 2), - (r: any) => (r.projectionVersion = 2), - (r: any) => (r.financialVersion = 2), - (r: any) => (r.receipts = []), - (r: any) => (r.identity.sessionId = 'wrong'), - (r: any) => (r.reporting.calendarId = 'wrong'), - (r: any) => (r.reporting.calendarRevision = 'wrong'), - (r: any) => r.reporting.tradeStart++, - (r: any) => (r.reporting.initialEquity = '9999'), - (r: any) => (r.reporting.sessions.at(-1).equity = '1'), - (r: any) => r.reporting.sessions[0].periodEnd++, - (r: any) => (r.reporting.sessions[0].partialStart = false), - (r: any) => (r.reporting.sessions.at(-1).partialEnd = true), - (r: any) => r.reporting.sessions.push(r.reporting.sessions[0]), - (r: any) => (r.reporting.occupiedMs = '0120000'), - (r: any) => (r.reporting.occupiedMs = '120001'), - (r: any) => (r.reporting.elapsedMs = '120001'), - (r: any) => r.reporting.occupiedIntervals[0].start--, - (r: any) => r.reporting.occupiedIntervals.push(r.reporting.occupiedIntervals[0]), - (r: any) => (r.policy.matching.risk.feeRate = '0.5'), - ]) { - const changed = structuredClone(result); - mutate(changed); - expect(() => - parseReplayReportResult(JSON.stringify(changed), result.identity, input.config) - ).toThrow(); - } - const projection = executeReplayTrace({ ...input, resultFormat: 'projection' }).result; - expect(() => parseReplayReportResult(JSON.stringify(projection), result.identity)).toThrow(); - }); - - test('report duration validation uses exact integers before subtracting timestamps', () => { - const input = request(); - input.trace = input.trace.map(row => ({ ...row, intent: hold() })); - const result = executeReplayTrace({ ...input, resultFormat: 'report' }).result; - const start = -Number.MAX_SAFE_INTEGER, - end = Number.MAX_SAFE_INTEGER - 1; - const session = { ...result.policy.matching.risk.ledger.riskSession, startsAt: start }; - result.policy.matching.risk.ledger.riskSession = session; - Object.assign(result.manifest.bounds as object, { tradeStart: start, tradeEnd: end }); - Object.assign(result.reporting, { - tradeStart: start, - tradeEnd: end, - elapsedMs: '18014398509481981', - sessions: [ - { - session, - periodStart: start, - periodEnd: end, - partialStart: false, - partialEnd: true, - equity: result.view.equity, - }, - ], - }); - expect( - parseReplayReportResult(JSON.stringify(result), result.identity).reporting.elapsedMs - ).toBe('18014398509481981'); - result.reporting.elapsedMs = String(end - start); - expect(() => parseReplayReportResult(JSON.stringify(result), result.identity)).toThrow( - 'duration' - ); - }); - - test('worker captures report format and preserves failure and post-result cancellation guards', async () => { - const input = { ...request(), resultFormat: 'report' as const }, - worker = new NativeBacktestWorker(); - const expected = executeReplayTrace(input).result; - const mutable = { ...input }; - const raw = await worker.execute(mutable, new AbortController().signal, () => { - (mutable as { resultFormat: string }).resultFormat = 'projection'; - }); - expect(parseReplayReportResult(raw, expected.identity, input.config)).toEqual(expected); - const fixture = new NativeBacktestWorker( - new URL('../fixtures/native-replay-worker.ts', import.meta.url) - ); - for (const mode of [ - 'wrong-format', - 'wrong-policy', - 'wrong-account', - 'wrong-session', - 'crash', - ]) { - const bad = { ...request(), resultFormat: 'report' as const }; - bad.config.matching.risk.ledger.accountId = mode; - await expect(fixture.execute(bad, new AbortController().signal, () => {})).rejects.toThrow(); - } - const blocked = { ...request(), resultFormat: 'report' as const }; - blocked.config.matching.risk.ledger.accountId = 'result-then-block'; - const cancellation = new AbortController(); - let observed = false; - const running = fixture.execute(blocked, cancellation.signal, () => {}); - const child = (fixture as unknown as { active: ChildProcess }).active; - child.on('message', (message: any) => { - if (message.type === 'result') { - observed = true; - cancellation.abort(new Error('report cancelled')); - } - }); - await expect(running).rejects.toThrow('report cancelled'); - expect(observed).toBe(true); - expect( - JSON.parse(await fixture.execute(input, new AbortController().signal, () => {})).format - ).toBe('report'); - }); -}); diff --git a/test/integration/strategy-runtime.test.ts b/test/integration/strategy-runtime.test.ts deleted file mode 100644 index c4420944..00000000 --- a/test/integration/strategy-runtime.test.ts +++ /dev/null @@ -1,623 +0,0 @@ -import { expect, test } from 'bun:test'; -import { parseFinancialDecimal, type FinancialStrategyDecision } from '@stock-bot/types'; -import { - NativeReplaySession, - prepareReplayLoad, -} from '../../apps/stock/orchestrator/src/backtest/native-replay'; -import { - runStrategyReplay, - StrategyReplayError, -} from '../../apps/stock/orchestrator/src/backtest/strategy-runtime'; -import type { - DeepReadonly, - StrategyContext, - StrategyDiagnosticSnapshot, - StrategyProgram, -} from '../../apps/stock/orchestrator/src/contracts/canonical-strategy'; -import { nativeReplayFixture } from '../fixtures/native-replay'; - -const hold = () => ({ mode: 'target' as const, targets: [] }); -const target = (quantity = '1') => ({ - mode: 'target' as const, - targets: [{ instrumentId: 'X0.US', quantity: parseFinancialDecimal(quantity) }], -}); -type CountState = { count: number; samples: number[] }; -const initial = (): CountState => ({ count: 0, samples: [] }); -function fixture(owners = ['A'], bars = 6, assets = 1) { - const value = nativeReplayFixture(bars, assets, owners); - return { ...value, load: prepareReplayLoad(value.dataset, value.config) }; -} -function program( - ownerId = 'A', - decide: StrategyProgram['decide'] = context => ({ - nextState: { - count: context.state.count + 1, - samples: [...context.state.samples, context.random()], - }, - intent: target(), - }), - seed = 0 -): StrategyProgram { - return { - ownerId, - strategyId: 'test-counter', - strategyVersion: '1', - mode: 'target', - seed, - initialState: initial(), - decide, - }; -} -function owner(snapshot: DeepReadonly, ownerId = 'A') { - const value = snapshot.strategies.find(strategy => strategy.ownerId === ownerId); - if (!value) { - throw new Error(`Missing diagnostics for ${ownerId}`); - } - return value; -} -function captureFailure(run: () => unknown): StrategyReplayError { - try { - run(); - } catch (error) { - expect(error).toBeInstanceOf(StrategyReplayError); - if (error instanceof StrategyReplayError) { - return error; - } - throw error; - } - throw new Error('Expected the attempted strategy replay to fail'); -} - -test('same seed, fresh retries, callback ordering and event budgets preserve all decisions and economics', () => { - const run = (reverse: boolean, eventBudget: number) => { - const f = fixture(['B', 'A']); - const programs = ['A', 'B'].map(id => - program( - id, - context => { - const samples = [context.random()]; - if (id === 'B') { - samples.push(context.random(), context.random()); - } - return { - nextState: { - count: context.state.count + 1, - samples: [...context.state.samples, ...samples], - }, - intent: target(samples[0]! < 0.5 ? '1' : '0'), - }; - }, - id === 'A' ? 0 : 42 - ) - ); - if (reverse) { - programs.reverse(); - } - const { result, diagnostics } = runStrategyReplay(f.load, programs, { - eventBudget, - resultFormat: 'trace', - }); - return { result, diagnostics }; - }; - const baseline = run(false, 1); - expect(run(true, 64)).toEqual(baseline); - expect(run(false, 64)).toEqual(baseline); - expect(owner(baseline.diagnostics).rng.draws).toBe(5); - expect(owner(baseline.diagnostics, 'B').rng.draws).toBe(15); - expect(owner(baseline.diagnostics).rng.algorithm).toBe('lcg32-v1'); - expect((owner(baseline.diagnostics).state as CountState).samples.slice(0, 2)).toEqual([ - 1013904223 / 4294967296, - 1196435762 / 4294967296, - ]); - expect(baseline.diagnostics.strategies.map(s => s.ownerId)).toEqual(['A', 'B']); -}); - -test('one owner consuming additional random draws cannot move another owner cursor', () => { - const run = (extra: boolean) => { - const f = fixture(['A', 'B']); - return runStrategyReplay( - f.load, - ['A', 'B'].map(id => - program(id, context => { - const draw = context.random(); - if (id === 'B' && extra) { - context.random(); - context.random(); - } - return { - nextState: { - count: context.state.count + 1, - samples: [...context.state.samples, draw], - }, - intent: hold(), - }; - }) - ), - { resultFormat: 'projection' } - ); - }; - expect(owner(run(true).diagnostics)).toEqual(owner(run(false).diagnostics)); -}); - -test('mixed cadence retains each owner prefix and consumes warmup once', () => { - const f = fixture(['A', 'B'], 6, 2); - // Trusted prepared fixture: X1 publishes only at minutes 1, 4 and terminal 6. - f.load.prepared.bars = f.load.prepared.bars.filter( - bar => bar.instrument_id === 'X0.US' || [0, 3, 5].includes(bar.source_sequence) - ); - f.load.config.cadence = [ - { owner_id: 'A', series_ids: ['X0.US:1m'] }, - { owner_id: 'B', series_ids: ['X1.US:1m'] }, - ]; - const seen = new Map(); - const programs = ['A', 'B'].map(id => - program(id, context => { - const rows = seen.get(id) ?? []; - rows.push({ - at: context.now, - bars: context.observations.map(bar => `${bar.instrument_id}:${bar.source_sequence}`), - }); - seen.set(id, rows); - expect(context.observations.every(bar => bar.available_at <= context.now)).toBe(true); - return { nextState: { count: context.state.count + 1, samples: [] }, intent: hold() }; - }) - ); - const { diagnostics } = runStrategyReplay(f.load, programs, { eventBudget: 1 }); - expect(seen.get('A')?.map(row => row.bars.length)).toEqual([2, 1, 1, 2, 1]); - expect(seen.get('B')).toEqual([ - { at: f.start + f.minute, bars: ['X0.US:0', 'X1.US:0'] }, - { at: f.start + 4 * f.minute, bars: ['X0.US:1', 'X0.US:2', 'X0.US:3', 'X1.US:3'] }, - ]); - expect(owner(diagnostics).observationCount).toBe(7); - expect(owner(diagnostics, 'B').observationCount).toBe(6); - expect(owner(diagnostics).nextDecisionSequence).toBe(5); - expect(owner(diagnostics, 'B').nextDecisionSequence).toBe(2); -}); - -test('callbacks share one frozen native barrier view while state, positions and feedback remain owned', () => { - const f = fixture(['A', 'B']); - const views = new Map['portfolio']>(); - const programs = ['B', 'A'].map(id => - program(id, context => { - const previous = views.get(context.now); - if (previous) { - expect(context.portfolio).toBe(previous); - } else { - views.set(context.now, context.portfolio); - } - expect(context.barrier.revision).toBe(context.portfolio.admissionRevision); - expect(Object.isFrozen(context.portfolio.portfolio.positions)).toBe(true); - expect(Object.isFrozen(context.state.samples)).toBe(true); - expect(Object.isFrozen(context.observations)).toBe(true); - expect(context.positions.every(position => position.ownerId === id)).toBe(true); - expect(context.previousAdmission?.decision.ownerId ?? id).toBe(id); - expect(() => (context.state as CountState).samples.push(4)).toThrow(); - expect(() => ((context.portfolio as unknown as { equity: string }).equity = '0')).toThrow(); - return { nextState: { count: context.state.count + 1, samples: [] }, intent: target() }; - }) - ); - const { result } = runStrategyReplay(f.load, programs, { resultFormat: 'report' }); - expect(result.projection.fills.map(fill => fill.ownerId)).toEqual(['A', 'B']); -}); - -test('late callback exception discards the staged barrier; fresh retry reconstructs the committed prefix', () => { - const f = fixture(['A', 'B']); - const ordinary = [program('A'), program('B')]; - const baseline = runStrategyReplay(f.load, ordinary, { resultFormat: 'report' }); - const originalSubmit = NativeReplaySession.prototype.submit; - let submitted = 0; - let failedSession: NativeReplaySession | undefined; - NativeReplaySession.prototype.submit = function (...args) { - submitted++; - failedSession = this; - return originalSubmit.apply(this, args); - }; - let failure: StrategyReplayError; - try { - const faulty = program('B', context => { - const output = ordinary[1]!.decide(context); - if (context.decisionSequence === 1) { - throw new Error('late callback failure'); - } - return output; - }); - failure = captureFailure(() => runStrategyReplay(f.load, [ordinary[0]!, faulty])); - } finally { - NativeReplaySession.prototype.submit = originalSubmit; - } - expect(submitted).toBe(1); - expect(failure.cause).toBeInstanceOf(Error); - expect(failure.diagnostics.committedBarriers).toBe(1); - for (const saved of failure.diagnostics.strategies) { - expect(saved.nextDecisionSequence).toBe(1); - expect(saved.rng.draws).toBe(1); - expect((saved.state as CountState).count).toBe(1); - } - expect(() => failedSession!.project()).toThrow('disposed'); - expect(failure).not.toHaveProperty('result'); - const retry = runStrategyReplay(f.load, ordinary, { resultFormat: 'report' }); - expect(retry.result).toEqual(baseline.result); - expect(retry.diagnostics).toEqual(baseline.diagnostics); -}); - -test('post-native-submit failure never publishes unconfirmed strategy state or reuses the resident attempt', () => { - const f = fixture(['A', 'B']); - const programs = [program('A'), program('B')]; - const baseline = runStrategyReplay(f.load, programs, { resultFormat: 'projection' }); - const originalSubmit = NativeReplaySession.prototype.submit; - let submitted = 0; - let failedSession: NativeReplaySession | undefined; - NativeReplaySession.prototype.submit = function (...args) { - const output = originalSubmit.apply(this, args); - failedSession = this; - if (++submitted === 2) { - throw new Error('response lost after native admission'); - } - return output; - }; - let failure: StrategyReplayError; - try { - failure = captureFailure(() => runStrategyReplay(f.load, programs)); - } finally { - NativeReplaySession.prototype.submit = originalSubmit; - } - expect(submitted).toBe(2); - expect(failure.diagnostics.committedBarriers).toBe(1); - expect( - failure.diagnostics.strategies.every(s => s.nextDecisionSequence === 1 && s.rng.draws === 1) - ).toBe(true); - expect(() => failedSession!.project()).toThrow('disposed'); - const retry = runStrategyReplay(f.load, programs, { resultFormat: 'projection' }); - expect(retry.result).toEqual(baseline.result); - expect(retry.diagnostics).toEqual(baseline.diagnostics); -}); - -test('malformed second-owner feedback after real native admission cannot partially commit diagnostic state', () => { - const f = fixture(['A', 'B']); - const programs = ['A', 'B'].map(id => - program(id, context => ({ - nextState: { - count: context.state.count + 1, - samples: [...context.state.samples, context.random()], - }, - intent: target(String(context.state.count + 1)), - })) - ); - const originalSubmit = NativeReplaySession.prototype.submit; - let submissions = 0; - let failedSession: NativeReplaySession | undefined; - NativeReplaySession.prototype.submit = function (...args) { - const output = originalSubmit.apply(this, args); - failedSession = this; - if (++submissions !== 2) { - return output; - } - const malformed = structuredClone(output); - const secondOwner = malformed.effects.find(effect => { - const order = effect.Order as { order: { decision: { ownerId: string } } } | undefined; - return order?.order.decision.ownerId === 'B'; - }); - expect(secondOwner).toBeDefined(); - (secondOwner!.Order as { status: unknown }).status = 'InventedStatus'; - return malformed; - }; - let failure: StrategyReplayError; - try { - failure = captureFailure(() => runStrategyReplay(f.load, programs)); - } finally { - NativeReplaySession.prototype.submit = originalSubmit; - } - expect(submissions).toBe(2); - expect(failure.diagnostics.committedBarriers).toBe(1); - for (const saved of failure.diagnostics.strategies) { - expect(saved.nextDecisionSequence).toBe(1); - expect(saved.rng.draws).toBe(1); - expect((saved.state as CountState).count).toBe(1); - expect(saved.previousAdmission?.decision.sequence).toBe(0); - } - expect(() => failedSession!.project()).toThrow('disposed'); -}); - -test('risk rejection commits state and cursors and returns the actual rejection at the next decision', () => { - const f = fixture(); - f.load.config.matching.risk.maxOrderQuantity = parseFinancialDecimal('1'); - const feedback: StrategyContext['previousAdmission'][] = []; - const strategy = program('A', context => { - feedback.push(context.previousAdmission); - return { - nextState: { - count: context.state.count + 1, - samples: [...context.state.samples, context.random()], - }, - intent: target('2'), - }; - }); - const { result, diagnostics } = runStrategyReplay(f.load, [strategy], { resultFormat: 'report' }); - expect(feedback[0]).toBeNull(); - expect( - feedback - .slice(1) - .every( - item => - item?.orders[0]?.status && - typeof item.orders[0].status === 'object' && - item.orders[0].status.Rejected === 'OrderSize' - ) - ).toBe(true); - expect(owner(diagnostics).nextDecisionSequence).toBe(5); - expect(owner(diagnostics).rng.draws).toBe(5); - expect(owner(diagnostics).observationCount).toBe(5); - expect((owner(diagnostics).state as CountState).count).toBe(5); - expect(result.projection.fills).toHaveLength(0); - expect(result.projection.valuation.equity).toBe('10000.00000000'); - expect(owner(diagnostics).previousAdmission?.orders[0]?.status).toEqual({ - Rejected: 'OrderSize', - }); -}); - -test('repeated target preserves a partially filled order and charges each actual fill once', () => { - const f = fixture(); - f.load.config.participation_rate = parseFinancialDecimal('0.001'); - const quantities: string[] = []; - const { result } = runStrategyReplay( - f.load, - [ - program('A', context => { - quantities.push(context.positions[0]?.quantity ?? '0.00000000'); - return { nextState: { count: context.state.count + 1, samples: [] }, intent: target('3') }; - }), - ], - { resultFormat: 'report' } - ); - expect(quantities).toEqual([ - '0.00000000', - '1.00000000', - '2.00000000', - '3.00000000', - '3.00000000', - ]); - expect(result.projection.fills).toHaveLength(3); - expect(new Set(result.projection.fills.map(fill => fill.orderId)).size).toBe(1); - expect(result.projection.fills.map(fill => String(fill.price))).toEqual([ - '12.00000000', - '14.00000000', - '16.00000000', - ]); - expect(result.projection.valuation.cash).toBe('9957.58000000'); - expect(result.projection.valuation.fees).toBe('0.42000000'); - expect(result.projection.valuation.equity).toBe('10020.58000000'); -}); - -test('cancellation feedback remains with the owner and retains the cancelled original decision identity', () => { - const f = fixture(['A', 'B']); - f.load.config.matching.latencyMs = f.minute; - const feedback: StrategyContext['previousAdmission'][] = []; - const a = program('A', context => { - feedback.push(context.previousAdmission); - return { - nextState: { count: context.state.count + 1, samples: [] }, - intent: target(context.state.count === 0 ? '3' : '0'), - }; - }); - const { result } = runStrategyReplay(f.load, [a, program('B')], { resultFormat: 'report' }); - const cancelled = feedback[2]!.orders; - expect(cancelled).toHaveLength(1); - expect(cancelled[0]?.status).toBe('Cancelled'); - expect(cancelled[0]?.decision.ownerId).toBe('A'); - expect(cancelled[0]?.decision.sequence).toBe(0); - expect(feedback[2]?.decision.sequence).toBe(1); - expect(result.projection.fills.every(fill => fill.ownerId === 'B')).toBe(true); - expect(result.projection.fills).toHaveLength(1); -}); - -test('unavailable future prices cannot alter earlier strategy state, random draws, observations or decisions', () => { - const run = (mutate: boolean) => { - const f = fixture(); - if (mutate) { - f.load.prepared.bars[3]!.high = '999.00000000'; - f.load.prepared.bars[3]!.close = '999.00000000'; - } - const seen: unknown[] = []; - const strategy = program('A', context => { - const draw = context.random(); - const intent = target(context.observations.some(bar => Number(bar.close) > 500) ? '2' : '1'); - seen.push({ - now: context.now, - state: context.state, - draw, - observations: context.observations, - portfolio: context.portfolio, - intent, - }); - expect(JSON.stringify(context)).not.toMatch(/"(prepared|binding|checkpoint|manifest)"/); - return { - nextState: { count: context.state.count + 1, samples: [...context.state.samples, draw] }, - intent, - }; - }); - const result = runStrategyReplay(f.load, [strategy], { resultFormat: 'projection' }); - return { seen, result }; - }; - const before = run(false), - after = run(true); - expect(after.seen.slice(0, 3)).toEqual(before.seen.slice(0, 3)); - expect(after.seen[3]).not.toEqual(before.seen[3]); - expect(after.result.result).not.toEqual(before.result.result); -}); - -test('caller and retained callback references cannot rewrite captured inputs or committed state and RNG', () => { - const f = fixture(); - let retainedRandom: (() => number) | undefined; - let retainedState: CountState | undefined; - const strategy = program('A', context => { - retainedRandom = context.random; - const nextState = { - count: context.state.count + 1, - samples: [...context.state.samples, context.random()], - }; - retainedState = nextState; - return { nextState, intent: target() }; - }); - let mutated = false; - const { result, diagnostics } = runStrategyReplay(f.load, [strategy], { - eventBudget: 1, - resultFormat: 'projection', - onProgress: () => { - if (!mutated) { - strategy.initialState.count = 900; - Object.assign(strategy, { - seed: 999, - ownerId: 'wrong', - strategyVersion: 'changed', - decide: () => { - throw new Error('caller replaced callback'); - }, - }); - f.load.config.matching.risk.ledger.initialCapital = parseFinancialDecimal('1'); - mutated = true; - } - if (retainedRandom) { - expect(() => retainedRandom!()).toThrow(); - } - if (retainedState) { - // Returning an object does not transfer mutation authority to its author. - try { - retainedState.count = 900; - } catch { - /* Freezing the returned object is also safe. */ - } - } - }, - }); - expect((owner(diagnostics).state as CountState).count).toBe(5); - expect(owner(diagnostics).rng.seed).toBe(0); - expect(owner(diagnostics).rng.draws).toBe(5); - expect(owner(diagnostics).strategyVersion).toBe('1'); - expect(() => retainedRandom!()).toThrow(); - expect(result.projection.valuation.cash).toBe('9987.88000000'); -}); - -test('lossy initial/next state, asynchronous output and incorrect intent mode never reach admission', () => { - const f = fixture(); - const cyclic: { self?: unknown } = {}; - cyclic.self = cyclic; - const withSymbol = { valid: 1, [Symbol('hidden')]: 2 }; - const nonenumerable = Object.defineProperty({ valid: 1 }, 'hidden', { value: 2 }); - const getter = Object.defineProperty({}, 'value', { enumerable: true, get: () => 1 }); - const invalid = [ - undefined, - NaN, - Infinity, - () => 1, - new Date(), - [undefined], - Array(1), - withSymbol, - nonenumerable, - getter, - cyclic, - ]; - const originalSubmit = NativeReplaySession.prototype.submit; - let submitted = 0; - NativeReplaySession.prototype.submit = function (...args) { - submitted++; - return originalSubmit.apply(this, args); - }; - try { - for (const value of invalid) { - const badInitial = { ...program(), initialState: value } as StrategyProgram; - expect(() => runStrategyReplay(f.load, [badInitial])).toThrow(); - const badNext = { - ...program(), - decide: () => ({ nextState: value, intent: hold() }), - } as StrategyProgram; - const failure = captureFailure(() => runStrategyReplay(f.load, [badNext])); - expect(failure.diagnostics.committedBarriers).toBe(0); - } - const asynchronous = { - ...program(), - decide: async () => ({ nextState: initial(), intent: hold() }), - } as unknown as StrategyProgram; - expect(() => runStrategyReplay(f.load, [asynchronous])).toThrow(); - const wrongMode = { - ...program(), - decide: () => ({ nextState: initial(), intent: { mode: 'orders', orders: [] } }), - } as StrategyProgram; - expect(() => runStrategyReplay(f.load, [wrongMode])).toThrow(); - } finally { - NativeReplaySession.prototype.submit = originalSubmit; - } - expect(submitted).toBe(0); -}); - -test('invalid owner/mode/seed configuration is rejected before strategy code runs', () => { - const f = fixture(); - let calls = 0; - const valid = program('A', context => { - calls++; - return { nextState: { ...context.state, samples: [] }, intent: hold() }; - }); - const cases = [ - [], - [valid, valid], - [{ ...valid, ownerId: 'B' }], - [{ ...valid, mode: 'orders' as const }], - ...[-1, 0.1, 4294967296, NaN].map(seed => [{ ...valid, seed }]), - ]; - for (const programs of cases) { - expect(() => runStrategyReplay(f.load, programs)).toThrow(); - } - expect(calls).toBe(0); -}); - -test('explicit-order strategies use the same native ledger and retain engine-stamped decision identity', () => { - const f = fixture(['A'], 3); - f.load.config.matching.owners[0]!.mode = 'Orders'; - const strategy: StrategyProgram = { - ...program(), - mode: 'orders', - decide: context => ({ - nextState: { count: context.state.count + 1, samples: [] }, - intent: { - mode: 'orders', - orders: - context.state.count === 0 - ? [ - { - kind: 'market', - orderId: 'author-order', - instrumentId: 'X0.US', - side: 'buy', - quantity: parseFinancialDecimal('2'), - timeInForce: 'GTC', - }, - ] - : [], - }, - }), - }; - const captured: FinancialStrategyDecision[] = []; - const originalSubmit = NativeReplaySession.prototype.submit; - NativeReplaySession.prototype.submit = function (barrierId, decisions) { - captured.push(...structuredClone(decisions)); - return originalSubmit.call(this, barrierId, decisions); - }; - try { - const { result, diagnostics } = runStrategyReplay(f.load, [strategy], { - resultFormat: 'report', - }); - expect(result.projection.valuation.cash).toBe('9975.76000000'); - expect(result.projection.valuation.equity).toBe('10005.76000000'); - expect(result.projection.fills[0]?.orderId).toBe('author-order'); - expect(captured.map(decision => decision.decision.sequence)).toEqual([0, 1]); - expect( - captured.every( - decision => - decision.decision.ownerId === 'A' && decision.sessionId === f.load.identity.sessionId - ) - ).toBe(true); - expect(owner(diagnostics).nextDecisionSequence).toBe(2); - } finally { - NativeReplaySession.prototype.submit = originalSubmit; - } -}); diff --git a/tsconfig.contracts.json b/tsconfig.contracts.json index 683ae2da..e7dc4cea 100644 --- a/tsconfig.contracts.json +++ b/tsconfig.contracts.json @@ -1,7 +1,4 @@ { "extends": "./tsconfig.check.json", - "include": [ - "libs/core/services/test/contracts.type-test.ts", - "test/contracts/strategy-runtime.type-test.ts" - ] + "include": ["libs/core/services/test/contracts.type-test.ts"] }