From b65acccd91c15a7fd82536c0c6b3a65e01055113 Mon Sep 17 00:00:00 2001 From: Boki Date: Thu, 22 Oct 2026 21:16:53 -0400 Subject: [PATCH] feat(research): add owner-aware ledger and intraday storage Implement reviewed F02/D02: exact owner accounting, atomic funding checks, idempotent receipts and ledger checkpoints; connect existing EOD intraday storage through validated research admission without active financial-engine cutover. --- Cargo.lock | 14 + apps/stock/engine/Cargo.toml | 97 +- apps/stock/engine/src/financial/contract.rs | 2 +- apps/stock/engine/src/financial/ledger.rs | 695 ++++++++++++++ .../engine/src/financial/ledger_tests.rs | 903 ++++++++++++++++++ apps/stock/engine/src/financial/mod.rs | 4 + apps/stock/engine/src/financial/scalar.rs | 68 +- .../src/services/StorageService.ts | 201 +++- docs/development/ROADMAP.md | 30 +- docs/development/backlog/README.md | 10 +- docs/development/backlog/manifest.json | 276 +++++- docs/development/backlog/tasks/D02.md | 10 + docs/development/backlog/tasks/F02.md | 10 + test/fixtures/intraday/eod.ts | 72 ++ test/integration/intraday-storage.test.ts | 416 ++++++++ 15 files changed, 2704 insertions(+), 104 deletions(-) create mode 100644 apps/stock/engine/src/financial/ledger.rs create mode 100644 apps/stock/engine/src/financial/ledger_tests.rs create mode 100644 test/fixtures/intraday/eod.ts create mode 100644 test/integration/intraday-storage.test.ts diff --git a/Cargo.lock b/Cargo.lock index 54d03558..2232d094 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -255,6 +255,9 @@ dependencies = [ "napi", "napi-build", "napi-derive", + "num-bigint", + "num-rational", + "num-traits", "parking_lot", "rand", "rand_distr", @@ -562,6 +565,16 @@ dependencies = [ "winapi", ] +[[package]] +name = "num-bigint" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" +dependencies = [ + "num-integer", + "num-traits", +] + [[package]] name = "num-complex" version = "0.4.6" @@ -586,6 +599,7 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" dependencies = [ + "num-bigint", "num-integer", "num-traits", ] diff --git a/apps/stock/engine/Cargo.toml b/apps/stock/engine/Cargo.toml index e189ded6..dbea6685 100644 --- a/apps/stock/engine/Cargo.toml +++ b/apps/stock/engine/Cargo.toml @@ -1,48 +1,51 @@ -[package] -name = "engine" -version = "0.1.0" -edition = "2021" - -[lib] -crate-type = ["cdylib", "rlib"] - -[dependencies] -# Core dependencies -chrono = { version = "0.4", features = ["serde"] } -serde = { version = "1.0", features = ["derive"] } -serde_json = "1.0" -thiserror = "1.0" -anyhow = "1.0" -uuid = { version = "1.0", features = ["v4", "serde"] } - -# Data structures -dashmap = "5.5" -parking_lot = "0.12" -crossbeam = "0.8" - -# Async runtime -tokio = { version = "1", features = ["full"] } -async-trait = "0.1" - -# NAPI for Node.js bindings -napi = { version = "2", features = ["async", "chrono_date", "serde-json"] } -napi-derive = "2" - -# Math and statistics +[package] +name = "engine" +version = "0.1.0" +edition = "2021" + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +# Core dependencies +chrono = { version = "0.4", features = ["serde"] } +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +thiserror = "1.0" +anyhow = "1.0" +uuid = { version = "1.0", features = ["v4", "serde"] } + +# Data structures +dashmap = "5.5" +parking_lot = "0.12" +crossbeam = "0.8" + +# Async runtime +tokio = { version = "1", features = ["full"] } +async-trait = "0.1" + +# NAPI for Node.js bindings +napi = { version = "2", features = ["async", "chrono_date", "serde-json"] } +napi-derive = "2" + +# Math and statistics rust_decimal = { version = "=1.43.0", default-features = false } -statrs = "0.16" -rand = "0.8" -rand_distr = "0.4" -nalgebra = "0.32" - -# Logging -tracing = "0.1" -tracing-subscriber = "0.3" - -[build-dependencies] -napi-build = "2" - -[profile.release] -lto = true -opt-level = 3 -codegen-units = 1 \ No newline at end of file +num-bigint = "=0.4.6" +num-rational = "=0.4.2" +num-traits = "=0.2.19" +statrs = "0.16" +rand = "0.8" +rand_distr = "0.4" +nalgebra = "0.32" + +# Logging +tracing = "0.1" +tracing-subscriber = "0.3" + +[build-dependencies] +napi-build = "2" + +[profile.release] +lto = true +opt-level = 3 +codegen-units = 1 diff --git a/apps/stock/engine/src/financial/contract.rs b/apps/stock/engine/src/financial/contract.rs index bcc70dda..368459fd 100644 --- a/apps/stock/engine/src/financial/contract.rs +++ b/apps/stock/engine/src/financial/contract.rs @@ -6,7 +6,7 @@ use serde::{de, Deserialize, Deserializer, Serialize}; const MAX_SAFE_INTEGER: i64 = 9_007_199_254_740_991; -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)] #[serde(transparent)] pub struct Id(String); diff --git a/apps/stock/engine/src/financial/ledger.rs b/apps/stock/engine/src/financial/ledger.rs new file mode 100644 index 00000000..2c3ab6de --- /dev/null +++ b/apps/stock/engine/src/financial/ledger.rs @@ -0,0 +1,695 @@ +//! Additive, cash-funded long-only economic kernel. Not wired to a legacy +//! simulator, NAPI, paper persistence, order matching or portfolio risk. +//! +//! apply() stages only the affected book/owner/instrument scalars before its +//! infallible commit. Marks touch owners of that instrument, not other books. +//! Checkpoint copying and history replay occur only at explicit boundaries. +//! Invalid internal commands return errors without receipts or state changes; +//! future F04 risk rejections are different, accepted/recorded outcomes. +use super::{ + contract::*, + scalar::{Posting, ScalarError}, +}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct LedgerConfig { + pub version: Version, + pub session_id: Id, + pub account_id: Id, + pub base_currency: Id, + pub reserve_owner_id: Id, + pub owner_ids: Vec, + pub initial_capital: NonNegative, + pub risk_session: RiskSessionIdentity, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct LedgerMark { + pub instrument_id: Id, + pub price: Positive, + pub event_time: EventTime, + pub command_id: Id, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ApplyOutcome { + /// A replay returns the ORIGINAL receipt, including original command ID, + /// event time and revision. Its deltas MUST NOT be published/applied again. + pub replayed: bool, + pub effects: FinancialEffects, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct LedgerReceipt { + pub command: EngineFinancialCommand, + pub outcome: ApplyOutcome, +} + +/// A restorable LEDGER checkpoint, not a complete engine/session checkpoint. +/// It contains no orders, reservations, risk limits/peaks, replay cursors, +/// strategy states or RNG. Identity indexes are reconstructed from receipts in +/// acceptance order (never lexical ID order). History is retained without +/// compaction in v1. Restore validates internal consistency, not authenticity +/// of the supplied genesis/history; durable provenance remains a caller duty. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct LedgerCheckpoint { + pub version: Version, + pub config: LedgerConfig, + pub economic: FinancialSnapshot, + pub marks: Vec, + pub receipts: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OwnerValuation { + pub owner_id: Id, + pub initial_capital: Posting, + pub marked_holdings: Posting, + pub remaining_cost: Posting, + pub realized_gross_pnl: Posting, + pub unrealized_pnl: Posting, + pub fees: Posting, + /// Reserve capital + realized + unrealized - fees. Not a separate cash + /// wallet or allocation limit; owner contributions may be negative. + pub equity_contribution: Posting, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LedgerValuation { + pub cash: Posting, + pub marked_holdings: Posting, + pub equity: Posting, + pub remaining_cost: Posting, + pub realized_gross_pnl: Posting, + pub unrealized_pnl: Posting, + pub fees: Posting, + pub owners: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AggregatePosition { + pub instrument_id: Id, + pub quantity: Posting, + pub remaining_cost: Posting, +} + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum LedgerError { + #[error(transparent)] + Arithmetic(#[from] ScalarError), + #[error("duplicate or reserve strategy owner in configuration")] + InvalidOwners, + #[error("command belongs to a different session/account")] + WrongScope, + #[error("command ID reused with a different payload")] + CommandConflict, + #[error("fill ID reused with a different payload or event time")] + FillConflict, + #[error("fee ID already belongs to another fill")] + FeeConflict, + #[error("order ID reused with different decision, instrument or side")] + OrderConflict, + #[error("owner is not registered or is the reserve owner")] + UnknownOwner, + #[error("owner does not have the requested inventory")] + InsufficientInventory, + #[error("cash cannot cover the fill and fee")] + InsufficientCash, + #[error("open inventory has no explicit market mark")] + MissingMark, + #[error("ledger revision exhausted safe integer range")] + RevisionOverflow, + #[error("risk session changes calendar or has an inconsistent/backward boundary")] + InvalidRiskSession, + #[error("checkpoint is inconsistent with its genesis and accepted receipts")] + InvalidCheckpoint, +} + +#[derive(Debug, Clone, Copy)] +struct Book { + quantity: Posting, + cost: Posting, + realized: Posting, +} +impl Default for Book { + fn default() -> Self { + Self { + quantity: Posting::ZERO, + cost: Posting::ZERO, + realized: Posting::ZERO, + } + } +} + +/// Cached aggregates are private and only changed by an accepted staged plan. +#[derive(Debug, Clone, Copy)] +struct Totals { + cost: Posting, + realized: Posting, + fees: Posting, + marked: Posting, + unmarked: usize, +} +impl Default for Totals { + fn default() -> Self { + Self { + cost: Posting::ZERO, + realized: Posting::ZERO, + fees: Posting::ZERO, + marked: Posting::ZERO, + unmarked: 0, + } + } +} +impl Totals { + fn owner_valuation( + self, + owner_id: Id, + capital: Posting, + ) -> Result { + if self.unmarked != 0 { + return Err(LedgerError::MissingMark); + } + let unrealized = self.marked.checked_sub(self.cost)?; + Ok(OwnerValuation { + owner_id, + initial_capital: capital, + marked_holdings: self.marked, + remaining_cost: self.cost, + realized_gross_pnl: self.realized, + unrealized_pnl: unrealized, + fees: self.fees, + equity_contribution: Posting::sum([ + capital, + self.realized, + unrealized, + negative(self.fees)?, + ])?, + }) + } +} + +#[derive(Debug)] +struct Instrument { + books: BTreeMap, + mark: Option, + quantity: Posting, + cost: Posting, + marked: Posting, +} +impl Default for Instrument { + fn default() -> Self { + Self { + books: BTreeMap::new(), + mark: None, + quantity: Posting::ZERO, + cost: Posting::ZERO, + marked: Posting::ZERO, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct OrderBinding { + decision: DecisionIdentity, + instrument_id: Id, + side: Side, +} + +/// Deliberately not Clone/Serialize: ordinary transitions cannot accidentally +/// copy or serialize the entire resident account/history. +#[derive(Debug)] +pub struct Ledger { + config: LedgerConfig, + cash: Posting, + revision: Counter, + risk_session: RiskSessionIdentity, + instruments: BTreeMap, + owners: BTreeMap, + totals: Totals, + receipts: Vec, + commands: BTreeMap, + fills: BTreeMap, + fees: BTreeMap, + orders: BTreeMap, +} + +fn negative(value: Posting) -> Result { + Posting::ZERO.checked_sub(value) +} +fn nonnegative(value: Posting) -> NonNegative { + NonNegative::try_from(value) + .expect("kernel preserves nonnegative quantities, costs, cash and fees") +} +fn replace(total: Posting, old: Posting, new: Posting) -> Result { + Posting::sum([total, negative(old)?, new]) +} + +impl Ledger { + pub fn new(mut config: LedgerConfig) -> Result { + config.owner_ids.sort(); + if config.owner_ids.windows(2).any(|w| w[0] == w[1]) + || config.owner_ids.contains(&config.reserve_owner_id) + { + return Err(LedgerError::InvalidOwners); + } + let owners = config + .owner_ids + .iter() + .cloned() + .map(|id| (id, Totals::default())) + .collect(); + Ok(Self { + cash: config.initial_capital.into(), + revision: Counter::try_from(0).expect("zero"), + risk_session: config.risk_session.clone(), + config, + owners, + instruments: BTreeMap::new(), + totals: Totals::default(), + receipts: Vec::new(), + commands: BTreeMap::new(), + fills: BTreeMap::new(), + fees: BTreeMap::new(), + orders: BTreeMap::new(), + }) + } + + pub fn apply(&mut self, command: &EngineFinancialCommand) -> Result { + if command.session_id != self.config.session_id + || command.account_id != self.config.account_id + { + return Err(LedgerError::WrongScope); + } + if let Some(index) = self.commands.get(&command.command_id) { + let receipt = &self.receipts[*index]; + if receipt.command != *command { + return Err(LedgerError::CommandConflict); + } + let mut outcome = receipt.outcome.clone(); + outcome.replayed = true; + return Ok(outcome); + } + if let EngineCommandBody::ApplyFill { fill_id, .. } = &command.body { + if let Some(index) = self.fills.get(fill_id) { + let receipt = &self.receipts[*index]; + if receipt.command.body != command.body + || receipt.command.event_time != command.event_time + { + return Err(LedgerError::FillConflict); + } + let mut outcome = receipt.outcome.clone(); + outcome.replayed = true; + self.record(command, outcome.clone()); + return Ok(outcome); + } + } + let revision = Counter::try_from(self.revision.get() + 1) + .map_err(|_| LedgerError::RevisionOverflow)?; + // Each method performs all fallible checks/calculations before writing. + let effects = match &command.body { + EngineCommandBody::ApplyFill { .. } => self.apply_fill(command)?, + EngineCommandBody::Mark { + instrument_id, + price, + } => self.apply_mark(command, instrument_id, *price)?, + EngineCommandBody::RiskSessionBoundary { risk_session } => { + if risk_session.calendar_id != self.config.risk_session.calendar_id + || risk_session.calendar_revision != self.config.risk_session.calendar_revision + || risk_session.starts_at.get() < self.risk_session.starts_at.get() + || (risk_session.session_id == self.risk_session.session_id + && risk_session.starts_at != self.risk_session.starts_at) + || (risk_session.session_id != self.risk_session.session_id + && risk_session.starts_at == self.risk_session.starts_at) + { + return Err(LedgerError::InvalidRiskSession); + } + // Identity only. F04 owns baseline/peak/halt policies. + if self.risk_session == *risk_session { + Vec::new() + } else { + self.risk_session = risk_session.clone(); + vec![FinancialEffect::RiskSessionChanged { + risk_session: risk_session.clone(), + }] + } + } + }; + self.revision = revision; + let outcome = ApplyOutcome { + replayed: false, + effects: FinancialEffects { + version: Version, + session_id: self.config.session_id.clone(), + account_id: self.config.account_id.clone(), + command_id: command.command_id.clone(), + event_time: command.event_time, + revision, + effects, + }, + }; + self.record(command, outcome.clone()); + Ok(outcome) + } + + fn record(&mut self, command: &EngineFinancialCommand, outcome: ApplyOutcome) { + self.commands + .insert(command.command_id.clone(), self.receipts.len()); + self.receipts.push(LedgerReceipt { + command: command.clone(), + outcome, + }); + } + + fn apply_fill( + &mut self, + command: &EngineFinancialCommand, + ) -> Result, LedgerError> { + let EngineCommandBody::ApplyFill { + decision, + order_id, + fill_id, + instrument_id, + side, + quantity, + price, + fee, + } = &command.body + else { + unreachable!("fill dispatch") + }; + let owner = self + .owners + .get(&decision.owner_id) + .copied() + .ok_or(LedgerError::UnknownOwner)?; + if self.fees.contains_key(&fee.fee_id) { + return Err(LedgerError::FeeConflict); + } + let binding = OrderBinding { + decision: decision.clone(), + instrument_id: instrument_id.clone(), + side: *side, + }; + if self + .orders + .get(order_id) + .is_some_and(|stored| *stored != binding) + { + return Err(LedgerError::OrderConflict); + } + let instrument = self.instruments.get(instrument_id); + let old = instrument + .and_then(|i| i.books.get(&decision.owner_id)) + .copied() + .unwrap_or_default(); + let quantity: Posting = (*quantity).into(); + let fee_amount: Posting = fee.amount.into(); + let notional = Posting::notional(quantity, (*price).into())?; + let (book, cash_delta, quantity_delta, released_basis, realized) = match side { + Side::Buy => ( + Book { + quantity: old.quantity.checked_add(quantity)?, + cost: old.cost.checked_add(notional)?, + realized: old.realized, + }, + negative(notional)?, + quantity, + Posting::ZERO, + Posting::ZERO, + ), + Side::Sell => { + if quantity > old.quantity { + return Err(LedgerError::InsufficientInventory); + } + let basis = Posting::released_basis(old.cost, quantity, old.quantity)?; + let realized = notional.checked_sub(basis)?; + ( + Book { + quantity: old.quantity.checked_sub(quantity)?, + cost: old.cost.checked_sub(basis)?, + realized: old.realized.checked_add(realized)?, + }, + notional, + negative(quantity)?, + basis, + realized, + ) + } + }; + let cash = Posting::sum([self.cash, cash_delta, negative(fee_amount)?])?; + if cash.is_negative() { + return Err(LedgerError::InsufficientCash); + } + let mark = instrument.and_then(|i| i.mark.as_ref()); + let old_value = match mark { + Some(m) => Posting::notional(old.quantity, m.price.into())?, + None => Posting::ZERO, + }; + let new_value = match mark { + Some(m) => Posting::notional(book.quantity, m.price.into())?, + None => Posting::ZERO, + }; + let old_unmarked = usize::from(mark.is_none() && !old.quantity.is_zero()); + let new_unmarked = usize::from(mark.is_none() && !book.quantity.is_zero()); + let update = |totals: Totals| -> Result { + Ok(Totals { + cost: replace(totals.cost, old.cost, book.cost)?, + realized: totals.realized.checked_add(realized)?, + fees: totals.fees.checked_add(fee_amount)?, + marked: replace(totals.marked, old_value, new_value)?, + unmarked: totals.unmarked - old_unmarked + new_unmarked, + }) + }; + let owner = update(owner)?; + let totals = update(self.totals)?; + // Even partial known holdings plus cash cannot exceed representable equity. + cash.checked_add(totals.marked)?; + if owner.unmarked == 0 { + owner.owner_valuation(decision.owner_id.clone(), Posting::ZERO)?; + } + let aggregate_quantity = replace( + instrument.map(|i| i.quantity).unwrap_or(Posting::ZERO), + old.quantity, + book.quantity, + )?; + let aggregate_cost = replace( + instrument.map(|i| i.cost).unwrap_or(Posting::ZERO), + old.cost, + book.cost, + )?; + let aggregate_marked = replace( + instrument.map(|i| i.marked).unwrap_or(Posting::ZERO), + old_value, + new_value, + )?; + let effects = vec![ + FinancialEffect::FillApplied { + owner_id: decision.owner_id.clone(), + order_id: order_id.clone(), + fill_id: fill_id.clone(), + instrument_id: instrument_id.clone(), + price: *price, + cash_delta, + quantity_delta, + released_basis: nonnegative(released_basis), + realized_gross_pnl: realized, + }, + FinancialEffect::FeeApplied { + owner_id: decision.owner_id.clone(), + fill_id: fill_id.clone(), + fee_id: fee.fee_id.clone(), + amount: fee.amount, + }, + ]; + // Infallible commit: no financial arithmetic after this point. + let instrument = self.instruments.entry(instrument_id.clone()).or_default(); + instrument.books.insert(decision.owner_id.clone(), book); + instrument.quantity = aggregate_quantity; + instrument.cost = aggregate_cost; + instrument.marked = aggregate_marked; + self.owners.insert(decision.owner_id.clone(), owner); + self.cash = cash; + self.totals = totals; + self.fills.insert(fill_id.clone(), self.receipts.len()); + self.fees.insert(fee.fee_id.clone(), fill_id.clone()); + self.orders.insert(order_id.clone(), binding); + Ok(effects) + } + + fn apply_mark( + &mut self, + command: &EngineFinancialCommand, + instrument_id: &Id, + price: Positive, + ) -> Result, LedgerError> { + let instrument = self.instruments.get(instrument_id); + let mut marked = Posting::ZERO; + let mut owners = Vec::new(); + let mut totals = self.totals; + if let Some(instrument) = instrument { + for (owner_id, book) in &instrument.books { + let old_value = match &instrument.mark { + Some(mark) => Posting::notional(book.quantity, mark.price.into())?, + None => Posting::ZERO, + }; + let value = Posting::notional(book.quantity, price.into())?; + marked = marked.checked_add(value)?; + let mut owner = self.owners[owner_id]; + owner.marked = replace(owner.marked, old_value, value)?; + if instrument.mark.is_none() && !book.quantity.is_zero() { + owner.unmarked -= 1; + totals.unmarked -= 1; + } + if owner.unmarked == 0 { + owner.owner_valuation(owner_id.clone(), Posting::ZERO)?; + } + owners.push((owner_id.clone(), owner)); + } + } + totals.marked = replace( + totals.marked, + instrument.map(|i| i.marked).unwrap_or(Posting::ZERO), + marked, + )?; + self.cash.checked_add(totals.marked)?; + let mark = LedgerMark { + instrument_id: instrument_id.clone(), + price, + event_time: command.event_time, + command_id: command.command_id.clone(), + }; + let effects = vec![FinancialEffect::MarkUpdated { + instrument_id: instrument_id.clone(), + price, + }]; + let instrument = self.instruments.entry(instrument_id.clone()).or_default(); + instrument.mark = Some(mark); + instrument.marked = marked; + for (owner_id, owner) in owners { + self.owners.insert(owner_id, owner); + } + self.totals = totals; + Ok(effects) + } + + /// Explicit marks retain their event time. Commands apply in caller arrival + /// order, including backdated marks; F06 owns monotonic replay admission and + /// F04 owns stale-price checks. A fill never substitutes its price for a mark. + pub fn mark(&self, instrument_id: &Id) -> Option<&LedgerMark> { + self.instruments + .get(instrument_id) + .and_then(|i| i.mark.as_ref()) + } + + pub fn aggregate_positions(&self) -> Vec { + self.instruments + .iter() + .filter(|(_, i)| !i.books.is_empty()) + .map(|(id, i)| AggregatePosition { + instrument_id: id.clone(), + quantity: i.quantity, + remaining_cost: i.cost, + }) + .collect() + } + + pub fn economic_snapshot(&self) -> FinancialSnapshot { + FinancialSnapshot { + version: Version, + session_id: self.config.session_id.clone(), + account_id: self.config.account_id.clone(), + revision: self.revision, + base_currency: self.config.base_currency.clone(), + reserve_owner_id: self.config.reserve_owner_id.clone(), + cash: nonnegative(self.cash), + positions: self + .instruments + .iter() + .flat_map(|(instrument_id, instrument)| { + instrument + .books + .iter() + .map(|(owner_id, book)| OwnerPosition { + owner_id: owner_id.clone(), + instrument_id: instrument_id.clone(), + quantity: nonnegative(book.quantity), + remaining_cost: nonnegative(book.cost), + realized_gross_pnl: book.realized, + }) + }) + .collect(), + fees: self + .owners + .iter() + .map(|(owner_id, totals)| OwnerFees { + owner_id: owner_id.clone(), + amount: nonnegative(totals.fees), + }) + .collect(), + risk_session: self.risk_session.clone(), + } + } + + pub fn valuation(&self) -> Result { + if self.totals.unmarked != 0 { + return Err(LedgerError::MissingMark); + } + let mut owners = vec![Totals::default().owner_valuation( + self.config.reserve_owner_id.clone(), + self.config.initial_capital.into(), + )?]; + for (owner_id, totals) in &self.owners { + owners.push(totals.owner_valuation(owner_id.clone(), Posting::ZERO)?); + } + owners.sort_by(|a, b| a.owner_id.cmp(&b.owner_id)); + Ok(LedgerValuation { + cash: self.cash, + marked_holdings: self.totals.marked, + equity: self.cash.checked_add(self.totals.marked)?, + remaining_cost: self.totals.cost, + realized_gross_pnl: self.totals.realized, + unrealized_pnl: self.totals.marked.checked_sub(self.totals.cost)?, + fees: self.totals.fees, + owners, + }) + } + + pub fn checkpoint(&self) -> LedgerCheckpoint { + LedgerCheckpoint { + version: Version, + config: self.config.clone(), + economic: self.economic_snapshot(), + marks: self + .instruments + .values() + .filter_map(|i| i.mark.clone()) + .collect(), + receipts: self.receipts.clone(), + } + } + + pub fn restore(checkpoint: LedgerCheckpoint) -> Result { + let mut ledger = + Self::new(checkpoint.config.clone()).map_err(|_| LedgerError::InvalidCheckpoint)?; + for receipt in &checkpoint.receipts { + let outcome = ledger + .apply(&receipt.command) + .map_err(|_| LedgerError::InvalidCheckpoint)?; + if outcome != receipt.outcome { + return Err(LedgerError::InvalidCheckpoint); + } + } + if ledger.checkpoint() != checkpoint { + return Err(LedgerError::InvalidCheckpoint); + } + Ok(ledger) + } +} diff --git a/apps/stock/engine/src/financial/ledger_tests.rs b/apps/stock/engine/src/financial/ledger_tests.rs new file mode 100644 index 00000000..9bf8b0b7 --- /dev/null +++ b/apps/stock/engine/src/financial/ledger_tests.rs @@ -0,0 +1,903 @@ +use super::{ + contract::*, + ledger::*, + scalar::{Posting, ScalarError, MAX_POSTING}, +}; +use rand::{rngs::StdRng, Rng, SeedableRng}; +use serde_json::{json, Value}; +use std::{ + collections::hash_map::DefaultHasher, + hash::{Hash, Hasher}, + time::Instant, +}; + +fn p(value: &str) -> Posting { + value.parse().unwrap() +} +fn id(value: &str) -> Id { + serde_json::from_value(json!(value)).unwrap() +} +fn config(capital: &str) -> LedgerConfig { + serde_json::from_value(json!({ + "version":1,"sessionId":"research:run-1","accountId":"account-1","baseCurrency":"USD", + "reserveOwnerId":"reserve","ownerIds":["strategy:B","strategy:A","strategy:C"],"initialCapital":capital, + "riskSession":{"calendarId":"XNYS","calendarRevision":"2026-01","sessionId":"day-1","startsAt":0} + })).unwrap() +} +fn ledger(capital: &str) -> Ledger { + Ledger::new(config(capital)).unwrap() +} +fn command(command_id: &str, body: Value) -> EngineFinancialCommand { + serde_json::from_value( + json!({"version":1,"sessionId":"research:run-1","accountId":"account-1", + "commandId":command_id,"eventTime":100,"body":body}), + ) + .unwrap() +} +fn fill( + n: usize, + owner: &str, + instrument: &str, + side: &str, + quantity: &str, + price: &str, + fee: &str, +) -> EngineFinancialCommand { + command( + &format!("command-{n}"), + json!({"kind":"applyFill", + "decision":{"ownerId":owner,"decisionId":format!("decision-{n}"),"sequence":n}, + "orderId":format!("order-{n}"),"fillId":format!("fill-{n}"),"instrumentId":instrument, + "side":side,"quantity":quantity,"price":price,"fee":{"feeId":format!("fee-{n}"),"amount":fee}}), + ) +} +fn mark(n: usize, instrument: &str, price: &str) -> EngineFinancialCommand { + command( + &format!("mark-{n}"), + json!({"kind":"mark","instrumentId":instrument,"price":price}), + ) +} +fn assert_unchanged(ledger: &mut Ledger, command: EngineFinancialCommand, expected: LedgerError) { + let before = ledger.checkpoint(); + assert_eq!(ledger.apply(&command), Err(expected)); + assert_eq!(ledger.checkpoint(), before); +} +fn reconcile(ledger: &Ledger) { + let value = ledger.valuation().unwrap(); + assert_eq!( + value.equity, + value.cash.checked_add(value.marked_holdings).unwrap() + ); + let capital: Posting = ledger.checkpoint().config.initial_capital.into(); + assert_eq!( + value.equity, + Posting::sum([ + capital, + value.realized_gross_pnl, + value.unrealized_pnl, + Posting::ZERO.checked_sub(value.fees).unwrap() + ]) + .unwrap() + ); + assert_eq!( + value.equity, + Posting::sum(value.owners.iter().map(|o| o.equity_contribution)).unwrap() + ); + assert_eq!( + value.marked_holdings, + Posting::sum(value.owners.iter().map(|o| o.marked_holdings)).unwrap() + ); + assert_eq!( + value.remaining_cost, + Posting::sum(value.owners.iter().map(|o| o.remaining_cost)).unwrap() + ); + assert_eq!( + value.realized_gross_pnl, + Posting::sum(value.owners.iter().map(|o| o.realized_gross_pnl)).unwrap() + ); + assert_eq!( + value.fees, + Posting::sum(value.owners.iter().map(|o| o.fees)).unwrap() + ); + let snapshot = ledger.economic_snapshot(); + assert_eq!(value.cash, Posting::from(snapshot.cash)); + assert_eq!( + value.remaining_cost, + Posting::sum(snapshot.positions.iter().map(|b| b.remaining_cost.into())).unwrap() + ); + assert_eq!( + value.realized_gross_pnl, + Posting::sum(snapshot.positions.iter().map(|b| b.realized_gross_pnl)).unwrap() + ); + assert_eq!( + value.fees, + Posting::sum(snapshot.fees.iter().map(|f| f.amount.into())).unwrap() + ); + let book_value = |book: &OwnerPosition| { + let quantity: Posting = book.quantity.into(); + if quantity.is_zero() { + Posting::ZERO + } else { + Posting::notional( + quantity, + ledger + .mark(&book.instrument_id) + .expect("open inventory requires an explicit mark") + .price + .into(), + ) + .unwrap() + } + }; + assert_eq!( + value.marked_holdings, + Posting::sum(snapshot.positions.iter().map(book_value)).unwrap() + ); + for owner in &value.owners { + let books: Vec<_> = snapshot + .positions + .iter() + .filter(|b| b.owner_id == owner.owner_id) + .collect(); + assert_eq!( + owner.remaining_cost, + Posting::sum(books.iter().map(|b| b.remaining_cost.into())).unwrap() + ); + assert_eq!( + owner.realized_gross_pnl, + Posting::sum(books.iter().map(|b| b.realized_gross_pnl)).unwrap() + ); + assert_eq!( + owner.marked_holdings, + Posting::sum(books.iter().map(|b| book_value(b))).unwrap() + ); + assert_eq!( + owner.fees, + Posting::sum( + snapshot + .fees + .iter() + .filter(|f| f.owner_id == owner.owner_id) + .map(|f| f.amount.into()) + ) + .unwrap() + ); + } + for aggregate in ledger.aggregate_positions() { + assert_eq!( + aggregate.quantity, + Posting::sum( + snapshot + .positions + .iter() + .filter(|b| b.instrument_id == aggregate.instrument_id) + .map(|b| b.quantity.into()) + ) + .unwrap() + ); + assert_eq!( + aggregate.remaining_cost, + Posting::sum( + snapshot + .positions + .iter() + .filter(|b| b.instrument_id == aggregate.instrument_id) + .map(|b| b.remaining_cost.into()) + ) + .unwrap() + ); + } +} + +#[test] +fn same_asset_two_owners_owner_basis_a_b() { + let mut l = ledger("10000"); + l.apply(&mark(0, "A^P.US", "200")).unwrap(); + let first = l + .apply(&fill(1, "strategy:A", "A^P.US", "buy", "10", "100", "1")) + .unwrap(); + l.apply(&fill(2, "strategy:B", "A^P.US", "buy", "10", "200", "2")) + .unwrap(); + l.apply(&fill(3, "strategy:A", "A^P.US", "sell", "10", "200", "3")) + .unwrap(); + let snapshot = l.economic_snapshot(); + let a = snapshot + .positions + .iter() + .find(|b| b.owner_id == id("strategy:A")) + .unwrap(); + let b = snapshot + .positions + .iter() + .find(|b| b.owner_id == id("strategy:B")) + .unwrap(); + assert_eq!(Posting::from(a.quantity), p("0")); + assert_eq!(Posting::from(a.remaining_cost), p("0")); + assert_eq!(a.realized_gross_pnl, p("1000")); + assert_eq!(Posting::from(b.quantity), p("10")); + assert_eq!(Posting::from(b.remaining_cost), p("2000")); + assert_eq!(b.realized_gross_pnl, p("0")); + assert_eq!(l.valuation().unwrap().cash, p("8994")); + assert_eq!(l.valuation().unwrap().equity, p("10994")); + assert!( + matches!(&first.effects.effects[..],[FinancialEffect::FillApplied{owner_id,..},FinancialEffect::FeeApplied{owner_id: fee_owner,..}] if owner_id==&id("strategy:A") && fee_owner==owner_id) + ); + reconcile(&l); +} + +#[test] +fn basis_residual_partial_final_shared_fixture() { + let fixture: Value = serde_json::from_str(include_str!( + "../../../../../test/fixtures/economics/ledger-specs.json" + )) + .unwrap(); + let mut l = ledger("100"); + l.apply(&mark(0, "A^P.US", "2")).unwrap(); + for (index, price) in ["1", "2", "2"].iter().enumerate() { + l.apply(&fill(index, "strategy:A", "A^P.US", "buy", "1", price, "0")) + .unwrap(); + } + assert_eq!( + Posting::from(l.economic_snapshot().positions[0].remaining_cost).to_string(), + fixture["basis"]["initialCost"] + ); + let mut sum = Posting::ZERO; + for index in 0..3 { + let result = l + .apply(&fill( + index + 3, + "strategy:A", + "A^P.US", + "sell", + "1", + "2", + "0", + )) + .unwrap(); + let FinancialEffect::FillApplied { released_basis, .. } = result.effects.effects[0] else { + panic!("fill effect") + }; + let released: Posting = released_basis.into(); + assert_eq!(released.to_string(), fixture["basis"]["releases"][index]); + assert_eq!( + Posting::from(l.economic_snapshot().positions[0].remaining_cost).to_string(), + fixture["basis"]["remainingCosts"][index] + ); + sum = sum.checked_add(released).unwrap(); + reconcile(&l); + } + assert_eq!(sum, p("5")); + assert_eq!( + l.economic_snapshot().positions[0].realized_gross_pnl, + p("1") + ); +} + +#[test] +fn exact_full_range_notional_and_proportional_basis() { + let max = p(MAX_POSTING); + assert_eq!(Posting::notional(max, p("1")).unwrap(), max); + assert_eq!(Posting::notional(p("1"), max).unwrap(), max); + assert_eq!(Posting::notional(max, max), Err(ScalarError::Overflow)); + assert_eq!( + Posting::notional(max, p("1.00000001")), + Err(ScalarError::Overflow) + ); + assert_eq!( + Posting::notional(p("0.00000001"), p("0.5")).unwrap(), + p("0.00000001") + ); + assert_eq!( + Posting::notional(p("-0.00000001"), p("0.5")).unwrap(), + p("-0.00000001") + ); + assert_eq!( + Posting::notional(p("0.00000001"), p("0.49999999")).unwrap(), + p("0") + ); + assert_eq!( + Posting::released_basis(max, p("1"), p("2")).unwrap(), + p("396140812571321687967.71975168") + ); + assert_eq!( + Posting::released_basis(max, p("1"), p("3")).unwrap(), + p("264093875047547791978.47983445") + ); + // Numerator exceeds both Decimal's96 and i128's127 coefficient bits. + assert_eq!(Posting::released_basis(max, max, max).unwrap(), max); + let almost = max.checked_sub(p("0.00000001")).unwrap(); + assert_eq!(Posting::released_basis(max, almost, max).unwrap(), almost); + assert_eq!(Posting::sum([max, p("1"), p("-1")]).unwrap(), max); + assert_eq!( + Posting::released_basis(p("1"), p("1"), p("0")), + Err(ScalarError::InvalidDecimal) + ); + let mut l = ledger(MAX_POSTING); + l.apply(&fill( + 1, + "strategy:A", + "A^P.US", + "buy", + "1", + MAX_POSTING, + "0", + )) + .unwrap(); + l.apply(&mark(1, "A^P.US", MAX_POSTING)).unwrap(); + reconcile(&l); + l.apply(&fill( + 2, + "strategy:A", + "A^P.US", + "sell", + "1", + MAX_POSTING, + "0", + )) + .unwrap(); + assert_eq!(l.valuation().unwrap().equity, max); + reconcile(&l); + assert_eq!( + Ledger::restore(l.checkpoint()).unwrap().checkpoint(), + l.checkpoint() + ); +} + +#[test] +fn smallest_positive_price_quantity_zero_cost_lifecycle() { + let mut l = ledger("1"); + let buy = l + .apply(&fill( + 1, + "strategy:A", + "A^P.US", + "buy", + "0.00000001", + "0.00000001", + "0.01", + )) + .unwrap(); + assert!( + matches!(buy.effects.effects[0], FinancialEffect::FillApplied {cash_delta, ..} if cash_delta == Posting::ZERO) + ); + let position = &l.economic_snapshot().positions[0]; + assert_eq!(Posting::from(position.quantity), p("0.00000001")); + assert_eq!(Posting::from(position.remaining_cost), Posting::ZERO); + assert_eq!(l.valuation(), Err(LedgerError::MissingMark)); + l.apply(&mark(1, "A^P.US", "0.00000001")).unwrap(); + assert_eq!(l.valuation().unwrap().marked_holdings, Posting::ZERO); + assert_eq!(l.valuation().unwrap().cash, p("0.99")); + reconcile(&l); + l = Ledger::restore(l.checkpoint()).unwrap(); + let sale = l + .apply(&fill( + 2, + "strategy:A", + "A^P.US", + "sell", + "0.00000001", + "0.00000001", + "0.01", + )) + .unwrap(); + assert!( + matches!(sale.effects.effects[0], FinancialEffect::FillApplied {cash_delta, released_basis, realized_gross_pnl, ..} if cash_delta == Posting::ZERO && Posting::from(released_basis) == Posting::ZERO && realized_gross_pnl == Posting::ZERO) + ); + let position = &l.economic_snapshot().positions[0]; + assert_eq!(Posting::from(position.quantity), Posting::ZERO); + assert_eq!(Posting::from(position.remaining_cost), Posting::ZERO); + assert_eq!(l.valuation().unwrap().cash, p("0.98")); + reconcile(&l); + assert_eq!( + Ledger::restore(l.checkpoint()).unwrap().checkpoint(), + l.checkpoint() + ); +} + +#[test] +fn distinct_partial_fills_share_order_binding_and_charge_each_fee_once() { + let mut l = ledger("1000"); + let first = fill(1, "strategy:A", "A^P.US", "buy", "1", "100", "1"); + l.apply(&first).unwrap(); + let mut second = first.clone(); + second.command_id = id("second-partial-command"); + if let EngineCommandBody::ApplyFill { + fill_id, + quantity, + price, + fee, + .. + } = &mut second.body + { + *fill_id = id("second-partial-fill"); + *quantity = Positive::try_from(p("2")).unwrap(); + *price = Positive::try_from(p("110")).unwrap(); + fee.fee_id = id("second-partial-fee"); + fee.amount = NonNegative::try_from(p("2")).unwrap(); + } + let receipt = l.apply(&second).unwrap(); + assert!(!receipt.replayed); + assert_eq!( + Posting::from(l.economic_snapshot().positions[0].quantity), + p("3") + ); + assert_eq!( + Posting::from(l.economic_snapshot().positions[0].remaining_cost), + p("320") + ); + assert_eq!(Posting::from(l.economic_snapshot().cash), p("677")); + let before = l.checkpoint(); + assert!(l.apply(&first).unwrap().replayed); + assert!(l.apply(&second).unwrap().replayed); + assert_eq!(l.checkpoint(), before); + let mut restored = Ledger::restore(before).unwrap(); + assert!(restored.apply(&second).unwrap().replayed); + assert_eq!(restored.checkpoint(), l.checkpoint()); + l.apply(&mark(1, "A^P.US", "110")).unwrap(); + reconcile(&l); +} + +#[test] +fn shared_command_identity_fixture_runs_through_ledger() { + let fixture: Value = serde_json::from_str(include_str!( + "../../../../../test/fixtures/economics/ledger-specs.json" + )) + .unwrap(); + let parse = |name: &str| { + serde_json::from_value::(fixture["commandIds"][name].clone()) + .unwrap() + }; + let mut l = ledger("1000"); + let original = l.apply(&parse("original")).unwrap(); + let retry = l.apply(&parse("retry")).unwrap(); + assert!(retry.replayed); + assert_eq!(retry.effects, original.effects); + assert_unchanged(&mut l, parse("conflict"), LedgerError::CommandConflict); + assert_unchanged(&mut l, parse("independent"), LedgerError::WrongScope); + let mut independent_config = config("1000"); + independent_config.session_id = id("research:run-2"); + assert!( + !Ledger::new(independent_config) + .unwrap() + .apply(&parse("independent")) + .unwrap() + .replayed + ); +} + +#[test] +fn wrong_owner_disposal_and_owner_order_conflicts_leave_state_unchanged() { + let mut l = ledger("1000"); + l.apply(&fill(1, "strategy:A", "A^P.US", "buy", "2", "100", "0")) + .unwrap(); + assert_unchanged( + &mut l, + fill(2, "strategy:B", "A^P.US", "sell", "1", "100", "0"), + LedgerError::InsufficientInventory, + ); + assert_unchanged( + &mut l, + fill(3, "unknown", "A^P.US", "buy", "1", "100", "0"), + LedgerError::UnknownOwner, + ); + assert_unchanged( + &mut l, + fill(4, "reserve", "A^P.US", "buy", "1", "100", "0"), + LedgerError::UnknownOwner, + ); + let mut conflict = fill(5, "strategy:B", "A^P.US", "buy", "1", "100", "0"); + let EngineCommandBody::ApplyFill { order_id, .. } = &mut conflict.body else { + unreachable!() + }; + *order_id = id("order-1"); + assert_unchanged(&mut l, conflict, LedgerError::OrderConflict); + let mut config = config("1"); + config.owner_ids.push(id("strategy:A")); + assert!(matches!( + Ledger::new(config), + Err(LedgerError::InvalidOwners) + )); +} + +#[test] +fn per_fill_fee_once_retry_after_intervening_commands_and_aliases() { + let mut l = ledger("1000"); + let original = fill(1, "strategy:A", "A^P.US", "buy", "2", "100", "1"); + let receipt = l.apply(&original).unwrap(); + l.apply(&mark(2, "A^P.US", "120")).unwrap(); + let before = l.checkpoint(); + let mut replay = receipt.clone(); + replay.replayed = true; + assert_eq!(l.apply(&original).unwrap(), replay); + assert_eq!(l.checkpoint(), before); + let mut alias = original.clone(); + alias.command_id = id("z-alias"); + assert_eq!(l.apply(&alias).unwrap(), replay); + assert_eq!(l.economic_snapshot(), before.economic); + assert_eq!(l.checkpoint().receipts.len(), before.receipts.len() + 1); + let before_alias = l.checkpoint(); + assert_eq!(l.apply(&alias).unwrap(), replay); + assert_eq!(l.checkpoint(), before_alias); + assert_eq!(l.valuation().unwrap().fees, p("1")); + assert_eq!(l.valuation().unwrap().cash, p("799")); + let mut restored = Ledger::restore(l.checkpoint()).unwrap(); + assert_eq!(restored.apply(&alias).unwrap(), replay); + assert_eq!(restored.checkpoint(), l.checkpoint()); + reconcile(&l); +} + +#[test] +fn conflicting_fill_command_and_fee_ids_reject_atomically() { + let mut l = ledger("1000"); + let original = fill(1, "strategy:A", "A^P.US", "buy", "2", "100", "1"); + l.apply(&original).unwrap(); + let mut command_conflict = original.clone(); + command_conflict.event_time = EventTime::try_from(101).unwrap(); + assert_unchanged(&mut l, command_conflict, LedgerError::CommandConflict); + let mut conflict = original.clone(); + conflict.command_id = id("alias"); + conflict.event_time = EventTime::try_from(101).unwrap(); + assert_unchanged(&mut l, conflict, LedgerError::FillConflict); + let mut conflict = original.clone(); + conflict.command_id = id("alias"); + if let EngineCommandBody::ApplyFill { fee, .. } = &mut conflict.body { + fee.amount = NonNegative::try_from(p("2")).unwrap(); + } + assert_unchanged(&mut l, conflict, LedgerError::FillConflict); + let mut conflict = fill(2, "strategy:A", "A^P.US", "buy", "1", "100", "1"); + if let EngineCommandBody::ApplyFill { fee, .. } = &mut conflict.body { + fee.fee_id = id("fee-1"); + } + assert_unchanged(&mut l, conflict, LedgerError::FeeConflict); + let mut conflict = original; + conflict.account_id = id("another-account"); + assert_unchanged(&mut l, conflict, LedgerError::WrongScope); +} + +#[test] +fn fee_inclusive_funding_and_fail_late_overflow_are_atomic() { + let mut l = ledger("10000"); + assert_unchanged( + &mut l, + fill(1, "strategy:A", "A^P.US", "buy", "100", "100", "0.01"), + LedgerError::InsufficientCash, + ); + l.apply(&fill(1, "strategy:A", "A^P.US", "buy", "100", "99.99", "1")) + .unwrap(); + assert_eq!(Posting::from(l.economic_snapshot().cash), p("0")); + let mut l = ledger(MAX_POSTING); + l.apply(&mark(1, "A^P.US", "1")).unwrap(); + // Fill arithmetic itself fits; account equity after applying the existing + // mark would overflow. Neither IDs nor a partial owned book may survive. + assert_unchanged( + &mut l, + fill(1, "strategy:A", "A^P.US", "buy", "1", "0.5", "0"), + LedgerError::Arithmetic(ScalarError::Overflow), + ); + l.apply(&fill(2, "strategy:A", "A^P.US", "buy", "1", "1", "0")) + .unwrap(); + assert_unchanged( + &mut l, + mark(2, "A^P.US", "2"), + LedgerError::Arithmetic(ScalarError::Overflow), + ); + assert_unchanged( + &mut l, + fill( + 3, + "strategy:A", + "A^P.US", + "buy", + MAX_POSTING, + MAX_POSTING, + "0", + ), + LedgerError::Arithmetic(ScalarError::Overflow), + ); + reconcile(&l); + let mut l = ledger("100"); + l.apply(&fill(1, "strategy:A", "A^P.US", "buy", "1", "100", "0")) + .unwrap(); + assert_unchanged( + &mut l, + fill(2, "strategy:A", "A^P.US", "sell", "1", "100", "100.01"), + LedgerError::InsufficientCash, + ); + let mut l = ledger(MAX_POSTING); + l.apply(&fill( + 1, + "strategy:A", + "A^P.US", + "buy", + MAX_POSTING, + "0.00000001", + "0", + )) + .unwrap(); + assert_unchanged( + &mut l, + fill( + 2, + "strategy:B", + "A^P.US", + "buy", + "0.00000001", + "0.00000001", + "0", + ), + LedgerError::Arithmetic(ScalarError::Overflow), + ); +} + +#[test] +fn mark_rounding_sums_owned_values_not_aggregate_quantity() { + let mut l = ledger("1"); + l.apply(&fill( + 1, + "strategy:A", + "A^P.US", + "buy", + "0.00000001", + "0.5", + "0", + )) + .unwrap(); + l.apply(&fill( + 2, + "strategy:B", + "A^P.US", + "buy", + "0.00000001", + "0.5", + "0", + )) + .unwrap(); + l.apply(&mark(1, "A^P.US", "0.5")).unwrap(); + assert_eq!(l.valuation().unwrap().marked_holdings, p("0.00000002")); + assert_eq!( + Posting::notional(l.aggregate_positions()[0].quantity, p("0.5")).unwrap(), + p("0.00000001") + ); + reconcile(&l); +} + +#[test] +fn terminal_mark_retains_positions_without_fill_and_missing_marks_fail() { + let mut l = ledger("1000"); + l.apply(&fill(1, "strategy:A", "A^P.US", "buy", "2", "100", "1")) + .unwrap(); + assert_eq!(l.valuation(), Err(LedgerError::MissingMark)); + let terminal = l.apply(&mark(1, "A^P.US", "120")).unwrap(); + assert!(matches!( + &terminal.effects.effects[..], + [FinancialEffect::MarkUpdated { .. }] + )); + assert_eq!( + Posting::from(l.economic_snapshot().positions[0].quantity), + p("2") + ); + assert_eq!(l.valuation().unwrap().equity, p("1039")); + let previous_mark = l.mark(&id("A^P.US")).unwrap().clone(); + l.apply(&fill(2, "strategy:A", "A^P.US", "buy", "1", "125", "1")) + .unwrap(); + assert_eq!(l.mark(&id("A^P.US")), Some(&previous_mark)); + let mut older = mark(2, "A^P.US", "119"); + older.event_time = EventTime::try_from(90).unwrap(); + l.apply(&older).unwrap(); + assert_eq!(l.mark(&id("A^P.US")).unwrap().event_time.get(), 90); + reconcile(&l); +} + +#[test] +fn session_boundary_keeps_calendar_and_does_not_reset_economics() { + let mut l = ledger("1000"); + l.apply(&fill(1, "strategy:A", "A^P.US", "buy", "1", "100", "1")) + .unwrap(); + let before = l.economic_snapshot(); + let next = command( + "boundary", + json!({"kind":"riskSessionBoundary","riskSession":{"calendarId":"XNYS","calendarRevision":"2026-01","sessionId":"day-2","startsAt":50}}), + ); + l.apply(&next).unwrap(); + let after = l.economic_snapshot(); + assert_eq!(after.cash, before.cash); + assert_eq!(after.positions, before.positions); + assert_eq!(after.fees, before.fees); + let mut repeated = next.clone(); + repeated.command_id = id("same-boundary-new-command"); + let noop = l.apply(&repeated).unwrap(); + assert!(!noop.replayed); + assert!(noop.effects.effects.is_empty()); + assert_eq!(noop.effects.revision.get(), after.revision.get() + 1); + let saved = l.checkpoint(); + let retry = l.apply(&repeated).unwrap(); + assert!(retry.replayed); + assert!(retry.effects.effects.is_empty()); + assert_eq!(l.checkpoint(), saved); + let mut restored = Ledger::restore(saved).unwrap(); + assert_eq!(restored.apply(&repeated).unwrap(), retry); + assert!(matches!( + &restored.apply(&next).unwrap().effects.effects[..], + [FinancialEffect::RiskSessionChanged { .. }] + )); + assert_eq!(restored.checkpoint(), l.checkpoint()); + for (calendar, revision, session, starts) in [ + ("OTHER", "2026-01", "day-3", 70), + ("XNYS", "changed", "day-3", 70), + ("XNYS", "2026-01", "day-3", 40), + ("XNYS", "2026-01", "day-2", 70), + ("XNYS", "2026-01", "day-3", 50), + ] { + let invalid = command( + "invalid-boundary", + json!({"kind":"riskSessionBoundary","riskSession":{"calendarId":calendar,"calendarRevision":revision,"sessionId":session,"startsAt":starts}}), + ); + assert_unchanged(&mut l, invalid, LedgerError::InvalidRiskSession); + } + assert_eq!( + Ledger::restore(l.checkpoint()).unwrap().checkpoint(), + l.checkpoint() + ); +} + +#[test] +fn snapshot_restore_parity_validation_and_ordered_receipts() { + let mut l = ledger("1000"); + let first = fill(10, "strategy:A", "A^P.US", "buy", "2", "100", "1"); + l.apply(&first).unwrap(); + l.apply(&mark(2, "A^P.US", "120")).unwrap(); + let mut alias = first; + alias.command_id = id("a-alias"); + l.apply(&alias).unwrap(); + let checkpoint = l.checkpoint(); + let json = serde_json::to_string(&checkpoint).unwrap(); + let mut restored = Ledger::restore(serde_json::from_str(&json).unwrap()).unwrap(); + let next = fill(2, "strategy:A", "A^P.US", "sell", "1", "125", "2"); + assert_eq!(l.apply(&next).unwrap(), restored.apply(&next).unwrap()); + assert_eq!(l.checkpoint(), restored.checkpoint()); + assert_eq!(l.valuation(), restored.valuation()); + let mut variants = Vec::new(); + let mut bad = checkpoint.clone(); + bad.economic.cash = NonNegative::try_from(p("999")).unwrap(); + variants.push(bad); + let mut bad = checkpoint.clone(); + bad.economic.revision = Counter::try_from(99).unwrap(); + variants.push(bad); + let mut bad = checkpoint.clone(); + bad.config.initial_capital = NonNegative::try_from(p("1001")).unwrap(); + variants.push(bad); + let mut bad = checkpoint.clone(); + bad.receipts.swap(0, 2); + variants.push(bad); + let mut bad = checkpoint.clone(); + bad.receipts[2].outcome.replayed = false; + variants.push(bad); + let mut bad = checkpoint.clone(); + bad.marks.clear(); + variants.push(bad); + let mut bad = checkpoint.clone(); + bad.receipts[0].command.account_id = id("foreign"); + variants.push(bad); + let mut bad = checkpoint.clone(); + bad.receipts.push(bad.receipts[2].clone()); + variants.push(bad); + for bad in variants { + assert!(matches!( + Ledger::restore(bad), + Err(LedgerError::InvalidCheckpoint) + )); + } + let mut invalid: Value = serde_json::from_str(&json).unwrap(); + invalid["version"] = json!(2); + assert!(serde_json::from_value::(invalid).is_err()); + assert!(serde_json::from_value::( + serde_json::to_value(&checkpoint.economic).unwrap() + ) + .is_err()); + reconcile(&restored); +} + +#[test] +fn deterministic_seeded_valid_sequences_reconcile_and_restore() { + fn run(seed: u64) -> LedgerCheckpoint { + let mut rng = StdRng::seed_from_u64(seed); + let mut l = ledger("1000000"); + let owners = ["strategy:A", "strategy:B", "strategy:C"]; + let instruments = ["A^P.US", "B.US", "C.US"]; + let mut quantities = [[0usize; 3]; 3]; + for (i, instrument) in instruments.iter().enumerate() { + l.apply(&mark(i, instrument, "100")).unwrap(); + } + for step in 0..512 { + let owner = rng.gen_range(0..3); + let instrument = rng.gen_range(0..3); + let price = rng.gen_range(80..121).to_string(); + if step % 7 == 0 { + l.apply(&mark(step + 3, instruments[instrument], &price)) + .unwrap(); + } + let sell = quantities[owner][instrument] > 0 && rng.gen_bool(0.5); + let side = if sell { + quantities[owner][instrument] -= 1; + "sell" + } else { + quantities[owner][instrument] += 1; + "buy" + }; + l.apply(&fill( + step, + owners[owner], + instruments[instrument], + side, + "1", + &price, + "0.01", + )) + .unwrap(); + reconcile(&l); + if step % 127 == 0 { + l = Ledger::restore(l.checkpoint()).unwrap(); + } + } + l.checkpoint() + } + assert_eq!(run(0xf02), run(0xf02)); + assert_ne!(run(0xf02), run(0xf03)); +} + +fn digest(bytes: &[u8]) -> u64 { + let mut h = DefaultHasher::new(); + bytes.hash(&mut h); + h.finish() +} + +/// Local release sanity workload, not a backtest benchmark or speedup claim. +/// Measures resident transitions separately from checkpoint+restore. Inputs +/// are prebuilt; effects/history serialization happens outside timed regions. +/// Fixed-artifact DefaultHasher is a repeatability checksum, not provenance. +#[test] +#[ignore = "manual measurement: cargo test -p engine --lib --release --offline ledger_transition_measurement -- --ignored --nocapture"] +fn ledger_transition_measurement() { + for (count, multi) in [(1000, false), (1000, true), (10000, false), (10000, true)] { + let mut commands = Vec::new(); + for index in 0..count { + let owner = if multi { + ["strategy:A", "strategy:B", "strategy:C"][index % 3] + } else { + "strategy:A" + }; + let instrument = if multi { + ["A^P.US", "B.US", "C.US", "D.US"][index % 4] + } else { + "A^P.US" + }; + commands.push(if index % 5 == 0 { + mark(index, instrument, "100") + } else { + fill(index, owner, instrument, "buy", "0.01", "100", "0.001") + }); + } + let mut reference = None; + for repeat in 0..3 { + let mut l = ledger("1000000"); + let started = Instant::now(); + let effects: Vec<_> = commands.iter().map(|c| l.apply(c).unwrap()).collect(); + let transition_ms = started.elapsed().as_secs_f64() * 1000.0; + let started = Instant::now(); + let checkpoint = l.checkpoint(); + let checkpoint_ms = started.elapsed().as_secs_f64() * 1000.0; + let restore_input = checkpoint.clone(); + let started = Instant::now(); + let restored = Ledger::restore(restore_input).unwrap(); + let restore_ms = started.elapsed().as_secs_f64() * 1000.0; + assert_eq!(restored.checkpoint(), checkpoint); + let bytes = serde_json::to_vec(&(checkpoint, effects)).unwrap(); + if let Some(reference) = &reference { + assert_eq!(&bytes, reference); + } else { + reference = Some(bytes.clone()); + } + println!("F02 count={count} multi={multi} repeat={repeat} transition_ms={transition_ms:.3} checkpoint_ms={checkpoint_ms:.3} restore_ms={restore_ms:.3} bytes={} checksum={:016x}",bytes.len(),digest(&bytes)); + } + } +} diff --git a/apps/stock/engine/src/financial/mod.rs b/apps/stock/engine/src/financial/mod.rs index 24ba2c01..3f60b9c5 100644 --- a/apps/stock/engine/src/financial/mod.rs +++ b/apps/stock/engine/src/financial/mod.rs @@ -3,7 +3,11 @@ //! F01 defines transport and checked posting primitives. F02 owns ledger //! transitions/idempotency; F04 owns risk; F06/F07 own replay/session state. pub mod contract; +pub mod ledger; pub mod scalar; #[cfg(test)] mod tests; + +#[cfg(test)] +mod ledger_tests; diff --git a/apps/stock/engine/src/financial/scalar.rs b/apps/stock/engine/src/financial/scalar.rs index bf4bfbc2..60deb76d 100644 --- a/apps/stock/engine/src/financial/scalar.rs +++ b/apps/stock/engine/src/financial/scalar.rs @@ -1,3 +1,6 @@ +use num_bigint::BigInt; +use num_rational::BigRational; +use num_traits::ToPrimitive; use rust_decimal::{Decimal, RoundingStrategy}; use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; use std::{fmt, str::FromStr}; @@ -15,9 +18,9 @@ pub enum ScalarError { } /// Money/quantity transport uses strings, never f64. No float constructor or -/// unchecked arithmetic operator is exposed. Multiplication and proportional -/// division are intentionally left to F02's operation-specific implementation: -/// checked decimal operations can still round intermediate precision. +/// unchecked arithmetic operator is exposed. Operation-specific notional and +/// basis calculations use exact rational intermediates; generic decimal +/// multiplication/division could silently reduce intermediate precision. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct Posting(Decimal); @@ -40,6 +43,65 @@ impl Posting { Self::from_exact_decimal(self.0.checked_sub(other.0).ok_or(ScalarError::Overflow)?) } + /// Exact integer coefficient at the declared posting scale. ZERO is the + /// only internal value whose Decimal scale can be smaller than eight. + fn units(self) -> BigInt { + BigInt::from(self.0.mantissa()) * BigInt::from(10u32).pow(POSTING_SCALE - self.0.scale()) + } + + fn from_units(units: BigInt) -> Result { + let coefficient = units.to_i128().ok_or(ScalarError::Overflow)?; + let decimal = Decimal::try_from_i128_with_scale(coefficient, POSTING_SCALE) + .map_err(|_| ScalarError::Overflow)?; + Self::from_exact_decimal(decimal) + } + + /// Quantity * price, rounded once at the posting boundary. BigRational + /// avoids rust_decimal's possible intermediate precision reduction. Its + /// round() is explicitly nearest with half ties away from zero. + pub(super) fn notional(quantity: Self, price: Self) -> Result { + let units = BigRational::new( + quantity.units() * price.units(), + BigInt::from(100_000_000u32), + ); + Self::rounded_units(units) + } + + /// Partial disposal only: quantity is positive and <= owned quantity. + /// A final disposal deliberately bypasses division and releases residue. + pub(super) fn released_basis( + cost: Self, + quantity: Self, + owned_quantity: Self, + ) -> Result { + if quantity.is_negative() || quantity.is_zero() || quantity > owned_quantity { + return Err(ScalarError::InvalidDecimal); + } + if quantity == owned_quantity { + return Ok(cost); + } + Self::rounded_units(BigRational::new( + cost.units() * quantity.units(), + owned_quantity.units(), + )) + } + + fn rounded_units(exact: BigRational) -> Result { + // As with from_exact_decimal, reject an out-of-range exact value even + // if rounding down would have brought it back inside the range. + let max = BigRational::from_integer(BigInt::from((1u128 << 96) - 1)); + if exact > max || exact < -max { + return Err(ScalarError::Overflow); + } + Self::from_units(exact.round().to_integer()) + } + + /// Exact sum of already quantized postings, without rejecting a valid + /// final result solely because an intermediate partial sum overflows. + pub(super) fn sum(values: impl IntoIterator) -> Result { + Self::from_units(values.into_iter().map(Self::units).sum()) + } + /// Posting boundary for an already exact internal decimal calculation. /// Callers must not pass a previously precision-losing intermediate. /// https://docs.rs/rust_decimal/1.43.0/rust_decimal/enum.RoundingStrategy.html diff --git a/apps/stock/orchestrator/src/services/StorageService.ts b/apps/stock/orchestrator/src/services/StorageService.ts index e802288e..6f9491d5 100644 --- a/apps/stock/orchestrator/src/services/StorageService.ts +++ b/apps/stock/orchestrator/src/services/StorageService.ts @@ -21,6 +21,33 @@ export interface HistoricalBar { source?: 'eod' | 'questdb' | 'synthetic'; adjustedClose?: number; } + +export type HistoricalStorageProvider = 'questdb' | 'eod'; +export type HistoricalStorageErrorCode = + | 'unsupported-provider' + | 'unsupported-interval' + | 'provider-unavailable' + | 'missing-range'; + +/** Storage routing failures are distinct from invalid records and transport failures. */ +export class HistoricalStorageError extends Error { + constructor( + readonly code: HistoricalStorageErrorCode, + message: string, + readonly provider?: HistoricalStorageProvider | 'synthetic' + ) { + super(message); + this.name = 'HistoricalStorageError'; + } +} + +const historicalIntervals = ['1m', '5m', '15m', '1h', '1d'] as const; +const eodIntradayCollections: Readonly> = { + '1m': 'eodIntraday1M', + '5m': 'eodIntraday5M', + '1h': 'eodIntraday1H', +}; + export class StorageService { private questdb: QuestDBClient | null = null; private postgres: PostgresClient | null = null; @@ -166,6 +193,59 @@ export class StorageService { ); } + /** Adapter support and current connectivity, not evidence of stored range coverage. */ + getHistoricalCapabilities() { + return [ + { + provider: 'questdb' as const, + configured: this.questdb !== null, + connected: this.questdb?.connected ?? false, + intervals: [...historicalIntervals], + }, + { + provider: 'eod' as const, + configured: this.mongodb !== null, + connected: this.mongodb?.connected ?? false, + intervals: ['1m', '5m', '1h', '1d'] as const, + }, + ]; + } + + private selectHistoricalProvider( + requested: HistoricalStorageProvider | 'auto' + ): HistoricalStorageProvider | 'synthetic' { + if (!['auto', 'questdb', 'eod'].includes(requested)) { + throw new HistoricalStorageError('unsupported-provider', 'Unsupported historical provider'); + } + if (requested === 'questdb' || (requested === 'auto' && this.questdb)) { + if (!this.questdb) { + throw new HistoricalStorageError( + 'provider-unavailable', + 'QuestDB historical storage is unavailable', + 'questdb' + ); + } + return 'questdb'; + } + if (requested === 'eod' || (requested === 'auto' && this.mongodb)) { + if (!this.mongodb) { + throw new HistoricalStorageError( + 'provider-unavailable', + 'EOD historical storage is unavailable', + 'eod' + ); + } + return 'eod'; + } + if (this.options.allowSyntheticData) { + return 'synthetic'; + } + throw new HistoricalStorageError( + 'provider-unavailable', + 'No historical data store configured; synthetic data requires explicit opt-in' + ); + } + /** One historical-data policy for native and TypeScript execution. */ async getHistoricalBars( symbol: string, @@ -176,7 +256,8 @@ export class StorageService { adjustment: 'raw', timestamp: interval === '1d' ? 'utc-session-date' : 'utc-instant', }, - signal?: AbortSignal + signal?: AbortSignal, + provider: HistoricalStorageProvider | 'auto' = 'auto' ): Promise { signal?.throwIfAborted(); parseInstrumentId(symbol); @@ -187,8 +268,8 @@ export class StorageService { ) { throw new Error('Invalid historical date range'); } - if (!['1m', '5m', '15m', '1h', '1d'].includes(interval)) { - throw new Error('Unsupported historical interval'); + if (!(historicalIntervals as readonly string[]).includes(interval)) { + throw new HistoricalStorageError('unsupported-interval', 'Unsupported historical interval'); } if ( (interval === '1d') !== (policy.timestamp === 'utc-session-date') || @@ -199,7 +280,15 @@ export class StorageService { 'Daily ranges must use UTC midnight session dates; intraday ranges use UTC instants' ); } - const rows = await this.readHistoricalBars(symbol, startTime, endTime, interval); + const selectedProvider = this.selectHistoricalProvider(provider); + const rows = await this.readHistoricalBars( + symbol, + startTime, + endTime, + interval, + selectedProvider, + signal + ); signal?.throwIfAborted(); const bars: HistoricalBar[] = []; let processed = 0; @@ -264,7 +353,11 @@ export class StorageService { signal?.throwIfAborted(); bars.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime()); if (!bars.length) { - throw new Error(`No historical data for ${symbol}`); + throw new HistoricalStorageError( + 'missing-range', + `No historical data for ${symbol} in the requested range`, + selectedProvider + ); } if ( bars.some( @@ -281,13 +374,12 @@ export class StorageService { symbol: string, startTime: Date, endTime: Date, - interval: string + interval: string, + provider: HistoricalStorageProvider | 'synthetic', + signal?: AbortSignal ): Promise { - // If QuestDB is available, use real data - if (this.questdb) { - if (!['1m', '5m', '15m', '1h', '1d'].includes(interval)) { - throw new Error('Unsupported historical interval'); - } + // Select once, before reading: empty ranges/errors never switch providers. + if (provider === 'questdb' && this.questdb) { const result = await this.questdb.query( `SELECT * FROM bars_${interval} WHERE symbol = $1 AND timestamp >= $2 AND timestamp < $3 ORDER BY timestamp`, [symbol, startTime, endTime] @@ -295,11 +387,85 @@ export class StorageService { return result.rows.map(row => ({ ...row, source: 'questdb' })); } - if (this.mongodb) { - if (interval !== '1d') { - throw new Error('Daily provider storage cannot satisfy an intraday request'); - } + if (provider === 'eod' && this.mongodb) { const identity = parseInstrumentId(symbol); + if (interval !== '1d') { + const collection = eodIntradayCollections[interval]; + if (!collection) { + throw new HistoricalStorageError( + 'unsupported-interval', + `EOD historical storage does not support ${interval}`, + 'eod' + ); + } + // fetchIntraday writes raw bar-start UTC Unix seconds, not local datetime labels. + // https://eodhd.com/financial-apis/intraday-historical-data-api + // This instant is not publication time; availability/calendar policy belongs to datasets. + const records = await this.mongodb.find<{ + symbol: string; + exchange: string; + eodSearchCode: string; + timestamp: number; + open: number; + high: number; + low: number; + close: number; + volume: number; + }>( + collection, + { + eodSearchCode: identity.id, + timestamp: { $gte: startTime.getTime() / 1000, $lt: endTime.getTime() / 1000 }, + }, + { + sort: { timestamp: 1 }, + projection: { + symbol: 1, + exchange: 1, + eodSearchCode: 1, + timestamp: 1, + open: 1, + high: 1, + low: 1, + close: 1, + volume: 1, + }, + } + ); + signal?.throwIfAborted(); + const bars: HistoricalBar[] = []; + for (const record of records) { + if ( + record.eodSearchCode !== identity.id || + record.symbol !== identity.symbol || + record.exchange !== identity.exchange + ) { + throw new Error(`Historical instrument identity mismatch for ${symbol}`); + } + const milliseconds = record.timestamp * 1000; + if ( + !Number.isSafeInteger(record.timestamp) || + !Number.isSafeInteger(milliseconds) || + !Number.isFinite(new Date(milliseconds).getTime()) + ) { + throw new Error(`Invalid historical Unix-seconds timestamp for ${symbol}`); + } + bars.push({ + symbol, + timestamp: new Date(milliseconds), + open: record.open, + high: record.high, + low: record.low, + close: record.close, + volume: record.volume, + source: 'eod', + }); + if (bars.length % PREPARATION_BATCH_SIZE === 0) { + await preparationCheckpoint(signal); + } + } + return bars; + } const prices = await this.mongodb.find<{ symbol: string; exchange: string; @@ -366,11 +532,6 @@ export class StorageService { }; }); } - if (!this.options.allowSyntheticData) { - throw new Error( - 'No historical data store configured; synthetic data requires explicit opt-in' - ); - } return this.generateMockBars(symbol, startTime, endTime, interval).map(bar => ({ ...bar, source: 'synthetic', diff --git a/docs/development/ROADMAP.md b/docs/development/ROADMAP.md index 5332950d..b4c72f44 100644 --- a/docs/development/ROADMAP.md +++ b/docs/development/ROADMAP.md @@ -1,8 +1,8 @@ # Revised development roadmap -Baseline `b7aeca4` · reviewed 2026-10-22 · **First five waves committed; ADR-002/003/004 approved; F01/D01 validated, uncommitted** +Baseline `b7aeca4` · reviewed 2026-10-22 · **First six waves committed; F02/D02 validated, uncommitted** -Authorization update: the first five waves are independently reviewed, validated and committed. After the W04 closeout, the owner explicitly answered “yes” to ADR-002/003/004 as written and continuation with F01/D01. Those two tasks were independently reviewed and integrated from isolated worktrees; combined gates passed. They remain `review` / `validated_uncommitted` pending owner acceptance/commit. No other ADR is approved. Sixth-wave commits, pushes, PRs and trading operations remain outside scope. +Authorization update: after explicitly approving ADR-002/003/004 and the validated F01/D01 implementation, the owner requested “commit and continue.” F01/D01 are committed as `b4af840`; F02/D02 were independently reviewed, integrated and validated from isolated worktrees. No other ADR is approved. Seventh-wave commits, pushes, PRs and trading operations remain outside scope. ## Strategy and review outcome @@ -81,7 +81,7 @@ Completed wave; the table records its original rationale. Exact prompts, paths, Recommend **3 simultaneous implementers**, reserving one slot for coordination/independent review. Start C01 + C03 + W01; rotate C04 into the first freed slot, or start C04 first if runtime containment is the immediate operational need. These four have no mutual code dependencies and disjoint writable files. Four concurrent implementers are technically possible but not recommended without separate review capacity. -O01/P01, W03 and W04 are committed. W04 adds validated real-browser end-to-end verification of the existing workbench. F01/D01 now have explicit ADR approval and passed integrated validation; subsequent tasks remain prerequisite-gated pending acceptance/commit. +O01/P01, W03 and W04 are committed. W04 adds validated real-browser end-to-end verification of the existing workbench. F01/D01 passed integrated validation and are committed; F02/D02 passed integrated validation and await acceptance/commit, while subsequent tasks remain prerequisite-gated. ## Second-wave handoff — 2026-10-22 @@ -171,7 +171,7 @@ At the fifth-wave closeout, the readiness review found 32 remaining scheduled ta ## Sixth-wave handoff — 2026-10-22 -F01 and D01 are independently accepted and `review` / `validated_uncommitted`. Base `243e9ab`; isolated worktrees under `/tmp/stock-bot-wave6.uIuYHz/`. Financial and dataset owners implemented in parallel, with an independent read-only reviewer; the integrator merged their common types exports. +F01 and D01 are independently accepted and `done` / `validated_committed` in `b4af840`. Base `243e9ab`; isolated worktrees under `/tmp/stock-bot-wave6.uIuYHz/`. Financial and dataset owners implemented in parallel, with an independent read-only reviewer; the integrator merged their common types exports. - **F01:** Pinned maintained decimal dependency; checked exact decimal ingress, fixed-8 half-away posting, bounded arithmetic, versioned Rust/TypeScript contracts, owner/decision identities and hand-derived economic fixtures. Strategy intents cannot parse as internal financial mutations. Safe integer, Unicode, strict decimal, overflow and wire-roundtrip regressions pass. The snapshot is only an economic projection. F02 still owns actual ledger/dedup transitions and operation-specific proportional basis arithmetic; generic multiply/divide was deliberately not introduced. - **D01:** Additive v2 normalizer retains interval/event/availability time, source sequence, explicit versioned calendars, execution-series selection, universe/action coverage and limitations. Hash-verified v1 conversion retains its parent hash and makes unverifiable legacy VWAP unknown. DST/half-days, delayed availability, conflicts, overlapping intervals, parent-hash syntax and prefix stability are tested. Unsupported action/adjusted execution data rejects; unknown coverage remains exploratory. Initial intraday support requires full-duration session-contained bars. @@ -186,7 +186,27 @@ No PostgreSQL/Redis or Chromium rerun was needed for these additive, unused cont Only the verified stalled sandbox test processes were stopped after the successful rerun. No user services or data were removed; worktrees and logs remain available. -Existing v1 snapshots and financial runtimes remain unchanged. F01 is not a working canonical ledger; D01 prefix tests are not F06 replay enforcement. No paper account conversion, extra backlog task, commit, push, PR or trading operation occurred. After acceptance/commit, the next coherent pair is **F02 owner-aware Rust ledger + D02 intraday storage integration**, with one financial owner and disjoint data ownership. +Existing v1 snapshots and financial runtimes remain unchanged. F01 is not a working canonical ledger; D01 prefix tests are not F06 replay enforcement. The subsequent owner request authorized the F01/D01 commit and F02/D02 continuation, not a push, PR or trading operation. + +## Seventh-wave handoff — 2026-10-22 + +F02/D02 are independently accepted and `review` / `validated_uncommitted`. Base `b4af840`; isolated worktrees under `/tmp/stock-bot-wave7.UIkAQD/`. Financial and data owners implemented in parallel; an independent reviewer checked both; root integrated all ten reviewed files with matching hashes. + +- **F02:** Owner-keyed quantity, remaining basis, realized P&L and fees; exact rational intermediates rounded once into the maintained decimal posting type. Fee-inclusive funding, wrong-owner disposal, overflow and identity conflicts reject atomically. Command/fill aliases return original replay-labelled receipts, including after intervening operations. Explicit market marks remain separate from fill prices; owner-level marked postings reconcile to account equity. Same-session boundary repetition is an accepted no-op, not a false session-change effect. Ledger-only checkpoints retain and validate ordered receipts by replay; ordinary transitions touch only affected state. +- **D02:** Existing EOD `1m`/`5m`/`1h` Mongo collections now feed the common research storage admission path. Unix-second timestamps/listing identities validate; supported-provider capability reports distinguish configuration/connectivity from coverage. Default QuestDB priority remains, explicit provider selection is available at the storage API, and missing/error ranges never switch to daily/synthetic data. Real writer/read/normalizer composition and repeated legacy native runs are tested on synthetic provider records; HTTP/Mongo transport alone is replaced. + +Combined validation: + +- `CARGO_BUILD_JOBS=2 bun run check`: 60 tooling, 43 utility, 35 calculation, 342 integration and 59 Rust tests passed, zero failures. Build, typecheck, contracts, lint and secret audit passed. One Rust test is intentionally ignored by the ordinary suite because it is a manually invoked release measurement. +- Independent review: 22 financial Rust tests passed; 36 intraday/ingestion/dataset tests with 264 assertions passed. These overlap the combined totals, not additional independent cases. +- Standalone strict TypeScript including the real ingestion import graph, explicit scoped ESLint, Prettier, scoped rustfmt and `git diff --check` passed. Cargo.toml line endings were normalized alongside its pinned dependency additions; no dependency upgrades occurred. Only num-bigint was newly added to the lockfile. +- A repeatable release ledger workload runs 1k/10k prebuilt commands over one owner/asset or three owners/four assets, with three repeats and full state/effect byte equality. Transition, checkpoint-copy and restore times are recorded separately. Detailed raw measurements/build identities are in the manifest; these are not end-to-end backtest throughput or a speedup claim. Receipt memory and restore work grow with history; compaction is not implemented. + +The manual release measurement also passed on the final integrated checkout (1 test, zero failures), with identical repeatability checksums to the author build. It is additional validation, not a skipped correctness test. + +Limits: no F04 reservation/portfolio-risk policy, matcher, F06 replay, native session API, SQL/paper cutover, order/strategy/RNG session restoration or canonical-engine release. D02's provider selector is not a web/run-configuration control; no Mongo server-conformance, range-completeness or live-availability claim. Provider delayed-finalization caveats and the explicit bar-close simulation assumption are retained in the task evidence. PostgreSQL/Redis and Chromium suites were not rerun because their persistence/API/UI boundaries did not change. Existing build warnings remain. + +Only exact identified stalled D02 sandbox test/worker processes were terminated after the successful escalated rerun; no development services/data were changed. Worktrees and logs remain available. The sixth-wave commit was made as requested; no seventh-wave commit, push, PR or trading operation occurred. Next after acceptance/commit: **F04 central cash reservations and portfolio risk enforcement**. Product/AI work remains subject to its unapproved ADRs. ## Deferred and rejected diff --git a/docs/development/backlog/README.md b/docs/development/backlog/README.md index d625105d..5bc7edcc 100644 --- a/docs/development/backlog/README.md +++ b/docs/development/backlog/README.md @@ -1,6 +1,6 @@ # Canonical development backlog -**First five waves committed; ADR-002/003/004 approved; F01/D01 validated, uncommitted.** Consult manifest execution_scope, [ROADMAP](../ROADMAP.md), [skeptical review](../REVIEW.md) and [first-wave handoff](../FIRST-WAVE.md). F01/D01 await owner acceptance/commit; other tasks and unresolved policies remain gated. +**First six waves committed; F02/D02 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; F02/D02 await owner acceptance/commit, and other tasks/policies remain gated. ## One source of truth @@ -29,8 +29,8 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr | Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size | | --- | --- | --- | --- | --- | -| [F01 Define the minimal financial contract and economic fixtures](tasks/F01.md) | P0 / review | ADR-002, ADR-003, ADR-004 (approved) | — | Rust financial contract owner / M | -| [F02 Implement one owner-aware financial ledger](tasks/F02.md) | P0 / blocked | F01, ADR-002 | — | Rust accounting / L | +| [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 / review | 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 / blocked | F02, ADR-002, ADR-003 | — | Rust financial risk / L | | [F05 Unify matching and order lifecycle on the ledger](tasks/F05.md) | P0 / blocked | F04, ADR-003 | F06 | Rust execution semantics / L | @@ -42,8 +42,8 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr | Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size | | --- | --- | --- | --- | --- | -| [D01 Introduce availability-aware dataset v2](tasks/D01.md) | P0 / review | ADR-003 (approved) | — | TypeScript trading infrastructure / M | -| [D02 Connect supported intraday storage to research datasets](tasks/D02.md) | P1 / blocked | D01 | — | TypeScript trading infrastructure / M | +| [D01 Introduce availability-aware dataset v2](tasks/D01.md) | P0 / done | ADR-003 (approved) | — | TypeScript trading infrastructure / M | +| [D02 Connect supported intraday storage to research datasets](tasks/D02.md) | P1 / review | D01 | — | TypeScript trading infrastructure / M | | [D03 Add dataset eligibility and corporate-action safeguards](tasks/D03.md) | P1 / merged → D01 | None | — | TypeScript trading infrastructure / M | | [D04 Provide prefix-safe shared feature calculation](tasks/D04.md) | P1 / deferred | S01, P01 | — | Quantitative feature engineering / M | diff --git a/docs/development/backlog/manifest.json b/docs/development/backlog/manifest.json index 07920277..a0de39bf 100644 --- a/docs/development/backlog/manifest.json +++ b/docs/development/backlog/manifest.json @@ -1,23 +1,24 @@ { "schema_version": 1, - "plan_revision": "2026-10-22.16", + "plan_revision": "2026-10-22.18", "repository_base": "b7aeca4", - "plan_status": "sixth_wave_validated_uncommitted", + "plan_status": "seventh_wave_validated_uncommitted", "execution_authorized": true, "execution_scope": { - "authorized_by": "User: yes (2026-10-22), explicitly approving ADR-002/003/004 as written and continuation with F01/D01", + "authorized_by": "User: commit and continue (2026-10-22); commit accepted F01/D01 and continue with the explicitly proposed F02/D02 pair", "tasks": [ - "F01", - "D01" + "F02", + "D02" ], "permissions": [ + "commit_validated_sixth_wave", "isolated_implementation", "local_tests", "local_integration_review", "planning_progress_updates" ], "excluded": [ - "sixth_wave_commits_without_further_approval", + "seventh_wave_commits_without_further_approval", "push", "pull_requests", "live_or_paper_operations", @@ -319,7 +320,7 @@ "epic": "E2", "priority": "P0", "severity": "Critical", - "status": "review", + "status": "done", "dependencies": [], "decision_dependencies": [ "ADR-002", @@ -341,7 +342,7 @@ "assignment": "/root/wave6_f01", "branch": "wave6/f01-financial-contract", "pull_request": null, - "completed_commit": null, + "completed_commit": "b4af840d4edde84b23c099e85c82f43721046067", "blocker": null, "release_gates": [], "worktree": "/tmp/stock-bot-wave6.uIuYHz/f01", @@ -356,10 +357,10 @@ "test/fixtures/economics/", "test/integration/financial-contract.test.ts" ], - "integration_state": "validated_uncommitted", + "integration_state": "validated_committed", "reviewed_by": "/root/wave6_review", "verification_reference": "ROADMAP.md#sixth-wave-handoff--2026-10-22", - "review_notes": "Independently accepted, integrated, and combined gates passed. No commit authorized in this wave; awaiting owner acceptance/commit before scheduling dependents." + "review_notes": "Independently accepted and combined gates passed; owner authorized commit and continuation. Completed commit contains the integrated F01/D01 implementation." }, { "id": "F02", @@ -367,7 +368,7 @@ "epic": "E2", "priority": "P0", "severity": "Critical", - "status": "blocked", + "status": "review", "dependencies": [ "F01" ], @@ -388,12 +389,24 @@ "rust-ledger" ], "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/wave7_f02", + "branch": "wave7/f02-owned-ledger", "pull_request": null, "completed_commit": null, "blocker": null, - "release_gates": [] + "release_gates": [], + "worktree": "/tmp/stock-bot-wave7.UIkAQD/f02", + "integration_base": "b4af840d4edde84b23c099e85c82f43721046067", + "concrete_write_scope": [ + "apps/stock/engine/src/financial/", + "apps/stock/engine/Cargo.toml", + "Cargo.lock", + "test/fixtures/economics/" + ], + "review_notes": "Independently accepted, exact frozen files integrated, combined repository checks passed. Seventh-wave changes remain uncommitted pending owner acceptance/commit; no downstream task started.", + "integration_state": "validated_uncommitted", + "reviewed_by": "/root/wave7_review", + "verification_reference": "ROADMAP.md#seventh-wave-handoff--2026-10-22" }, { "id": "F03", @@ -595,7 +608,7 @@ "epic": "E3", "priority": "P0", "severity": "Critical", - "status": "review", + "status": "done", "dependencies": [], "decision_dependencies": [ "ADR-003" @@ -615,7 +628,7 @@ "assignment": "/root/wave6_d01", "branch": "wave6/d01-dataset-v2", "pull_request": null, - "completed_commit": null, + "completed_commit": "b4af840d4edde84b23c099e85c82f43721046067", "blocker": null, "release_gates": [], "worktree": "/tmp/stock-bot-wave6.uIuYHz/d01", @@ -628,10 +641,10 @@ "test/integration/historical-dataset-v2.test.ts", "test/fixtures/historical-v2/" ], - "integration_state": "validated_uncommitted", + "integration_state": "validated_committed", "reviewed_by": "/root/wave6_review", "verification_reference": "ROADMAP.md#sixth-wave-handoff--2026-10-22", - "review_notes": "Independently accepted, integrated, and combined gates passed. No commit authorized in this wave; awaiting owner acceptance/commit before scheduling dependents." + "review_notes": "Independently accepted and combined gates passed; owner authorized commit and continuation. Completed commit contains the integrated F01/D01 implementation." }, { "id": "D02", @@ -639,7 +652,7 @@ "epic": "E3", "priority": "P1", "severity": "High", - "status": "blocked", + "status": "review", "dependencies": [ "D01" ], @@ -654,12 +667,24 @@ "storage-adapters" ], "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/wave7_d02", + "branch": "wave7/d02-intraday-storage", "pull_request": null, "completed_commit": null, "blocker": null, - "release_gates": [] + "release_gates": [], + "worktree": "/tmp/stock-bot-wave7.UIkAQD/d02", + "integration_base": "b4af840d4edde84b23c099e85c82f43721046067", + "concrete_write_scope": [ + "apps/stock/orchestrator/src/services/StorageService.ts", + "apps/stock/orchestrator/src/data/", + "test/integration/intraday-storage.test.ts", + "test/fixtures/intraday/" + ], + "review_notes": "Independently accepted, exact frozen files integrated, combined repository checks passed. Seventh-wave changes remain uncommitted pending owner acceptance/commit; no downstream task started.", + "integration_state": "validated_uncommitted", + "reviewed_by": "/root/wave7_review", + "verification_reference": "ROADMAP.md#seventh-wave-handoff--2026-10-22" }, { "id": "D03", @@ -2785,6 +2810,211 @@ "Existing Rust/frontend build warnings remain." ], "cleanup": "Only verified stale sandbox check/test/worker processes were stopped after the successful escalated run; root session13178 exited143 and author session45451 exited143. No user services, databases, containers or files were removed. Worktrees/logs remain available.", - "handoff": "F01/D01 remain review/validated_uncommitted; F02/D02 await accepted integration and further execution authorization. No sixth-wave commit, push, PR, trading operation or other task started." + "handoff": "F01/D01 were independently accepted and subsequently committed at owner request as b4af840d4edde84b23c099e85c82f43721046067. The same request authorized F02/D02 continuation; no push, PR or trading operation." + }, + "seventh_wave": [ + "F02", + "D02" + ], + "seventh_wave_base": "b4af840d4edde84b23c099e85c82f43721046067", + "seventh_wave_notes": [ + "User authorized committing validated F01/D01 and continuing with the proposed F02/D02 pair; no additional ADR approval.", + "F02 owns financial modules/dependencies and economic fixtures. D02 owns StorageService, narrow data helpers, new intraday tests/fixtures; no shared DTO/index/ingestion source change without coordination.", + "One financial owner, one data owner and an independent read-only reviewer. Root owns planning and integration.", + "No active engine/paper/SQL cutover, native session API or unrelated task. Independent review and combined gates passed; awaiting owner acceptance/commit." + ], + "seventh_wave_validation": { + "result": "passed", + "reviewer": "/root/wave7_review", + "base": "b4af840d4edde84b23c099e85c82f43721046067", + "repository_check": { + "command": "CARGO_BUILD_JOBS=2 bun run check", + "log": "/tmp/stock-bot-wave7.UIkAQD/check.log", + "tooling_tests": 60, + "utility_tests": 43, + "calculation_tests": 35, + "integration_tests": 342, + "rust_tests": 59, + "manual_rust_measurement_ignored_by_default": 1, + "failed": 0, + "note": "Escalated native build/worker execution; full build/typecheck/contracts/lint/secret audit passed." + }, + "independent_review": { + "financial": "22 financial Rust tests passed;1manualmeasurement ignored;37unrelated tests filtered. All7 frozen hashes matched.", + "intraday": "36 intraday/ingestion/dataset tests passed;264assertions;3 frozen hashes and private rebuilt addon matched. These tests overlap repository totals." + }, + "scoped_checks": [ + "Standalone strict TypeScript with experimentalDecorators traversing the real ingestion import graph passed.", + "Explicit ESLint and Prettier on all3 D02 files passed.", + "Scoped rustfmt --check on financial modules and git diff --check passed." + ], + "source_hashes": { + "Cargo.lock": "8f2ecaa4f1790f14e1650326f78fbf246f454dad6139dc4cb0d61383b9e301e8", + "apps/stock/engine/Cargo.toml": "f7eb29311a0ca2a943607f722ad4fa447857bdf951a8f8d9fa30dab9095a7525", + "apps/stock/engine/src/financial/contract.rs": "06d57c12d33c4f128482544cda31347e4c640f879998dc17f0da379c3f37f9db", + "apps/stock/engine/src/financial/mod.rs": "36645e77811740de41c017dbff6193715009da708f9377d17510dd738fdefdba", + "apps/stock/engine/src/financial/scalar.rs": "65da81ecf33db78935f50aeb53094293e9d4b0814ac25e0d0c281b53b75c5e06", + "apps/stock/engine/src/financial/ledger.rs": "b9016744e76256de4af080a5eba0e635e900b3fc6cb21caee581d88519e7a707", + "apps/stock/engine/src/financial/ledger_tests.rs": "96b5f40ff4cbeeaedc09d824effc1b35888c7d30bfae850e426b48f1d0d7ab05", + "apps/stock/orchestrator/src/services/StorageService.ts": "b06b67fd1d7e29e26d6c9c4f241169f88c18c355395c0e1b9de5813012c45458", + "test/integration/intraday-storage.test.ts": "9c209620097ada21d4a47fab5092f8e3308474708ef7db2422be6daaf3eebe3e", + "test/fixtures/intraday/eod.ts": "bdb9df09718a723736d88ba62ca57dbf842cfdafdb7a6ca2a279a97a20894d45" + }, + "native_artifact": { + "path": "apps/stock/engine/dist/engine.node", + "sha256": "b8e272e5846bf8efe37f9f941920f489d012f1bacb3d5675352d1d55a63e772c", + "d02_author_sha256": "48ab4c24e8f56c1fbc537982b54ba07d42dc4b0ecec2ce34ced5ecfd354ef0ae", + "note": "Addons independently built in their own worktrees; no shared/copied native artifact. Active native simulator remains legacy." + }, + "financial_measurement": { + "command": "CARGO_BUILD_JOBS=2 cargo test -p engine --lib --release --offline ledger_transition_measurement -- --ignored --nocapture", + "log": "/tmp/stock-bot-wave7.UIkAQD/f02-measurement.log", + "artifact": "/tmp/stock-bot-wave7.UIkAQD/f02/target/release/deps/engine-abe56cbc3e15ae30", + "sha256": "b21531e5c3e97c2d09f827ffccfb89858ed88f04f3055c0d57e5a82255539424", + "host": { + "cpu": "AMD Ryzen 9 9950X3D", + "logical_cpus": 32, + "ram_bytes": 98683457536, + "os": "Linux6.8.0-146-generic x86_64", + "rustc": "1.88.0(6b00bc388),LLVM20.1.5", + "cargo_build_jobs": 2 + }, + "workload": "Prebuilt commands;80%buys(0.01@100,fee0.001),20%marks;initialcapital1m. Single1owner/1asset vs multi3owners/4assets.3repeats;no explicit warmup. Transition time includes receipts and returned-effect collection;checkpointcopy separate;restore excludes inputclone;serialization outside timed regions.", + "columns": [ + "transition_ms", + "checkpoint_ms", + "restore_ms" + ], + "rows": { + "1000_single": [ + [ + 4.823, + 0.576, + 5.484 + ], + [ + 4.16, + 0.286, + 5.9 + ], + [ + 4.244, + 0.387, + 4.99 + ] + ], + "1000_multi": [ + [ + 4.685, + 0.298, + 5.415 + ], + [ + 4.807, + 0.298, + 5.585 + ], + [ + 4.763, + 0.282, + 5.778 + ] + ], + "10000_single": [ + [ + 47.394, + 8.028, + 59.606 + ], + [ + 44.356, + 5.27, + 60.23 + ], + [ + 44.07, + 5.32, + 54.266 + ] + ], + "10000_multi": [ + [ + 50.48, + 5.235, + 62.177 + ], + [ + 51.257, + 5.547, + 65.779 + ], + [ + 51.003, + 5.662, + 60.142 + ] + ] + }, + "repeatability": "Full state+effect serialized bytes equal across repeats; DefaultHasher checksums are fixed-artifact diagnostics, not cryptographic provenance.", + "state_and_effect_bytes": { + "1000_single": 1294915, + "1000_multi": 1292139, + "10000_single": 13093921, + "10000_multi": 13050658 + }, + "limitations": "Scoped ledger sanity workload; no cold dataset/native startup/IPC/storage measurements, end-to-end throughput, legacy speedup or independent performance certification. Receipt history memory and restore work grow linearly; no compaction.", + "integration_recheck": { + "command": "CARGO_BUILD_JOBS=2 cargo test -p engine --lib --release --offline ledger_transition_measurement -- --ignored --nocapture", + "log": "/tmp/stock-bot-wave7.UIkAQD/integration-ledger-measurement.log", + "artifact": "target/release/deps/engine-abe56cbc3e15ae30", + "sha256": "b21531e5c3e97c2d09f827ffccfb89858ed88f04f3055c0d57e5a82255539424", + "result": "1passed,0failed;59filtered. Same state/effect checksums and full byte equality across repetitions.", + "raw_rows": [ + "F02 count=1000 multi=false repeat=0 transition_ms=4.819 checkpoint_ms=0.810 restore_ms=5.722 bytes=1294915 checksum=446ce8be40fd4ba1", + "F02 count=1000 multi=false repeat=1 transition_ms=4.131 checkpoint_ms=0.304 restore_ms=5.615 bytes=1294915 checksum=446ce8be40fd4ba1", + "F02 count=1000 multi=false repeat=2 transition_ms=4.203 checkpoint_ms=0.286 restore_ms=4.858 bytes=1294915 checksum=446ce8be40fd4ba1", + "F02 count=1000 multi=true repeat=0 transition_ms=4.712 checkpoint_ms=0.329 restore_ms=5.562 bytes=1292139 checksum=a1df70fcbb707e69", + "F02 count=1000 multi=true repeat=1 transition_ms=4.759 checkpoint_ms=0.288 restore_ms=5.947 bytes=1292139 checksum=a1df70fcbb707e69", + "F02 count=1000 multi=true repeat=2 transition_ms=4.733 checkpoint_ms=0.295 restore_ms=5.511 bytes=1292139 checksum=a1df70fcbb707e69", + "F02 count=10000 multi=false repeat=0 transition_ms=49.398 checkpoint_ms=8.299 restore_ms=58.845 bytes=13093921 checksum=0f92079aeb5beff5", + "F02 count=10000 multi=false repeat=1 transition_ms=42.911 checkpoint_ms=5.375 restore_ms=58.622 bytes=13093921 checksum=0f92079aeb5beff5", + "F02 count=10000 multi=false repeat=2 transition_ms=43.119 checkpoint_ms=5.354 restore_ms=53.319 bytes=13093921 checksum=0f92079aeb5beff5", + "F02 count=10000 multi=true repeat=0 transition_ms=50.560 checkpoint_ms=5.266 restore_ms=61.046 bytes=13050658 checksum=36dcaa5fd201208a", + "F02 count=10000 multi=true repeat=1 transition_ms=49.624 checkpoint_ms=5.318 restore_ms=63.990 bytes=13050658 checksum=36dcaa5fd201208a", + "F02 count=10000 multi=true repeat=2 transition_ms=50.276 checkpoint_ms=5.395 restore_ms=59.666 bytes=13050658 checksum=36dcaa5fd201208a" + ] + } + }, + "intraday_measurement": { + "kind": "author exploratory adapter-only sanity measurement", + "host": "Same Ryzen9 9950X3D/Linux x64 host;Bun1.2.17/Nodecompat22.6.0", + "recipe": "Synthetic in-memory find() rows, start2024-03-11T13:30Z at300s spacing;FIXTURE.TEST,open100/high101/low99/close100/volume1000. Time only await getHistoricalBars(...,'5m'); construction/hash serialization excluded. Three repeats;no explicitwarmup.", + "milliseconds_1000": [ + 1.727282, + 0.602739, + 0.521505 + ], + "milliseconds_10000": [ + 6.232302, + 5.555884, + 4.477247 + ], + "normalized_hash_1000": "fb2d3f213487a7a2ff0ce4a6b98d74ba793b13355439b88c3eb1efb296339158", + "normalized_hash_10000": "18138da32c3758770703c7376ef05f8c1aae941cb7884bda3c2e628fb6fdabe4", + "limits": "Identical normalized hashes across3repeats per size. No Mongo/network/real-range throughput, baseline speedup or release performance claim; no new benchmark framework." + }, + "not_run": [ + "PostgreSQL/Redis fixture suite and Chromium E2E not rerun: persistent execution/API/UI boundaries unchanged.", + "No real Mongo server/provider network test; D02 replaces HTTP/Mongo transport and executes real ingestion/storage/dataset/native code." + ], + "limitations": [ + "F02 remains additive/unwired to active engines. No F04 reservations/portfolio risk, F05 matching, F06 availability/replay, NAPI sessions, SQL/paper cutover or full order/strategy/RNG restore.", + "Ledger checkpoints validate consistency by retained-history replay, not input authenticity; restore/memory scale with receipt history. No compaction or full financial-session snapshot.", + "D02 real ingestion fixture covers5m;1m/1h routing is checked. Provider selector remains StorageService-only; existing loadDataset/UI use auto priority. Connectivity is not range coverage.", + "Provider timestamps/prices checked against https://eodhd.com/financial-apis/intraday-historical-data-api on2026-10-22. Delayed finalization/corrections mean bar-close availability is only an explicit simulation assumption, not observed publication time.", + "Initial isolated D02 builds needed existing logger/config dependencies; native sandbox attempt timed out. Escalated tests and independent rerun passed unchanged. Existing build warnings remain." + ], + "cleanup": "Only D02 stale test980112/worker980619 were terminated after exact PID/cwd checks; original session exited143 and process absence verified. No development services, databases or data touched. Worktrees/logs retained.", + "handoff": "F01/D01 committedb4af840 at owner request. F02/D02 independently accepted and validated_uncommitted, awaiting owner acceptance/commit. F04 is next prerequisite-dependent task; other ADR approvals unchanged. No push/PR/trading operation or extra task." } } diff --git a/docs/development/backlog/tasks/D02.md b/docs/development/backlog/tasks/D02.md index 10e1b8df..d8a53f08 100644 --- a/docs/development/backlog/tasks/D02.md +++ b/docs/development/backlog/tasks/D02.md @@ -14,6 +14,16 @@ Trace the actual intraday collection/schema, add the smallest provider adapter o Measurable benefit: Makes supported intraday requests usable and honest. +### Verified ingestion evidence and seventh-wave boundary + +Before implementation, inspected `apps/stock/data-ingestion/src/handlers/eod/actions/intraday.ts`: `fetchIntraday` looks up the listing, uses `eodExchange || Exchange`, copies provider Unix-second `timestamp`, `datetime`, `gmtoffset` and OHLCV, then upserts `eodIntraday1M`, `eodIntraday5M` or `eodIntraday1H` keyed by timestamp + `eodSearchCode` (lines 486–585 at base `b4af840`). The research reader currently chooses QuestDB first, otherwise only daily `eodPrices`. + +Retain the common `getHistoricalBars` admission path. Add the existing EOD intraday mapping, explicit provider selection/capabilities and typed unavailable/unsupported errors. Capabilities describe connected stores and supported intervals, not proven range coverage. Preserve default QuestDB priority and never switch provider on an empty range/error. Explicit provider requests never fall back to daily or synthetic data. Validate whole Unix seconds and listing identity; Unix timestamps are already UTC and must not be shifted by `gmtoffset`. QM's adjusted/unpinned interval records remain unsupported. + +Tests invoke the actual EOD writer with replaced HTTP/Mongo transport, then the real storage reader and v1/v2 dataset normalizers with explicit retained calendar/action metadata. This proves adapter composition, not database-server conformance or F06 replay. No optional v2 loader, active-runtime cutover or storage migration is required here. + +Provider check (2026-10-22): [EODHD's intraday documentation](https://eodhd.com/financial-apis/intraday-historical-data-api) identifies the timestamp as UTC bar start and prices as unadjusted for subsequent corporate actions. It also describes delayed finalization after market close and possible historical corrections. Retrieval therefore does **not** establish point-in-time publication availability. Interval-end availability remains an explicit simulation assumption, never provider evidence; frozen content hashes retain the actual retrieved revision. Provider choice is initially a storage API parameter, not a new web/run-configuration control. + ## Exclusions No unrelated refactor, new service or broker activation. diff --git a/docs/development/backlog/tasks/F02.md b/docs/development/backlog/tasks/F02.md index 4a77ffc7..387cee88 100644 --- a/docs/development/backlog/tasks/F02.md +++ b/docs/development/backlog/tasks/F02.md @@ -15,6 +15,16 @@ Scheduling source of truth: [manifest entry F02](../manifest.json). No task is a Implement one owner-keyed ledger from its first version; absorb F03 rather than building aggregate cost basis and replacing it later. Adapt existing Rust position calculations. Store owned quantity and remaining cost amount; derive average price and account aggregates. For a partial disposal, round the proportional released basis at posting precision; final disposal releases the exact residual. Fees are separate postings. Use one internal apply(state,command) kernel for resident research and staged durable transactions. +### Seventh-wave implementation boundary + +F01 is committed in `b4af840`. Keep this ledger additive: no replacement of active legacy position/accounting code, native binding, SQL transaction integration or paper migration. ADR-005 remains unapproved; F02 provides the in-memory transition/checkpoint seam, not its durable adapter. + +- A ledger checkpoint is distinct from F01's economic projection. It retains genesis, books including closed-position realized P&L, cash/fees, marks, risk-session identity, revision and ordered accepted receipts/aliases. Restore verifies by replay and canonical state comparison. It is not an order/replay/strategy/RNG session snapshot. +- Exact multiplication and proportional release use maintained arithmetic with a single final half-away posting boundary, not precision-losing decimal intermediates. Account valuation sums owner-level marked postings; missing marks reject valuation instead of inventing zero or cost-based prices. +- Invalid commands fail atomically without changing balances, books, marks or receipts. Basic cash funding includes fees. Reservation and portfolio risk policies remain F04, including recording accepted risk-rejection outcomes. +- Identical command retry returns its original receipt even after later transitions. Identical fill under a new command ID aliases that receipt, explicitly marked replayed: compare event time and the entire canonical fill body, excluding only command ID. Different fill content or reuse of a fee ID by another fill rejects. Never emit duplicate economic deltas. +- Normal transitions stage only affected state; checkpoint serialization/replay is explicit. Record repeatable scoped transition and checkpoint/restore measurements without claiming end-to-end research throughput. + ## Exclusions No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results. diff --git a/test/fixtures/intraday/eod.ts b/test/fixtures/intraday/eod.ts new file mode 100644 index 00000000..832de912 --- /dev/null +++ b/test/fixtures/intraday/eod.ts @@ -0,0 +1,72 @@ +import type { HistoricalDatasetMetadataV2 } from '@stock-bot/types'; + +export const identity = { symbol: 'FIXTURE', exchange: 'TEST', eodSearchCode: 'FIXTURE.TEST' }; +export const start = new Date('2024-03-11T13:30:00.000Z'); +export const end = new Date('2024-03-11T20:00:00.000Z'); + +/** Synthetic provider response matching fetchIntraday's retained fields; not market evidence. */ +export function intradayResponse() { + return Array.from({ length: 78 }, (_, index) => { + const timestamp = start.getTime() / 1000 + index * 300; + const close = 100 + Math.sin((index * Math.PI) / 6) * 8; + return { + timestamp, + datetime: new Date(timestamp * 1000).toISOString().slice(0, 19).replace('T', ' '), + gmtoffset: 0, + open: close - 0.1, + high: close + 1, + low: close - 1, + close, + volume: 100_000, + }; + }); +} + +/** Pinned by the research caller; storage must not invent calendars or eligibility. */ +export function metadata(): HistoricalDatasetMetadataV2 { + return { + calendars: [ + { + id: 'test-session', + venue: 'TEST', + timeZone: 'UTC', + revision: 'fixture-session-v1', + source: 'synthetic-regression-fixture', + startDate: '2024-03-11', + endDate: '2024-03-12', + sessions: [{ date: '2024-03-11', open: start.getTime(), close: end.getTime() }], + }, + ], + series: [ + { + id: 'fixture-5m', + instrumentId: identity.eodSearchCode, + interval: '5m', + calendarId: 'test-session', + venue: 'TEST', + source: { provider: 'eod', revision: 'synthetic-response-v1' }, + timestamp: 'interval-start', + availability: 'interval-end-assumption', + adjustment: 'raw', + }, + ], + executionSeries: [{ instrumentId: identity.eodSearchCode, seriesId: 'fixture-5m' }], + bounds: { warmupStart: start.getTime(), tradeStart: start.getTime(), tradeEnd: end.getTime() }, + universe: { + selection: 'unknown', + asOf: null, + revision: 'fixture-universe-v1', + instrumentIds: [identity.eodSearchCode], + }, + corporateActions: [ + { + instrumentId: identity.eodSearchCode, + status: 'unknown', + start: start.getTime(), + end: end.getTime(), + revision: 'fixture-action-coverage-v1', + actions: [], + }, + ], + }; +} diff --git a/test/integration/intraday-storage.test.ts b/test/integration/intraday-storage.test.ts new file mode 100644 index 00000000..a06e645b --- /dev/null +++ b/test/integration/intraday-storage.test.ts @@ -0,0 +1,416 @@ +import { describe, expect, spyOn, test } from 'bun:test'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import type { MongoDBClient, QuestDBClient } from '@stock-bot/services'; +import { fetchIntraday } from '../../apps/stock/data-ingestion/src/handlers/eod/actions/intraday'; +import type { EodHandler } from '../../apps/stock/data-ingestion/src/handlers/eod/eod.handler'; +import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter'; +import { + loadDataset, + validateDataset, +} from '../../apps/stock/orchestrator/src/data/historical-dataset'; +import { + createDatasetV2, + validateDatasetV2, +} from '../../apps/stock/orchestrator/src/data/historical-dataset-v2'; +import { + HistoricalStorageError, + StorageService, + type HistoricalStorageProvider, +} from '../../apps/stock/orchestrator/src/services/StorageService'; +import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types'; +import { end, identity, intradayResponse, metadata, start } from '../fixtures/intraday/eod'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('intraday-storage-test'); +type StoredBar = ReturnType[number] & typeof identity & { source: string }; + +/** Only HTTP and Mongo transport are replaced. Ingestion mapping and research admission are real. */ +function memoryStore() { + const documents: StoredBar[] = []; + const reads: { collection: string; filter: unknown; options: unknown }[] = []; + const mongodb = { + connected: true, + collection(name: string) { + expect(name).toBe('eodSymbols'); + return { + async findOne(filter: unknown) { + expect(filter).toEqual({ eodSearchCode: identity.eodSearchCode }); + return { + Code: identity.symbol, + Exchange: 'VENUE-METADATA', + eodExchange: identity.exchange, + }; + }, + }; + }, + async batchUpsert(collection: string, rows: StoredBar[], keys: string[]) { + expect(collection).toBe('eodIntraday5M'); + expect(keys).toEqual(['timestamp', 'eodSearchCode']); + for (const row of rows) { + const index = documents.findIndex( + old => old.timestamp === row.timestamp && old.eodSearchCode === row.eodSearchCode + ); + if (index < 0) { + documents.push(structuredClone(row)); + } else { + documents[index] = structuredClone(row); + } + } + return { insertedCount: rows.length }; + }, + async find( + collection: string, + filter: { eodSearchCode: string; timestamp: { $gte: number; $lt: number } }, + options: unknown + ) { + reads.push({ collection, filter, options }); + return documents + .filter( + row => + row.eodSearchCode === filter.eodSearchCode && + row.timestamp >= filter.timestamp.$gte && + row.timestamp < filter.timestamp.$lt + ) + .sort((a, b) => a.timestamp - b.timestamp); + }, + } as unknown as MongoDBClient; + return { mongodb, documents, reads }; +} + +async function ingest(mongodb: MongoDBClient, bars = intradayResponse()) { + const fakeFetch = async (input: Parameters[0]) => { + const url = new URL(String(input)); + // Do not print URLs: production writer includes its existing provider credentials. + expect(url.origin).toBe('https://eodhd.com'); + expect(url.pathname).toBe(`/api/intraday/${identity.eodSearchCode}`); + expect(url.searchParams.get('interval')).toBe('5m'); + expect(url.searchParams.get('from')).toBe(String(start.getTime() / 1000)); + expect(url.searchParams.get('to')).toBe(String(end.getTime() / 1000)); + return Response.json(bars); + }; + const request = spyOn(globalThis, 'fetch').mockImplementation( + Object.assign(fakeFetch, { preconnect: globalThis.fetch.preconnect }) + ); + try { + return await fetchIntraday.call({ mongodb, logger } as unknown as EodHandler, { + eodSearchCode: identity.eodSearchCode, + interval: '5m', + fromDate: start, + toDate: end, + }); + } finally { + request.mockRestore(); + } +} + +const config = () => + BacktestConfigSchema.parse({ + mode: 'backtest', + symbols: [identity.eodSearchCode], + strategy: 'sma-crossover', + startDate: start.toISOString(), + endDate: end.toISOString(), + initialCapital: 100_000, + dataFrequency: '5m', + commission: 0, + slippage: 0, + config: { fastPeriod: 3, slowPeriod: 7 }, + }); + +describe('EOD intraday ingestion → research storage', () => { + test('ingest_5m_freeze_replay: real writer/admission, v2 freeze and legacy native replay', async () => { + const store = memoryStore(); + const response = intradayResponse(); + expect(await ingest(store.mongodb, response)).toEqual({ + success: true, + recordsSaved: 78, + recordsFetched: 78, + }); + const storage = new StorageService({ logger }, store.mongodb, null, null); + const bars = await storage.getHistoricalBars(identity.eodSearchCode, start, end, '5m'); + const economicRows = bars.map(({ timestamp, open, high, low, close, volume }) => ({ + timestamp: timestamp.getTime(), + open, + high, + low, + close, + volume, + })); + const expected = response.map(({ timestamp, open, high, low, close, volume }) => ({ + timestamp: timestamp * 1000, + open, + high, + low, + close, + volume, + })); + expect(economicRows).toEqual(expected); + expect(bars.every(bar => bar.source === 'eod' && bar.vwap === undefined)).toBe(true); + const freeze = (rows: typeof expected) => + createDatasetV2({ + metadata: metadata(), + bars: rows.map((row, sourceSequence) => ({ + ...row, + seriesId: 'fixture-5m', + sourceSequence, + })), + }); + const dataset = freeze(economicRows); + expect(dataset.manifest.hash).toBe(freeze(expected).manifest.hash); + expect(dataset.manifest.barCount).toBe(response.length); + expect(dataset.manifest.eligibility).toBe('exploratory'); + expect(dataset.bars[0]?.intervalStart).toBe(start.getTime()); + expect(dataset.bars.at(-1)?.intervalEnd).toBe(end.getTime()); + expect( + dataset.bars.every(bar => bar.vwap === null && bar.availableAt === bar.intervalEnd) + ).toBe(true); + expect(validateDatasetV2(JSON.parse(JSON.stringify(dataset)))).toEqual(dataset); + + // V1 runtime stays V1. This checks storage compatibility, not future F06 replay correctness. + const legacy = await loadDataset(storage, config()); + expect( + legacy.bars.map(({ timestamp, open, high, low, close, volume }) => ({ + timestamp, + open, + high, + low, + close, + volume, + })) + ).toEqual(expected); + expect(validateDataset(JSON.parse(JSON.stringify(legacy))).manifest.hash).toBe( + legacy.manifest.hash + ); + const engine = new RustBacktestAdapter({ logger, storage }); + try { + const first = await engine.runBacktest(config(), async () => legacy); + const second = await engine.runBacktest(config(), async () => legacy); + expect(first.status).toBe('completed'); + expect(first.ohlcData[identity.eodSearchCode]).toHaveLength(78); + expect(first.ohlcData[identity.eodSearchCode]?.[0]?.timestamp).toBe(start.getTime()); + expect(first.trades.length).toBeGreaterThan(0); + expect(first.trades).toEqual(second.trades); + expect(first.equity).toEqual(second.equity); + expect(first.metrics).toEqual(second.metrics); + } finally { + await engine.shutdown(); + } + }); + + test('supported collections, UTC seconds and half-open fractional boundaries', async () => { + const store = memoryStore(); + await ingest( + store.mongodb, + intradayResponse() + .slice(0, 3) + .map(row => ({ ...row, gmtoffset: -14_400, datetime: 'untrusted local label' })) + ); + const storage = new StorageService({ logger }, store.mongodb, null, null); + for (const [interval, collection] of [ + ['1m', 'eodIntraday1M'], + ['5m', 'eodIntraday5M'], + ['1h', 'eodIntraday1H'], + ]) { + const bars = await storage.getHistoricalBars( + identity.eodSearchCode, + new Date(start.getTime() + 1), + new Date(start.getTime() + 600_000), + interval + ); + expect(bars.map(bar => bar.timestamp.getTime())).toEqual([start.getTime() + 300_000]); + expect(store.reads.at(-1)?.collection).toBe(collection); + expect(store.reads.at(-1)?.filter).toEqual({ + eodSearchCode: identity.eodSearchCode, + timestamp: { $gte: (start.getTime() + 1) / 1000, $lt: (start.getTime() + 600_000) / 1000 }, + }); + } + }); + + test('capabilities report configured connectivity and supported intervals, never stored coverage', () => { + const store = memoryStore(); + const storage = new StorageService({ logger }, store.mongodb, null, { + connected: false, + } as QuestDBClient); + expect(storage.getHistoricalCapabilities()).toEqual([ + { + provider: 'questdb', + configured: true, + connected: false, + intervals: ['1m', '5m', '15m', '1h', '1d'], + }, + { provider: 'eod', configured: true, connected: true, intervals: ['1m', '5m', '1h', '1d'] }, + ]); + expect( + new StorageService({ logger }, null, null, null) + .getHistoricalCapabilities() + .every(capability => !capability.configured && !capability.connected) + ).toBe(true); + }); + + test('unsupported_interval and provider reject explicitly without queries or synthetic fallback', async () => { + const store = memoryStore(); + const storage = new StorageService({ logger }, store.mongodb, null, null, { + allowSyntheticData: true, + }); + for (const interval of ['15m', '2m']) { + await expect( + storage.getHistoricalBars(identity.eodSearchCode, start, end, interval) + ).rejects.toMatchObject({ name: 'HistoricalStorageError', code: 'unsupported-interval' }); + } + await expect( + storage.getHistoricalBars( + identity.eodSearchCode, + start, + end, + '5m', + undefined, + undefined, + 'qm' as HistoricalStorageProvider + ) + ).rejects.toMatchObject({ code: 'unsupported-provider' }); + expect(store.reads).toHaveLength(0); + const absent = new StorageService({ logger }, null, null, null, { allowSyntheticData: true }); + for (const provider of ['eod', 'questdb'] as const) { + await expect( + absent.getHistoricalBars( + identity.eodSearchCode, + start, + end, + '5m', + undefined, + undefined, + provider + ) + ).rejects.toMatchObject({ code: 'provider-unavailable', provider }); + } + }); + + test('missing_range is typed; selecting a real provider never falls back to synthetic data', async () => { + const store = memoryStore(); + const storage = new StorageService({ logger }, store.mongodb, null, null, { + allowSyntheticData: true, + }); + try { + await storage.getHistoricalBars(identity.eodSearchCode, start, end, '5m'); + throw new Error('Expected rejection'); + } catch (error) { + expect(error).toBeInstanceOf(HistoricalStorageError); + expect(error).toMatchObject({ code: 'missing-range', provider: 'eod' }); + } + expect(store.reads.map(read => read.collection)).toEqual(['eodIntraday5M']); + }); + + test('provider_priority selects QuestDB once; empty/error never falls through, explicit EOD is available', async () => { + const store = memoryStore(); + await ingest(store.mongodb); + let fail = false; + const failure = new Error('Transport unavailable'); + let questReads = 0; + const questdb = { + async query() { + questReads++; + if (fail) { + throw failure; + } + return { rows: [] }; + }, + } as unknown as QuestDBClient; + const storage = new StorageService({ logger }, store.mongodb, null, questdb); + await expect( + storage.getHistoricalBars(identity.eodSearchCode, start, end, '5m') + ).rejects.toMatchObject({ code: 'missing-range', provider: 'questdb' }); + fail = true; + await expect(storage.getHistoricalBars(identity.eodSearchCode, start, end, '5m')).rejects.toBe( + failure + ); + expect(store.reads).toHaveLength(0); + expect( + await storage.getHistoricalBars( + identity.eodSearchCode, + start, + end, + '5m', + undefined, + undefined, + 'eod' + ) + ).toHaveLength(78); + expect(questReads).toBe(2); + }); + + test('invalid seconds, OHLCV, duplicate timestamps and incomplete listing identity fail admission', async () => { + const row = { ...intradayResponse()[0]!, ...identity, source: 'eod' }; + let records: unknown[] = [row]; + const mongodb = { + async find() { + return records; + }, + } as unknown as MongoDBClient; + const storage = new StorageService({ logger }, mongodb, null, null); + for (const timestamp of [ + String(row.timestamp), + row.timestamp + 0.5, + NaN, + Infinity, + Number.MAX_SAFE_INTEGER, + 8_640_000_000_001, + ]) { + records = [{ ...row, timestamp }]; + await expect( + storage.getHistoricalBars(identity.eodSearchCode, start, end, '5m') + ).rejects.toThrow('Unix-seconds timestamp'); + } + for (const changed of [ + { symbol: 'OTHER' }, + { exchange: 'VENUE-METADATA' }, + { exchange: undefined }, + { eodSearchCode: 'FIXTURE.OTHER' }, + ]) { + records = [{ ...row, ...changed }]; + await expect( + storage.getHistoricalBars(identity.eodSearchCode, start, end, '5m') + ).rejects.toThrow('identity mismatch'); + } + records = [{ ...row, low: -1 }]; + await expect( + storage.getHistoricalBars(identity.eodSearchCode, start, end, '5m') + ).rejects.toThrow('Invalid historical OHLCV'); + records = [row, row]; + await expect( + storage.getHistoricalBars(identity.eodSearchCode, start, end, '5m') + ).rejects.toThrow('Duplicate historical timestamps'); + records = [row]; + await expect(storage.getHistoricalBars('FIXTURE', start, end, '5m')).rejects.toThrow( + 'exchange-qualified' + ); + await expect( + storage.getHistoricalBars(identity.eodSearchCode, start, end, '5m', { + adjustment: 'provider-adjusted', + timestamp: 'utc-instant', + }) + ).rejects.toThrow('Provider-adjusted prices unavailable'); + }); + + test('cancellation before and after a read never publishes late bars', async () => { + let reads = 0; + const before = new AbortController(); + before.abort(new Error('cancelled before query')); + const after = new AbortController(); + const mongodb = { + async find() { + reads++; + after.abort(new Error('cancelled during query')); + return [{ ...intradayResponse()[0]!, ...identity }]; + }, + } as unknown as MongoDBClient; + const storage = new StorageService({ logger }, mongodb, null, null); + await expect( + storage.getHistoricalBars(identity.eodSearchCode, start, end, '5m', undefined, before.signal) + ).rejects.toThrow('cancelled before query'); + expect(reads).toBe(0); + await expect( + storage.getHistoricalBars(identity.eodSearchCode, start, end, '5m', undefined, after.signal) + ).rejects.toThrow('cancelled during query'); + expect(reads).toBe(1); + }); +});