944 lines
36 KiB
Rust
944 lines
36 KiB
Rust
//! Deterministic historical clock driving the canonical financial account.
|
|
//!
|
|
//! 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.
|
|
//!
|
|
//! Bars are stored once; published history is an index prefix, never a clone on
|
|
//! advance. Only explicit checkpoints copy retained history. Matching remains
|
|
//! the sole financial authority. No strategy can access the future event vector
|
|
//! through the context API. This is API separation, not a security sandbox.
|
|
use super::{
|
|
contract::*,
|
|
matching::*,
|
|
reporting::{Reporting, ReportingFacts},
|
|
scalar::{Posting, ScalarError},
|
|
};
|
|
use serde::{Deserialize, Serialize};
|
|
use std::collections::{BTreeMap, BTreeSet};
|
|
|
|
/// Always disclose these in addition to retained dataset limitations. Changing
|
|
/// mark batching is a financial-policy decision, not a replay optimization.
|
|
pub const MODEL_LIMITATIONS: &[&str] = &[
|
|
"Open-only matching uses previously available completed-bar volume, not contemporaneous liquidity.",
|
|
"Equal-time asset marks apply in lexical instrument order; intermediate equity may latch portfolio risk before the synchronized decision barrier.",
|
|
"Quote replay and abutting same-series venue sessions are not supported.",
|
|
];
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub enum DatasetEligibility {
|
|
Eligible,
|
|
Exploratory,
|
|
Ineligible,
|
|
}
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub enum PriceAdjustment {
|
|
Raw,
|
|
ProviderAdjusted,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub struct ReplaySeries {
|
|
pub series_id: Id,
|
|
pub instrument_id: Id,
|
|
pub adjustment: PriceAdjustment,
|
|
/// Exact retained venue boundaries, including the actual preceding open
|
|
/// for a mid-session warmup. Abutting sessions are unsupported in v1.
|
|
pub sessions: Vec<VenueSession>,
|
|
}
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub struct PreparedBar {
|
|
pub series_id: Id,
|
|
pub instrument_id: Id,
|
|
pub interval_start: EventTime,
|
|
pub interval_end: EventTime,
|
|
pub event_time: EventTime,
|
|
pub available_at: EventTime,
|
|
pub source_sequence: Counter,
|
|
pub open: Positive,
|
|
pub high: Positive,
|
|
pub low: Positive,
|
|
pub close: Positive,
|
|
pub volume: NonNegative,
|
|
}
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub struct ReplayBounds {
|
|
pub warmup_start: EventTime,
|
|
pub trade_start: EventTime,
|
|
pub trade_end: EventTime,
|
|
}
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub struct PreparedReplay {
|
|
pub dataset_id: Id,
|
|
pub eligibility: DatasetEligibility,
|
|
pub limitations: Vec<String>,
|
|
pub bounds: ReplayBounds,
|
|
pub series: Vec<ReplaySeries>,
|
|
pub bars: Vec<PreparedBar>,
|
|
}
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub struct DecisionCadence {
|
|
pub owner_id: Id,
|
|
/// Union of completed observation arrivals; one decision per timestamp.
|
|
pub series_ids: Vec<Id>,
|
|
}
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub struct ReplayConfig {
|
|
pub matching: MatchingConfig,
|
|
pub participation_rate: NonNegative,
|
|
pub cadence: Vec<DecisionCadence>,
|
|
pub allow_exploratory: bool,
|
|
/// Separate account clock, never inferred from an instrument's sessions.
|
|
pub risk_boundaries: Vec<RiskSessionIdentity>,
|
|
}
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub enum InputAvailability {
|
|
Missing,
|
|
Fresh {
|
|
event_time: EventTime,
|
|
available_at: EventTime,
|
|
},
|
|
Stale {
|
|
event_time: EventTime,
|
|
available_at: EventTime,
|
|
},
|
|
}
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub struct SeriesAvailability {
|
|
pub series_id: Id,
|
|
pub availability: InputAvailability,
|
|
}
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub struct DecisionBarrier {
|
|
pub barrier_id: Id,
|
|
pub at: EventTime,
|
|
/// Reservation/order-aware matching revision, not ledger revision.
|
|
pub revision: Counter,
|
|
pub owner_ids: Vec<Id>,
|
|
pub observation_count: usize,
|
|
/// Feature freshness uses the same declared age budget as financial marks.
|
|
pub inputs: Vec<SeriesAvailability>,
|
|
}
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub enum ReplayStatus {
|
|
Running,
|
|
Complete,
|
|
Failed { diagnostic: String },
|
|
}
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub enum ReplayStep {
|
|
Progress { processed: usize },
|
|
Decision(DecisionBarrier),
|
|
Complete,
|
|
Failed { diagnostic: String },
|
|
}
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub struct DecisionSubmission {
|
|
pub barrier_id: Id,
|
|
pub decisions: Vec<StrategyDecision>,
|
|
}
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub struct ReplayCheckpoint {
|
|
pub version: Version,
|
|
pub binding: String,
|
|
pub next_event: usize,
|
|
pub observation_count: usize,
|
|
pub pending: Option<DecisionBarrier>,
|
|
pub status: ReplayStatus,
|
|
pub submissions: Vec<DecisionSubmission>,
|
|
pub matching: MatchingCheckpoint,
|
|
}
|
|
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
|
pub enum ReplayError {
|
|
#[error("invalid prepared replay input: {0}")]
|
|
InvalidInput(&'static str),
|
|
#[error("advance requires a positive event budget")]
|
|
InvalidBudget,
|
|
#[error("submission does not match the pending barrier and exact due owners")]
|
|
InvalidSubmission,
|
|
#[error("replay is terminal")]
|
|
Terminal,
|
|
#[error("checkpoint input/config or retained replay state does not match")]
|
|
InvalidCheckpoint,
|
|
#[error(transparent)]
|
|
Matching(#[from] MatchingError),
|
|
#[error(transparent)]
|
|
Arithmetic(#[from] ScalarError),
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
enum EventBody {
|
|
OpenSession(VenueSession),
|
|
RiskBoundary(RiskSessionIdentity),
|
|
Observe(usize),
|
|
Decision(Vec<Id>),
|
|
Open(usize),
|
|
CloseSession(Id),
|
|
Finish,
|
|
}
|
|
#[derive(Debug, Clone)]
|
|
struct Event {
|
|
key: EventKey,
|
|
// Session/account controls precede observations; series ID breaks feature
|
|
// source-sequence ties. Matcher observation keys receive canonical ranks.
|
|
control_rank: u8,
|
|
series_id: Id,
|
|
body: EventBody,
|
|
}
|
|
fn id(value: impl Serialize) -> Id {
|
|
serde_json::from_value(serde_json::Value::String(
|
|
serde_json::to_string(&value).unwrap(),
|
|
))
|
|
.unwrap()
|
|
}
|
|
fn time_order(bar: &PreparedBar) -> (i64, u64) {
|
|
(bar.event_time.get(), bar.source_sequence.get())
|
|
}
|
|
fn invalid(reason: &'static str) -> ReplayError {
|
|
ReplayError::InvalidInput(reason)
|
|
}
|
|
|
|
/// 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,
|
|
config: ReplayConfig,
|
|
binding: String,
|
|
events: Vec<Event>,
|
|
next_event: usize,
|
|
published: Vec<usize>,
|
|
latest: BTreeMap<Id, usize>,
|
|
execution_series: BTreeSet<Id>,
|
|
pending: Option<DecisionBarrier>,
|
|
status: ReplayStatus,
|
|
submissions: Vec<DecisionSubmission>,
|
|
matching: MatchingAccount,
|
|
reporting: Reporting,
|
|
}
|
|
|
|
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)?;
|
|
let matching = MatchingAccount::new(config.matching.clone())?.0;
|
|
let events = Self::events(&input, &config)?;
|
|
let binding =
|
|
serde_json::to_string(&(&input, &config)).expect("serializable prepared input");
|
|
let execution_series = config
|
|
.matching
|
|
.series
|
|
.iter()
|
|
.map(|s| s.series_id.clone())
|
|
.collect();
|
|
let reporting = Reporting::new(
|
|
&config.matching.risk.ledger.risk_session,
|
|
&config.risk_boundaries,
|
|
&input.bounds,
|
|
matching.ledger().cash(),
|
|
);
|
|
Ok(Self {
|
|
input,
|
|
config,
|
|
binding,
|
|
events,
|
|
next_event: 0,
|
|
published: Vec::new(),
|
|
latest: BTreeMap::new(),
|
|
execution_series,
|
|
pending: None,
|
|
status: ReplayStatus::Running,
|
|
submissions: Vec::new(),
|
|
matching,
|
|
reporting,
|
|
})
|
|
}
|
|
fn canonicalize(input: &mut PreparedReplay, config: &mut ReplayConfig) {
|
|
input.series.sort_by(|a, b| a.series_id.cmp(&b.series_id));
|
|
for series in &mut input.series {
|
|
series.sessions.sort_by_key(|s| s.opens_at.get());
|
|
}
|
|
input.bars.sort_by(|a, b| {
|
|
(
|
|
&a.series_id,
|
|
a.interval_start.get(),
|
|
a.source_sequence.get(),
|
|
)
|
|
.cmp(&(
|
|
&b.series_id,
|
|
b.interval_start.get(),
|
|
b.source_sequence.get(),
|
|
))
|
|
});
|
|
input.limitations.sort();
|
|
config
|
|
.matching
|
|
.owners
|
|
.sort_by(|a, b| a.owner_id.cmp(&b.owner_id));
|
|
config.matching.risk.ledger.owner_ids.sort();
|
|
config
|
|
.matching
|
|
.series
|
|
.sort_by(|a, b| a.instrument_id.cmp(&b.instrument_id));
|
|
config.cadence.sort_by(|a, b| a.owner_id.cmp(&b.owner_id));
|
|
for cadence in &mut config.cadence {
|
|
cadence.series_ids.sort();
|
|
}
|
|
config.risk_boundaries.sort_by_key(|s| s.starts_at.get());
|
|
}
|
|
fn validate(input: &PreparedReplay, config: &ReplayConfig) -> Result<(), ReplayError> {
|
|
let b = &input.bounds;
|
|
if b.warmup_start.get() > b.trade_start.get() || b.trade_start.get() >= b.trade_end.get() {
|
|
return Err(invalid(
|
|
"bounds must satisfy warmupStart <= tradeStart < tradeEnd",
|
|
));
|
|
}
|
|
if input.eligibility == DatasetEligibility::Ineligible
|
|
|| (input.eligibility == DatasetEligibility::Exploratory
|
|
&& (!config.allow_exploratory || input.limitations.is_empty()))
|
|
{
|
|
return Err(invalid(
|
|
"dataset eligibility/limitations do not permit this run",
|
|
));
|
|
}
|
|
if Posting::from(config.participation_rate) > "1".parse::<Posting>().unwrap() {
|
|
return Err(invalid("participation must be between zero and one"));
|
|
}
|
|
if input.series.is_empty()
|
|
|| input
|
|
.series
|
|
.windows(2)
|
|
.any(|w| w[0].series_id == w[1].series_id)
|
|
{
|
|
return Err(invalid("series IDs must be unique and nonempty"));
|
|
}
|
|
let series: BTreeMap<_, _> = input.series.iter().map(|s| (&s.series_id, s)).collect();
|
|
for s in &input.series {
|
|
let mut ids = BTreeSet::new();
|
|
for session in &s.sessions {
|
|
if session.opens_at.get() >= session.closes_at.get()
|
|
|| !ids.insert(&session.session_id)
|
|
{
|
|
return Err(invalid("invalid or duplicate retained session"));
|
|
}
|
|
}
|
|
if s.sessions
|
|
.windows(2)
|
|
.any(|w| w[0].closes_at.get() >= w[1].opens_at.get())
|
|
{
|
|
return Err(invalid(
|
|
"overlapping or abutting retained sessions are unsupported",
|
|
));
|
|
}
|
|
}
|
|
let instruments: BTreeSet<_> = input.series.iter().map(|s| &s.instrument_id).collect();
|
|
let execution: BTreeSet<_> = config
|
|
.matching
|
|
.series
|
|
.iter()
|
|
.map(|s| &s.instrument_id)
|
|
.collect();
|
|
if instruments != execution {
|
|
return Err(invalid(
|
|
"each instrument needs exactly one execution series",
|
|
));
|
|
}
|
|
let initial = config.matching.risk.ledger.risk_session.starts_at.get();
|
|
if initial > b.warmup_start.get() {
|
|
return Err(invalid("initial account clock follows warmup"));
|
|
}
|
|
for e in &config.matching.series {
|
|
let s = series
|
|
.get(&e.series_id)
|
|
.ok_or_else(|| invalid("unknown execution series"))?;
|
|
if e.mode != ExecutionMode::Open {
|
|
return Err(invalid("quote replay has no D01 dataset contract yet"));
|
|
}
|
|
if e.instrument_id != s.instrument_id || s.adjustment != PriceAdjustment::Raw {
|
|
return Err(invalid(
|
|
"execution series must agree with instrument and contain raw prices",
|
|
));
|
|
}
|
|
for session in &s.sessions {
|
|
if session.closes_at.get() > b.warmup_start.get()
|
|
&& session.opens_at.get() < b.trade_end.get()
|
|
&& session.opens_at.get() < initial
|
|
{
|
|
return Err(invalid(
|
|
"initial account clock follows true preceding venue open",
|
|
));
|
|
}
|
|
}
|
|
}
|
|
let mut sequences = BTreeSet::new();
|
|
let mut intervals = BTreeMap::new();
|
|
for bar in &input.bars {
|
|
let s = series
|
|
.get(&bar.series_id)
|
|
.ok_or_else(|| invalid("bar references unknown series"))?;
|
|
if bar.instrument_id != s.instrument_id
|
|
|| bar.interval_start.get() < b.warmup_start.get()
|
|
|| bar.interval_start.get() >= b.trade_end.get()
|
|
|| bar.interval_end.get() > b.trade_end.get()
|
|
|| bar.interval_start.get() >= bar.interval_end.get()
|
|
|| bar.event_time != bar.interval_end
|
|
|| bar.available_at.get() < bar.interval_end.get()
|
|
{
|
|
return Err(invalid("invalid bar identity, timing or bounds"));
|
|
}
|
|
if !sequences.insert((&bar.series_id, bar.source_sequence.get())) {
|
|
return Err(invalid("source sequence must be unique within its series"));
|
|
}
|
|
if intervals
|
|
.insert(&bar.series_id, bar.interval_end.get())
|
|
.is_some_and(|end| end > bar.interval_start.get())
|
|
{
|
|
return Err(invalid("overlapping or duplicate bar intervals"));
|
|
}
|
|
let low: Posting = bar.low.into();
|
|
let high: Posting = bar.high.into();
|
|
if low > high
|
|
|| Posting::from(bar.open) < low
|
|
|| Posting::from(bar.open) > high
|
|
|| Posting::from(bar.close) < low
|
|
|| Posting::from(bar.close) > high
|
|
{
|
|
return Err(invalid("inconsistent OHLC prices"));
|
|
}
|
|
// Session lookup is logarithmic, not a full calendar scan per bar.
|
|
let session = s
|
|
.sessions
|
|
.partition_point(|v| v.opens_at.get() <= bar.interval_start.get());
|
|
if session == 0 || s.sessions[session - 1].closes_at.get() < bar.interval_end.get() {
|
|
return Err(invalid("bar is not contained in a retained venue session"));
|
|
}
|
|
}
|
|
if intervals.len() != input.series.len() {
|
|
return Err(invalid(
|
|
"every declared series requires at least one prepared bar",
|
|
));
|
|
}
|
|
let owners: Vec<_> = config.matching.owners.iter().map(|o| &o.owner_id).collect();
|
|
if owners
|
|
!= config
|
|
.cadence
|
|
.iter()
|
|
.map(|c| &c.owner_id)
|
|
.collect::<Vec<_>>()
|
|
{
|
|
return Err(invalid("each owner requires exactly one declared cadence"));
|
|
}
|
|
for c in &config.cadence {
|
|
if c.series_ids.is_empty()
|
|
|| c.series_ids.windows(2).any(|w| w[0] == w[1])
|
|
|| c.series_ids.iter().any(|s| !series.contains_key(s))
|
|
{
|
|
return Err(invalid("cadence series must be known and distinct"));
|
|
}
|
|
}
|
|
let risk = &config.matching.risk.ledger.risk_session;
|
|
let mut prior = initial;
|
|
let mut risk_ids = BTreeSet::from([&risk.session_id]);
|
|
for boundary in &config.risk_boundaries {
|
|
if boundary.calendar_id != risk.calendar_id
|
|
|| boundary.calendar_revision != risk.calendar_revision
|
|
|| boundary.starts_at.get() <= prior
|
|
|| boundary.starts_at.get() > b.trade_end.get()
|
|
|| !risk_ids.insert(&boundary.session_id)
|
|
{
|
|
return Err(invalid("invalid account risk boundary"));
|
|
}
|
|
prior = boundary.starts_at.get();
|
|
}
|
|
Ok(())
|
|
}
|
|
/// 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
|
|
.matching
|
|
.series
|
|
.first()
|
|
.ok_or_else(|| invalid("missing execution series"))?
|
|
.instrument_id
|
|
.clone();
|
|
let last = config.matching.series.last().unwrap().instrument_id.clone();
|
|
let mut push = |at, phase, instrument_id: Id, sequence: Counter, rank, series_id, body| {
|
|
events.push(Event {
|
|
key: EventKey {
|
|
at,
|
|
phase,
|
|
instrument_id,
|
|
source_sequence: sequence,
|
|
},
|
|
control_rank: rank,
|
|
series_id,
|
|
body,
|
|
});
|
|
};
|
|
let zero: Counter = 0.try_into().unwrap();
|
|
let mut execution = BTreeMap::new();
|
|
for e in &config.matching.series {
|
|
execution.insert(&e.series_id, &e.instrument_id);
|
|
let s = input
|
|
.series
|
|
.iter()
|
|
.find(|s| s.series_id == e.series_id)
|
|
.unwrap();
|
|
for session in &s.sessions {
|
|
if session.closes_at.get() <= input.bounds.warmup_start.get()
|
|
|| session.opens_at.get() >= input.bounds.trade_end.get()
|
|
{
|
|
continue;
|
|
}
|
|
push(
|
|
session.opens_at,
|
|
EventPhase::Observation,
|
|
e.instrument_id.clone(),
|
|
zero,
|
|
0,
|
|
s.series_id.clone(),
|
|
EventBody::OpenSession(session.clone()),
|
|
);
|
|
if session.closes_at.get() <= input.bounds.trade_end.get() {
|
|
push(
|
|
session.closes_at,
|
|
EventPhase::SessionClose,
|
|
e.instrument_id.clone(),
|
|
zero,
|
|
0,
|
|
s.series_id.clone(),
|
|
EventBody::CloseSession(session.session_id.clone()),
|
|
);
|
|
}
|
|
}
|
|
}
|
|
for boundary in &config.risk_boundaries {
|
|
push(
|
|
boundary.starts_at,
|
|
EventPhase::Observation,
|
|
first.clone(),
|
|
zero,
|
|
1,
|
|
first.clone(),
|
|
EventBody::RiskBoundary(boundary.clone()),
|
|
);
|
|
}
|
|
let mut cadence: BTreeMap<&Id, Vec<&Id>> = BTreeMap::new();
|
|
for c in &config.cadence {
|
|
for series in &c.series_ids {
|
|
cadence.entry(series).or_default().push(&c.owner_id);
|
|
}
|
|
}
|
|
let mut decisions: BTreeMap<i64, BTreeSet<Id>> = BTreeMap::new();
|
|
for (index, bar) in input.bars.iter().enumerate() {
|
|
if bar.available_at.get() <= input.bounds.trade_end.get() {
|
|
push(
|
|
bar.available_at,
|
|
EventPhase::Observation,
|
|
bar.instrument_id.clone(),
|
|
bar.source_sequence,
|
|
2,
|
|
bar.series_id.clone(),
|
|
EventBody::Observe(index),
|
|
);
|
|
if bar.available_at.get() >= input.bounds.trade_start.get()
|
|
&& bar.available_at.get() < input.bounds.trade_end.get()
|
|
{
|
|
for owner in cadence.get(&bar.series_id).into_iter().flatten() {
|
|
decisions
|
|
.entry(bar.available_at.get())
|
|
.or_default()
|
|
.insert((*owner).clone());
|
|
}
|
|
}
|
|
}
|
|
if execution.contains_key(&bar.series_id)
|
|
&& bar.interval_start.get() >= input.bounds.trade_start.get()
|
|
{
|
|
push(
|
|
bar.interval_start,
|
|
EventPhase::Execution,
|
|
bar.instrument_id.clone(),
|
|
bar.source_sequence,
|
|
0,
|
|
bar.series_id.clone(),
|
|
EventBody::Open(index),
|
|
);
|
|
}
|
|
}
|
|
for (at, owners) in decisions {
|
|
push(
|
|
at.try_into().unwrap(),
|
|
EventPhase::Decision,
|
|
first.clone(),
|
|
zero,
|
|
0,
|
|
first.clone(),
|
|
EventBody::Decision(owners.into_iter().collect()),
|
|
);
|
|
}
|
|
push(
|
|
input.bounds.trade_end,
|
|
EventPhase::SessionClose,
|
|
last.clone(),
|
|
zero,
|
|
3,
|
|
last,
|
|
EventBody::Finish,
|
|
);
|
|
events.sort_by(|a, b| {
|
|
(
|
|
a.key.at.get(),
|
|
a.key.phase,
|
|
&a.key.instrument_id,
|
|
a.control_rank,
|
|
a.key.source_sequence.get(),
|
|
&a.series_id,
|
|
)
|
|
.cmp(&(
|
|
b.key.at.get(),
|
|
b.key.phase,
|
|
&b.key.instrument_id,
|
|
b.control_rank,
|
|
b.key.source_sequence.get(),
|
|
&b.series_id,
|
|
))
|
|
});
|
|
// Matcher has no series field in its key. Give same-phase observations
|
|
// canonical ranks after sorting by source sequence + stable series ID;
|
|
// execution keys retain the actual pinned-series source sequence.
|
|
let mut previous = None;
|
|
let mut rank = 0_u64;
|
|
for event in &mut events {
|
|
let group = (
|
|
event.key.at.get(),
|
|
event.key.phase,
|
|
event.key.instrument_id.clone(),
|
|
);
|
|
if previous.as_ref() == Some(&group) {
|
|
rank += 1;
|
|
} else {
|
|
rank = 0;
|
|
}
|
|
if event.key.phase != EventPhase::Execution {
|
|
event.key.source_sequence = rank
|
|
.try_into()
|
|
.map_err(|_| invalid("event rank overflow"))?;
|
|
}
|
|
previous = Some(group);
|
|
}
|
|
Ok(events)
|
|
}
|
|
pub fn status(&self) -> &ReplayStatus {
|
|
&self.status
|
|
}
|
|
pub fn barrier(&self) -> Option<&DecisionBarrier> {
|
|
self.pending.as_ref()
|
|
}
|
|
pub fn financial(&self) -> &MatchingAccount {
|
|
&self.matching
|
|
}
|
|
/// Only already published bars, in canonical arrival order.
|
|
pub fn observations(&self) -> impl Iterator<Item = &PreparedBar> {
|
|
self.published.iter().map(|i| &self.input.bars[*i])
|
|
}
|
|
/// Host transfer cursor over the published prefix only. Beyond the current
|
|
/// prefix is empty; no future bar is revealed, and no preceding rows scan.
|
|
pub fn observations_since(&self, offset: usize) -> impl Iterator<Item = &PreparedBar> {
|
|
self.published
|
|
.get(offset..)
|
|
.unwrap_or_default()
|
|
.iter()
|
|
.map(|i| &self.input.bars[*i])
|
|
}
|
|
pub fn latest_observation(&self, series: &Id) -> Option<&PreparedBar> {
|
|
self.latest.get(series).map(|i| &self.input.bars[*i])
|
|
}
|
|
pub fn limitations(&self) -> &[String] {
|
|
&self.input.limitations
|
|
}
|
|
pub fn model_limitations(&self) -> &'static [&'static str] {
|
|
MODEL_LIMITATIONS
|
|
}
|
|
pub fn reporting(&self) -> Result<&ReportingFacts, &str> {
|
|
if self.status != ReplayStatus::Complete {
|
|
return Err("only a complete replay can report successfully");
|
|
}
|
|
self.reporting.facts()
|
|
}
|
|
|
|
fn command(
|
|
&mut self,
|
|
index: usize,
|
|
key: EventKey,
|
|
body: MatchingCommandBody,
|
|
) -> Result<(), ReplayError> {
|
|
let at = key.at;
|
|
let out = self.matching.apply(&MatchingCommand {
|
|
command_id: id(("replay", index)),
|
|
key,
|
|
body,
|
|
})?;
|
|
self.reporting.committed(at, &out, self.matching.ledger());
|
|
if let AttemptStatus::Failed { diagnostic } = out.status {
|
|
self.status = ReplayStatus::Failed { diagnostic };
|
|
}
|
|
Ok(())
|
|
}
|
|
fn process(&mut self, index: usize, event: Event) -> Result<(), ReplayError> {
|
|
let key = event.key;
|
|
match event.body {
|
|
EventBody::OpenSession(session) => {
|
|
self.command(index, key, MatchingCommandBody::OpenSession { session })?
|
|
}
|
|
EventBody::RiskBoundary(risk_session) => self.command(
|
|
index,
|
|
key,
|
|
MatchingCommandBody::RiskSessionBoundary { risk_session },
|
|
)?,
|
|
EventBody::CloseSession(session_id) => {
|
|
self.command(index, key, MatchingCommandBody::CloseSession { session_id })?
|
|
}
|
|
EventBody::Observe(bar_index) => {
|
|
let bar = &self.input.bars[bar_index];
|
|
self.published.push(bar_index);
|
|
if self
|
|
.latest
|
|
.get(&bar.series_id)
|
|
.is_none_or(|old| time_order(bar) > time_order(&self.input.bars[*old]))
|
|
{
|
|
self.latest.insert(bar.series_id.clone(), bar_index);
|
|
}
|
|
if self.execution_series.contains(&bar.series_id)
|
|
&& self.latest.get(&bar.series_id) == Some(&bar_index)
|
|
// A delayed close at t must not replace the next interval's
|
|
// already processed open at t (Execution follows Observation).
|
|
&& self.matching.ledger().mark(&bar.instrument_id).is_none_or(|m| bar.event_time.get() > m.event_time.get())
|
|
{
|
|
let body = MatchingCommandBody::Mark {
|
|
series_id: bar.series_id.clone(),
|
|
price: bar.close,
|
|
observed_at: bar.event_time,
|
|
};
|
|
self.command(index, key, body)?;
|
|
}
|
|
}
|
|
EventBody::Decision(owner_ids) => {
|
|
let max_age = self.config.matching.risk.max_mark_age_ms.get();
|
|
let inputs = self
|
|
.input
|
|
.series
|
|
.iter()
|
|
.map(|series| {
|
|
let availability = match self.latest_observation(&series.series_id) {
|
|
None => InputAvailability::Missing,
|
|
Some(b) if (key.at.get() - b.event_time.get()) as u64 > max_age => {
|
|
InputAvailability::Stale {
|
|
event_time: b.event_time,
|
|
available_at: b.available_at,
|
|
}
|
|
}
|
|
Some(b) => InputAvailability::Fresh {
|
|
event_time: b.event_time,
|
|
available_at: b.available_at,
|
|
},
|
|
};
|
|
SeriesAvailability {
|
|
series_id: series.series_id.clone(),
|
|
availability,
|
|
}
|
|
})
|
|
.collect();
|
|
self.pending = Some(DecisionBarrier {
|
|
barrier_id: id(("barrier", index, key.at.get())),
|
|
at: key.at,
|
|
revision: self.matching.admission_revision(),
|
|
owner_ids,
|
|
observation_count: self.published.len(),
|
|
inputs,
|
|
});
|
|
}
|
|
EventBody::Open(bar_index) => {
|
|
let bar = &self.input.bars[bar_index];
|
|
// 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)
|
|
.unwrap_or_else(|| Posting::ZERO.try_into().unwrap());
|
|
let capacity =
|
|
Posting::notional(volume.into(), self.config.participation_rate.into())?
|
|
.try_into()
|
|
.expect("nonnegative participation");
|
|
let body = MatchingCommandBody::Execute {
|
|
series_id: bar.series_id.clone(),
|
|
observation: ExecutionObservation::Open {
|
|
opens_at: bar.interval_start,
|
|
price: bar.open,
|
|
capacity,
|
|
},
|
|
};
|
|
self.command(index, key, body)?;
|
|
}
|
|
EventBody::Finish => {
|
|
self.command(index, key, MatchingCommandBody::Finish)?;
|
|
if self.status == ReplayStatus::Running {
|
|
self.status = ReplayStatus::Complete;
|
|
self.reporting.finish(self.matching.ledger());
|
|
}
|
|
}
|
|
}
|
|
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);
|
|
}
|
|
if let Some(barrier) = &self.pending {
|
|
return Ok(ReplayStep::Decision(barrier.clone()));
|
|
}
|
|
let mut processed = 0;
|
|
while self.status == ReplayStatus::Running && processed < budget {
|
|
let index = self.next_event;
|
|
let event = self.events[index].clone();
|
|
let at = event.key.at;
|
|
let observation = event.key.phase == EventPhase::Observation;
|
|
self.next_event += 1;
|
|
processed += 1;
|
|
if let Err(error) = self.process(index, event) {
|
|
self.status = ReplayStatus::Failed {
|
|
diagnostic: error.to_string(),
|
|
};
|
|
}
|
|
if observation
|
|
&& self.status == ReplayStatus::Running
|
|
&& self.events.get(self.next_event).is_none_or(|next| {
|
|
next.key.at != at || next.key.phase != EventPhase::Observation
|
|
})
|
|
{
|
|
self.reporting
|
|
.after_observations(at, self.matching.ledger());
|
|
}
|
|
if let Some(barrier) = &self.pending {
|
|
return Ok(ReplayStep::Decision(barrier.clone()));
|
|
}
|
|
}
|
|
Ok(match &self.status {
|
|
ReplayStatus::Running => ReplayStep::Progress { processed },
|
|
ReplayStatus::Complete => ReplayStep::Complete,
|
|
ReplayStatus::Failed { diagnostic } => ReplayStep::Failed {
|
|
diagnostic: diagnostic.clone(),
|
|
},
|
|
})
|
|
}
|
|
/// 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,
|
|
) -> Result<MatchingOutcome, ReplayError> {
|
|
if self.status != ReplayStatus::Running {
|
|
return Err(ReplayError::Terminal);
|
|
}
|
|
let barrier = self
|
|
.pending
|
|
.as_ref()
|
|
.ok_or(ReplayError::InvalidSubmission)?;
|
|
submission
|
|
.decisions
|
|
.sort_by(|a, b| a.decision.owner_id.cmp(&b.decision.owner_id));
|
|
let owners: Vec<_> = submission
|
|
.decisions
|
|
.iter()
|
|
.map(|d| &d.decision.owner_id)
|
|
.collect();
|
|
if submission.barrier_id != barrier.barrier_id
|
|
|| owners != barrier.owner_ids.iter().collect::<Vec<_>>()
|
|
|| submission
|
|
.decisions
|
|
.iter()
|
|
.any(|d| d.barrier_id != barrier.barrier_id || d.revision != barrier.revision)
|
|
{
|
|
return Err(ReplayError::InvalidSubmission);
|
|
}
|
|
let index = self.next_event - 1;
|
|
let out = self.matching.apply(&MatchingCommand {
|
|
command_id: id(("replay", index)),
|
|
key: self.events[index].key.clone(),
|
|
body: MatchingCommandBody::Submit {
|
|
decisions: submission.decisions.clone(),
|
|
},
|
|
})?;
|
|
self.submissions.push(submission);
|
|
self.pending = None;
|
|
if let AttemptStatus::Failed { diagnostic } = &out.status {
|
|
self.status = ReplayStatus::Failed {
|
|
diagnostic: diagnostic.clone(),
|
|
};
|
|
}
|
|
Ok(out)
|
|
}
|
|
pub fn checkpoint(&self) -> ReplayCheckpoint {
|
|
ReplayCheckpoint {
|
|
version: Version,
|
|
binding: self.binding.clone(),
|
|
next_event: self.next_event,
|
|
observation_count: self.published.len(),
|
|
pending: self.pending.clone(),
|
|
status: self.status.clone(),
|
|
submissions: self.submissions.clone(),
|
|
matching: self.matching.checkpoint(),
|
|
}
|
|
}
|
|
/// 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,
|
|
checkpoint: &ReplayCheckpoint,
|
|
) -> Result<Self, ReplayError> {
|
|
let mut replay = Self::new(input, config)?;
|
|
if replay.binding != checkpoint.binding || checkpoint.next_event > replay.events.len() {
|
|
return Err(ReplayError::InvalidCheckpoint);
|
|
}
|
|
let mut submissions = checkpoint.submissions.iter();
|
|
while replay.next_event < checkpoint.next_event {
|
|
if replay.status != ReplayStatus::Running {
|
|
return Err(ReplayError::InvalidCheckpoint);
|
|
}
|
|
replay.advance(1)?;
|
|
if replay.pending.is_some() {
|
|
if replay.next_event == checkpoint.next_event && checkpoint.pending.is_some() {
|
|
break;
|
|
}
|
|
replay
|
|
.submit(
|
|
submissions
|
|
.next()
|
|
.ok_or(ReplayError::InvalidCheckpoint)?
|
|
.clone(),
|
|
)
|
|
.map_err(|_| ReplayError::InvalidCheckpoint)?;
|
|
}
|
|
}
|
|
if submissions.next().is_some() || replay.checkpoint() != *checkpoint {
|
|
return Err(ReplayError::InvalidCheckpoint);
|
|
}
|
|
Ok(replay)
|
|
}
|
|
}
|