Skip to main content

nautilus_live/
testing.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Engine-wired support for live adapter integration tests.
17//!
18//! This module records whether adapter output follows the typed order-event path or the
19//! reconciliation-report path before routing each event through the live runner.
20
21#![warn(rustc::all)]
22#![warn(clippy::pedantic)]
23#![allow(
24    clippy::manual_let_else,
25    clippy::option_if_let_else,
26    clippy::or_fun_call,
27    clippy::redundant_else,
28    clippy::similar_names,
29    clippy::single_match_else,
30    reason = "workspace policy; generated by scripts/update-clippy-allowances.py"
31)]
32#![deny(unsafe_code)]
33#![deny(unsafe_op_in_unsafe_fn)]
34#![deny(nonstandard_style)]
35#![deny(missing_debug_implementations)]
36#![deny(rustdoc::broken_intra_doc_links)]
37#![allow(
38    clippy::missing_panics_doc,
39    reason = "test support reports invalid setup and failed assertions by panicking"
40)]
41
42use std::{cell::RefCell, fmt::Debug, rc::Rc, time::Duration};
43
44use nautilus_common::{
45    cache::Cache,
46    clients::ExecutionClient,
47    clock::{Clock, VirtualClock},
48    live::{
49        dst,
50        runner::{replace_data_event_sender, replace_exec_event_sender},
51    },
52    messages::{
53        ExecutionEvent,
54        execution::{
55            TradingCommand, cancel::CancelOrder, modify::ModifyOrder, submit::SubmitOrder,
56        },
57    },
58    msgbus::{self, MessageBus, MessagingSwitchboard},
59};
60use nautilus_core::{UUID4, UnixNanos};
61use nautilus_execution::engine::{ExecutionEngine, config::ExecutionEngineConfig};
62use nautilus_model::{
63    events::{OrderEventAny, OrderPendingCancel, OrderPendingUpdate},
64    identifiers::{AccountId, ClientId, InstrumentId, StrategyId, TraderId},
65    instruments::{Instrument, InstrumentAny},
66    orders::{Order, OrderAny},
67    reports::ExecutionMassStatus,
68    types::{Price, Quantity},
69};
70use nautilus_portfolio::Portfolio;
71use nautilus_risk::engine::{RiskEngine, config::RiskEngineConfig};
72use nautilus_testkit::testers::{ExecTester, ExecTesterConfig};
73use nautilus_trading::strategy::StrategyNative;
74
75use crate::runner::AsyncRunner;
76
77/// Engine-wired state for deterministic live execution seam tests.
78pub struct ExecutionHarness {
79    clock: Rc<RefCell<dyn Clock>>,
80    cache: Rc<RefCell<Cache>>,
81    risk_engine: Rc<RefCell<RiskEngine>>,
82    exec_engine: Rc<RefCell<ExecutionEngine>>,
83    exec_rx: tokio::sync::mpsc::UnboundedReceiver<ExecutionEvent>,
84    routed: Vec<RoutedKind>,
85    trader_id: TraderId,
86    client_id: ClientId,
87    account_id: AccountId,
88    instrument_id: InstrumentId,
89}
90
91impl Debug for ExecutionHarness {
92    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
93        f.debug_struct(stringify!(ExecutionHarness))
94            .field("trader_id", &self.trader_id)
95            .field("client_id", &self.client_id)
96            .field("account_id", &self.account_id)
97            .field("instrument_id", &self.instrument_id)
98            .field("routed", &self.routed)
99            .finish_non_exhaustive()
100    }
101}
102
103impl ExecutionHarness {
104    /// Creates a harness with real risk and execution engines and the supplied instrument.
105    ///
106    /// Replaces the current thread's message bus and live event senders.
107    #[must_use]
108    pub fn new(
109        trader_id: TraderId,
110        client_id: ClientId,
111        account_id: AccountId,
112        instrument: InstrumentAny,
113    ) -> Self {
114        let _bus = MessageBus::new(trader_id, UUID4::new(), None, None).register_message_bus();
115        let clock: Rc<RefCell<dyn Clock>> = Rc::new(RefCell::new(VirtualClock::new()));
116        let cache = Rc::new(RefCell::new(Cache::default()));
117        let instrument_id = instrument.id();
118        cache
119            .borrow_mut()
120            .add_instrument(instrument)
121            .expect("instrument should be added to the harness cache");
122
123        let portfolio = Portfolio::new(clock.clone(), cache.clone(), None);
124
125        let risk_engine = Rc::new(RefCell::new(RiskEngine::new(
126            RiskEngineConfig::default(),
127            portfolio,
128            clock.clone(),
129            cache.clone(),
130        )));
131        RiskEngine::register_msgbus_handlers(&risk_engine);
132
133        let exec_config = ExecutionEngineConfig::builder()
134            .manage_own_order_books(true)
135            .build()
136            .expect("execution engine config should be valid");
137
138        let exec_engine = Rc::new(RefCell::new(ExecutionEngine::new(
139            clock.clone(),
140            cache.clone(),
141            Some(exec_config),
142        )));
143        ExecutionEngine::register_msgbus_handlers(&exec_engine);
144
145        let (exec_tx, exec_rx) = tokio::sync::mpsc::unbounded_channel();
146        replace_exec_event_sender(exec_tx);
147        let (data_tx, _data_rx) = tokio::sync::mpsc::unbounded_channel();
148        replace_data_event_sender(data_tx);
149
150        Self {
151            clock,
152            cache,
153            risk_engine,
154            exec_engine,
155            exec_rx,
156            routed: Vec::new(),
157            trader_id,
158            client_id,
159            account_id,
160            instrument_id,
161        }
162    }
163
164    /// Returns the clock shared by the harness components.
165    #[must_use]
166    pub const fn clock(&self) -> &Rc<RefCell<dyn Clock>> {
167        &self.clock
168    }
169
170    /// Returns the cache shared by the harness components.
171    #[must_use]
172    pub const fn cache(&self) -> &Rc<RefCell<Cache>> {
173        &self.cache
174    }
175
176    /// Returns the risk engine used to route trading commands.
177    #[must_use]
178    pub const fn risk_engine(&self) -> &Rc<RefCell<RiskEngine>> {
179        &self.risk_engine
180    }
181
182    /// Returns the execution engine containing the adapter client under test.
183    #[must_use]
184    pub const fn exec_engine(&self) -> &Rc<RefCell<ExecutionEngine>> {
185        &self.exec_engine
186    }
187
188    /// Returns the trader ID used by the harness.
189    #[must_use]
190    pub const fn trader_id(&self) -> TraderId {
191        self.trader_id
192    }
193
194    /// Returns the execution client ID used by the harness.
195    #[must_use]
196    pub const fn client_id(&self) -> ClientId {
197        self.client_id
198    }
199
200    /// Returns the account ID used by the harness.
201    #[must_use]
202    pub const fn account_id(&self) -> AccountId {
203        self.account_id
204    }
205
206    /// Returns the instrument ID registered in the cache.
207    #[must_use]
208    pub const fn instrument_id(&self) -> InstrumentId {
209        self.instrument_id
210    }
211
212    /// Returns the routing kinds observed before live-runner dispatch.
213    #[must_use]
214    pub fn routed(&self) -> &[RoutedKind] {
215        &self.routed
216    }
217
218    /// Asserts that the execution client is registered and its engine is ready.
219    pub fn assert_engine_ready(&self) {
220        let engine = self.exec_engine.borrow();
221        assert!(engine.get_client(&self.client_id).is_some());
222        assert!(engine.check_integrity());
223        assert!(engine.check_connected());
224    }
225
226    /// Returns the total commands received by the risk engine.
227    #[must_use]
228    pub fn risk_command_count(&self) -> u64 {
229        self.risk_engine.borrow().command_count()
230    }
231
232    /// Registers an adapter execution client and its native venue route with the execution engine.
233    ///
234    /// # Errors
235    ///
236    /// Returns an error if the engine already contains the client ID or venue route.
237    pub fn register_client(&self, client: Box<dyn ExecutionClient>) -> anyhow::Result<()> {
238        let client_id = client.client_id();
239        let venue = client.venue();
240        let mut engine = self.exec_engine.borrow_mut();
241        engine.register_client(client)?;
242        if let Err(e) = engine.register_venue_routing(client_id, venue) {
243            engine.deregister_client(client_id)?;
244            return Err(e);
245        }
246
247        Ok(())
248    }
249
250    /// Caches an order and sends its submission command through the risk engine.
251    pub fn submit_via_risk(&self, order: &OrderAny) {
252        let cmd = SubmitOrder::from_order(
253            order,
254            self.trader_id,
255            Some(self.client_id),
256            None,
257            UUID4::new(),
258            UnixNanos::default(),
259        );
260        self.cache
261            .borrow_mut()
262            .add_order(order.clone(), None, Some(self.client_id), false)
263            .expect("order should be added to the harness cache");
264        msgbus::send_trading_command(
265            MessagingSwitchboard::risk_engine_execute(),
266            TradingCommand::SubmitOrder(cmd),
267        );
268    }
269
270    /// Marks an order pending update and sends its modification through the risk engine.
271    pub fn modify_via_risk(
272        &self,
273        order: &OrderAny,
274        price: Option<Price>,
275        quantity: Option<Quantity>,
276    ) {
277        let command_id = UUID4::new();
278        self.mark_pending_update(order, command_id);
279        let venue_order_id = self
280            .cache
281            .borrow()
282            .order(&order.client_order_id())
283            .and_then(|cached| cached.venue_order_id());
284
285        let cmd = ModifyOrder::new(
286            self.trader_id,
287            Some(self.client_id),
288            order.strategy_id(),
289            order.instrument_id(),
290            order.client_order_id(),
291            venue_order_id,
292            quantity,
293            price,
294            None,
295            command_id,
296            UnixNanos::default(),
297            None,
298            None,
299        );
300        msgbus::send_trading_command(
301            MessagingSwitchboard::risk_engine_execute(),
302            TradingCommand::ModifyOrder(cmd),
303        );
304    }
305
306    /// Marks an order pending cancel and sends its cancellation through the execution engine.
307    pub fn cancel_via_execution(&self, order: &OrderAny) {
308        let command_id = UUID4::new();
309        self.mark_pending_cancel(order, Some(command_id));
310        let venue_order_id = self
311            .cache
312            .borrow()
313            .order(&order.client_order_id())
314            .and_then(|cached| cached.venue_order_id());
315
316        let cmd = CancelOrder::new(
317            self.trader_id,
318            Some(self.client_id),
319            order.strategy_id(),
320            order.instrument_id(),
321            order.client_order_id(),
322            venue_order_id,
323            command_id,
324            UnixNanos::default(),
325            None,
326            None,
327        );
328        msgbus::send_trading_command(
329            MessagingSwitchboard::exec_engine_queue_execute(),
330            TradingCommand::CancelOrder(cmd),
331        );
332    }
333
334    /// Routes emitted execution events until the cache predicate holds or the deadline expires.
335    pub async fn pump_until(
336        &mut self,
337        timeout: Duration,
338        predicate: impl Fn(&Cache) -> bool,
339    ) -> bool {
340        self.pump_until_condition(timeout, |harness| predicate(&harness.cache.borrow()))
341            .await
342    }
343
344    /// Routes emitted execution events until the expected routing kind is observed.
345    pub async fn pump_until_routed(&mut self, timeout: Duration, kind: RoutedKind) -> bool {
346        self.pump_until_condition(timeout, |harness| harness.routed.contains(&kind))
347            .await
348    }
349
350    /// Routes every execution event received during the supplied duration.
351    pub async fn pump_for(&mut self, duration: Duration) {
352        let deadline = dst::time::Instant::now() + duration;
353
354        while dst::time::Instant::now() < deadline {
355            let remaining = deadline.saturating_duration_since(dst::time::Instant::now());
356            match dst::time::timeout(remaining.min(EVENT_POLL_INTERVAL), self.exec_rx.recv()).await
357            {
358                Ok(Some(event)) => self.route_event(event),
359                Ok(None) => return,
360                Err(_) => dst::task::yield_now().await,
361            }
362        }
363    }
364
365    /// Registers an `ExecTester` against the harness clock and cache.
366    #[must_use]
367    pub fn register_exec_tester(&self, strategy_id: StrategyId, order_qty: Quantity) -> ExecTester {
368        let mut config =
369            ExecTesterConfig::new(strategy_id, self.instrument_id, self.client_id, order_qty);
370        config.subscribe_quotes = false;
371        config.subscribe_trades = false;
372        config.enable_limit_sells = false;
373        config.tob_offset_ticks = 1;
374        config.cancel_orders_on_stop = false;
375        config.close_positions_on_stop = false;
376
377        let mut tester = ExecTester::new(config);
378
379        let portfolio = Rc::new(RefCell::new(Portfolio::new(
380            self.clock.clone(),
381            self.cache.clone(),
382            None,
383        )));
384        StrategyNative::strategy_core_mut(&mut tester)
385            .register(
386                self.trader_id,
387                self.clock.clone(),
388                self.cache.clone(),
389                portfolio,
390            )
391            .expect("ExecTester should register against the harness");
392        tester
393    }
394
395    /// Applies a pending-cancel event to the cached order.
396    pub fn mark_pending_cancel(&self, order: &OrderAny, causation_id: Option<UUID4>) {
397        let cached = self.cached_order(order);
398        let ts_now = self.clock.borrow().timestamp_ns();
399
400        let mut pending = OrderPendingCancel::new(
401            cached.trader_id(),
402            cached.strategy_id(),
403            cached.instrument_id(),
404            cached.client_order_id(),
405            cached.account_id(),
406            UUID4::new(),
407            ts_now,
408            ts_now,
409            false,
410            cached.venue_order_id(),
411        );
412        pending.causation_id = causation_id;
413        self.apply_pending_event(&OrderEventAny::PendingCancel(pending));
414    }
415
416    /// Generates and applies execution mass status from the registered adapter client.
417    #[allow(
418        clippy::await_holding_refcell_ref,
419        reason = "single-threaded test harness only runs mock venue tasks during the await"
420    )]
421    pub async fn reconcile_from_venue(&self) -> ExecutionMassStatus {
422        let mass_status = self
423            .exec_engine
424            .borrow_mut()
425            .generate_mass_status(&self.client_id, None)
426            .await
427            .expect("mass-status request should succeed")
428            .expect("mass-status request should return a report");
429        self.exec_engine
430            .borrow_mut()
431            .reconcile_execution_mass_status(&mass_status);
432        mass_status
433    }
434
435    fn mark_pending_update(&self, order: &OrderAny, command_id: UUID4) {
436        let cached = self.cached_order(order);
437        let ts_now = self.clock.borrow().timestamp_ns();
438
439        let mut pending = OrderPendingUpdate::new(
440            cached.trader_id(),
441            cached.strategy_id(),
442            cached.instrument_id(),
443            cached.client_order_id(),
444            cached.account_id(),
445            UUID4::new(),
446            ts_now,
447            ts_now,
448            false,
449            cached.venue_order_id(),
450        );
451        pending.causation_id = Some(command_id);
452        self.apply_pending_event(&OrderEventAny::PendingUpdate(pending));
453    }
454
455    fn cached_order(&self, order: &OrderAny) -> OrderAny {
456        self.cache
457            .borrow()
458            .order(&order.client_order_id())
459            .map(|cached| cached.clone())
460            .expect("order must be cached before a pending transition")
461    }
462
463    fn apply_pending_event(&self, event: &OrderEventAny) {
464        self.cache
465            .borrow_mut()
466            .update_order(event)
467            .expect("pending event should update the cached order");
468    }
469
470    async fn pump_until_condition(
471        &mut self,
472        timeout: Duration,
473        predicate: impl Fn(&Self) -> bool,
474    ) -> bool {
475        let start = dst::time::Instant::now();
476
477        loop {
478            if predicate(self) {
479                return true;
480            }
481
482            if start.elapsed() >= timeout {
483                return false;
484            }
485
486            match dst::time::timeout(EVENT_POLL_INTERVAL, self.exec_rx.recv()).await {
487                Ok(Some(event)) => self.route_event(event),
488                Ok(None) => return predicate(self),
489                Err(_) => dst::task::yield_now().await,
490            }
491        }
492    }
493
494    fn route_event(&mut self, event: ExecutionEvent) {
495        self.routed.push(RoutedKind::of(&event));
496        AsyncRunner::handle_exec_event(event);
497    }
498}
499
500const EVENT_POLL_INTERVAL: Duration = Duration::from_millis(50);
501
502/// Classifies which branch of the live execution routing fork handles an event.
503#[derive(Debug, Clone, Copy, PartialEq, Eq)]
504pub enum RoutedKind {
505    /// Typed order-event path.
506    Order,
507    /// Reconciliation-report path.
508    Report,
509    /// Account-state path.
510    Account,
511    /// Custom-data publication path.
512    Data,
513}
514
515impl RoutedKind {
516    fn of(event: &ExecutionEvent) -> Self {
517        match event {
518            ExecutionEvent::Report(_) => Self::Report,
519            ExecutionEvent::Account(_) => Self::Account,
520            ExecutionEvent::Data(_) => Self::Data,
521            _ => Self::Order,
522        }
523    }
524}
525
526/// Cross-layer invariants for live execution tests.
527pub mod invariants {
528    use ahash::AHashSet;
529    use nautilus_common::cache::Cache;
530    use nautilus_model::{
531        enums::OrderStatus,
532        identifiers::{ClientOrderId, InstrumentId},
533        orderbook::own::should_handle_own_book_order,
534        orders::Order,
535    };
536    use rust_decimal::Decimal;
537
538    use super::RoutedKind;
539
540    /// Asserts that a tracked lifecycle used typed order events and no reports.
541    pub fn assert_tracked_used_events(routed: &[RoutedKind]) {
542        assert!(
543            routed.contains(&RoutedKind::Order),
544            "tracked lifecycle routed no typed order event: {routed:?}",
545        );
546        let reports = routed
547            .iter()
548            .filter(|kind| **kind == RoutedKind::Report)
549            .count();
550        assert_eq!(
551            reports, 0,
552            "tracked happy path routed {reports} report(s), expected 0: {routed:?}",
553        );
554    }
555
556    /// Asserts the exact status of a cached order.
557    pub fn assert_order_status(cache: &Cache, id: &ClientOrderId, expected: OrderStatus) {
558        let status = cache.order(id).map(|order| order.status());
559        assert_eq!(
560            status,
561            Some(expected),
562            "order {id} status was {status:?}, expected {expected:?}",
563        );
564    }
565
566    /// Asserts that an instrument's own order book contains its eligible nonterminal cached orders.
567    ///
568    /// Every own-book entry must match its nonterminal cached order's projection field by field,
569    /// and every nonterminal cached order that `should_handle_own_book_order` accepts must be
570    /// present. Requires own-book management and a settled state: call it once queued commands
571    /// and events are processed, and not while an order awaits submission, such as a contingent
572    /// order held for its parent or an external-client order before its first event.
573    pub fn assert_own_book_consistent(cache: &Cache, instrument_id: &InstrumentId) {
574        let mut tracked_ids = AHashSet::new();
575
576        if let Some(book) = cache.own_order_book(instrument_id) {
577            let entries = book
578                .bids()
579                .chain(book.asks())
580                .flat_map(|level| level.orders.values());
581
582            for entry in entries {
583                let id = entry.client_order_id;
584
585                let Some(order) = cache.order(&id).filter(|order| !order.is_closed()) else {
586                    panic!("own order book retains closed or missing order {id}");
587                };
588
589                // `OwnBookOrder` equality compares only the client order ID
590                assert_eq!(
591                    format!("{entry:?}"),
592                    format!("{:?}", order.to_own_book_order()),
593                    "own order book entry for {id} diverges from the cached order",
594                );
595                tracked_ids.insert(id);
596            }
597        }
598
599        for order in cache.orders(None, Some(instrument_id), None, None, None) {
600            let id = order.client_order_id();
601            let eligible = !order.is_closed() && should_handle_own_book_order(&order);
602            assert!(
603                !eligible || tracked_ids.contains(&id),
604                "own order book is missing open order {id}",
605            );
606        }
607    }
608
609    /// Asserts the exact cumulative filled quantity of a cached order.
610    pub fn assert_filled_qty(cache: &Cache, id: &ClientOrderId, expected: Decimal) {
611        let filled = cache.order(id).map(|order| order.filled_qty().as_decimal());
612        assert_eq!(
613            filled,
614            Some(expected),
615            "order {id} filled_qty was {filled:?}, expected {expected}",
616        );
617    }
618
619    /// Asserts whether an order is present in the instrument's own order book.
620    pub fn assert_in_own_book(
621        cache: &Cache,
622        instrument_id: &InstrumentId,
623        id: &ClientOrderId,
624        expected: bool,
625    ) {
626        let present = cache
627            .own_order_book(instrument_id)
628            .is_some_and(|book| book.is_order_in_book(id));
629        assert_eq!(
630            present, expected,
631            "order {id} own-book membership was {present}, expected {expected}",
632        );
633    }
634}
635
636#[cfg(test)]
637mod tests {
638    use std::panic::{AssertUnwindSafe, catch_unwind};
639
640    use nautilus_common::cache::Cache;
641    use nautilus_execution::engine::stubs::StubExecutionClient;
642    use nautilus_model::{
643        enums::{OmsType, OrderSide, OrderStatus, OrderType},
644        identifiers::{AccountId, ClientId, ClientOrderId, TraderId, VenueOrderId},
645        instruments::{Instrument, stubs::audusd_sim},
646        orderbook::own::OwnOrderBook,
647        orders::{Order, OrderAny, OrderTestBuilder, stubs::TestOrderEventStubs},
648        types::{Price, Quantity},
649    };
650    use rstest::rstest;
651
652    use super::{ExecutionHarness, invariants};
653
654    #[derive(Clone, Copy, Debug)]
655    enum OwnBookFault {
656        Missing,
657        StaleSize,
658        Closed,
659        Unknown,
660    }
661
662    #[rstest]
663    #[case::occupied_route(false, "Venue SIM already routed to A, cannot re-route to B")]
664    #[case::duplicate_client(true, "Client already registered with ID A")]
665    fn test_registration_failure_preserves_client_and_route(
666        #[case] duplicate_id: bool,
667        #[case] expected: &str,
668    ) {
669        let instrument = audusd_sim();
670        let client_id = ClientId::from("A");
671        let account_id = AccountId::from("A-001");
672
673        let harness = ExecutionHarness::new(
674            TraderId::from("TRADER-001"),
675            client_id,
676            account_id,
677            instrument.clone().into(),
678        );
679        harness
680            .register_client(Box::new(StubExecutionClient::new(
681                client_id,
682                account_id,
683                instrument.id().venue,
684                OmsType::Netting,
685                None,
686            )))
687            .unwrap();
688
689        let replacement_id = if duplicate_id {
690            client_id
691        } else {
692            ClientId::from("B")
693        };
694
695        let error = harness
696            .register_client(Box::new(StubExecutionClient::new(
697                replacement_id,
698                AccountId::from("B-002"),
699                instrument.id().venue,
700                OmsType::Hedging,
701                None,
702            )))
703            .unwrap_err();
704        let order = OrderTestBuilder::new(OrderType::Market)
705            .instrument_id(instrument.id())
706            .quantity(Quantity::from(1))
707            .build();
708        let engine = harness.exec_engine().borrow();
709        let routed = engine.get_clients_for_orders(&[order]);
710
711        assert_eq!(error.to_string(), expected);
712        assert_eq!(engine.client_ids(), vec![client_id]);
713        assert_eq!(routed.len(), 1);
714        assert_eq!(routed[0].client_id(), client_id);
715        assert_eq!(routed[0].account_id(), account_id);
716        assert_eq!(routed[0].oms_type(), OmsType::Netting);
717    }
718
719    #[rstest]
720    #[case::consistent(None, None)]
721    #[case::missing(
722        Some(OwnBookFault::Missing),
723        Some("own order book is missing open order O-001")
724    )]
725    #[case::stale_size(
726        Some(OwnBookFault::StaleSize),
727        Some("own order book entry for O-001 diverges from the cached order")
728    )]
729    #[case::closed(
730        Some(OwnBookFault::Closed),
731        Some("own order book retains closed or missing order O-001")
732    )]
733    #[case::unknown(
734        Some(OwnBookFault::Unknown),
735        Some("own order book retains closed or missing order O-UNKNOWN")
736    )]
737    fn test_assert_own_book_consistent_detects_divergence(
738        #[case] fault: Option<OwnBookFault>,
739        #[case] expected: Option<&str>,
740    ) {
741        let (mut cache, order) = cache_with_accepted_order(false);
742        let instrument_id = order.instrument_id();
743        let entry = order.to_own_book_order();
744
745        match fault {
746            None => {}
747            Some(OwnBookFault::Missing) => {
748                let own_book = cache.own_order_book_mut(&instrument_id).unwrap();
749                own_book.delete(entry).unwrap();
750            }
751            Some(OwnBookFault::StaleSize) => {
752                let mut stale = entry;
753                stale.size = Quantity::from(50_000);
754                let own_book = cache.own_order_book_mut(&instrument_id).unwrap();
755                own_book.update(stale).unwrap();
756            }
757            Some(OwnBookFault::Closed) => {
758                let account_id = order.account_id().unwrap();
759                let canceled = TestOrderEventStubs::canceled(&order, account_id, None);
760                cache.update_order(&canceled).unwrap();
761                let own_book = cache.own_order_book_mut(&instrument_id).unwrap();
762                own_book.add(entry);
763            }
764            Some(OwnBookFault::Unknown) => {
765                let mut unknown = entry;
766                unknown.client_order_id = ClientOrderId::from("O-UNKNOWN");
767                let own_book = cache.own_order_book_mut(&instrument_id).unwrap();
768                own_book.add(unknown);
769            }
770        }
771
772        let result = catch_unwind(AssertUnwindSafe(|| {
773            invariants::assert_own_book_consistent(&cache, &instrument_id);
774        }));
775
776        let message = result.err().map(|payload| {
777            payload
778                .downcast_ref::<String>()
779                .cloned()
780                .unwrap_or_default()
781        });
782
783        match expected {
784            None => assert!(message.is_none(), "unexpected panic: {message:?}"),
785            Some(expected) => assert!(
786                message.as_deref().is_some_and(|m| m.contains(expected)),
787                "panic message {message:?} lacks {expected:?}",
788            ),
789        }
790    }
791
792    #[rstest]
793    fn test_assert_own_book_consistent_ignores_ineligible_open_order() {
794        let (cache, order) = cache_with_accepted_order(true);
795        let instrument_id = order.instrument_id();
796        let own_book = cache.own_order_book(&instrument_id).unwrap();
797        let in_own_book = own_book.is_order_in_book(&order.client_order_id());
798
799        invariants::assert_own_book_consistent(&cache, &instrument_id);
800
801        assert_eq!(order.status(), OrderStatus::Accepted);
802        assert!(!in_own_book);
803    }
804
805    fn cache_with_accepted_order(quote_quantity: bool) -> (Cache, OrderAny) {
806        let instrument = audusd_sim();
807        let instrument_id = instrument.id();
808        let account_id = AccountId::from("SIM-001");
809        let mut cache = Cache::default();
810        cache.add_instrument(instrument.into()).unwrap();
811        cache
812            .add_own_order_book(OwnOrderBook::new(instrument_id))
813            .unwrap();
814
815        let order = OrderTestBuilder::new(OrderType::Limit)
816            .instrument_id(instrument_id)
817            .client_order_id(ClientOrderId::from("O-001"))
818            .side(OrderSide::Buy)
819            .quantity(Quantity::from(100_000))
820            .price(Price::from("1.00000"))
821            .quote_quantity(quote_quantity)
822            .build();
823        cache.add_order(order.clone(), None, None, false).unwrap();
824        let order = cache
825            .update_order(&TestOrderEventStubs::submitted(&order, account_id))
826            .unwrap();
827        let order = cache
828            .update_order(&TestOrderEventStubs::accepted(
829                &order,
830                account_id,
831                VenueOrderId::from("V-001"),
832            ))
833            .unwrap();
834
835        (cache, order)
836    }
837}