From 417a7bd21efc3cf906ae88001066ad9984a19324 Mon Sep 17 00:00:00 2001 From: Boki Date: Thu, 22 Oct 2026 23:34:35 -0400 Subject: [PATCH] feat(engine): add deterministic historical replay --- apps/stock/engine/src/financial/mod.rs | 4 + apps/stock/engine/src/financial/replay.rs | 888 ++++++++++++++++ .../engine/src/financial/replay_tests.rs | 967 ++++++++++++++++++ docs/development/ROADMAP.md | 22 +- docs/development/backlog/README.md | 12 +- docs/development/backlog/manifest.json | 170 ++- docs/development/backlog/tasks/F06.md | 11 + docs/development/backlog/tasks/F07.md | 6 +- docs/development/backlog/tasks/F08.md | 1 + docs/development/backlog/tasks/R05.md | 2 + 10 files changed, 2055 insertions(+), 28 deletions(-) create mode 100644 apps/stock/engine/src/financial/replay.rs create mode 100644 apps/stock/engine/src/financial/replay_tests.rs diff --git a/apps/stock/engine/src/financial/mod.rs b/apps/stock/engine/src/financial/mod.rs index 480a4fb6..261c9548 100644 --- a/apps/stock/engine/src/financial/mod.rs +++ b/apps/stock/engine/src/financial/mod.rs @@ -5,6 +5,7 @@ pub mod contract; pub mod ledger; pub mod matching; +pub mod replay; pub mod risk; pub mod scalar; @@ -19,3 +20,6 @@ mod risk_tests; #[cfg(test)] mod matching_tests; + +#[cfg(test)] +mod replay_tests; diff --git a/apps/stock/engine/src/financial/replay.rs b/apps/stock/engine/src/financial/replay.rs new file mode 100644 index 00000000..2168e5c2 --- /dev/null +++ b/apps/stock/engine/src/financial/replay.rs @@ -0,0 +1,888 @@ +//! Internal F06 bar replay, not a public/native session or a legacy cutover. +//! +//! F07 must verify the frozen D01 snapshot, retain its eligibility/limitations, +//! and adapt prices to canonical decimals before calling this trusted host API. +//! This module does not authenticate provenance or repeat D01 normalization. +//! Exact canonical prepared input/config bytes bind checkpoints independently +//! of the caller's dataset label. They are not a replacement dataset hash. +//! +//! Bars are stored once; published history is an index prefix, never a clone on +//! advance. Only explicit checkpoints copy retained history. Matching remains +//! the sole financial authority. No strategy can access the future event vector +//! through the context API. This is API separation, not a security sandbox. +use super::{ + contract::*, + matching::*, + scalar::{Posting, ScalarError}, +}; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, BTreeSet}; + +/// Always disclose these in addition to retained dataset limitations. Changing +/// mark batching is a financial-policy decision, not a replay optimization. +pub const MODEL_LIMITATIONS: &[&str] = &[ + "Open-only matching uses previously available completed-bar volume, not contemporaneous liquidity.", + "Equal-time asset marks apply in lexical instrument order; intermediate equity may latch portfolio risk before the synchronized decision barrier.", + "Quote replay and abutting same-series venue sessions are not supported.", +]; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum DatasetEligibility { + Eligible, + Exploratory, + Ineligible, +} +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum PriceAdjustment { + Raw, + ProviderAdjusted, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ReplaySeries { + pub series_id: Id, + pub instrument_id: Id, + pub adjustment: PriceAdjustment, + /// Exact retained venue boundaries, including the actual preceding open + /// for a mid-session warmup. Abutting sessions are unsupported in v1. + pub sessions: Vec, +} +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct PreparedBar { + pub series_id: Id, + pub instrument_id: Id, + pub interval_start: EventTime, + pub interval_end: EventTime, + pub event_time: EventTime, + pub available_at: EventTime, + pub source_sequence: Counter, + pub open: Positive, + pub high: Positive, + pub low: Positive, + pub close: Positive, + pub volume: NonNegative, +} +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ReplayBounds { + pub warmup_start: EventTime, + pub trade_start: EventTime, + pub trade_end: EventTime, +} +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct PreparedReplay { + pub dataset_id: Id, + pub eligibility: DatasetEligibility, + pub limitations: Vec, + pub bounds: ReplayBounds, + pub series: Vec, + pub bars: Vec, +} +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct DecisionCadence { + pub owner_id: Id, + /// Union of completed observation arrivals; one decision per timestamp. + pub series_ids: Vec, +} +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ReplayConfig { + pub matching: MatchingConfig, + pub participation_rate: NonNegative, + pub cadence: Vec, + pub allow_exploratory: bool, + /// Separate account clock, never inferred from an instrument's sessions. + pub risk_boundaries: Vec, +} +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum InputAvailability { + Missing, + Fresh { + event_time: EventTime, + available_at: EventTime, + }, + Stale { + event_time: EventTime, + available_at: EventTime, + }, +} +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SeriesAvailability { + pub series_id: Id, + pub availability: InputAvailability, +} +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct DecisionBarrier { + pub barrier_id: Id, + pub at: EventTime, + /// Reservation/order-aware matching revision, not ledger revision. + pub revision: Counter, + pub owner_ids: Vec, + pub observation_count: usize, + /// Feature freshness uses the same declared age budget as financial marks. + pub inputs: Vec, +} +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum ReplayStatus { + Running, + Complete, + Failed { diagnostic: String }, +} +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ReplayStep { + Progress { processed: usize }, + Decision(DecisionBarrier), + Complete, + Failed { diagnostic: String }, +} +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct DecisionSubmission { + pub barrier_id: Id, + pub decisions: Vec, +} +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ReplayCheckpoint { + pub version: Version, + pub binding: String, + pub next_event: usize, + pub observation_count: usize, + pub pending: Option, + pub status: ReplayStatus, + pub submissions: Vec, + pub matching: MatchingCheckpoint, +} +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum ReplayError { + #[error("invalid prepared replay input: {0}")] + InvalidInput(&'static str), + #[error("advance requires a positive event budget")] + InvalidBudget, + #[error("submission does not match the pending barrier and exact due owners")] + InvalidSubmission, + #[error("replay is terminal")] + Terminal, + #[error("checkpoint input/config or retained replay state does not match")] + InvalidCheckpoint, + #[error(transparent)] + Matching(#[from] MatchingError), + #[error(transparent)] + Arithmetic(#[from] ScalarError), +} + +#[derive(Debug, Clone)] +enum EventBody { + OpenSession(VenueSession), + RiskBoundary(RiskSessionIdentity), + Observe(usize), + Decision(Vec), + Open(usize), + CloseSession(Id), + Finish, +} +#[derive(Debug, Clone)] +struct Event { + key: EventKey, + // Session/account controls precede observations; series ID breaks feature + // source-sequence ties. Matcher observation keys receive canonical ranks. + control_rank: u8, + series_id: Id, + body: EventBody, +} +fn id(value: impl Serialize) -> Id { + serde_json::from_value(serde_json::Value::String( + serde_json::to_string(&value).unwrap(), + )) + .unwrap() +} +fn time_order(bar: &PreparedBar) -> (i64, u64) { + (bar.event_time.get(), bar.source_sequence.get()) +} +fn invalid(reason: &'static str) -> ReplayError { + ReplayError::InvalidInput(reason) +} + +/// No mutable matcher/ledger accessor or strategy-facing future-data accessor. +#[derive(Debug)] +pub struct Replay { + input: PreparedReplay, + config: ReplayConfig, + binding: String, + events: Vec, + next_event: usize, + published: Vec, + latest: BTreeMap, + execution_series: BTreeSet, + pending: Option, + status: ReplayStatus, + submissions: Vec, + matching: MatchingAccount, +} + +impl Replay { + pub fn new(mut input: PreparedReplay, mut config: ReplayConfig) -> Result { + Self::canonicalize(&mut input, &mut config); + Self::validate(&input, &config)?; + let matching = MatchingAccount::new(config.matching.clone())?.0; + let events = Self::events(&input, &config)?; + let binding = + serde_json::to_string(&(&input, &config)).expect("serializable prepared input"); + let execution_series = config + .matching + .series + .iter() + .map(|s| s.series_id.clone()) + .collect(); + Ok(Self { + input, + config, + binding, + events, + next_event: 0, + published: Vec::new(), + latest: BTreeMap::new(), + execution_series, + pending: None, + status: ReplayStatus::Running, + submissions: Vec::new(), + matching, + }) + } + fn canonicalize(input: &mut PreparedReplay, config: &mut ReplayConfig) { + input.series.sort_by(|a, b| a.series_id.cmp(&b.series_id)); + for series in &mut input.series { + series.sessions.sort_by_key(|s| s.opens_at.get()); + } + input.bars.sort_by(|a, b| { + ( + &a.series_id, + a.interval_start.get(), + a.source_sequence.get(), + ) + .cmp(&( + &b.series_id, + b.interval_start.get(), + b.source_sequence.get(), + )) + }); + input.limitations.sort(); + config + .matching + .owners + .sort_by(|a, b| a.owner_id.cmp(&b.owner_id)); + config.matching.risk.ledger.owner_ids.sort(); + config + .matching + .series + .sort_by(|a, b| a.instrument_id.cmp(&b.instrument_id)); + config.cadence.sort_by(|a, b| a.owner_id.cmp(&b.owner_id)); + for cadence in &mut config.cadence { + cadence.series_ids.sort(); + } + config.risk_boundaries.sort_by_key(|s| s.starts_at.get()); + } + fn validate(input: &PreparedReplay, config: &ReplayConfig) -> Result<(), ReplayError> { + let b = &input.bounds; + if b.warmup_start.get() > b.trade_start.get() || b.trade_start.get() >= b.trade_end.get() { + return Err(invalid( + "bounds must satisfy warmupStart <= tradeStart < tradeEnd", + )); + } + if input.eligibility == DatasetEligibility::Ineligible + || (input.eligibility == DatasetEligibility::Exploratory + && (!config.allow_exploratory || input.limitations.is_empty())) + { + return Err(invalid( + "dataset eligibility/limitations do not permit this run", + )); + } + if Posting::from(config.participation_rate) > "1".parse::().unwrap() { + return Err(invalid("participation must be between zero and one")); + } + if input.series.is_empty() + || input + .series + .windows(2) + .any(|w| w[0].series_id == w[1].series_id) + { + return Err(invalid("series IDs must be unique and nonempty")); + } + let series: BTreeMap<_, _> = input.series.iter().map(|s| (&s.series_id, s)).collect(); + for s in &input.series { + let mut ids = BTreeSet::new(); + for session in &s.sessions { + if session.opens_at.get() >= session.closes_at.get() + || !ids.insert(&session.session_id) + { + return Err(invalid("invalid or duplicate retained session")); + } + } + if s.sessions + .windows(2) + .any(|w| w[0].closes_at.get() >= w[1].opens_at.get()) + { + return Err(invalid( + "overlapping or abutting retained sessions are unsupported", + )); + } + } + let instruments: BTreeSet<_> = input.series.iter().map(|s| &s.instrument_id).collect(); + let execution: BTreeSet<_> = config + .matching + .series + .iter() + .map(|s| &s.instrument_id) + .collect(); + if instruments != execution { + return Err(invalid( + "each instrument needs exactly one execution series", + )); + } + let initial = config.matching.risk.ledger.risk_session.starts_at.get(); + if initial > b.warmup_start.get() { + return Err(invalid("initial account clock follows warmup")); + } + for e in &config.matching.series { + let s = series + .get(&e.series_id) + .ok_or_else(|| invalid("unknown execution series"))?; + if e.mode != ExecutionMode::Open { + return Err(invalid("quote replay has no D01 dataset contract yet")); + } + if e.instrument_id != s.instrument_id || s.adjustment != PriceAdjustment::Raw { + return Err(invalid( + "execution series must agree with instrument and contain raw prices", + )); + } + for session in &s.sessions { + if session.closes_at.get() > b.warmup_start.get() + && session.opens_at.get() < b.trade_end.get() + && session.opens_at.get() < initial + { + return Err(invalid( + "initial account clock follows true preceding venue open", + )); + } + } + } + let mut sequences = BTreeSet::new(); + let mut intervals = BTreeMap::new(); + for bar in &input.bars { + let s = series + .get(&bar.series_id) + .ok_or_else(|| invalid("bar references unknown series"))?; + if bar.instrument_id != s.instrument_id + || bar.interval_start.get() < b.warmup_start.get() + || bar.interval_start.get() >= b.trade_end.get() + || bar.interval_end.get() > b.trade_end.get() + || bar.interval_start.get() >= bar.interval_end.get() + || bar.event_time != bar.interval_end + || bar.available_at.get() < bar.interval_end.get() + { + return Err(invalid("invalid bar identity, timing or bounds")); + } + if !sequences.insert((&bar.series_id, bar.source_sequence.get())) { + return Err(invalid("source sequence must be unique within its series")); + } + if intervals + .insert(&bar.series_id, bar.interval_end.get()) + .is_some_and(|end| end > bar.interval_start.get()) + { + return Err(invalid("overlapping or duplicate bar intervals")); + } + let low: Posting = bar.low.into(); + let high: Posting = bar.high.into(); + if low > high + || Posting::from(bar.open) < low + || Posting::from(bar.open) > high + || Posting::from(bar.close) < low + || Posting::from(bar.close) > high + { + return Err(invalid("inconsistent OHLC prices")); + } + // Session lookup is logarithmic, not a full calendar scan per bar. + let session = s + .sessions + .partition_point(|v| v.opens_at.get() <= bar.interval_start.get()); + if session == 0 || s.sessions[session - 1].closes_at.get() < bar.interval_end.get() { + return Err(invalid("bar is not contained in a retained venue session")); + } + } + if intervals.len() != input.series.len() { + return Err(invalid( + "every declared series requires at least one prepared bar", + )); + } + let owners: Vec<_> = config.matching.owners.iter().map(|o| &o.owner_id).collect(); + if owners + != config + .cadence + .iter() + .map(|c| &c.owner_id) + .collect::>() + { + return Err(invalid("each owner requires exactly one declared cadence")); + } + for c in &config.cadence { + if c.series_ids.is_empty() + || c.series_ids.windows(2).any(|w| w[0] == w[1]) + || c.series_ids.iter().any(|s| !series.contains_key(s)) + { + return Err(invalid("cadence series must be known and distinct")); + } + } + let risk = &config.matching.risk.ledger.risk_session; + let mut prior = initial; + let mut risk_ids = BTreeSet::from([&risk.session_id]); + for boundary in &config.risk_boundaries { + if boundary.calendar_id != risk.calendar_id + || boundary.calendar_revision != risk.calendar_revision + || boundary.starts_at.get() <= prior + || boundary.starts_at.get() > b.trade_end.get() + || !risk_ids.insert(&boundary.session_id) + { + return Err(invalid("invalid account risk boundary")); + } + prior = boundary.starts_at.get(); + } + Ok(()) + } + fn events(input: &PreparedReplay, config: &ReplayConfig) -> Result, ReplayError> { + let mut events = Vec::with_capacity(input.bars.len().saturating_mul(2)); + let first = config + .matching + .series + .first() + .ok_or_else(|| invalid("missing execution series"))? + .instrument_id + .clone(); + let last = config.matching.series.last().unwrap().instrument_id.clone(); + let mut push = |at, phase, instrument_id: Id, sequence: Counter, rank, series_id, body| { + events.push(Event { + key: EventKey { + at, + phase, + instrument_id, + source_sequence: sequence, + }, + control_rank: rank, + series_id, + body, + }); + }; + let zero: Counter = 0.try_into().unwrap(); + let mut execution = BTreeMap::new(); + for e in &config.matching.series { + execution.insert(&e.series_id, &e.instrument_id); + let s = input + .series + .iter() + .find(|s| s.series_id == e.series_id) + .unwrap(); + for session in &s.sessions { + if session.closes_at.get() <= input.bounds.warmup_start.get() + || session.opens_at.get() >= input.bounds.trade_end.get() + { + continue; + } + push( + session.opens_at, + EventPhase::Observation, + e.instrument_id.clone(), + zero, + 0, + s.series_id.clone(), + EventBody::OpenSession(session.clone()), + ); + if session.closes_at.get() <= input.bounds.trade_end.get() { + push( + session.closes_at, + EventPhase::SessionClose, + e.instrument_id.clone(), + zero, + 0, + s.series_id.clone(), + EventBody::CloseSession(session.session_id.clone()), + ); + } + } + } + for boundary in &config.risk_boundaries { + push( + boundary.starts_at, + EventPhase::Observation, + first.clone(), + zero, + 1, + first.clone(), + EventBody::RiskBoundary(boundary.clone()), + ); + } + let mut cadence: BTreeMap<&Id, Vec<&Id>> = BTreeMap::new(); + for c in &config.cadence { + for series in &c.series_ids { + cadence.entry(series).or_default().push(&c.owner_id); + } + } + let mut decisions: BTreeMap> = BTreeMap::new(); + for (index, bar) in input.bars.iter().enumerate() { + if bar.available_at.get() <= input.bounds.trade_end.get() { + push( + bar.available_at, + EventPhase::Observation, + bar.instrument_id.clone(), + bar.source_sequence, + 2, + bar.series_id.clone(), + EventBody::Observe(index), + ); + if bar.available_at.get() >= input.bounds.trade_start.get() + && bar.available_at.get() < input.bounds.trade_end.get() + { + for owner in cadence.get(&bar.series_id).into_iter().flatten() { + decisions + .entry(bar.available_at.get()) + .or_default() + .insert((*owner).clone()); + } + } + } + if execution.contains_key(&bar.series_id) + && bar.interval_start.get() >= input.bounds.trade_start.get() + { + push( + bar.interval_start, + EventPhase::Execution, + bar.instrument_id.clone(), + bar.source_sequence, + 0, + bar.series_id.clone(), + EventBody::Open(index), + ); + } + } + for (at, owners) in decisions { + push( + at.try_into().unwrap(), + EventPhase::Decision, + first.clone(), + zero, + 0, + first.clone(), + EventBody::Decision(owners.into_iter().collect()), + ); + } + push( + input.bounds.trade_end, + EventPhase::SessionClose, + last.clone(), + zero, + 3, + last, + EventBody::Finish, + ); + events.sort_by(|a, b| { + ( + a.key.at.get(), + a.key.phase, + &a.key.instrument_id, + a.control_rank, + a.key.source_sequence.get(), + &a.series_id, + ) + .cmp(&( + b.key.at.get(), + b.key.phase, + &b.key.instrument_id, + b.control_rank, + b.key.source_sequence.get(), + &b.series_id, + )) + }); + // Matcher has no series field in its key. Give same-phase observations + // canonical ranks after sorting by source sequence + stable series ID; + // execution keys retain the actual pinned-series source sequence. + let mut previous = None; + let mut rank = 0_u64; + for event in &mut events { + let group = ( + event.key.at.get(), + event.key.phase, + event.key.instrument_id.clone(), + ); + if previous.as_ref() == Some(&group) { + rank += 1; + } else { + rank = 0; + } + if event.key.phase != EventPhase::Execution { + event.key.source_sequence = rank + .try_into() + .map_err(|_| invalid("event rank overflow"))?; + } + previous = Some(group); + } + Ok(events) + } + pub fn status(&self) -> &ReplayStatus { + &self.status + } + pub fn barrier(&self) -> Option<&DecisionBarrier> { + self.pending.as_ref() + } + pub fn financial(&self) -> &MatchingAccount { + &self.matching + } + /// Only already published bars, in canonical arrival order. + pub fn observations(&self) -> impl Iterator { + self.published.iter().map(|i| &self.input.bars[*i]) + } + pub fn latest_observation(&self, series: &Id) -> Option<&PreparedBar> { + self.latest.get(series).map(|i| &self.input.bars[*i]) + } + pub fn limitations(&self) -> &[String] { + &self.input.limitations + } + pub fn model_limitations(&self) -> &'static [&'static str] { + MODEL_LIMITATIONS + } + + fn command( + &mut self, + index: usize, + key: EventKey, + body: MatchingCommandBody, + ) -> Result<(), ReplayError> { + let out = self.matching.apply(&MatchingCommand { + command_id: id(("replay", index)), + key, + body, + })?; + if let AttemptStatus::Failed { diagnostic } = out.status { + self.status = ReplayStatus::Failed { diagnostic }; + } + Ok(()) + } + fn process(&mut self, index: usize, event: Event) -> Result<(), ReplayError> { + let key = event.key; + match event.body { + EventBody::OpenSession(session) => { + self.command(index, key, MatchingCommandBody::OpenSession { session })? + } + EventBody::RiskBoundary(risk_session) => self.command( + index, + key, + MatchingCommandBody::RiskSessionBoundary { risk_session }, + )?, + EventBody::CloseSession(session_id) => { + self.command(index, key, MatchingCommandBody::CloseSession { session_id })? + } + EventBody::Observe(bar_index) => { + let bar = &self.input.bars[bar_index]; + self.published.push(bar_index); + if self + .latest + .get(&bar.series_id) + .is_none_or(|old| time_order(bar) > time_order(&self.input.bars[*old])) + { + self.latest.insert(bar.series_id.clone(), bar_index); + } + if self.execution_series.contains(&bar.series_id) + && self.latest.get(&bar.series_id) == Some(&bar_index) + // A delayed close at t must not replace the next interval's + // already processed open at t (Execution follows Observation). + && self.matching.ledger().mark(&bar.instrument_id).is_none_or(|m| bar.event_time.get() > m.event_time.get()) + { + let body = MatchingCommandBody::Mark { + series_id: bar.series_id.clone(), + price: bar.close, + observed_at: bar.event_time, + }; + self.command(index, key, body)?; + } + } + EventBody::Decision(owner_ids) => { + let max_age = self.config.matching.risk.max_mark_age_ms.get(); + let inputs = self + .input + .series + .iter() + .map(|series| { + let availability = match self.latest_observation(&series.series_id) { + None => InputAvailability::Missing, + Some(b) if (key.at.get() - b.event_time.get()) as u64 > max_age => { + InputAvailability::Stale { + event_time: b.event_time, + available_at: b.available_at, + } + } + Some(b) => InputAvailability::Fresh { + event_time: b.event_time, + available_at: b.available_at, + }, + }; + SeriesAvailability { + series_id: series.series_id.clone(), + availability, + } + }) + .collect(); + self.pending = Some(DecisionBarrier { + barrier_id: id(("barrier", index, key.at.get())), + at: key.at, + revision: self.matching.admission_revision(), + owner_ids, + observation_count: self.published.len(), + inputs, + }); + } + EventBody::Open(bar_index) => { + let bar = &self.input.bars[bar_index]; + let volume = self + .latest_observation(&bar.series_id) + .map(|b| b.volume) + .unwrap_or_else(|| Posting::ZERO.try_into().unwrap()); + let capacity = + Posting::notional(volume.into(), self.config.participation_rate.into())? + .try_into() + .expect("nonnegative participation"); + let body = MatchingCommandBody::Execute { + series_id: bar.series_id.clone(), + observation: ExecutionObservation::Open { + opens_at: bar.interval_start, + price: bar.open, + capacity, + }, + }; + self.command(index, key, body)?; + } + EventBody::Finish => { + self.command(index, key, MatchingCommandBody::Finish)?; + if self.status == ReplayStatus::Running { + self.status = ReplayStatus::Complete; + } + } + } + Ok(()) + } + pub fn advance(&mut self, budget: usize) -> Result { + if budget == 0 { + return Err(ReplayError::InvalidBudget); + } + if let Some(barrier) = &self.pending { + return Ok(ReplayStep::Decision(barrier.clone())); + } + let mut processed = 0; + while self.status == ReplayStatus::Running && processed < budget { + let index = self.next_event; + let event = self.events[index].clone(); + self.next_event += 1; + processed += 1; + if let Err(error) = self.process(index, event) { + self.status = ReplayStatus::Failed { + diagnostic: error.to_string(), + }; + } + if let Some(barrier) = &self.pending { + return Ok(ReplayStep::Decision(barrier.clone())); + } + } + Ok(match &self.status { + ReplayStatus::Running => ReplayStep::Progress { processed }, + ReplayStatus::Complete => ReplayStep::Complete, + ReplayStatus::Failed { diagnostic } => ReplayStep::Failed { + diagnostic: diagnostic.clone(), + }, + }) + } + pub fn submit( + &mut self, + mut submission: DecisionSubmission, + ) -> Result { + if self.status != ReplayStatus::Running { + return Err(ReplayError::Terminal); + } + let barrier = self + .pending + .as_ref() + .ok_or(ReplayError::InvalidSubmission)?; + submission + .decisions + .sort_by(|a, b| a.decision.owner_id.cmp(&b.decision.owner_id)); + let owners: Vec<_> = submission + .decisions + .iter() + .map(|d| &d.decision.owner_id) + .collect(); + if submission.barrier_id != barrier.barrier_id + || owners != barrier.owner_ids.iter().collect::>() + || submission + .decisions + .iter() + .any(|d| d.barrier_id != barrier.barrier_id || d.revision != barrier.revision) + { + return Err(ReplayError::InvalidSubmission); + } + let index = self.next_event - 1; + let out = self.matching.apply(&MatchingCommand { + command_id: id(("replay", index)), + key: self.events[index].key.clone(), + body: MatchingCommandBody::Submit { + decisions: submission.decisions.clone(), + }, + })?; + self.submissions.push(submission); + self.pending = None; + if let AttemptStatus::Failed { diagnostic } = &out.status { + self.status = ReplayStatus::Failed { + diagnostic: diagnostic.clone(), + }; + } + Ok(out) + } + pub fn checkpoint(&self) -> ReplayCheckpoint { + ReplayCheckpoint { + version: Version, + binding: self.binding.clone(), + next_event: self.next_event, + observation_count: self.published.len(), + pending: self.pending.clone(), + status: self.status.clone(), + submissions: self.submissions.clone(), + matching: self.matching.checkpoint(), + } + } + /// Deterministic fixed-decision-trace recovery. Strategy state/RNG and + /// strategy recomputation are separately owned by F07/S01. + pub fn restore( + input: PreparedReplay, + config: ReplayConfig, + checkpoint: &ReplayCheckpoint, + ) -> Result { + let mut replay = Self::new(input, config)?; + if replay.binding != checkpoint.binding || checkpoint.next_event > replay.events.len() { + return Err(ReplayError::InvalidCheckpoint); + } + let mut submissions = checkpoint.submissions.iter(); + while replay.next_event < checkpoint.next_event { + if replay.status != ReplayStatus::Running { + return Err(ReplayError::InvalidCheckpoint); + } + replay.advance(1)?; + if replay.pending.is_some() { + if replay.next_event == checkpoint.next_event && checkpoint.pending.is_some() { + break; + } + replay + .submit( + submissions + .next() + .ok_or(ReplayError::InvalidCheckpoint)? + .clone(), + ) + .map_err(|_| ReplayError::InvalidCheckpoint)?; + } + } + if submissions.next().is_some() || replay.checkpoint() != *checkpoint { + return Err(ReplayError::InvalidCheckpoint); + } + Ok(replay) + } +} diff --git a/apps/stock/engine/src/financial/replay_tests.rs b/apps/stock/engine/src/financial/replay_tests.rs new file mode 100644 index 00000000..de3e1d94 --- /dev/null +++ b/apps/stock/engine/src/financial/replay_tests.rs @@ -0,0 +1,967 @@ +use super::{contract::*, matching::*, replay::*, scalar::Posting}; +use serde_json::json; +use std::time::Instant; + +fn id(s: &str) -> Id { + serde_json::from_value(json!(s)).unwrap() +} +fn t(n: i64) -> EventTime { + n.try_into().unwrap() +} +fn p(s: &str) -> Posting { + s.parse().unwrap() +} +fn pos(s: &str) -> Positive { + p(s).try_into().unwrap() +} +fn nn(s: &str) -> NonNegative { + p(s).try_into().unwrap() +} +fn venue(name: &str, start: i64, end: i64) -> VenueSession { + VenueSession { + session_id: id(name), + opens_at: t(start), + closes_at: t(end), + } +} +fn series(name: &str, symbol: &str) -> ReplaySeries { + ReplaySeries { + series_id: id(name), + instrument_id: id(symbol), + adjustment: PriceAdjustment::Raw, + sessions: vec![venue("day1", 0, 10000000)], + } +} +fn bar( + series: &str, + symbol: &str, + start: i64, + end: i64, + available: i64, + seq: u64, + open: &str, + close: &str, + volume: &str, +) -> PreparedBar { + PreparedBar { + series_id: id(series), + instrument_id: id(symbol), + interval_start: t(start), + interval_end: t(end), + event_time: t(end), + available_at: t(available), + source_sequence: seq.try_into().unwrap(), + open: pos(open), + high: p(open).max(p(close)).try_into().unwrap(), + low: p(open).min(p(close)).try_into().unwrap(), + close: pos(close), + volume: nn(volume), + } +} +fn fixture() -> (PreparedReplay, ReplayConfig) { + let matching:MatchingConfig=serde_json::from_value(json!({ + "risk":{"ledger":{"version":1,"sessionId":"run","accountId":"account","baseCurrency":"USD","reserveOwnerId":"reserve","ownerIds":["A"],"initialCapital":"10000","riskSession":{"calendarId":"account","calendarRevision":"1","sessionId":"risk1","startsAt":0}}, + "feeRate":"0.01","maxOrderQuantity":"1000000","maxPositionQuantity":"1000000","maxSymbolExposure":"1000000","maxGrossExposure":"1000000","maxDailyLoss":"1000000","maxDrawdownAmount":"1000000","maxMarkAgeMs":10000000}, + "owners":[{"ownerId":"A","mode":"Target"}],"series":[{"instrumentId":"X","seriesId":"X-bars","mode":"Open"}],"halfSpreadRate":"0","slippageRate":"0","latencyMs":0 + })).unwrap(); + ( + PreparedReplay { + dataset_id: id("frozen-fixture"), + eligibility: DatasetEligibility::Eligible, + limitations: vec!["previous completed volume capacity; zero modeled latency".into()], + bounds: ReplayBounds { + warmup_start: t(0), + trade_start: t(10), + trade_end: t(30), + }, + series: vec![series("X-bars", "X")], + bars: vec![ + bar("X-bars", "X", 0, 10, 10, 7, "10", "11", "100"), + bar("X-bars", "X", 10, 20, 20, 3, "12", "13", "100"), + bar("X-bars", "X", 20, 30, 30, 9, "14", "15", "100"), + ], + }, + ReplayConfig { + matching, + participation_rate: nn("1"), + cadence: vec![DecisionCadence { + owner_id: id("A"), + series_ids: vec![id("X-bars")], + }], + allow_exploratory: false, + risk_boundaries: vec![], + }, + ) +} +fn next(r: &mut Replay) -> Option { + loop { + match r.advance(100).unwrap() { + ReplayStep::Decision(b) => return Some(b), + ReplayStep::Complete => return None, + ReplayStep::Failed { diagnostic } => panic!("replay failed: {diagnostic}"), + ReplayStep::Progress { .. } => {} + } + } +} +fn target(r: &mut Replay, b: &DecisionBarrier, quantity: &str) -> MatchingOutcome { + let decisions = b + .owner_ids + .iter() + .map(|owner| StrategyDecision { + version: Version, + session_id: id("run"), + barrier_id: b.barrier_id.clone(), + revision: b.revision, + decision: DecisionIdentity { + owner_id: owner.clone(), + decision_id: id(&format!("{}-{owner:?}", b.at.get())), + sequence: (b.at.get() as u64).try_into().unwrap(), + }, + intent: StrategyIntent::Target { + targets: vec![Target { + instrument_id: id("X"), + quantity: nn(quantity), + }], + }, + }) + .collect(); + r.submit(DecisionSubmission { + barrier_id: b.barrier_id.clone(), + decisions, + }) + .unwrap() +} +fn no_change(r: &mut Replay, b: &DecisionBarrier) -> MatchingOutcome { + let decisions = b + .owner_ids + .iter() + .map(|owner| StrategyDecision { + version: Version, + session_id: id("run"), + barrier_id: b.barrier_id.clone(), + revision: b.revision, + decision: DecisionIdentity { + owner_id: owner.clone(), + decision_id: id(&format!("{}-{owner:?}", b.at.get())), + sequence: (b.at.get() as u64).try_into().unwrap(), + }, + intent: StrategyIntent::Target { targets: vec![] }, + }) + .collect(); + r.submit(DecisionSubmission { + barrier_id: b.barrier_id.clone(), + decisions, + }) + .unwrap() +} +fn complete(r: &mut Replay) { + while let Some(b) = next(r) { + no_change(r, &b); + } +} +fn fill_prices(r: &Replay) -> Vec { + r.financial() + .receipts() + .iter() + .flat_map(|r| &r.outcome.effects) + .filter_map(|effect| { + if let MatchingEffect::Risk { command, outcome } = effect { + if let super::risk::RiskCommandBody::Fill { price, .. } = command.body { + if outcome.financial.is_some() + && outcome.disposition == super::risk::RiskDisposition::Accepted + { + return Some(price.into()); + } + } + } + None + }) + .collect() +} +#[test] +fn adjacent_open_zero_latency() { + let (input, config) = fixture(); + let mut r = Replay::new(input, config).unwrap(); + let b = next(&mut r).unwrap(); + assert_eq!(b.at, t(10)); + assert_eq!(b.observation_count, 1); + assert_eq!(r.observations().next().unwrap().close, pos("11")); + target(&mut r, &b, "2"); + complete(&mut r); + assert_eq!(fill_prices(&r), vec![p("12")]); + assert_eq!(r.financial().ledger().cash(), p("9975.76")); + assert_eq!(r.financial().ledger().equity().unwrap(), p("10005.76")); +} +#[test] +fn positive_latency_skips_open() { + let (input, mut config) = fixture(); + config.matching.latency_ms = 1.try_into().unwrap(); + let mut r = Replay::new(input, config).unwrap(); + let b = next(&mut r).unwrap(); + target(&mut r, &b, "2"); + complete(&mut r); + assert_eq!(fill_prices(&r), vec![p("14")]); +} +#[test] +fn future_ohlcv_does_not_change_open_fill() { + let (input, config) = fixture(); + let mut changed = input.clone(); + changed.bars[1].high = pos("999"); + changed.bars[1].low = pos("1"); + changed.bars[1].close = pos("888"); + changed.bars[1].volume = nn("0"); + let mut traces = vec![]; + for data in [input, changed] { + let mut r = Replay::new(data, config.clone()).unwrap(); + let b = next(&mut r).unwrap(); + target(&mut r, &b, "2"); + let _ = next(&mut r).unwrap(); + traces.push((fill_prices(&r), r.financial().ledger().cash())); + } + assert_eq!(traces[0], traces[1]); + assert_eq!(traces[0].0, vec![p("12")]); +} +#[test] +fn future_suffix_mutation() { + let (input, config) = fixture(); + let mut changed = input.clone(); + changed.bars[2].open = pos("999"); + changed.bars[2].high = pos("999"); + let mut prefix = vec![]; + for data in [input, changed] { + let mut r = Replay::new(data, config.clone()).unwrap(); + let b = next(&mut r).unwrap(); + target(&mut r, &b, "2"); + let b = next(&mut r).unwrap(); + prefix.push(( + b, + r.observations().cloned().collect::>(), + r.financial().checkpoint(), + )); + } + assert_eq!(prefix[0], prefix[1]); +} +#[test] +fn daily_close_target_survives_to_open() { + let (mut input, config) = fixture(); + input.bounds.trade_start = t(0); + input.bounds.trade_end = t(40); + input.series[0].sessions = vec![ + venue("day1", 0, 10), + venue("day2", 20, 30), + venue("day3", 35, 40), + ]; + input.bars = vec![ + bar("X-bars", "X", 0, 10, 10, 0, "10", "11", "100"), + bar("X-bars", "X", 20, 30, 30, 1, "12", "13", "100"), + bar("X-bars", "X", 35, 40, 40, 2, "14", "15", "100"), + ]; + let mut r = Replay::new(input, config).unwrap(); + let b = next(&mut r).unwrap(); + assert_eq!(b.at, t(10)); + target(&mut r, &b, "2"); + complete(&mut r); + assert_eq!(fill_prices(&r), vec![p("12")]); + let fill = r + .financial() + .receipts() + .iter() + .find(|r| { + r.outcome.effects.iter().any(|e| { + matches!( + e, + MatchingEffect::Risk { + command: super::risk::RiskCommand { + body: super::risk::RiskCommandBody::Fill { .. }, + .. + }, + .. + } + ) + }) + }) + .unwrap(); + let MatchingInput::Engine(c) = &fill.input else { + panic!() + }; + assert_eq!(c.key.at, t(20)); +} +#[test] +fn feature_timeframe_does_not_duplicate_liquidity() { + let (input, config) = fixture(); + let mut extra = input.clone(); + extra.series.push(series("feature", "X")); + extra.bars.extend([ + bar("feature", "X", 0, 5, 5, 0, "10", "99", "9999"), + bar("feature", "X", 5, 15, 15, 1, "99", "999", "9999"), + ]); + let mut traces = vec![]; + for data in [input, extra] { + let mut r = Replay::new(data, config.clone()).unwrap(); + let b = next(&mut r).unwrap(); + target(&mut r, &b, "150"); + let b = next(&mut r).unwrap(); + assert_eq!(b.at, t(20)); + no_change(&mut r, &b); + complete(&mut r); + traces.push((fill_prices(&r), r.financial().ledger().economic_snapshot())); + } + assert_eq!(traces[0], traces[1]); + assert_eq!(traces[0].0.len(), 2); +} +#[test] +fn equal_timestamp_symbol_permutation() { + let (mut input, mut config) = fixture(); + input.series.push(series("Y-bars", "Y")); + input + .bars + .extend(input.bars.clone().into_iter().map(|mut b| { + b.series_id = id("Y-bars"); + b.instrument_id = id("Y"); + b + })); + config.matching.series.push(ExecutionSeries { + instrument_id: id("Y"), + series_id: id("Y-bars"), + mode: ExecutionMode::Open, + }); + config.matching.owners.push(OwnerMode { + owner_id: id("B"), + mode: StrategyMode::Target, + }); + config.matching.risk.ledger.owner_ids.push(id("B")); + config.cadence.push(DecisionCadence { + owner_id: id("B"), + series_ids: vec![id("Y-bars")], + }); + config.risk_boundaries.push(RiskSessionIdentity { + calendar_id: id("account"), + calendar_revision: id("1"), + session_id: id("risk2"), + starts_at: t(10), + }); + let mut changed = input.clone(); + changed.bars.reverse(); + changed.series.reverse(); + let mut reversed = config.clone(); + reversed.cadence.reverse(); + reversed.matching.series.reverse(); + reversed.matching.owners.reverse(); + reversed.matching.risk.ledger.owner_ids.reverse(); + let mut traces = vec![]; + for (data, cfg) in [(input, config), (changed, reversed)] { + let mut r = Replay::new(data, cfg).unwrap(); + let b = next(&mut r).unwrap(); + assert_eq!(b.owner_ids, vec![id("A"), id("B")]); + assert_eq!(b.observation_count, 2); + assert_eq!(b.revision, r.financial().admission_revision()); + assert_ne!( + b.revision, + r.financial().ledger().economic_snapshot().revision + ); + target(&mut r, &b, "2"); + complete(&mut r); + traces.push(r.checkpoint()); + } + assert_eq!(traces[0], traces[1]); +} +#[test] +fn warmup_cannot_trade() { + let (mut input, config) = fixture(); + input.bounds.trade_start = t(20); + let mut r = Replay::new(input, config).unwrap(); + assert!(matches!( + r.submit(DecisionSubmission { + barrier_id: id("invented"), + decisions: vec![] + }), + Err(ReplayError::InvalidSubmission) + )); + let b = next(&mut r).unwrap(); + assert_eq!(b.at, t(20)); + assert_eq!(b.observation_count, 2); + assert!(fill_prices(&r).is_empty()); + assert!(!r.financial().receipts().iter().any(|r| matches!( + &r.input, + MatchingInput::Engine(MatchingCommand { + body: MatchingCommandBody::Execute { .. }, + .. + }) + ))); + target(&mut r, &b, "2"); + complete(&mut r); + assert_eq!(fill_prices(&r), vec![p("14")]); +} +#[test] +fn stale_mark_timestamp_preserved() { + let (mut input, mut config) = fixture(); + input.bars[0].available_at = t(15); + config.matching.risk.max_mark_age_ms = 2.try_into().unwrap(); + let mut r = Replay::new(input, config).unwrap(); + let b = next(&mut r).unwrap(); + assert_eq!(b.at, t(15)); + assert_eq!( + r.financial().ledger().mark(&id("X")).unwrap().event_time, + t(10) + ); + assert!( + matches!(b.inputs[0].availability,InputAvailability::Stale {event_time,available_at} if event_time==t(10)&&available_at==t(15)) + ); + target(&mut r, &b, "2"); + complete(&mut r); + assert!(fill_prices(&r).is_empty()); +} +#[test] +fn delayed_older_observation_preserves_mark_and_capacity() { + let (mut input, config) = fixture(); + input.bounds.trade_end = t(40); + input.bars[0].available_at = t(25); + input.bars[0].volume = nn("999"); + input.bars[1].volume = nn("2"); + input + .bars + .push(bar("X-bars", "X", 30, 40, 40, 15, "16", "17", "100")); + let mut r = Replay::new(input, config).unwrap(); + let b = next(&mut r).unwrap(); + assert_eq!(b.at, t(20)); + target(&mut r, &b, "10"); + let b = next(&mut r).unwrap(); + assert_eq!(b.at, t(25)); + assert_eq!( + r.financial().ledger().mark(&id("X")).unwrap().price, + pos("14") + ); + assert_eq!(r.latest_observation(&id("X-bars")).unwrap().volume, nn("2")); + no_change(&mut r, &b); + let b = next(&mut r).unwrap(); + assert_eq!( + r.financial().ledger().owner_quantity(&id("A"), &id("X")), + p("2") + ); + no_change(&mut r, &b); + complete(&mut r); + assert_eq!(fill_prices(&r), vec![p("14"), p("16")]); +} +#[test] +fn delayed_close_at_prior_open_timestamp_cannot_regress_mark() { + let (mut input, config) = fixture(); + input.bars[1].available_at = t(25); + input.bars[2].open = pos("30"); + input.bars[2].high = pos("30"); + let mut r = Replay::new(input, config).unwrap(); + let b = next(&mut r).unwrap(); + no_change(&mut r, &b); + let b = next(&mut r).unwrap(); + assert_eq!(b.at, t(25)); + let mark = r.financial().ledger().mark(&id("X")).unwrap(); + assert_eq!(mark.event_time, t(20)); + assert_eq!(mark.price, pos("30")); +} +#[test] +fn mid_session_start_retains_true_session_open() { + let (mut input, config) = fixture(); + input.bounds.warmup_start = t(5); + input.bars[0].interval_start = t(5); + let mut r = Replay::new(input.clone(), config.clone()).unwrap(); + let _ = next(&mut r).unwrap(); + let MatchingInput::Engine(c) = &r.financial().receipts()[0].input else { + panic!() + }; + assert_eq!(c.key.at, t(0)); + let mut bad = config; + bad.matching.risk.ledger.risk_session.starts_at = t(5); + assert!(matches!( + Replay::new(input, bad), + Err(ReplayError::InvalidInput( + "initial account clock follows true preceding venue open" + )) + )); +} +#[test] +fn terminal_observations_mark_only_and_later_rows_unavailable() { + let (mut input, config) = fixture(); + input.series.push(series("feature", "X")); + input + .bars + .push(bar("feature", "X", 0, 30, 31, 0, "99", "999", "10")); + let mut r = Replay::new(input, config).unwrap(); + let b = next(&mut r).unwrap(); + target(&mut r, &b, "2"); + complete(&mut r); + assert_eq!(r.observations().count(), 3); + assert_eq!( + r.financial().ledger().mark(&id("X")).unwrap().price, + pos("15") + ); + assert_eq!(r.checkpoint().submissions.len(), 2); + assert!(r.latest_observation(&id("feature")).is_none()); +} +#[test] +fn equal_time_feature_series_sequence_ties_stable_and_missing_explicit() { + let (mut input, config) = fixture(); + input.series.extend([ + series("feature-z", "X"), + series("feature-a", "X"), + series("missing", "X"), + ]); + input.bars.extend([ + bar("feature-z", "X", 0, 10, 10, 7, "10", "99", "1"), + bar("feature-a", "X", 0, 10, 10, 7, "10", "88", "1"), + bar("missing", "X", 0, 20, 20, 7, "10", "88", "1"), + ]); + let mut changed = input.clone(); + changed.bars.reverse(); + let mut results = vec![]; + for data in [input, changed] { + let mut r = Replay::new(data, config.clone()).unwrap(); + let b = next(&mut r).unwrap(); + assert!(b + .inputs + .iter() + .any(|i| i.series_id == id("missing") && i.availability == InputAvailability::Missing)); + results.push(( + b, + r.observations() + .map(|b| b.series_id.clone()) + .collect::>(), + r.checkpoint(), + )); + } + assert_eq!(results[0], results[1]); + assert_eq!( + results[0].1, + vec![id("X-bars"), id("feature-a"), id("feature-z")] + ); +} +#[test] +fn restore_before_and_after_every_decision_and_at_complete() { + let (input, config) = fixture(); + let mut r = Replay::new(input.clone(), config.clone()).unwrap(); + loop { + let step = r.advance(1).unwrap(); + let checkpoint = r.checkpoint(); + r = Replay::restore(input.clone(), config.clone(), &checkpoint).unwrap(); + assert_eq!(checkpoint, r.checkpoint()); + match step { + ReplayStep::Decision(b) => { + target(&mut r, &b, "2"); + let cp = r.checkpoint(); + r = Replay::restore(input.clone(), config.clone(), &cp).unwrap(); + } + ReplayStep::Complete => break, + ReplayStep::Progress { .. } => {} + other => panic!("{other:?}"), + } + } + let mut uninterrupted = Replay::new(input, config).unwrap(); + while let Some(b) = next(&mut uninterrupted) { + target(&mut uninterrupted, &b, "2"); + } + assert_eq!(r.checkpoint(), uninterrupted.checkpoint()); +} +#[test] +fn altered_input_config_and_checkpoint_rejected() { + let (input, config) = fixture(); + let mut r = Replay::new(input.clone(), config.clone()).unwrap(); + let _ = next(&mut r); + let cp = r.checkpoint(); + let mut changed = input.clone(); + changed.bars[2].volume = nn("101"); + assert!(matches!( + Replay::restore(changed, config.clone(), &cp), + Err(ReplayError::InvalidCheckpoint) + )); + let mut changed = config.clone(); + changed.matching.latency_ms = 1.try_into().unwrap(); + assert!(matches!( + Replay::restore(input.clone(), changed, &cp), + Err(ReplayError::InvalidCheckpoint) + )); + let mut bad = cp.clone(); + bad.pending.as_mut().unwrap().revision = 999.try_into().unwrap(); + assert!(matches!( + Replay::restore(input.clone(), config.clone(), &bad), + Err(ReplayError::InvalidCheckpoint) + )); + let mut bad = cp; + bad.observation_count += 1; + assert!(matches!( + Replay::restore(input, config, &bad), + Err(ReplayError::InvalidCheckpoint) + )); +} +#[test] +fn bounded_advance_and_atomic_due_owner_validation() { + let (input, config) = fixture(); + let mut r = Replay::new(input, config).unwrap(); + assert_eq!(r.advance(0), Err(ReplayError::InvalidBudget)); + assert!(matches!( + r.advance(1).unwrap(), + ReplayStep::Progress { processed: 1 } + )); + assert_eq!(r.observations().count(), 0); + let b = next(&mut r).unwrap(); + let cp = r.checkpoint(); + assert_eq!(r.advance(1000).unwrap(), ReplayStep::Decision(b.clone())); + assert!(matches!( + r.submit(DecisionSubmission { + barrier_id: b.barrier_id.clone(), + decisions: vec![] + }), + Err(ReplayError::InvalidSubmission) + )); + assert_eq!(cp, r.checkpoint()); + target(&mut r, &b, "2"); + assert!(matches!( + r.submit(DecisionSubmission { + barrier_id: b.barrier_id, + decisions: vec![] + }), + Err(ReplayError::InvalidSubmission) + )); +} +#[test] +fn explicit_input_contract_rejections() { + let (input, config) = fixture(); + let mut bad = input.clone(); + bad.bars.clear(); + assert!(Replay::new(bad, config.clone()).is_err()); + let mut bad = input.clone(); + bad.eligibility = DatasetEligibility::Ineligible; + assert!(Replay::new(bad, config.clone()).is_err()); + let mut bad = input.clone(); + bad.eligibility = DatasetEligibility::Exploratory; + assert!(Replay::new(bad.clone(), config.clone()).is_err()); + let mut allowed = config.clone(); + allowed.allow_exploratory = true; + assert!(Replay::new(bad, allowed).is_ok()); + let mut bad = input.clone(); + bad.series[0].adjustment = PriceAdjustment::ProviderAdjusted; + assert!(Replay::new(bad, config.clone()).is_err()); + let mut bad = config.clone(); + bad.matching.series[0].mode = ExecutionMode::Quote; + assert!(Replay::new(input.clone(), bad).is_err()); + let mut bad = input.clone(); + bad.series[0].sessions = vec![venue("a", 0, 10), venue("b", 10, 30)]; + assert!(matches!( + Replay::new(bad, config.clone()), + Err(ReplayError::InvalidInput( + "overlapping or abutting retained sessions are unsupported" + )) + )); + let mut bad = input.clone(); + bad.bars[1].source_sequence = bad.bars[0].source_sequence; + assert!(Replay::new(bad, config.clone()).is_err()); + let mut bad = input.clone(); + bad.bars[1].available_at = t(19); + assert!(Replay::new(bad, config.clone()).is_err()); + let mut bad = config.clone(); + bad.participation_rate = nn("1.1"); + assert!(Replay::new(input, bad).is_err()); +} + +#[test] +fn financial_failure_is_terminal_with_reproducible_diagnostic_prefix() { + let (mut input, config) = fixture(); + let maximum = super::scalar::MAX_POSTING; + input.bars[0].high = pos(maximum); + input.bars[0].close = pos(maximum); + let mut r = Replay::new(input.clone(), config.clone()).unwrap(); + let b = next(&mut r).unwrap(); + let outcome = target(&mut r, &b, "2"); + assert!(matches!(outcome.status, AttemptStatus::Failed { .. })); + assert!(matches!(r.advance(100).unwrap(), ReplayStep::Failed { .. })); + let checkpoint = r.checkpoint(); + let restored = Replay::restore(input, config, &checkpoint).unwrap(); + assert_eq!(restored.checkpoint(), checkpoint); + assert!(matches!( + r.submit(DecisionSubmission { + barrier_id: b.barrier_id, + decisions: vec![] + }), + Err(ReplayError::Terminal) + )); +} + +#[test] +fn irrelevant_old_sessions_do_not_backdate_initialization() { + let (mut input, config) = fixture(); + input.series[0].sessions.insert(0, venue("old", -20, -10)); + let mut r = Replay::new(input, config).unwrap(); + complete(&mut r); + let MatchingInput::Engine(first) = &r.financial().receipts()[0].input else { + panic!() + }; + assert_eq!(first.key.at, t(0)); +} + +#[test] +fn automatic_execution_failure_preserves_committed_prefix_and_restores() { + let (mut input, mut config) = fixture(); + config.matching.slippage_rate = nn("0.9"); + input.bars[1].open = pos(super::scalar::MAX_POSTING); + input.bars[1].high = pos(super::scalar::MAX_POSTING); + let mut r = Replay::new(input.clone(), config.clone()).unwrap(); + let b = next(&mut r).unwrap(); + target(&mut r, &b, "2"); + assert!(matches!(r.advance(100).unwrap(), ReplayStep::Failed { .. })); + let receipt = r.financial().receipts().last().unwrap(); + assert!(matches!( + receipt.outcome.status, + AttemptStatus::Failed { .. } + )); + assert!(!receipt.outcome.effects.is_empty()); + assert!(fill_prices(&r).is_empty()); + let checkpoint = r.checkpoint(); + let mut restored = Replay::restore(input, config, &checkpoint).unwrap(); + assert_eq!(restored.checkpoint(), checkpoint); + assert!(matches!( + restored.advance(100).unwrap(), + ReplayStep::Failed { .. } + )); +} + +#[test] +fn same_time_risk_boundary_venue_opens_and_marks_have_monotone_keys() { + let (mut input, mut config) = fixture(); + input.series.push(ReplaySeries { + sessions: vec![venue("Y-day", 10, 30)], + ..series("Y-bars", "Y") + }); + input + .bars + .push(bar("Y-bars", "Y", 10, 20, 20, 7, "20", "21", "100")); + config.matching.series.push(ExecutionSeries { + instrument_id: id("Y"), + series_id: id("Y-bars"), + mode: ExecutionMode::Open, + }); + config.risk_boundaries.push(RiskSessionIdentity { + calendar_id: id("account"), + calendar_revision: id("1"), + session_id: id("risk2"), + starts_at: t(10), + }); + let mut r = Replay::new(input, config).unwrap(); + let b = next(&mut r).unwrap(); + assert_eq!(b.at, t(10)); + assert_eq!( + r.financial().risk().state().risk_session.session_id, + id("risk2") + ); + let at10 = r + .financial() + .receipts() + .iter() + .filter_map(|r| match &r.input { + MatchingInput::Engine(c) if c.key.at == t(10) => Some(c), + _ => None, + }) + .collect::>(); + assert!(at10.windows(2).all(|w| w[0].key < w[1].key)); + assert!(at10.iter().any( + |c| matches!(c.body, MatchingCommandBody::OpenSession { .. }) + && c.key.instrument_id == id("Y") + )); + no_change(&mut r, &b); + complete(&mut r); +} + +#[test] +fn sequential_equal_time_marks_can_latch_risk_before_synchronized_barrier() { + let (mut input, mut config) = fixture(); + for b in &mut input.bars { + b.open = pos("100"); + b.high = pos("100"); + b.low = pos("100"); + b.close = pos("100"); + } + input.series.push(series("Y-bars", "Y")); + input + .bars + .extend(input.bars.clone().into_iter().map(|mut b| { + b.series_id = id("Y-bars"); + b.instrument_id = id("Y"); + b + })); + input.bars[1].close = pos("50"); + input.bars[1].low = pos("50"); + input.bars[4].close = pos("150"); + input.bars[4].high = pos("150"); + config.matching.series.push(ExecutionSeries { + instrument_id: id("Y"), + series_id: id("Y-bars"), + mode: ExecutionMode::Open, + }); + config.matching.risk.fee_rate = nn("0"); + config.matching.risk.max_daily_loss = pos("10"); + config.matching.risk.max_drawdown_amount = pos("10"); + let mut permuted = input.clone(); + permuted.bars.reverse(); + let mut checkpoints = vec![]; + for data in [input, permuted] { + let mut r = Replay::new(data, config.clone()).unwrap(); + let b = next(&mut r).unwrap(); + r.submit(DecisionSubmission { + barrier_id: b.barrier_id.clone(), + decisions: vec![StrategyDecision { + version: Version, + session_id: id("run"), + barrier_id: b.barrier_id, + revision: b.revision, + decision: DecisionIdentity { + owner_id: id("A"), + decision_id: id("pair"), + sequence: 1.try_into().unwrap(), + }, + intent: StrategyIntent::Target { + targets: vec![ + Target { + instrument_id: id("X"), + quantity: nn("1"), + }, + Target { + instrument_id: id("Y"), + quantity: nn("1"), + }, + ], + }, + }], + }) + .unwrap(); + let b = next(&mut r).unwrap(); + assert_eq!(b.at, t(20)); + assert_eq!(r.financial().ledger().equity().unwrap(), p("10000")); + assert!(r.financial().risk().state().daily_halted); + assert!(r.financial().risk().state().drawdown_halted); + checkpoints.push(r.checkpoint()); + } + assert_eq!(checkpoints[0], checkpoints[1]); + assert!(MODEL_LIMITATIONS + .iter() + .any(|s| s.contains("intermediate equity"))); +} +#[test] +fn no_known_volume_and_zero_capacity_cannot_fill() { + let (mut input, config) = fixture(); + input.bars[0].volume = nn("0"); + let mut r = Replay::new(input, config).unwrap(); + let b = next(&mut r).unwrap(); + target(&mut r, &b, "2"); + let b = next(&mut r).unwrap(); + assert!(fill_prices(&r).is_empty()); + no_change(&mut r, &b); + complete(&mut r); + assert_eq!(fill_prices(&r), vec![p("14")]); +} + +#[test] +fn unknown_completed_volume_does_not_fill_a_live_order() { + let (mut input, mut config) = fixture(); + input.bounds.trade_start = t(0); + input.bars[0].available_at = t(25); + input.bars[1].available_at = t(25); + input.series.push(series("feature", "X")); + input + .bars + .push(bar("feature", "X", 0, 11, 11, 0, "10", "10", "9999")); + config.cadence[0].series_ids = vec![id("feature")]; + let mut r = Replay::new(input, config).unwrap(); + let b = next(&mut r).unwrap(); + assert_eq!(b.at, t(11)); + assert!(r.latest_observation(&id("X-bars")).is_none()); + target(&mut r, &b, "2"); + assert!(r + .financial() + .orders() + .any(|o| o.status == OrderStatus::Open)); + complete(&mut r); + assert!(fill_prices(&r).is_empty()); + assert_eq!(r.financial().ledger().cash(), p("10000")); + assert!(r + .financial() + .orders() + .all(|o| o.status == OrderStatus::Cancelled)); +} + +#[test] +#[ignore = "manual release component measurement; no timing CI assertion"] +fn replay_scaling_measurement() { + for instruments in [1, 2] { + for count in [1000, 10000, 100000] { + let (mut input, mut config) = fixture(); + let per_instrument = count / instruments; + if instruments == 2 { + input.series.push(series("Y-bars", "Y")); + config.matching.series.push(ExecutionSeries { + instrument_id: id("Y"), + series_id: id("Y-bars"), + mode: ExecutionMode::Open, + }); + } + input.bounds.trade_start = t(10); + input.bounds.trade_end = t((per_instrument * 10) as i64); + input.bars = (0..count) + .map(|i| { + let (series, symbol) = if i < per_instrument { + ("X-bars", "X") + } else { + ("Y-bars", "Y") + }; + let index = i % per_instrument; + bar( + series, + symbol, + (index * 10) as i64, + ((index + 1) * 10) as i64, + ((index + 1) * 10) as i64, + index as u64, + "10", + "10", + "100", + ) + }) + .collect(); + // One barrier/buy, then mark-only traversal measures the cursor rather + // than pretending 100k orders have no F05 journal/memory cost. + input.series.push(series("cadence", "X")); + input + .bars + .push(bar("cadence", "X", 0, 10, 10, 0, "10", "10", "100")); + config.cadence[0].series_ids = vec![id("cadence")]; + let mut expected = None; + for repeat in 0..3 { + let data = input.clone(); + let cfg = config.clone(); + let started = Instant::now(); + let mut r = Replay::new(data, cfg).unwrap(); + let load = started.elapsed(); + let started = Instant::now(); + while let Some(b) = next(&mut r) { + target(&mut r, &b, "1"); + } + let traverse = started.elapsed(); + assert_eq!(fill_prices(&r), vec![p("10")]); + assert_eq!(r.financial().ledger().cash(), p("9989.9")); + assert_eq!(r.financial().ledger().equity().unwrap(), p("9999.9")); + let started = Instant::now(); + let checkpoint = r.checkpoint(); + let checkpoint_time = started.elapsed(); + let bytes = serde_json::to_vec(&checkpoint).unwrap(); + if let Some(expected) = &expected { + assert_eq!(&bytes, expected); + } else { + expected = Some(bytes.clone()); + } + drop(r); + let data = input.clone(); + let cfg = config.clone(); + let started = Instant::now(); + let restored = Replay::restore(data, cfg, &checkpoint).unwrap(); + let restore = started.elapsed(); + assert_eq!(restored.checkpoint(), checkpoint); + println!("replay instruments={instruments} execution_bars={count} total_bars={} repeat={repeat} load_us={} replay_us={} checkpoint_us={} restore_us={} checkpoint_bytes={} fills=1",count+1,load.as_micros(),traverse.as_micros(),checkpoint_time.as_micros(),restore.as_micros(),bytes.len()); + } + } + } +} diff --git a/docs/development/ROADMAP.md b/docs/development/ROADMAP.md index 929ee146..d8b82a3c 100644 --- a/docs/development/ROADMAP.md +++ b/docs/development/ROADMAP.md @@ -1,8 +1,8 @@ # Revised development roadmap -Baseline `b7aeca4` · reviewed 2026-10-22 · **F04/F05 independently reviewed and validated, uncommitted** +Baseline `b7aeca4` · reviewed 2026-10-22 · **F04/F05 committed; F06 independently reviewed and validated, uncommitted** -Authorization update: the latest owner request “do it” authorizes the explicitly proposed F05 continuation on accepted, independently reviewed and validated F04. No commit was requested: F04's exact source is applied as an explicit prerequisite overlay to F05's isolated worktree based on `b65accc`. No other ADR is approved. Commits, pushes, PRs and trading operations remain outside scope. +Authorization update: the latest owner request “commit all and do it” authorized committing the reviewed F04/F05 source and planning changes (`ccf333c`), then implementing F06. Its worktree starts at that commit; no prerequisite overlay is needed. No other ADR is approved. Pushes, PRs, trading operations and further task implementation remain outside scope. ## Strategy and review outcome @@ -27,6 +27,8 @@ The existing web workbench improves during engine migration. Legacy results rema Long-only is the approved first canonical model, not deletion of short history or a silent change to current paper accounts. Short/margin support still needs a separate approved borrowing policy and fixtures. C01/C03/C04/W01 preserve the legacy behavior described in their task scopes. +**Pre-default multi-asset risk decision:** F06 review confirms existing ordered mark transitions can latch an intermediate portfolio loss/drawdown halt even when simultaneous offsetting moves leave final equity unchanged. Additive F06/F07 work can proceed under the current deterministic policy, but R05 must not enable canonical multi-asset default research until the owner explicitly accepts the disclosed versioned approximation or approves a coordinated atomic-mark correction with fixtures. Determinism alone does not resolve this modeling issue. + ## Milestones | Milestone | Tasks | Exit criterion | @@ -237,6 +239,22 @@ The narrow release workload uses 1k/10k execution events and fills, each precede Limits: active legacy simulator and NAPI unchanged; no replay scheduler, paper/SQL cutover or full session restore. Checkpoints validate consistency, not authenticity or arbitrary-code security. PostgreSQL/Redis, browser and Python suites were not rerun because their boundaries did not change. Existing build warnings remain. No services/data removed; worktree/logs retained. **F04/F05 remain uncommitted. Next after acceptance: F06 deterministic availability-aware replay**, still the release gate for this matcher. No commit, push, PR or trading operation occurred. +## Tenth-wave handoff — 2026-10-22 + +F04/F05 were accepted and committed as `ccf333c` at owner request, superseding their uncommitted handoff status above. F06 is independently reviewed and `review` / `validated_uncommitted`. Isolated worktree `/tmp/stock-bot-wave10.8uCLfa/f06` starts at that commit. One implementation owner wrote three replay files; independent timing/execution and quant/performance reviewers accepted the frozen source; root integrated exactly matching hashes. See [F06 execution clarifications](backlog/tasks/F06.md#execution-handoff-clarifications). + +- **Replay** owns MatchingAccount and one sorted immutable event vector. Available observations use an index prefix rather than repeated history copies. Declared cadence produces one synchronized barrier per timestamp; exact due owners submit against the matching admission revision. Missing/stale feature inputs remain explicit. Prepared input/config ordering is canonicalized; file permutations preserve trace/checkpoint bytes. +- Only the pinned execution series provides open opportunities, marks and liquidity derived from the physically latest completed available volume. Warmup cannot trade; terminal observations mark only. Late prior closes cannot overwrite a physically newer open even when their timestamps tie. True retained session opens are never restamped for mid-session starts. Risk-session boundaries are a separate explicit clock. +- Exact canonical input/config content, not an unverified label, binds checkpoints. Restore reconstructs event prefixes and fixed decision submissions, then verifies the full state. Both submission-time and automatic-event financial failures preserve terminal diagnostic prefixes without producing a successful run. Strategy-state/RNG recomputation remains F07/S01. + +Combined validation: `CARGO_BUILD_JOBS=2 bun run check` passed build/types/contracts/lint/audit plus 60 tooling, 43 utility, 35 calculation, 342 integration and **131 Rust tests**, zero failures. The **25 replay regressions** passed independently; the timing reviewer also ran the full frozen test binary. Four manual benchmarks are ignored by ordinary Rust runs; the new release replay measurement passed in both author and integrated checkouts. Scoped rustfmt, diff, task DAG/readiness and final source/artifact checks passed. + +Release measurement: one/two assets, 1k/10k/100k execution bars plus one cadence-only row, three repeats each, one buy/fill per run. Full checkpoint bytes repeat exactly; independent expected cash/equity and restored checkpoints match. Integrated 100k load was 76–85ms and traversal 0.91–1.11s. Load includes canonicalization, validation, sorting and exact binding serialization; traversal includes financial marks/journals and the fixture decision. Input generation/cloning and output serialization are excluded. Checkpoint copying and full restore are timed separately. At 100k the serialized checkpoint is approximately 429MB, not RSS. Receipt history is retained; no compaction or cross-trial cache was introduced. This is not order-heavy, TS/NAPI, batch or storage throughput, nor a baseline speedup claim. Raw rows and hashes are in the manifest. + +**Material model restriction:** existing sequential equal-time marks can latch intermediate portfolio loss/drawdown despite unchanged final synchronized equity. The implementation exposes this limitation and pins a permutation regression. R05's multi-asset default activation requires explicit owner acceptance or an approved coordinated atomic-mark correction. F06 acceptance does not waive that gate. + +Other limits: trusted internal prepared bars only; F07 must verify/adapt frozen D01 inputs and preserve provenance/model limitations. Quote replay and abutting sessions explicitly reject. Event budget bounds count, not wall time. Active legacy simulator, native API, SQL/paper and web paths are unchanged; no PostgreSQL/Redis, browser or Python rerun was needed. Existing build warnings remain. No services/data removed; worktree/logs retained. **F06 remains uncommitted. Next after acceptance: F07 native pull-session/dataset adapter**; F08 result projection may follow with coordinated contract ownership. No push, PR, trading operation or further task implementation occurred. + ## 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/backlog/README.md b/docs/development/backlog/README.md index 9ab068c6..fcf824fe 100644 --- a/docs/development/backlog/README.md +++ b/docs/development/backlog/README.md @@ -1,6 +1,6 @@ # Canonical development backlog -**First seven waves committed; F04/F05 independently reviewed and validated, uncommitted.** Consult manifest execution_scope, [ROADMAP](../ROADMAP.md), [skeptical review](../REVIEW.md) and [first-wave handoff](../FIRST-WAVE.md). ADR-002/003/004 are approved. The owner authorized F05 on F04's validated integrated source without requesting a commit. Other tasks/policies remain gated. +**First nine waves committed; F06 independently reviewed and validated, uncommitted.** Consult manifest execution_scope, [ROADMAP](../ROADMAP.md), [skeptical review](../REVIEW.md) and [first-wave handoff](../FIRST-WAVE.md). ADR-002/003/004 are approved. The owner authorized the F04/F05 commit (`ccf333c`) and F06 continuation. Other tasks/policies remain gated. ## One source of truth @@ -32,9 +32,9 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr | [F01 Define the minimal financial contract and economic fixtures](tasks/F01.md) | P0 / done | ADR-002, ADR-003, ADR-004 (approved) | — | Rust financial contract owner / M | | [F02 Implement one owner-aware financial ledger](tasks/F02.md) | P0 / done | F01, ADR-002 | — | Rust accounting / L | | [F03 Add strategy-owned position books and fill allocations](tasks/F03.md) | P0 / merged → F02 | None | — | Rust portfolio accounting / M | -| [F04 Enforce cash reservations and portfolio risk centrally](tasks/F04.md) | P0 / review | F02, ADR-002, ADR-003 | — | Rust financial risk / L | -| [F05 Unify matching and order lifecycle on the ledger](tasks/F05.md) | P0 / review | F04, ADR-003 | F06 | Rust execution semantics / L | -| [F06 Implement deterministic replay once, with linear historical traversal](tasks/F06.md) | P0 / blocked | F05, D01, P01, ADR-003 | — | Rust deterministic replay / M | +| [F04 Enforce cash reservations and portfolio risk centrally](tasks/F04.md) | P0 / done | F02, ADR-002, ADR-003 | — | Rust financial risk / L | +| [F05 Unify matching and order lifecycle on the ledger](tasks/F05.md) | P0 / done | F04, ADR-003 | F06 | Rust execution semantics / L | +| [F06 Implement deterministic replay once, with linear historical traversal](tasks/F06.md) | P0 / review | F05, D01, P01, ADR-003 | — | Rust deterministic replay / M | | [F07 Expose bounded Rust step sessions through existing NAPI workers](tasks/F07.md) | P0 / blocked | F06, C02, ADR-004 | — | Rust/TypeScript integration / M | | [F08 Publish canonical metrics and versioned result projections](tasks/F08.md) | P1 / blocked | F06, ADR-002, ADR-003 | — | Quant analytics/Rust integration / M | @@ -75,7 +75,7 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr | [R02 Deliver strategy catalog and version-aware backtest setup](tasks/R02.md) | P1 / blocked | R01, W03, ADR-006 | W04 | Full-stack research product / M | | [R03 Add projects, hypotheses and evidence-linked findings APIs](tasks/R03.md) | P1 / blocked | R01, R10, ADR-006 | — | Full-stack research product / M | | [R04 Deliver research workspace and save-findings flow](tasks/R04.md) | P1 / blocked | R03, W02, ADR-006 | W04 | Full-stack research product / M | -| [R05 Freeze complete provenance and cut over durable canonical runs](tasks/R05.md) | P0 / blocked | F08, S02, R01, R10, D01, W03, C06, ADR-006 | — | Full-stack research product / M | +| [R05 Freeze complete provenance and cut over durable canonical runs](tasks/R05.md) | P0 / blocked | F08, S02, R01, R10, D01, W03, C06, ADR-006 | Multi-asset default mark-policy disposition | Full-stack research product / M | | [R06 Create immutable experiments and bounded sweep expansion](tasks/R06.md) | P1 / blocked | R05, ADR-006 | — | Full-stack research product / M | | [R07 Deliver sweep configuration and comparable-result views](tasks/R07.md) | P1 / blocked | R06, ADR-006 | W04 | Full-stack research product / M | | [R08 Add bounded chronological and reset-segment validation](tasks/R08.md) | P1 / blocked | R06, ADR-006 | — | Quantitative research integrity / M | @@ -115,4 +115,4 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr Before any wave: unique IDs; existing task/ADR references; acyclic implementation graph; no scheduled task dependent on merged/deferred work; approvals/readiness; actual file locks; isolated native build outputs/workspace dependencies and test databases. Release gates are checked separately at activation. -The first seven waves are independently reviewed, validated and committed with owner approval. Evidence is recorded in [FIRST-WAVE.md](../FIRST-WAVE.md#execution-record--2026-10-22), the [ROADMAP handoffs](../ROADMAP.md#ninth-wave-handoff--2026-10-22) and the manifest. The latest owner request authorized **F05** using accepted integrated F04. Both implementations are now independently reviewed and `validated_uncommitted`; F05's explicit integration overlay pins its prerequisite source, and ninth-wave validation records the resulting cumulative seven-file financial overlay. Next after acceptance: F06. R01 still needs ADR-006; other consumers wait for their dependencies. No commit, push, PR or trading operation is authorized. +The first nine waves are independently reviewed, validated and committed with owner approval. Evidence is recorded in [FIRST-WAVE.md](../FIRST-WAVE.md#execution-record--2026-10-22), the [ROADMAP handoffs](../ROADMAP.md#tenth-wave-handoff--2026-10-22) and the manifest. The latest owner request committed F04/F05 as `ccf333c` and authorized **F06**, now reviewed and `validated_uncommitted`. Next after acceptance: F07's verified dataset/native adapter. F08 is another eligible component successor after acceptance; coordinate any shared result/native contracts. R01 still needs ADR-006. The manifest's canonical release gate records the unresolved multi-asset mark-policy decision; this does not block additive adapter work. No push, PR, trading operation or further task implementation is authorized. diff --git a/docs/development/backlog/manifest.json b/docs/development/backlog/manifest.json index 615bfa44..f88348d0 100644 --- a/docs/development/backlog/manifest.json +++ b/docs/development/backlog/manifest.json @@ -1,13 +1,13 @@ { "schema_version": 1, - "plan_revision": "2026-10-22.21", + "plan_revision": "2026-10-22.23", "repository_base": "b7aeca4", - "plan_status": "ninth_wave_validated_uncommitted", + "plan_status": "tenth_wave_validated_uncommitted", "execution_authorized": true, "execution_scope": { - "authorized_by": "User: do it (2026-10-22), authorizing the explicitly proposed F05 continuation on accepted integrated F04; no commit requested", + "authorized_by": "User: commit all and do it (2026-10-22), authorizing the F04/F05 commit and proposed F06 continuation", "tasks": [ - "F05" + "F06" ], "permissions": [ "isolated_implementation", @@ -16,7 +16,7 @@ "planning_progress_updates" ], "excluded": [ - "commits_without_further_approval", + "new_wave_commits_without_further_approval", "push", "pull_requests", "live_or_paper_operations", @@ -437,7 +437,7 @@ "epic": "E2", "priority": "P0", "severity": "Critical", - "status": "review", + "status": "done", "dependencies": [ "F02" ], @@ -460,7 +460,7 @@ "assignment": "/root/wave8_f04", "branch": "wave8/f04-financial-risk", "pull_request": null, - "completed_commit": null, + "completed_commit": "ccf333cc0ae9bcf1cc81ff6cc50099686738def2", "blocker": null, "release_gates": [], "worktree": "/tmp/stock-bot-wave8.pKzr7p/f04", @@ -468,14 +468,14 @@ "concrete_write_scope": [ "apps/stock/engine/src/financial/" ], - "integration_state": "validated_uncommitted", + "integration_state": "validated_committed", "reviewed_by": [ "/root/wave8_risk_review", "/root/wave8_quant_review" ], - "review_notes": "Both independent reviewers and combined gates passed; owner accepted continuation to F05. Integrated F04 remains uncommitted, with frozen source hashes recorded in eighth_wave_validation.", + "review_notes": "Both independent reviewers and combined gates passed; owner accepted continuation to F05. Integrated F04 remains uncommitted, with frozen source hashes recorded in eighth_wave_validation. Subsequently committed at owner request as ccf333c.", "verification_reference": "ROADMAP.md#eighth-wave-handoff--2026-10-22", - "accepted_by": "Owner: do it, authorizing proposed F05 continuation on validated integrated F04 (2026-10-22)" + "accepted_by": "Owner: commit all and do it (2026-10-22), accepting F04/F05 and authorizing F06" }, { "id": "F05", @@ -483,7 +483,7 @@ "epic": "E2", "priority": "P0", "severity": "Critical", - "status": "review", + "status": "done", "dependencies": [ "F04" ], @@ -507,7 +507,7 @@ "assignment": "/root/wave9_f05", "branch": "wave9/f05-matching", "pull_request": null, - "completed_commit": null, + "completed_commit": "ccf333cc0ae9bcf1cc81ff6cc50099686738def2", "blocker": null, "release_gates": [ "F06" @@ -523,13 +523,14 @@ "concrete_write_scope": [ "apps/stock/engine/src/financial/" ], - "integration_state": "validated_uncommitted", - "review_notes": "Both independent reviewers accepted the final frozen source; root integrated matching hashes and passed all repository checks plus the release matching measurement. No active runtime cutover; F06 remains the replay release gate.", + "integration_state": "validated_committed", + "review_notes": "Both independent reviewers accepted the final frozen source; root integrated matching hashes and passed all repository checks plus the release matching measurement. No active runtime cutover; F06 remains the replay release gate. Subsequently committed at owner request as ccf333c.", "reviewed_by": [ "/root/wave9_execution_review", "/root/wave9_quant_review" ], - "verification_reference": "ROADMAP.md#ninth-wave-handoff--2026-10-22" + "verification_reference": "ROADMAP.md#ninth-wave-handoff--2026-10-22", + "accepted_by": "Owner: commit all and do it (2026-10-22), accepting F04/F05 and authorizing F06" }, { "id": "F06", @@ -537,7 +538,7 @@ "epic": "E2", "priority": "P0", "severity": "Critical", - "status": "blocked", + "status": "review", "dependencies": [ "F05", "D01", @@ -558,12 +559,26 @@ "rust-replay" ], "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", - "assignment": null, - "branch": null, + "assignment": "/root/wave10_f06", + "branch": "wave10/f06-replay", "pull_request": null, "completed_commit": null, "blocker": null, - "release_gates": [] + "release_gates": [], + "worktree": "/tmp/stock-bot-wave10.8uCLfa/f06", + "integration_base": "ccf333cc0ae9bcf1cc81ff6cc50099686738def2", + "concrete_write_scope": [ + "apps/stock/engine/src/financial/replay.rs", + "apps/stock/engine/src/financial/replay_tests.rs", + "apps/stock/engine/src/financial/mod.rs" + ], + "integration_state": "validated_uncommitted", + "review_notes": "Both independent reviewers accepted exact frozen source; combined repository gates and integrated release replay measurement passed. Internal bar replay only; active simulator/NAPI/SQL unchanged. Material sequential equal-time risk approximation remains the canonical multi-asset default policy gate.", + "reviewed_by": [ + "/root/wave10_replay_review", + "/root/wave10_quant_review" + ], + "verification_reference": "ROADMAP.md#tenth-wave-handoff--2026-10-22" }, { "id": "F07", @@ -3230,5 +3245,122 @@ ], "handoff": "F04/F05 independently reviewed and validated, uncommitted. Next after owner acceptance: F06 availability-aware deterministic replay. No commit, push, PR, other task implementation or trading operation.", "cleanup": "No services/data removed; isolated worktree and logs retained." + }, + "canonical_release_gates": [ + { + "id": "multi_asset_mark_policy", + "status": "requires_owner_disposition", + "applies_to": [ + "R05" + ], + "capability": "Canonical multi-asset research as the default", + "evidence": "F06 sequential_equal_time_marks_can_latch_risk_before_synchronized_barrier: offsetting same-time marks preserve final equity but latch intermediate daily/drawdown halts under F04/F05 per-mark risk.", + "resolution": "Owner must explicitly accept the disclosed versioned sequential-mark approximation or approve a coordinated atomic-mark policy change with independent fixtures before default activation.", + "does_not_block": [ + "F06 additive integration", + "F07 internal/native adapter work", + "single-asset component work" + ], + "task_reference": "backlog/tasks/R05.md", + "approved_by": null + } + ], + "tenth_wave": [ + "F06" + ], + "tenth_wave_base": "ccf333cc0ae9bcf1cc81ff6cc50099686738def2", + "tenth_wave_notes": [ + "Owner authorized committing all existing reviewed F04/F05 work and continuing F06; existing work committed ccf333c. No push, PR or trading operations.", + "One isolated implementation owner, two independent read-only reviewers; root owns planning/integration. Dependencies F05/D01/P01 committed; ADR003 approved.", + "Internal prepared-bar replay only. Frozen D01 adaptation and public NAPI sessions stay F07; TypeScript strategy state/RNG stays S01; metrics F08. No active legacy cutover.", + "Pin true session initialization, late-data mark/volume handling, series tie breaks, shared coordinator barrier revision, terminal failure and half-open trading bounds." + ], + "tenth_wave_validation": { + "base": "ccf333cc0ae9bcf1cc81ff6cc50099686738def2", + "integration_state": "validated_uncommitted", + "committed_prerequisites": "Owner requested all existing changes committed, producing ccf333c for F04/F05 plus planning. F06 uses that exact base without overlays.", + "repository_check": { + "command": "CARGO_BUILD_JOBS=2 bun run check", + "log": "/tmp/stock-bot-wave10.8uCLfa/integration-check.log", + "exit_code": 0, + "passed": { + "tooling": 60, + "utils": 43, + "calculations": 35, + "integration": 342, + "rust": 131 + }, + "rust_manual_benchmarks_ignored": 4, + "other_gates": "Build, typecheck, contracts, lint and secret audit passed." + }, + "independent_review": { + "timing": "/root/wave10_replay_review: accepted frozen source; independently ran debug artifact focused25passed/1ignored and full131passed/4ignored, zero failures. Reviewed completed frozen release measurement.", + "quant": "/root/wave10_quant_review: accepted frozen source; focused25passed/1ignored, zero failures; reviewed full-suite log and release measurement. No competing financial authority or future-data exposure through prefix API.", + "debug_artifact": "/tmp/stock-bot-wave10.8uCLfa/f06/target/debug/deps/engine-318becfe365f2c10", + "debug_artifact_sha256": "1e90db0aa3aeb327ac1aeb6985b47f0226c1231077d78b499e969b49b43c688f", + "coordination": "Quant focused Cargo invocation finished without recompilation before direct-binary-only coordination; subsequent timing review executed the frozen test binary. No shared/symlinked native build output between worktrees." + }, + "scoped_checks": [ + "rustfmt --edition 2021 --check --config skip_children=true on three changed financial files passed.", + "git diff --check; manifest IDs/task/ADR references, acyclic dependencies and authorized prerequisite readiness passed.", + "Integrated source hashes match the three independently reviewed files; base and previously committed financial files remain unchanged." + ], + "source_hashes": { + "apps/stock/engine/src/financial/replay.rs": "0c9d466e96549571ae29247528351058f5a91563215f5bed83cfaea0205411cf", + "apps/stock/engine/src/financial/replay_tests.rs": "3e2b150bc142f5361592328f807a5e577732bc515a3d38ca525bed8e52952ee4", + "apps/stock/engine/src/financial/mod.rs": "6c90bd6ec2bd2702f9c9e3a13c226e3578749c83cd2b06dcdb51dd6aceb3bb90" + }, + "native_artifact": { + "path": "apps/stock/engine/dist/engine.node", + "sha256": "26c323c45ab947146db71424008406ae37c6603293ed46b8b81cda80c1d2fd95", + "note": "Built from integrated checkout; native API still uses legacy simulator." + }, + "measurement": { + "command": "CARGO_BUILD_JOBS=2 cargo test -p engine --lib --release --offline replay_scaling_measurement -- --ignored --nocapture", + "author_log": "/tmp/stock-bot-wave10.8uCLfa/f06-replay-release-frozen.log", + "integrated_log": "/tmp/stock-bot-wave10.8uCLfa/integration-replay-release.log", + "result": "1 passed,0 failed;134 filtered. Author and integrated frozen builds passed18 rows each; earlier ledger/risk/matching manual measurements not repeated.", + "artifact": "target/release/deps/engine-abe56cbc3e15ae30", + "artifact_sha256": "0d20d304471e0f780b72f133ceefb120a5f3f20becb3b5042137efeb46b29f73", + "host": "AMD Ryzen9 9950X3D; Linux6.8 x86_64; Rust/Cargo1.88.0; build jobs2. Author/integrated release artifact hashes match.", + "workload": "1/2assets with1k/10k/100k total execution bars plus1feature/cadence row;3repeats, no explicit warmup. Exactly1decision/buy/fill quantity1@10,fee0.1,initialcapital10000; remaining traversal performs marks/open events. Fixed synthetic10ms bars exercise internal prepared cursor, not D01 interval normalization.", + "timing": "Input generation/cloning excluded. Load includes canonicalization/validation/event sorting/exact binding serialization. Traversal includes fixture decision construction and matcher marks/journals. Checkpoint copy and restore separately timed; restore includes new/load/fixed-trace replay and full checkpoint validation copy. Output serialization excluded.", + "equality": "Expected cash9989.9/equity9999.9 and one accepted fill asserted. Full checkpoint bytes identical across3repeats per fixture; restored checkpoint equal. Ordinary permutation regressions also compare full checkpoints. No cross-platform determinism claim.", + "raw_integrated_rows": [ + "replay instruments=1 execution_bars=1000 total_bars=1001 repeat=0 load_us=808 replay_us=10823 checkpoint_us=3512 restore_us=14572 checkpoint_bytes=4204033 fills=1", + "replay instruments=1 execution_bars=1000 total_bars=1001 repeat=1 load_us=662 replay_us=9907 checkpoint_us=1736 restore_us=14115 checkpoint_bytes=4204033 fills=1", + "replay instruments=1 execution_bars=1000 total_bars=1001 repeat=2 load_us=766 replay_us=9337 checkpoint_us=1582 restore_us=12684 checkpoint_bytes=4204033 fills=1", + "replay instruments=1 execution_bars=10000 total_bars=10001 repeat=0 load_us=7004 replay_us=108708 checkpoint_us=37550 restore_us=160897 checkpoint_bytes=42449082 fills=1", + "replay instruments=1 execution_bars=10000 total_bars=10001 repeat=1 load_us=6876 replay_us=101074 checkpoint_us=26523 restore_us=151922 checkpoint_bytes=42449082 fills=1", + "replay instruments=1 execution_bars=10000 total_bars=10001 repeat=2 load_us=7099 replay_us=99939 checkpoint_us=24254 restore_us=149012 checkpoint_bytes=42449082 fills=1", + "replay instruments=1 execution_bars=100000 total_bars=100001 repeat=0 load_us=78537 replay_us=1062133 checkpoint_us=338708 restore_us=1631855 checkpoint_bytes=429579131 fills=1", + "replay instruments=1 execution_bars=100000 total_bars=100001 repeat=1 load_us=77106 replay_us=1113410 checkpoint_us=288906 restore_us=1546489 checkpoint_bytes=429579131 fills=1", + "replay instruments=1 execution_bars=100000 total_bars=100001 repeat=2 load_us=76279 replay_us=1061281 checkpoint_us=277388 restore_us=1556940 checkpoint_bytes=429579131 fills=1", + "replay instruments=2 execution_bars=1000 total_bars=1001 repeat=0 load_us=721 replay_us=8325 checkpoint_us=1334 restore_us=11212 checkpoint_bytes=4200000 fills=1", + "replay instruments=2 execution_bars=1000 total_bars=1001 repeat=1 load_us=697 replay_us=8090 checkpoint_us=1246 restore_us=11194 checkpoint_bytes=4200000 fills=1", + "replay instruments=2 execution_bars=1000 total_bars=1001 repeat=2 load_us=721 replay_us=7795 checkpoint_us=1207 restore_us=10951 checkpoint_bytes=4200000 fills=1", + "replay instruments=2 execution_bars=10000 total_bars=10001 repeat=0 load_us=7768 replay_us=87483 checkpoint_us=25049 restore_us=140364 checkpoint_bytes=42419059 fills=1", + "replay instruments=2 execution_bars=10000 total_bars=10001 repeat=1 load_us=7793 replay_us=87431 checkpoint_us=25305 restore_us=136945 checkpoint_bytes=42419059 fills=1", + "replay instruments=2 execution_bars=10000 total_bars=10001 repeat=2 load_us=7667 replay_us=87640 checkpoint_us=26653 restore_us=138028 checkpoint_bytes=42419059 fills=1", + "replay instruments=2 execution_bars=100000 total_bars=100001 repeat=0 load_us=84055 replay_us=958878 checkpoint_us=286388 restore_us=1422346 checkpoint_bytes=429289118 fills=1", + "replay instruments=2 execution_bars=100000 total_bars=100001 repeat=1 load_us=83135 replay_us=906061 checkpoint_us=275798 restore_us=1394171 checkpoint_bytes=429289118 fills=1", + "replay instruments=2 execution_bars=100000 total_bars=100001 repeat=2 load_us=85020 replay_us=961257 checkpoint_us=278030 restore_us=1421355 checkpoint_bytes=429289118 fills=1" + ], + "limits": "One-fill canonical Rust component workload, not order-heavy TS/NAPI, storage, batch or cold-process throughput; no speedup claim. Preparation O(n log n); event traversal linear plus existing matching/risk/map/journal work. Serialized full checkpoint~4.2/42.4/429MB at1k/10k/100k, not RSS. Journals/history retained; no compaction." + }, + "not_run": [ + "Disposable PostgreSQL/Redis, browser and Python suites: persistence/API/UI/Python boundaries unchanged." + ], + "limitations": [ + "Trusted prepared bars/session tables, not frozen D01 admission. F07 must verify/adapt dataset hashes, decimals, calendars, execution selection, eligibility and limitations.", + "Quote replay and abutting same-series venue sessions reject. Internal synthetic test intervals are not a new persisted dataset timeframe.", + "Sequential equal-time marks can latch intermediate daily/drawdown halts despite recovered synchronized equity. Explicit regression/model limitation; canonical_release_gates.multi_asset_mark_policy remains unresolved before R05 multi-asset default.", + "Event budgets bound count, not wall time. No mutable matcher access, but host APIs are not untrusted-code security boundaries; F07 must not expose checkpoints/full prepared data to strategies.", + "Checkpoints bind exact canonical input/config content and validate fixed decision replay; not authenticated provenance, arbitrary TS determinism or strategy/RNG recomputation.", + "Event-index-derived IDs can differ when a feature dataset changes; unused-feature tests compare unchanged economic/cadence behavior, not IDs across different bindings.", + "No active simulator, NAPI, SQL/paper or web cutover. Existing build warnings remain." + ], + "handoff": "F04/F05 committed ccf333c at owner request. F06 independently reviewed and validated, uncommitted. Next after acceptance: F07 verified dataset/native pull adapter; F08 result projection may follow with coordinated contracts. No push, PR, other task implementation or trading operation.", + "cleanup": "No services/data removed; isolated worktree and logs retained." } } diff --git a/docs/development/backlog/tasks/F06.md b/docs/development/backlog/tasks/F06.md index a8f48f2f..434897ca 100644 --- a/docs/development/backlog/tasks/F06.md +++ b/docs/development/backlog/tasks/F06.md @@ -16,6 +16,16 @@ Implement the replay cursor once: sorted immutable events with stable availabili Consume F05's explicit event contract without reconstructing a second matcher: quote observation time is not delivery time, and eligibility requires an order to be ready by physical quote time. Open time must equal its execution key; skip/reject missed opens, never relabel them as newly occurring. Decision admission uses the coordinator's shared portfolio/order revision, distinct from the nested economic ledger revision. Terminal F05 failures retain diagnostic prefixes but must fail/discard the replay attempt, never produce successful performance results. +## Execution handoff clarifications + +- Add an internal prepared-input cursor over MatchingAccount, not a second public session API or a legacy-runtime cutover. D01 currently has bar datasets only: reject quote-mode replay input until a quote dataset contract exists. Existing F05 quote tests remain relevant matcher evidence, not a claim of quote replay support. +- Accept typed prepared bars with canonical decimals and retained session boundaries. Document that F07 must verify/adapt the frozen D01 snapshot; do not duplicate the TS normalizer/hash algorithm. Validate executable-series/config agreement, raw execution prices, bounds and eligibility; retain exploratory limitations. Bind checkpoints to the exact prepared input/config, not only a caller-supplied dataset label. +- Initialize using true venue open times, including the preceding open for a mid-session warmup/start. Never restamp missed opens. Publish late observations without regressing authoritative mark time; capacity uses the physically latest completed available execution-series volume, not latest arrival or future volume. +- Resolve feature-series sequence ties with stable series identity. Only declared cadence triggers decisions; due owners share one immutable context/revision. Warmup cannot trade; observations at tradeEnd may mark only; later observations are unavailable. +- Internal barrier/cursor/checkpoint and fixed decision-trace replay belong here. Public NAPI session protocol, frozen dataset transport, TS strategy state/RNG and strategy recomputation belong to F07/S01. Prefer offset-based observation prefixes to copying all history on every advance. +- Sorting may be O(n log n); traversal is linear plus matching/risk work. Measure 1k/10k/100k release workloads with economics equality and explicit load/replay timing. This is a canonical Rust component measurement, not TS callback or end-to-end research throughput. +- Existing F04/F05 policy evaluates risk after each mark. Equal-time cross-asset marks are applied in deterministic instrument order, not atomically: an intermediate portfolio value can latch a loss/drawdown halt even when the final same-time valuation recovers. Pin this behavior with a permutation regression and disclose it as a modeling limitation. Do not implement an F06-local risk bypass or silently introduce atomic marking; changing that economic policy requires coordinated approval and fixtures. + ## Exclusions No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results. @@ -47,6 +57,7 @@ Parallel eligibility: only with disjoint actual files and reserved write locks; - adjacent_open_zero_latency, positive_latency_skips_open, future_ohlcv_does_not_change_open_fill, daily_close_target_survives_to_open. - feature_timeframe_does_not_duplicate_liquidity, equal_timestamp_symbol_permutation, warmup_cannot_trade, stale_mark_timestamp_preserved. - Replay/restore trace equality. Extend P01 with1k/10k/100k release-build load/replay scaling; preserve economics before accepting faster runs. +- Delayed older observations do not regress marks/capacity; mid-session starts retain true session boundaries; terminal observations are mark-only; equal-time feature-series sequence ties are stable; altered input/config checkpoint restore rejects. Apply relevant [quality gates](../../QUALITY-GATES.md). Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests. diff --git a/docs/development/backlog/tasks/F07.md b/docs/development/backlog/tasks/F07.md index c57e5112..13ec30d6 100644 --- a/docs/development/backlog/tasks/F07.md +++ b/docs/development/backlog/tasks/F07.md @@ -12,7 +12,11 @@ Scheduling source of truth: [manifest entry F07](../manifest.json). No task is a ## Intended behavior and implementation scope -Expose a small pull session (load/create/advance/submit/finalize/dispose) in the existing worker, backed by the same financial kernel. advance returns a tagged union: progress, decision batch, or complete. For a decision batch, all due strategies receive immutable views from the same ledger revision; collect all decisions before ordered admission. Use one native test strategy/intent trace for conformance, not a port of every Rust built-in. Per-session dataset load once; cross-trial residency is P03. +Expose a small pull session (load/create/advance/submit/finalize/dispose) in the existing worker, backed by the same financial kernel. advance returns a tagged union: progress, decision batch, or complete. For a decision batch, all due strategies receive the same immutable financial view; collect all decisions before ordered admission. The submission token is F05/F06's coordinator admission revision, not the nested ledger snapshot revision (reservations and order state can change without an economic posting). Use one native test strategy/intent trace for conformance, not a port of every Rust built-in. Per-session dataset load once; cross-trial residency is P03. + +F06 consumes internal typed prepared bars/session tables, not an independently authenticated D01 snapshot. This adapter must verify the frozen v2 dataset with the existing normalizer/hash verifier, preserve its hash/eligibility/limitations, convert numeric fields through canonical decimal ingress, and map exact calendars/execution series/bounds into F06. Do not trust a supplied hash label alone or reconstruct a competing normalizer. Quote replay stays unsupported until its dataset contract is explicitly added. Retain prefix-only strategy contexts; do not expose native full-dataset/checkpoint host handles to strategy callbacks. + +Expose recorded model limitations, including F06's explicitly unsupported abutting venue sessions and F04/F05's sequential equal-time portfolio marks (intermediate valuations can latch risk halts). An event budget bounds event count, not wall time or the cost of an individual matching transition. These are not promises of atomic multi-asset valuation, arbitrary-calendar support or constant-latency cancellation. ## Exclusions diff --git a/docs/development/backlog/tasks/F08.md b/docs/development/backlog/tasks/F08.md index f2c11048..3188cf47 100644 --- a/docs/development/backlog/tasks/F08.md +++ b/docs/development/backlog/tasks/F08.md @@ -48,6 +48,7 @@ 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. +- 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 diff --git a/docs/development/backlog/tasks/R05.md b/docs/development/backlog/tasks/R05.md index f7b7f9d8..c86e5e2d 100644 --- a/docs/development/backlog/tasks/R05.md +++ b/docs/development/backlog/tasks/R05.md @@ -42,11 +42,13 @@ Parallel eligibility: only with disjoint actual files and reserved write locks; - Changing template, strategy source or provider history after dataset freezing cannot alter an admitted run. A source query alone is not labelled a frozen dataset. - No strategy decision executes before artifact verification and atomic dataset binding; failed preparation remains diagnosed and retry-safe. - New results declare financialEngine=rust and strategyExecution separately; correctness-gate evidence requires approved engine/data gates, not a UI flag. +- Before making canonical multi-asset research the default, obtain explicit owner disposition of sequential equal-time mark risk: either accept the disclosed versioned approximation or approve a coordinated atomic-mark policy/implementation with independent fixtures. F04/F05 currently evaluate each ordered mark; F06 demonstrates offsetting simultaneous moves can latch intermediate loss/drawdown halts. A passing deterministic replay suite alone does not resolve this material modeling issue. Single-asset component work and additive native integration need not wait for this decision. ## Mandatory tests - 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. +- 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.