docs: explain strategy replay and durable execution code

This commit is contained in:
Boki 2026-10-25 11:31:23 -04:00
parent 8587c71cf3
commit dd7ac53c51
19 changed files with 494 additions and 41 deletions

View file

@ -1,11 +1,14 @@
//! Additive, cash-funded long-only economic kernel. Not wired to a legacy
//! simulator, NAPI, paper persistence, order matching or portfolio risk.
//! Cash-funded, long-only accounting beneath the matcher and risk gate.
//!
//! One account shares cash, while each instrument holds separate owner books.
//! Fills change quantity/cost/cash; marks change valuation; fees are explicit
//! postings. No order eligibility, strategy sizing or exposure policy lives here.
//!
//! 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.
//! risk-policy rejections are different, accepted/recorded outcomes upstream.
use super::{
contract::*,
scalar::{Posting, ScalarError},
@ -284,6 +287,10 @@ impl Ledger {
})
}
/// Post a scoped command once. Reused command/fill IDs must retain their
/// original economic payload; exact retries return the original effects.
/// Fallible arithmetic and ownership/funding checks finish before mutation,
/// so an error leaves cash, books, revisions and receipts unchanged.
pub fn apply(&mut self, command: &EngineFinancialCommand) -> Result<ApplyOutcome, LedgerError> {
if command.session_id != self.config.session_id
|| command.account_id != self.config.account_id
@ -333,7 +340,7 @@ impl Ledger {
{
return Err(LedgerError::InvalidRiskSession);
}
// Identity only. F04 owns baseline/peak/halt policies.
// Identity only. RiskAccount owns baseline/peak/halt policies.
if self.risk_session == *risk_session {
Vec::new()
} else {
@ -370,6 +377,10 @@ impl Ledger {
});
}
/// Stage a fill in its owner's book and update account aggregates together.
/// Sells release proportional cost basis and cannot use another owner's
/// inventory. Fees reduce shared cash separately from gross realized P&L;
/// all calculations use checked fixed-decimal postings.
fn apply_fill(
&mut self,
command: &EngineFinancialCommand,
@ -671,6 +682,10 @@ impl Ledger {
}
}
/// Value actual holdings without synthesizing a liquidation trade.
/// Owner contributions plus reserve capital reconcile to account equity;
/// contributions are attribution, not separate spendable cash balances.
/// Any unmarked open holding makes valuation an error rather than zero.
pub fn valuation(&self) -> Result<LedgerValuation, LedgerError> {
if self.totals.unmarked != 0 {
return Err(LedgerError::MissingMark);
@ -715,6 +730,9 @@ impl Ledger {
}
}
/// Replay accepted receipts from genesis and compare the resulting snapshot.
/// This reconstructs indexes and validates consistency, not authenticity;
/// the durable host must retain and authenticate the checkpoint's provenance.
pub fn restore(checkpoint: LedgerCheckpoint) -> Result<Self, LedgerError> {
let mut ledger =
Self::new(checkpoint.config.clone()).map_err(|_| LedgerError::InvalidCheckpoint)?;

View file

@ -1,6 +1,9 @@
//! Additive F05 order coordinator; not connected to legacy execution.
//! F06 supplies ordered events, prior-available capacity and venue calendars.
//! No OHLC path, scheduler, strategy callback, or mutable financial escape hatch.
//! Order lifecycle shared by historical replay and quote-driven paper execution.
//!
//! The host supplies ordered events, liquidity capacity and venue sessions.
//! This module reconciles strategy intent, applies latency/price/TIF rules and
//! sends candidate fills through [`RiskAccount`]. It never calls strategies or
//! invents an intrabar OHLC path. The nested ledger is exposed read-only.
use super::{
contract::*,
ledger::Ledger,
@ -315,7 +318,8 @@ fn internal_id(value: impl Serialize) -> Id {
.expect("valid generated identity")
}
/// Pure timing predicate. F06 must separately guarantee prefix availability.
/// Pure timing predicate. The replay/paper host separately guarantees that
/// the decision used only observations available before this execution event.
pub fn eligible(submitted: &EventKey, ready_at: EventTime, event: &EventKey) -> bool {
event.phase == EventPhase::Execution && event > submitted && event.at.get() >= ready_at.get()
}
@ -474,6 +478,10 @@ impl MatchingAccount {
&self.receipts
}
/// Process one host event, checking identity, chronology and ownership first.
/// Exact retries return their original receipt with `replayed = true`;
/// callers must not publish those effects twice. An unexpected processing
/// error can terminally fail the attempt: inspect the returned status too.
pub fn apply(&mut self, command: &MatchingCommand) -> Result<MatchingOutcome, MatchingError> {
self.apply_input(&MatchingInput::Engine(command.clone()), None)
}
@ -1008,6 +1016,10 @@ impl MatchingAccount {
});
ids
}
/// Admit owners in stable lexical order against shared account resources.
/// Targets are total owner holdings, not buy/sell deltas: pending orders
/// count toward the projected holding, so repeating a target preserves an
/// already correct working order. Omitted instruments receive no update.
fn submit(
&mut self,
input: &MatchingInput,
@ -1135,6 +1147,10 @@ impl MatchingAccount {
Ok(())
}
/// Match only eligible active orders against this event's finite capacity.
/// Open events share capacity across both sides; quotes have bid/ask sizes.
/// Risk rechecks the proposed quantity and actual price before the order or
/// capacity is advanced, so an admitted order can still be rejected here.
fn execute(
&mut self,
input: &MatchingInput,
@ -1323,6 +1339,8 @@ impl MatchingAccount {
self.sessions.remove(&command.key.instrument_id);
}
MatchingCommandBody::Finish => {
// End of research cancels working orders, not holdings. Terminal
// equity therefore marks inventory without a fabricated sale/fee.
let instruments: Vec<_> = self.active.keys().cloned().collect();
for instrument in instruments {
for id in self.active_ids(&instrument) {

View file

@ -1,7 +1,17 @@
//! Canonical financial contracts, not yet connected to either legacy simulator.
//! Authoritative financial core shared by canonical research and paper execution.
//!
//! F01 defines transport and checked posting primitives. F02 owns ledger
//! transitions/idempotency; F04 owns risk; F06/F07 own replay/session state.
//! Follow one historical decision through these modules:
//! - [`replay`] publishes available bars and pauses at a strategy decision barrier.
//! - [`matching`] turns the submitted intent into orders and selects eligible fills.
//! - [`risk`] reserves cash/inventory and checks constraints again before a fill.
//! - [`ledger`] posts the accepted fill and fee to owned positions and shared cash.
//!
//! [`scalar`] supplies checked decimal arithmetic; [`contract`] defines commands
//! and effects. [`result`] and [`reporting`] read committed facts for output.
//! The native adapters in `api/replay.rs` and `api/paper.rs` expose this core to
//! TypeScript. Strategies, SQL custody and worker supervision stay outside it.
//! Historical replay supplies bar-open events; paper supplies quote events to
//! the same matcher/risk/ledger rather than a second accounting implementation.
pub mod contract;
pub mod ledger;
pub mod matching;

View file

@ -1,8 +1,8 @@
//! Internal F06 bar replay, not a public/native session or a legacy cutover.
//! Deterministic historical clock driving the canonical financial account.
//!
//! F07 must verify the frozen D01 snapshot, retain its eligibility/limitations,
//! and adapt prices to canonical decimals before calling this trusted host API.
//! This module does not authenticate provenance or repeat D01 normalization.
//! The TypeScript dataset loader verifies the retained snapshot and converts it
//! to prepared bars; `api/replay.rs` exposes this module through the native addon.
//! This module validates prepared input but does not authenticate its provenance.
//! Exact canonical prepared input/config bytes bind checkpoints independently
//! of the caller's dataset label. They are not a replacement dataset hash.
//!
@ -200,7 +200,10 @@ fn invalid(reason: &'static str) -> ReplayError {
ReplayError::InvalidInput(reason)
}
/// No mutable matcher/ledger accessor or strategy-facing future-data accessor.
/// A replay owns the event cursor, published-observation prefix and account.
/// `advance` pauses at a barrier; `submit` accepts exactly its due owners before
/// any later event can run. No mutable matcher/ledger accessor or strategy-facing
/// future-data accessor is exposed.
#[derive(Debug)]
pub struct Replay {
input: PreparedReplay,
@ -219,6 +222,8 @@ pub struct Replay {
}
impl Replay {
/// Canonicalize identity/order, validate the prepared input and build the
/// event schedule once. Construction does not publish bars or execute trades.
pub fn new(mut input: PreparedReplay, mut config: ReplayConfig) -> Result<Self, ReplayError> {
Self::canonicalize(&mut input, &mut config);
Self::validate(&input, &config)?;
@ -453,6 +458,10 @@ impl Replay {
}
Ok(())
}
/// Keep observation availability separate from physical execution time.
/// At one timestamp, observations precede the shared decision barrier,
/// then eligible opens execute, then sessions close. Stable tie-breaking
/// is economic policy: changing it can change marks, risk latches and fills.
fn events(input: &PreparedReplay, config: &ReplayConfig) -> Result<Vec<Event>, ReplayError> {
let mut events = Vec::with_capacity(input.bars.len().saturating_mul(2));
let first = config
@ -761,6 +770,8 @@ impl Replay {
}
EventBody::Open(bar_index) => {
let bar = &self.input.bars[bar_index];
// Current-bar volume is future information at its open. Use the
// latest published completed bar; no known volume means no fills.
let volume = self
.latest_observation(&bar.series_id)
.map(|b| b.volume)
@ -789,6 +800,9 @@ impl Replay {
}
Ok(())
}
/// Process at most `budget` events, yielding earlier for a decision or end.
/// An unanswered barrier is returned again without advancing. The budget
/// changes host scheduling granularity, not event order or financial policy.
pub fn advance(&mut self, budget: usize) -> Result<ReplayStep, ReplayError> {
if budget == 0 {
return Err(ReplayError::InvalidBudget);
@ -830,6 +844,9 @@ impl Replay {
},
})
}
/// Require exactly the pending owners and their shared admission revision.
/// Input validation happens before matcher mutation. A valid batch can still
/// contain risk-rejected orders; admission is not a promise of future fills.
pub fn submit(
&mut self,
mut submission: DecisionSubmission,
@ -887,8 +904,9 @@ impl Replay {
matching: self.matching.checkpoint(),
}
}
/// Deterministic fixed-decision-trace recovery. Strategy state/RNG and
/// strategy recomputation are separately owned by F07/S01.
/// Rebuild from identical prepared inputs and the recorded decision trace,
/// then compare the complete checkpoint. This recovers Rust replay state,
/// not TypeScript callback state or RNG; it does not rerun strategy logic.
pub fn restore(
input: PreparedReplay,
config: ReplayConfig,

View file

@ -1,7 +1,11 @@
//! Additive authoritative cash/risk gate. Not connected to legacy execution.
//! F05 supplies normalized orders/matching; F06 supplies the engine clock.
//! Limit crossing, TIF and execution-event eligibility are not certified here.
//! This host API is not a sandbox for arbitrary in-process Rust code.
//! Financial admission and fill-time gate between matching and the ledger.
//!
//! Orders reserve fee-inclusive cash or owner inventory before execution.
//! Actual fills recheck funding and portfolio constraints; a reservation is not
//! permission to borrow after a price gap. Marks update loss/drawdown latches.
//! The matcher owns price crossing, time-in-force and event eligibility; the
//! host owns the clock and authenticates operator actions. These Rust interfaces
//! separate responsibilities but are not an untrusted-code sandbox.
use super::{
contract::*,
ledger::*,
@ -30,7 +34,7 @@ pub enum OrderOrigin {
Target,
}
/// Already normalized by the future order coordinator. Origin is provenance,
/// Already normalized by the order coordinator. Origin is provenance,
/// never an alternate risk path. No target expansion, TIF or matching here.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
@ -196,7 +200,7 @@ pub struct RiskReceipt {
/// Journal replay validates consistency, not authenticity of genesis/history.
/// Durable provenance and operator authentication belong to the host. This is
/// risk+ledger recovery only, not F07 replay/strategy/RNG recovery.
/// risk+ledger recovery only, not replay/strategy/RNG recovery.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RiskCheckpoint {
@ -321,6 +325,10 @@ impl RiskAccount {
.checked_sub(self.reserved_cash)
.expect("cash reservations are funded")
}
/// Apply an engine command under the account's clock and identity rules.
/// A policy rejection is a recorded `RiskDisposition::Rejected`, not an
/// infrastructure error. Exact retries return their original receipt and do
/// not charge another fee, reserve more cash or move the clock.
pub fn apply(&mut self, command: &RiskCommand) -> Result<RiskOutcome, RiskError> {
self.apply_input(&RiskInput::Engine(command.clone()))
}
@ -498,6 +506,10 @@ impl RiskAccount {
Ok(None)
}
/// Buys reserve notional plus fees using fresh marks and any higher limit;
/// pending buys also consume exposure. Sells reserve only this owner's
/// uncommitted inventory, allowing reductions without passing buy-only
/// freshness and loss-halt checks. Both still obey maximum order quantity.
fn reservation(
&self,
order: &RiskOrder,
@ -558,6 +570,8 @@ impl RiskAccount {
Ok(Ok(reservation))
}
/// Loss breaches latch until an explicit reset or applicable risk-session
/// boundary; a subsequent price recovery does not itself lift the halt.
/// All operands are nonnegative representable ledger equity values, so
/// their ordered differences cannot overflow. No fallible state arithmetic
/// occurs after a ledger commit.
@ -762,6 +776,9 @@ impl RiskAccount {
let mut next = None;
let mut rejected = None;
if reservation.order.side == Side::Buy {
// Fund this fill AND the still-working remainder without
// spending other orders' reservations. A price gap may
// reject the fill and release the rest of this order.
let mark = match self
.fresh(&reservation.order.instrument_id, command.event_time)
{