use super::{ contract::*, ledger::LedgerError, risk::*, scalar::{Posting, ScalarError, MAX_POSTING}, }; use serde_json::json; use std::time::Instant; fn p(v: &str) -> Posting { v.parse().unwrap() } fn id(v: &str) -> Id { serde_json::from_value(json!(v)).unwrap() } fn positive(v: &str) -> Positive { p(v).try_into().unwrap() } fn time(v: i64) -> EventTime { v.try_into().unwrap() } fn config(capital: &str) -> RiskConfig { serde_json::from_value(json!({ "ledger":{"version":1,"sessionId":"run","accountId":"account","baseCurrency":"USD", "reserveOwnerId":"reserve","ownerIds":["A","B"],"initialCapital":capital, "riskSession":{"calendarId":"account-calendar","calendarRevision":"v1","sessionId":"day1","startsAt":0}}, "feeRate":"0","maxOrderQuantity":"1000000","maxPositionQuantity":"1000000", "maxSymbolExposure":"1000000","maxGrossExposure":"1000000","maxDailyLoss":"1000000", "maxDrawdownAmount":"1000000","maxMarkAgeMs":100 })).unwrap() } fn account(capital: &str) -> RiskAccount { RiskAccount::new(config(capital)).unwrap().0 } fn cmd(key: &str, t: i64, body: RiskCommandBody) -> RiskCommand { RiskCommand { command_id: id(key), event_time: time(t), body, } } fn mark_command(key: &str, instrument: &str, price: &str, t: i64, observed: i64) -> RiskCommand { cmd( key, t, RiskCommandBody::Mark { instrument_id: id(instrument), price: positive(price), observed_at: time(observed), }, ) } fn mark(a: &mut RiskAccount, key: &str, instrument: &str, price: &str, t: i64) { accepted( a.apply(&mark_command(key, instrument, price, t, t)) .unwrap(), ); } fn order(key: &str, owner: &str, instrument: &str, side: Side, quantity: &str) -> RiskOrder { RiskOrder { order_id: id(key), decision: DecisionIdentity { owner_id: id(owner), decision_id: id(&format!("decision-{key}")), sequence: 0.try_into().unwrap(), }, instrument_id: id(instrument), side, quantity: positive(quantity), limit_price: None, origin: OrderOrigin::Explicit, } } fn admit_command(o: RiskOrder, t: i64) -> RiskCommand { cmd( &format!("admit-{}", serde_json::to_string(&o.order_id).unwrap()), t, RiskCommandBody::Admit { order: o }, ) } fn admit(a: &mut RiskAccount, o: RiskOrder, t: i64) -> RiskOutcome { a.apply(&admit_command(o, t)).unwrap() } fn fill_command(order: &str, fill: &str, quantity: &str, price: &str, t: i64) -> RiskCommand { cmd( fill, t, RiskCommandBody::Fill { order_id: id(order), fill_id: id(fill), fee_id: id(&format!("fee-{fill}")), quantity: positive(quantity), price: positive(price), }, ) } fn fill( a: &mut RiskAccount, order: &str, key: &str, quantity: &str, price: &str, t: i64, ) -> RiskOutcome { a.apply(&fill_command(order, key, quantity, price, t)) .unwrap() } fn release( a: &mut RiskAccount, key: &str, order: &str, owner: &str, reason: ReleaseReason, t: i64, ) -> RiskOutcome { a.apply(&cmd( key, t, RiskCommandBody::Release { owner_id: id(owner), order_id: id(order), reason, }, )) .unwrap() } fn accepted(out: RiskOutcome) { assert_eq!(out.disposition, RiskDisposition::Accepted); } fn rejected(out: RiskOutcome, reason: RiskRejection) { assert_eq!(out.disposition, RiskDisposition::Rejected(reason)); } fn unchanged(a: &mut RiskAccount, c: &RiskCommand, error: RiskError) { let before = a.checkpoint(); assert_eq!(a.apply(c), Err(error)); assert_eq!(a.checkpoint(), before); } fn buy( a: &mut RiskAccount, key: &str, owner: &str, instrument: &str, quantity: &str, price: &str, t: i64, ) { accepted(admit( a, order(key, owner, instrument, Side::Buy, quantity), t, )); accepted(fill(a, key, &format!("fill-{key}"), quantity, price, t)); } fn boundary(key: &str, session: &str, starts: i64, t: i64) -> RiskCommand { cmd( key, t, RiskCommandBody::RiskSessionBoundary { risk_session: RiskSessionIdentity { calendar_id: id("account-calendar"), calendar_revision: id("v1"), session_id: id(session), starts_at: time(starts), }, }, ) } fn reset(key: &str, t: i64) -> OperatorReset { OperatorReset { command_id: id(key), event_time: time(t), actor_id: id("operator"), reason: id("reviewed incident"), } } fn reconcile(a: &RiskAccount) { let value = a.ledger().valuation().unwrap(); assert_eq!( value.equity, value.cash.checked_add(value.marked_holdings).unwrap() ); let reserved = Posting::sum(a.reservations().map(|r| r.cash.into())).unwrap(); assert_eq!( a.available_cash().checked_add(reserved).unwrap(), value.cash ); assert!(!a.available_cash().is_negative()); assert_eq!( value.equity, Posting::sum(value.owners.iter().map(|o| o.equity_contribution)).unwrap() ); } #[test] fn competing_reservations_and_all_release_reasons() { let mut c = config("100"); c.fee_rate = p("0.01").try_into().unwrap(); let mut a = RiskAccount::new(c).unwrap().0; mark(&mut a, "m", "X", "10", 0); accepted(admit(&mut a, order("one", "A", "X", Side::Buy, "6"), 0)); assert_eq!(a.available_cash(), p("39.4")); rejected( admit(&mut a, order("two", "B", "X", Side::Buy, "4"), 0), RiskRejection::InsufficientCash, ); assert_eq!(a.reservations().count(), 1); accepted(fill(&mut a, "one", "part", "2", "10", 1)); assert_eq!( a.reservations().next().unwrap().cash, p("40.4").try_into().unwrap() ); assert_eq!(a.available_cash(), p("39.4")); accepted(release( &mut a, "cancel", "one", "A", ReleaseReason::Cancelled, 1, )); assert_eq!(a.available_cash(), p("79.8")); for (i, reason) in [ReleaseReason::Rejected, ReleaseReason::Expired] .into_iter() .enumerate() { let oid = format!("later-{i}"); accepted(admit(&mut a, order(&oid, "A", "X", Side::Buy, "1"), 1)); accepted(release( &mut a, &format!("release-{i}"), &oid, "A", reason, 1, )); } assert_eq!(a.reservations().count(), 0); reconcile(&a); } #[test] fn adverse_gap_reject_remainder_preserves_prior_fills_and_receipts() { let mut a = account("100"); mark(&mut a, "m", "X", "10", 0); accepted(admit(&mut a, order("o", "A", "X", Side::Buy, "10"), 0)); accepted(fill(&mut a, "o", "first", "2", "10", 1)); let command = fill_command("o", "gap", "2", "11", 2); let outcome = a.apply(&command).unwrap(); rejected(outcome.clone(), RiskRejection::InsufficientCash); assert_eq!(outcome.released_order, Some(id("o"))); assert!(outcome.financial.is_none()); assert_eq!(a.ledger().cash(), p("80")); assert_eq!(a.ledger().owner_quantity(&id("A"), &id("X")), p("2")); assert_eq!(a.reservations().count(), 0); let checkpoint = a.checkpoint(); let mut retry = outcome.clone(); retry.replayed = true; assert_eq!(a.apply(&command).unwrap(), retry); assert_eq!(a.checkpoint(), checkpoint); let mut alias = command.clone(); alias.command_id = id("gap-alias"); assert_eq!(a.apply(&alias).unwrap(), retry); assert_eq!(a.ledger().cash(), p("80")); let mut restored = RiskAccount::restore(a.checkpoint()).unwrap().0; assert_eq!(restored.apply(&alias).unwrap(), retry); reconcile(&restored); } #[test] fn stale_other_symbol_and_other_pending_symbol_block_increases_not_reductions() { for pending_only in [false, true] { let mut a = account("1000"); mark(&mut a, "mx", "X", "10", 0); accepted(admit(&mut a, order("old", "A", "X", Side::Buy, "1"), 0)); if !pending_only { accepted(fill(&mut a, "old", "old-fill", "1", "10", 0)); } mark(&mut a, "my", "Y", "10", 101); rejected( admit(&mut a, order("new", "B", "Y", Side::Buy, "1"), 101), RiskRejection::StaleMark, ); if !pending_only { accepted(admit(&mut a, order("sell", "A", "X", Side::Sell, "1"), 101)); accepted(fill(&mut a, "sell", "sell-fill", "1", "9", 101)); } reconcile(&a); } } #[test] fn delayed_mark_is_not_freshened_and_future_or_backdated_time_is_atomic() { let mut a = account("100"); accepted( a.apply(&mark_command("delayed", "X", "10", 101, 0)) .unwrap(), ); assert_eq!(a.ledger().mark(&id("X")).unwrap().event_time, time(0)); rejected( admit(&mut a, order("o", "A", "X", Side::Buy, "1"), 101), RiskRejection::StaleMark, ); unchanged( &mut a, &mark_command("future", "Y", "10", 101, 102), RiskError::InvalidMarkTime, ); unchanged( &mut a, &mark_command("backdated", "Y", "10", 100, 100), RiskError::BackdatedCommand, ); unchanged( &mut a, &mark_command("older", "X", "10", 101, -1), RiskError::InvalidMarkTime, ); } #[test] fn marked_loss_halt_and_explicit_risk_session_boundary() { let mut c = config("100"); c.max_daily_loss = positive("10"); c.max_drawdown_amount = positive("50"); let mut a = RiskAccount::new(c).unwrap().0; mark(&mut a, "m", "X", "10", 0); buy(&mut a, "buy", "A", "X", "5", "10", 0); mark(&mut a, "loss", "X", "8", 1); assert_eq!(a.ledger().valuation().unwrap().realized_gross_pnl, p("0")); assert!(a.state().daily_halted); rejected( admit(&mut a, order("halted", "A", "X", Side::Buy, "1"), 1), RiskRejection::DailyLoss, ); accepted(a.apply(&boundary("same", "day1", 0, 1)).unwrap()); assert!(a.state().daily_halted); mark(&mut a, "recover", "X", "10", 2); assert!(a.state().daily_halted); accepted(admit(&mut a, order("sell", "A", "X", Side::Sell, "1"), 2)); accepted(fill(&mut a, "sell", "sell-fill", "1", "10", 2)); accepted(a.apply(&boundary("next", "day2", 3, 3)).unwrap()); assert!(!a.state().daily_halted); assert_eq!(a.state().daily_baseline, p("100").try_into().unwrap()); accepted(admit(&mut a, order("after", "A", "X", Side::Buy, "1"), 3)); reconcile(&a); } #[test] fn drawdown_halt_survives_rollover_restore_and_requires_authorized_reset() { let mut c = config("100"); c.max_drawdown_amount = positive("10"); let (mut a, authority) = RiskAccount::new(c).unwrap(); mark(&mut a, "m", "X", "10", 0); buy(&mut a, "buy", "A", "X", "5", "10", 0); mark(&mut a, "peak", "X", "12", 1); mark(&mut a, "loss", "X", "10", 2); assert!(a.state().drawdown_halted); accepted(a.apply(&boundary("next", "day2", 3, 3)).unwrap()); assert_eq!(a.state().peak_equity, p("110").try_into().unwrap()); let (mut restored, restored_authority) = RiskAccount::restore(a.checkpoint()).unwrap(); assert!(restored.state().drawdown_halted); rejected( admit(&mut restored, order("halted", "A", "X", Side::Buy, "1"), 3), RiskRejection::Drawdown, ); let before = restored.checkpoint(); assert_eq!( restored.reset(&authority, &reset("bad", 3)), Err(RiskError::UnauthorizedReset) ); assert_eq!(restored.checkpoint(), before); let outcome = restored .reset(&restored_authority, &reset("reset", 3)) .unwrap(); assert_eq!(outcome.reset_baseline, Some(p("100").try_into().unwrap())); assert!(!restored.state().drawdown_halted); assert!(!restored.state().daily_halted); assert_eq!(restored.state().peak_equity, p("100").try_into().unwrap()); assert_eq!( RiskAccount::restore(restored.checkpoint()) .unwrap() .0 .checkpoint(), restored.checkpoint() ); } #[test] fn unauthorized_reset_denied_and_not_deserializable_as_engine_command() { let (mut a, _) = RiskAccount::new(config("100")).unwrap(); let (_, wrong_authority) = RiskAccount::new(config("100")).unwrap(); let before = a.checkpoint(); assert_eq!( a.reset(&wrong_authority, &reset("unauthorized", 0)), Err(RiskError::UnauthorizedReset) ); assert_eq!(a.checkpoint(), before); assert!(serde_json::from_value::( json!({"kind":"reset","actorId":"operator"}) ) .is_err()); } #[test] fn alternate_venue_does_not_reset_account_day_and_invalid_boundaries_are_atomic() { let mut a = account("100"); mark(&mut a, "m", "X", "10", 10); let mut venue = boundary("venue", "day2", 10, 10); if let RiskCommandBody::RiskSessionBoundary { risk_session } = &mut venue.body { risk_session.calendar_id = id("another-venue"); } unchanged( &mut a, &venue, RiskError::Ledger(LedgerError::InvalidRiskSession), ); unchanged( &mut a, &boundary("future", "day2", 11, 10), RiskError::InvalidBoundaryTime, ); unchanged( &mut a, &boundary("past", "day2", 9, 10), RiskError::InvalidBoundaryTime, ); unchanged( &mut a, &boundary("changed-start", "day1", 10, 10), RiskError::Ledger(LedgerError::InvalidRiskSession), ); } #[test] fn inventory_reservations_wrong_owner_and_zero_cash_sell() { let mut c = config("110"); c.fee_rate = p("0.1").try_into().unwrap(); let mut a = RiskAccount::new(c).unwrap().0; mark(&mut a, "m", "X", "10", 0); buy(&mut a, "buy", "A", "X", "10", "10", 0); assert_eq!(a.ledger().cash(), p("0")); rejected( admit(&mut a, order("steal", "B", "X", Side::Sell, "1"), 0), RiskRejection::InsufficientInventory, ); accepted(admit(&mut a, order("sell", "A", "X", Side::Sell, "6"), 101)); rejected( admit(&mut a, order("oversell", "A", "X", Side::Sell, "5"), 101), RiskRejection::InsufficientInventory, ); unchanged( &mut a, &cmd( "steal-cancel", 101, RiskCommandBody::Release { owner_id: id("B"), order_id: id("sell"), reason: ReleaseReason::Cancelled, }, ), RiskError::WrongOwner, ); accepted(fill(&mut a, "sell", "sell-fill", "2", "10", 101)); assert_eq!(a.ledger().cash(), p("18")); accepted(release( &mut a, "release", "sell", "A", ReleaseReason::Expired, 101, )); accepted(admit(&mut a, order("rest", "A", "X", Side::Sell, "8"), 101)); accepted(fill(&mut a, "rest", "rest-fill", "8", "10", 101)); assert_eq!(a.ledger().cash(), p("90")); reconcile(&a); } #[test] fn pending_sells_never_fund_buys_or_reduce_exposure_and_fill_price_is_checked() { let mut c = config("200"); c.max_gross_exposure = positive("100"); let mut a = RiskAccount::new(c).unwrap().0; mark(&mut a, "mx", "X", "10", 0); mark(&mut a, "my", "Y", "10", 0); buy(&mut a, "buy", "A", "X", "10", "10", 0); accepted(admit(&mut a, order("sell", "A", "X", Side::Sell, "10"), 0)); rejected( admit(&mut a, order("new", "B", "Y", Side::Buy, "1"), 0), RiskRejection::GrossExposure, ); let mut b = account("100"); mark(&mut b, "m", "X", "10", 0); buy(&mut b, "buy", "A", "X", "10", "10", 0); accepted(admit(&mut b, order("sell", "A", "X", Side::Sell, "10"), 0)); rejected( admit(&mut b, order("fund", "B", "X", Side::Buy, "1"), 0), RiskRejection::InsufficientCash, ); let mut c = config("1000"); c.max_symbol_exposure = positive("100"); let mut a = RiskAccount::new(c).unwrap().0; mark(&mut a, "m", "X", "10", 0); accepted(admit(&mut a, order("o", "A", "X", Side::Buy, "10"), 0)); rejected( fill(&mut a, "o", "gap", "1", "11", 1), RiskRejection::SymbolExposure, ); assert_eq!(a.ledger().cash(), p("1000")); assert_eq!(a.reservations().count(), 0); } #[test] fn fee_is_rounded_once_and_quantum_partial_fill_cannot_leave_unfunded_remainder() { let mut c = config("0.00000001"); c.fee_rate = p("0.5").try_into().unwrap(); let mut a = RiskAccount::new(c).unwrap().0; mark(&mut a, "m", "X", "0.5", 0); buy(&mut a, "buy", "A", "X", "0.00000001", "0.5", 0); assert_eq!(a.ledger().cash(), p("0")); assert_eq!(a.ledger().valuation().unwrap().fees, p("0")); let mut a = account("0.00000001"); mark(&mut a, "m", "X", "0.5", 0); accepted(admit( &mut a, order("o", "A", "X", Side::Buy, "0.00000002"), 0, )); rejected( fill(&mut a, "o", "split", "0.00000001", "0.5", 0), RiskRejection::InsufficientCash, ); assert_eq!(a.ledger().cash(), p("0.00000001")); assert_eq!(a.reservations().count(), 0); reconcile(&a); } #[test] fn exposure_respects_owner_rounding_and_combined_pending_quantities() { let mut c = config("1"); c.max_gross_exposure = positive("0.00000002"); let mut a = RiskAccount::new(c).unwrap().0; mark(&mut a, "m", "X", "0.5", 0); buy(&mut a, "a", "A", "X", "0.00000001", "0.5", 0); buy(&mut a, "b", "B", "X", "0.00000001", "0.5", 0); assert_eq!( a.ledger().valuation().unwrap().marked_holdings, p("0.00000002") ); rejected( admit(&mut a, order("c", "A", "X", Side::Buy, "0.00000002"), 0), RiskRejection::GrossExposure, ); let mut c = config("1"); c.max_symbol_exposure = positive("0.00000001"); let mut a = RiskAccount::new(c).unwrap().0; mark(&mut a, "m", "X", "0.49", 0); buy(&mut a, "existing", "A", "X", "0.00000003", "0.49", 0); rejected( admit( &mut a, order("candidate", "A", "X", Side::Buy, "0.00000001"), 0, ), RiskRejection::SymbolExposure, ); let mut c = config("1"); c.max_symbol_exposure = positive("0.00000001"); let mut a = RiskAccount::new(c).unwrap().0; mark(&mut a, "m", "X", "0.49", 0); accepted(admit( &mut a, order("pending", "A", "X", Side::Buy, "0.00000003"), 0, )); rejected( admit( &mut a, order("candidate", "A", "X", Side::Buy, "0.00000001"), 0, ), RiskRejection::SymbolExposure, ); } #[test] fn duplicate_accepted_rejected_and_conflicting_ids_preserve_state() { let mut a = account("100"); mark(&mut a, "m", "X", "10", 0); for (key, quantity) in [("good", "1"), ("bad", "100")] { let command = admit_command(order(key, "A", "X", Side::Buy, quantity), 0); let mut expected = a.apply(&command).unwrap(); expected.replayed = true; let checkpoint = a.checkpoint(); assert_eq!(a.apply(&command).unwrap(), expected); assert_eq!(a.checkpoint(), checkpoint); let mut conflicting = command.clone(); conflicting.event_time = time(1); unchanged(&mut a, &conflicting, RiskError::CommandConflict); conflicting.command_id = id(&format!("new-{key}")); unchanged(&mut a, &conflicting, RiskError::OrderConflict); } let fill = fill_command("good", "fill", "1", "10", 0); let mut expected = a.apply(&fill).unwrap(); expected.replayed = true; let mut alias = fill.clone(); alias.command_id = id("alias"); assert_eq!(a.apply(&alias).unwrap(), expected); let mut conflict = alias.clone(); conflict.command_id = id("conflict"); conflict.event_time = time(1); unchanged(&mut a, &conflict, RiskError::FillConflict); accepted(admit(&mut a, order("later", "A", "X", Side::Buy, "1"), 0)); let mut fee_conflict = fill_command("later", "later-fill", "1", "10", 0); if let RiskCommandBody::Fill { fee_id, .. } = &mut fee_conflict.body { *fee_id = id("fee-fill"); } unchanged(&mut a, &fee_conflict, RiskError::FeeConflict); unchanged( &mut a, &fill_command("unreserved", "bypass", "1", "10", 0), RiskError::OrderConflict, ); unchanged( &mut a, &fill_command("later", "too-big", "2", "10", 0), RiskError::ExcessFill, ); reconcile(&a); } #[test] fn replay_after_clock_advance_returns_original_receipt_without_republishing() { let mut a = account("100"); mark(&mut a, "m", "X", "10", 0); let rejected_command = admit_command(order("bad", "A", "X", Side::Buy, "100"), 0); let mut rejected_outcome = a.apply(&rejected_command).unwrap(); rejected_outcome.replayed = true; accepted(admit(&mut a, order("good", "A", "X", Side::Buy, "1"), 0)); let fill = fill_command("good", "filled", "1", "10", 0); let mut outcome = a.apply(&fill).unwrap(); outcome.replayed = true; assert!(!outcome.financial.as_ref().unwrap().replayed); mark(&mut a, "later-mark", "X", "11", 10); let before = a.checkpoint(); assert_eq!(a.apply(&rejected_command).unwrap(), rejected_outcome); assert_eq!(a.apply(&fill).unwrap(), outcome); assert_eq!(a.checkpoint(), before); let mut alias = fill.clone(); alias.command_id = id("later-alias"); assert_eq!(a.apply(&alias).unwrap(), outcome); assert_eq!(a.state().last_event_time, time(10)); assert_eq!(a.checkpoint().revision, before.revision); assert_eq!(a.ledger().checkpoint(), before.ledger); let mut restored = RiskAccount::restore(a.checkpoint()).unwrap().0; let checkpoint = restored.checkpoint(); assert_eq!(restored.apply(&alias).unwrap(), outcome); assert_eq!(restored.checkpoint(), checkpoint); } #[test] fn quantity_limits_limit_reservations_and_pending_mark_repricing() { let mut c = config("1000"); c.max_order_quantity = positive("2"); c.max_position_quantity = positive("3"); let mut a = RiskAccount::new(c).unwrap().0; mark(&mut a, "m", "X", "10", 0); rejected( admit(&mut a, order("large", "A", "X", Side::Buy, "3"), 0), RiskRejection::OrderSize, ); accepted(admit(&mut a, order("a", "A", "X", Side::Buy, "2"), 0)); rejected( admit(&mut a, order("b", "B", "X", Side::Buy, "2"), 0), RiskRejection::PositionSize, ); accepted(fill(&mut a, "a", "fill-a", "2", "10", 0)); rejected( admit(&mut a, order("sell-large", "A", "X", Side::Sell, "3"), 0), RiskRejection::OrderSize, ); let mut c = config("1000"); c.max_gross_exposure = positive("100"); let mut a = RiskAccount::new(c).unwrap().0; mark(&mut a, "mx", "X", "10", 0); mark(&mut a, "my", "Y", "10", 0); let mut limit = order("limit", "A", "X", Side::Buy, "5"); limit.limit_price = Some(positive("11")); accepted(admit(&mut a, limit, 0)); assert_eq!(a.available_cash(), p("945")); mark(&mut a, "up", "X", "20", 1); // The pending reservation remains funded at its admitted price, but risk // exposure revalues the open commitment at the new canonical mark. assert_eq!(a.available_cash(), p("945")); rejected( admit(&mut a, order("new", "B", "Y", Side::Buy, "1"), 1), RiskRejection::GrossExposure, ); // Limit crossing remains F05's job; F04's fill rejection here is freshness. rejected( fill(&mut a, "limit", "stale", "1", "10", 102), RiskRejection::StaleMark, ); assert_eq!(a.reservations().count(), 0); reconcile(&a); } #[test] fn checkpoint_tamper_is_rejected_and_replay_is_byte_identical() { let (mut a, authority) = RiskAccount::new(config("100")).unwrap(); mark(&mut a, "m", "X", "10", 0); accepted(admit(&mut a, order("o", "A", "X", Side::Buy, "5"), 0)); accepted(fill(&mut a, "o", "part", "2", "10", 1)); accepted(a.reset(&authority, &reset("reset", 1)).unwrap()); let checkpoint = a.checkpoint(); let encoded = serde_json::to_vec(&checkpoint).unwrap(); let restored = RiskAccount::restore(serde_json::from_slice(&encoded).unwrap()) .unwrap() .0; assert_eq!(serde_json::to_vec(&restored.checkpoint()).unwrap(), encoded); for variant in 0..8 { let mut changed = checkpoint.clone(); match variant { 0 => changed.state.drawdown_halted = true, 1 => changed.reservations[0].cash = p("1").try_into().unwrap(), 2 => changed.state.last_event_time = time(999), 3 => { changed.receipts[1].outcome.disposition = RiskDisposition::Rejected(RiskRejection::DailyLoss) } 4 => changed.receipts.swap(0, 1), 5 => changed.state.daily_baseline = p("99").try_into().unwrap(), 6 => changed.ledger.economic.cash = p("99").try_into().unwrap(), _ => { changed.receipts.last_mut().unwrap().outcome.reset_baseline = Some(p("99").try_into().unwrap()) } } assert!(matches!( RiskAccount::restore(changed), Err(RiskError::InvalidCheckpoint) )); } } #[test] fn malformed_limits_overflow_and_failed_marks_are_atomic() { let mut invalid = config("100"); invalid.fee_rate = p("1.00000001").try_into().unwrap(); assert!(matches!( RiskAccount::new(invalid), Err(RiskError::InvalidFeeRate) )); let mut a = account("100"); mark(&mut a, "m", "X", "1", 0); buy(&mut a, "a", "A", "X", "1", "1", 0); buy(&mut a, "b", "B", "X", "2", "1", 0); unchanged( &mut a, &mark_command("overflow", "X", MAX_POSTING, 1, 1), RiskError::Ledger(LedgerError::Arithmetic(ScalarError::Overflow)), ); let mut c = config(MAX_POSTING); c.max_order_quantity = positive(MAX_POSTING); c.max_position_quantity = positive(MAX_POSTING); c.max_symbol_exposure = positive(MAX_POSTING); c.max_gross_exposure = positive(MAX_POSTING); let mut a = RiskAccount::new(c).unwrap().0; mark(&mut a, "m", "X", "0.00000001", 0); accepted(admit( &mut a, order("large", "A", "X", Side::Buy, MAX_POSTING), 0, )); unchanged( &mut a, &admit_command(order("more", "A", "X", Side::Buy, "1"), 0), RiskError::Arithmetic(ScalarError::Overflow), ); // Unrepresentable arithmetic is an atomic command error, not an ordinary // affordable-range risk rejection. The host must fail the unsupported // attempt rather than silently borrowing, resizing or retrying forever. unchanged( &mut a, &fill_command("large", "overflow-fill", MAX_POSTING, "2", 1), RiskError::Arithmetic(ScalarError::Overflow), ); } #[test] fn raw_order_and_target_normalization_cannot_bypass_identical_policy() { // Exhaustive bounded parameter property, including fee/cash rejection and // fill gaps. The actual target expansion/mode coordinator belongs to F05. for capital in 1..=12 { for quantity in 1..=15 { let mut c = config(&capital.to_string()); c.fee_rate = p("0.1").try_into().unwrap(); let mut explicit = RiskAccount::new(c.clone()).unwrap().0; let mut target = RiskAccount::new(c).unwrap().0; for a in [&mut explicit, &mut target] { mark(a, "m", "X", "1", 0); } let original = order("o", "A", "X", Side::Buy, &quantity.to_string()); let mut normalized = original.clone(); normalized.origin = OrderOrigin::Target; let raw = admit(&mut explicit, original, 0); let target_out = admit(&mut target, normalized, 0); assert_eq!(raw.disposition, target_out.disposition); assert_eq!(explicit.available_cash(), target.available_cash()); if raw.disposition == RiskDisposition::Accepted { let raw_fill = fill(&mut explicit, "o", "fill", &quantity.to_string(), "1.1", 1); let target_fill = fill(&mut target, "o", "fill", &quantity.to_string(), "1.1", 1); assert_eq!(raw_fill.disposition, target_fill.disposition); assert_eq!(raw_fill.financial, target_fill.financial); } assert_eq!(explicit.ledger().checkpoint(), target.ledger().checkpoint()); reconcile(&explicit); reconcile(&target); } } } #[test] #[ignore = "manual release workload; no unstable timing assertion"] fn risk_transition_measurement() { for multi in [false, true] { for count in [1000, 10000] { let mut inputs = Vec::new(); for n in 0..count / 4 { let symbol = if multi { format!("asset-{}", n % 4) } else { "asset".into() }; let owner = if multi && n % 2 == 1 { "B" } else { "A" }; let oid = format!("order-{n}"); let t = n as i64; inputs.push(mark_command(&format!("mark-{n}"), &symbol, "10", t, t)); inputs.push(admit_command( order(&oid, owner, &symbol, Side::Buy, "2"), t, )); inputs.push(fill_command(&oid, &format!("fill-{n}"), "1", "10", t)); inputs.push(cmd( &format!("release-{n}"), t, RiskCommandBody::Release { owner_id: id(owner), order_id: id(&oid), reason: ReleaseReason::Cancelled, }, )); } let mut expected = None; for repeat in 0..3 { let mut c = config("1000000"); c.fee_rate = p("0.01").try_into().unwrap(); let mut a = RiskAccount::new(c).unwrap().0; let started = Instant::now(); let outcomes: Vec<_> = inputs.iter().map(|c| a.apply(c).unwrap()).collect(); let elapsed = started.elapsed(); let snap_start = Instant::now(); let checkpoint = a.checkpoint(); let snapshot_elapsed = snap_start.elapsed(); let bytes = serde_json::to_vec(&checkpoint).unwrap(); let economic_and_receipts = serde_json::to_vec(&(checkpoint.clone(), outcomes)).unwrap(); if let Some(expected) = &expected { assert_eq!(&economic_and_receipts, expected); } else { expected = Some(economic_and_receipts); } let restore_start = Instant::now(); let restored = RiskAccount::restore(checkpoint).unwrap().0; let restore_elapsed = restore_start.elapsed(); assert_eq!(serde_json::to_vec(&restored.checkpoint()).unwrap(), bytes); reconcile(&restored); println!("risk multi={multi} commands={count} repeat={repeat} apply_us={} checkpoint_us={} restore_us={} checkpoint_bytes={} open_orders={} owners={} assets={}", elapsed.as_micros(), snapshot_elapsed.as_micros(), restore_elapsed.as_micros(), bytes.len(), a.reservations().count(), if multi {2} else {1}, if multi {4} else {1}); } } } }