stock-bot/apps/stock/engine/src/financial/ledger_tests.rs
Boki b65acccd91 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.
2026-10-22 21:16:53 -04:00

903 lines
31 KiB
Rust

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::<EngineFinancialCommand>(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::<LedgerCheckpoint>(invalid).is_err());
assert!(serde_json::from_value::<LedgerCheckpoint>(
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));
}
}
}