feat(execution): preserve durable recovery on canonical Rust core

This commit is contained in:
Boki 2026-10-23 15:58:44 -04:00
parent 5e9655de0b
commit c01e96e4dd
27 changed files with 3644 additions and 182 deletions

View file

@ -1,12 +1,14 @@
mod backtest;
mod indicators;
mod replay;
mod paper;
mod risk;
mod strategy_parameters;
pub use backtest::BacktestEngine;
pub use indicators::{IncrementalEMA, IncrementalRSI, IncrementalSMA, TechnicalIndicators};
pub use replay::FinancialReplaySession;
pub use paper::stage_financial_transaction;
pub use risk::{OrderbookAnalyzer, RiskAnalyzer};
use crate::risk::RiskLimits;

View file

@ -0,0 +1,184 @@
//! Stateless trusted durable-host seam. SQL owns custody and commit/publication;
//! MatchingAccount owns all financial transitions. No process-resident mutation.
use crate::financial::{contract::*, matching::*, risk::RiskAccount};
use napi::{Error, Result};
#[cfg(not(test))]
use napi_derive::napi;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::BTreeMap;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct Identity {
session_id: Id,
account_id: Id,
}
#[derive(Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
enum Request {
Initialize {
version: Version,
identity: Identity,
config: MatchingConfig,
},
Apply {
version: Version,
identity: Identity,
checkpoint: MatchingCheckpoint,
command: MatchingCommand,
},
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct JournalEntry {
index: Counter,
effect: MatchingEffect,
view_after: Value,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct Response {
version: Version,
identity: Identity,
checkpoint: MatchingCheckpoint,
view: Value,
outcome: Option<MatchingOutcome>,
journal: Vec<JournalEntry>,
}
fn error(error: impl std::fmt::Display) -> Error {
Error::from_reason(error.to_string())
}
// Option fields in checkpoints are required wire fields, including explicit nulls.
fn keys_match(input: &Value, typed: &Value) -> bool {
match (input, typed) {
(Value::Object(a), Value::Object(b)) => {
a.len() == b.len()
&& a.iter()
.all(|(k, v)| b.get(k).is_some_and(|other| keys_match(v, other)))
}
(Value::Array(a), Value::Array(b)) => {
a.len() == b.len() && a.iter().zip(b).all(|(a, b)| keys_match(a, b))
}
_ => true,
}
}
fn view(
risk: &RiskAccount,
orders: &BTreeMap<Id, ManagedOrder>,
revision: Counter,
) -> Result<Value> {
Ok(json!({
"admissionRevision": revision,
"portfolio": risk.ledger().economic_snapshot(),
"equity": risk.ledger().equity().map_err(error)?,
"availableCash": risk.available_cash(),
"orders": risk.reservations().filter_map(|r|orders.get(&r.order.order_id)).filter(|o|o.status == OrderStatus::Open).collect::<Vec<_>>(),
"reservations": risk.reservations().collect::<Vec<_>>(),
"risk": risk.state(),
}))
}
fn order_map(orders: impl IntoIterator<Item = ManagedOrder>) -> BTreeMap<Id, ManagedOrder> {
orders
.into_iter()
.map(|order| (order.order.order_id.clone(), order))
.collect()
}
fn stage(request: Request) -> Result<Response> {
let (identity, mut account, command) = match request {
Request::Initialize {
identity, config, ..
} => (
identity,
MatchingAccount::new(config).map_err(error)?.0,
None,
),
Request::Apply {
identity,
checkpoint,
command,
..
} => (
identity,
MatchingAccount::restore(checkpoint).map_err(error)?.0,
Some(command),
),
};
let before = account.checkpoint();
if before.config.risk.ledger.session_id != identity.session_id
|| before.config.risk.ledger.account_id != identity.account_id
{
return Err(error("financial transaction identity mismatch"));
}
let outcome = command
.as_ref()
.map(|command| account.apply(command).map_err(error))
.transpose()?;
let checkpoint = account.checkpoint();
let mut journal = Vec::new();
if let Some(outcome) = &outcome {
if !outcome.replayed {
// Recovery-only projections: reapply exact retained commands through
// the same risk kernel. Never approximate intermediate state in TS.
let (mut risk, authority) = RiskAccount::restore(before.risk).map_err(error)?;
let mut orders = order_map(before.orders);
for (index, effect) in outcome.effects.iter().enumerate() {
let reproduced = match effect {
MatchingEffect::Risk { command, outcome } => {
Some((risk.apply(command).map_err(error)?, outcome))
}
MatchingEffect::Operator { command, outcome } => {
Some((risk.reset(&authority, command).map_err(error)?, outcome))
}
MatchingEffect::Order(order) => {
orders.insert(order.order.order_id.clone(), order.clone());
None
}
};
if reproduced.is_some_and(|(actual, expected)| actual != *expected) {
return Err(error("financial effect reconstruction mismatch"));
}
journal.push(JournalEntry {
index: (index as u64).try_into().map_err(error)?,
effect: effect.clone(),
view_after: view(&risk, &orders, before.revision)?,
});
}
if risk.checkpoint() != checkpoint.risk
|| orders.into_values().collect::<Vec<_>>() != checkpoint.orders
{
return Err(error("financial checkpoint reconstruction mismatch"));
}
}
}
let final_view = view(
account.risk(),
&order_map(checkpoint.orders.clone()),
checkpoint.revision,
)?;
Ok(Response {
version: Version,
identity,
checkpoint,
view: final_view,
outcome,
journal,
})
}
/// The caller persists the returned checkpoint/journal atomically before publish.
/// Failed outcomes carry a valid terminal prefix to persist; Err returns no state.
/// Replayed outcomes retain the original receipt but always emit an empty journal.
#[cfg_attr(not(test), napi)]
pub fn stage_financial_transaction(input: String) -> Result<String> {
let raw: Value = serde_json::from_str(&input).map_err(error)?;
let request: Request = serde_json::from_str(&input).map_err(error)?;
if !keys_match(&raw, &serde_json::to_value(&request).map_err(error)?) {
return Err(error("unexpected or missing financial transaction fields"));
}
serde_json::to_string(&stage(request)?).map_err(error)
}
#[cfg(test)]
#[path = "paper/tests.rs"]
mod tests;

View file

@ -0,0 +1,348 @@
use super::*;
use crate::financial::scalar::MAX_POSTING;
fn config() -> Value {
json!({
"risk":{"ledger":{"version":1,"sessionId":"run","accountId":"account","baseCurrency":"USD","reserveOwnerId":"reserve","ownerIds":["A","B"],"initialCapital":"1000","riskSession":{"calendarId":"account","calendarRevision":"1","sessionId":"day1","startsAt":0}},
"feeRate":"0.01","maxOrderQuantity":"1000000","maxPositionQuantity":"1000000","maxSymbolExposure":"1000000","maxGrossExposure":"1000000","maxDailyLoss":"1000000","maxDrawdownAmount":"1000000","maxMarkAgeMs":1000000},
"owners":[{"ownerId":"A","mode":"Orders"},{"ownerId":"B","mode":"Orders"}],
"series":[{"instrumentId":"X","seriesId":"X-quotes","mode":"Quote"}],
"halfSpreadRate":"0","slippageRate":"0","latencyMs":0
})
}
fn identity() -> Value {
json!({"sessionId":"run","accountId":"account"})
}
fn wire(value: Value) -> Result<Response> {
serde_json::from_str(&stage_financial_transaction(value.to_string())?).map_err(error)
}
fn command(name: &str, at: i64, phase: &str, sequence: u64, body: Value) -> Value {
json!({"commandId":name,"key":{"at":at,"phase":phase,"instrumentId":"X","sourceSequence":sequence},"body":body})
}
fn quote(name: &str, at: i64, sequence: u64, price: &str, capacity: &str) -> Value {
command(
name,
at,
"Execution",
sequence,
json!({"kind":"execute","seriesId":"X-quotes","observation":{"kind":"quote","observedAt":at,"bid":price,"ask":price,"bidSize":capacity,"askSize":capacity}}),
)
}
fn order(name: &str, side: &str, quantity: &str, tif: &str) -> Value {
json!({"kind":"market","orderId":name,"instrumentId":"X","side":side,"quantity":quantity,"timeInForce":tif})
}
struct Harness {
checkpoint: MatchingCheckpoint,
direct: MatchingAccount,
}
impl Harness {
fn new(config: Value) -> Self {
let direct = MatchingAccount::new(serde_json::from_value(config.clone()).unwrap())
.unwrap()
.0;
let initialized =
wire(json!({"version":1,"kind":"initialize","identity":identity(),"config":config}))
.unwrap();
assert!(initialized.outcome.is_none());
assert!(initialized.journal.is_empty());
assert_eq!(initialized.view["admissionRevision"], json!(0));
assert_eq!(initialized.checkpoint, direct.checkpoint());
Self {
checkpoint: initialized.checkpoint,
direct,
}
}
fn apply(&mut self, command: Value) -> Response {
let direct = self
.direct
.apply(&serde_json::from_value(command.clone()).unwrap())
.unwrap();
let result = wire(json!({"version":1,"kind":"apply","identity":identity(),"checkpoint":self.checkpoint,"command":command})).unwrap();
assert_eq!(result.outcome.as_ref().unwrap(), &direct);
assert_eq!(result.checkpoint, self.direct.checkpoint());
assert_eq!(
result.view,
view(
self.direct.risk(),
&order_map(self.direct.orders().cloned()),
self.direct.admission_revision()
)
.unwrap()
);
if direct.replayed {
assert!(result.journal.is_empty());
} else {
assert_eq!(result.journal.len(), direct.effects.len());
for (index, row) in result.journal.iter().enumerate() {
assert_eq!(row.index.get(), index as u64);
assert_eq!(row.effect, direct.effects[index]);
assert_eq!(
row.view_after["admissionRevision"],
json!(self.checkpoint.revision)
);
}
}
self.checkpoint = result.checkpoint.clone();
result
}
fn setup(config: Value, price: &str) -> Self {
let mut h = Self::new(config);
h.apply(command("session",0,"Observation",0,json!({"kind":"openSession","session":{"sessionId":"venue","opensAt":0,"closesAt":100}})));
h.apply(command(
"mark",
0,
"Observation",
1,
json!({"kind":"mark","seriesId":"X-quotes","price":price,"observedAt":0}),
));
h
}
fn decision(&self, owner: &str, sequence: u64, orders: Vec<Value>) -> Value {
json!({"version":1,"sessionId":"run","barrierId":format!("barrier-{}",self.checkpoint.revision.get()),"revision":self.checkpoint.revision,"decision":{"ownerId":owner,"decisionId":format!("decision-{owner}-{sequence}"),"sequence":sequence},"intent":{"mode":"orders","orders":orders}})
}
fn submit(&mut self, name: &str, at: i64, decisions: Vec<Value>) -> Response {
self.apply(command(
name,
at,
"Decision",
0,
json!({"kind":"submit","decisions":decisions}),
))
}
}
#[test]
fn staged_multi_owner_fills_match_kernel_and_record_each_effect_view() {
let mut h = Harness::setup(config(), "10");
h.submit(
"orders",
1,
vec![
h.decision("A", 0, vec![order("a", "buy", "2", "GTC")]),
h.decision("B", 0, vec![order("b", "buy", "3", "GTC")]),
],
);
let result = h.apply(quote("fill", 2, 0, "10", "5"));
let fills: Vec<_> = result.journal.iter().filter(|row| matches!(&row.effect,MatchingEffect::Risk{outcome,..} if outcome.financial.as_ref().is_some_and(|financial| financial.effects.effects.iter().any(|effect|matches!(effect,FinancialEffect::FillApplied{..}))))).collect();
assert_eq!(fills.len(), 2);
assert_eq!(
fills[0].view_after["portfolio"]["cash"],
json!("979.80000000")
);
assert_eq!(
fills[1].view_after["portfolio"]["cash"],
json!("949.50000000")
);
assert_ne!(fills[0].view_after, result.view);
assert_eq!(result.view["equity"], json!("999.50000000"));
assert_eq!(result.view["availableCash"], json!("949.50000000"));
assert_eq!(
result.view["portfolio"]["positions"]
.as_array()
.unwrap()
.len(),
2
);
// Failure or a lost SQL commit discards the private returned state; retrying
// the prior checkpoint deterministically reconstructs exactly this result.
let restored = MatchingAccount::restore(result.checkpoint.clone())
.unwrap()
.0;
assert_eq!(restored.checkpoint(), result.checkpoint);
}
#[test]
fn replay_of_old_command_and_alias_preserves_current_state_without_publication() {
let mut h = Harness::setup(config(), "10");
let first = quote("quote", 1, 0, "10", "5");
let original = h.apply(first.clone());
h.apply(quote("later", 2, 0, "11", "5"));
let current = h.checkpoint.clone();
let replay = h.apply(first.clone());
assert!(replay.outcome.unwrap().replayed);
assert_eq!(replay.checkpoint, current);
let mut alias = first;
alias["commandId"] = json!("alias");
let aliased = h.apply(alias.clone());
assert_eq!(aliased.checkpoint.revision, current.revision);
assert_eq!(
aliased.checkpoint.receipts.len(),
current.receipts.len() + 1
);
assert_eq!(aliased.view, replay.view);
assert_eq!(
aliased.outcome.unwrap().effects,
original.outcome.unwrap().effects
);
h.apply(alias);
}
#[test]
fn failed_committed_prefix_is_returned_and_restorable_without_reapplying_fees() {
let mut c = config();
c["risk"]["ledger"]["initialCapital"] = json!("100000000000000000000");
for key in [
"maxOrderQuantity",
"maxPositionQuantity",
"maxSymbolExposure",
"maxGrossExposure",
] {
c["risk"][key] = json!(MAX_POSTING);
}
let mut h = Harness::setup(c, "0.00000001");
h.submit(
"seed",
1,
vec![h.decision("A", 0, vec![order("seed", "buy", "1", "GTC")])],
);
h.apply(quote("seed-fill", 1, 0, "0.00000001", "1"));
h.submit(
"orders",
2,
vec![
h.decision("A", 1, vec![order("sell", "sell", "1", "GTC")]),
h.decision(
"B",
1,
vec![order("overflow", "buy", "396140812571321687967", "GTC")],
),
],
);
let failure = quote("failure", 2, 0, "3", MAX_POSTING);
let result = h.apply(failure.clone());
assert!(matches!(
result.outcome.as_ref().unwrap().status,
AttemptStatus::Failed { .. }
));
assert!(!result.journal.is_empty());
assert_eq!(
h.direct.ledger().valuation().unwrap().fees.to_string(),
"0.03000000"
);
assert_eq!(
h.direct
.order(&serde_json::from_value(json!("sell")).unwrap())
.unwrap()
.status,
OrderStatus::Filled
);
assert_eq!(
MatchingAccount::restore(result.checkpoint.clone())
.unwrap()
.0
.checkpoint(),
result.checkpoint
);
h.apply(failure);
let next = json!({"version":1,"kind":"apply","identity":identity(),"checkpoint":h.checkpoint,"command":quote("next",3,0,"3","1")});
assert!(wire(next).unwrap_err().reason.contains("terminal"));
}
#[test]
fn partial_and_time_in_force_states_survive_each_staged_checkpoint() {
for (tif, expected) in [
("GTC", OrderStatus::Open),
("DAY", OrderStatus::Open),
("IOC", OrderStatus::Cancelled),
("FOK", OrderStatus::Cancelled),
] {
let mut h = Harness::setup(config(), "10");
h.submit(
"orders",
1,
vec![h.decision("A", 0, vec![order("o", "buy", "2", tif)])],
);
h.apply(quote("fill", 2, 0, "10", "1"));
let stored = h.checkpoint.orders.first().unwrap();
assert_eq!(stored.status, expected);
assert_eq!(
serde_json::to_value(stored.filled).unwrap(),
json!(if tif == "FOK" {
"0.00000000"
} else {
"1.00000000"
})
);
h.apply(command(
"close",
100,
"SessionClose",
0,
json!({"kind":"closeSession","sessionId":"venue"}),
));
if tif == "DAY" {
assert_eq!(h.checkpoint.orders[0].status, OrderStatus::Expired);
}
if tif == "GTC" {
assert_eq!(h.checkpoint.orders[0].status, OrderStatus::Open);
}
}
}
#[test]
fn wrong_identity_conflicts_corruption_and_operator_inputs_return_no_state() {
let mut h = Harness::setup(config(), "10");
h.submit(
"orders",
1,
vec![h.decision("A", 0, vec![order("o", "buy", "2", "GTC")])],
);
let checkpoint = h.checkpoint.clone();
let request = json!({"version":1,"kind":"apply","identity":identity(),"checkpoint":checkpoint,"command":quote("next",2,0,"10","1")});
for field in [
"identity", "version", "revision", "order", "receipt", "risk", "missing",
] {
let mut bad = request.clone();
match field {
"identity" => bad["identity"]["accountId"] = json!("other"),
"version" => bad["checkpoint"]["version"] = json!(2),
"revision" => bad["checkpoint"]["revision"] = json!(99),
"order" => bad["checkpoint"]["orders"][0]["remaining"] = json!("1"),
"receipt" => bad["checkpoint"]["receipts"][1]["outcome"]["effects"] = json!([]),
"risk" => bad["checkpoint"]["risk"]["revision"] = json!(99),
_ => {
bad["checkpoint"].as_object_mut().unwrap().remove("cursor");
}
}
assert!(wire(bad).is_err(), "{field}");
}
let mut conflict = request.clone();
conflict["command"]["commandId"] = json!("mark");
assert!(wire(conflict).unwrap_err().reason.contains("conflicts"));
let mut operator = request.clone();
operator["command"]["body"] = json!({"kind":"reset","actorId":"operator","reason":"reason"});
assert!(wire(operator).is_err());
assert_eq!(h.checkpoint, checkpoint);
h.apply(quote("next", 2, 0, "10", "1"));
}
#[test]
fn quote_cannot_be_reused_for_a_new_decision_and_capital_is_enforced() {
let mut h = Harness::setup(config(), "10");
let q = quote("quote", 1, 0, "10", "100");
h.apply(q.clone());
// Quote-driven decisions use the exact consumed event cursor, not a false
// earlier Decision phase. The next physical event is required to fill.
let decision = h.decision(
"A",
0,
vec![
order("o", "buy", "2", "GTC"),
order("unfunded", "buy", "1000", "GTC"),
],
);
h.apply(command(
"orders",
1,
"Execution",
0,
json!({"kind":"submit","decisions":[decision]}),
));
assert!(matches!(
h.checkpoint
.orders
.iter()
.find(|o| o.order.order_id == serde_json::from_value(json!("unfunded")).unwrap())
.unwrap()
.status,
OrderStatus::Rejected(_)
));
h.apply(q);
assert!(h.direct.ledger().economic_snapshot().positions.is_empty());
h.apply(quote("next", 2, 0, "10", "100"));
assert_eq!(h.direct.ledger().economic_snapshot().positions.len(), 1);
}