From 6b938798dd91693f5d2311894d82d230fd7b638b Mon Sep 17 00:00:00 2001 From: MathisWellmann Date: Wed, 25 Nov 2026 19:57:50 +0100 Subject: [PATCH 1/3] stop_orders, exchange: keep pre-allocated buffer capacity through Clone `Exchange`, its per-market stores inside `PortfolioExchange` and the event buffers derive `Clone`, but `Vec::clone` keeps only the length while the pre-allocated capacity is load-bearing: - `PendingStops` admission uses the capacity as the configured bound, so a cloned exchange or market rejected every stop with `StopOrderError::MaxPendingStops(0)`. - The event and scratch buffers are pushed into with `push_within_capacity`, so the first fill, forced cancellation or stop event after a clone panicked. `PendingStops` now has a `Clone` that retains its capacity, the same pattern `SortedOrders` already uses, which fixes both `Exchange` and the portfolio's per-market stores. `Exchange` gets a manual `Clone` that restores its event and scratch buffers, sharing the capacity formulas with `new` through `BufferCapacities` so the two cannot drift apart. Clone is cold, so the push paths stay free of capacity checks. Tests: a cloned exchange accepts new stops, reports a triggered stop and a fill, and a cloned portfolio accepts new stops. All four fail without this change. Serializing and deserializing still drops the capacity (serde has no hook to restore it), the same pre-existing gap as `SortedOrders`. --- src/exchange.rs | 107 ++++++++++++++++++++++++++++--- src/stop_orders/pending_stops.rs | 19 +++++- src/tests/stop_orders.rs | 63 ++++++++++++++++++ src/tests/update_state.rs | 34 ++++++++++ 4 files changed, 213 insertions(+), 10 deletions(-) diff --git a/src/exchange.rs b/src/exchange.rs index b2ba8a98..9952d239 100644 --- a/src/exchange.rs +++ b/src/exchange.rs @@ -1,3 +1,5 @@ +use std::num::NonZeroU16; + use assert2::assert; use getset::{ Getters, @@ -161,7 +163,7 @@ where } /// The main leveraged futures exchange for simulated trading -#[derive(Debug, Clone, Getters, MutGetters)] +#[derive(Debug, Getters, MutGetters)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr( feature = "serde", @@ -238,6 +240,83 @@ where order_rate_limiter: OrderRateLimiter, } +impl Clone for Exchange +where + I: Mon, + BaseOrQuote: Currency, + BaseOrQuote::PairedCurrency: MarginCurrency, + UserOrderIdT: UserOrderId, +{ + /// Clone the exchange with the pre-allocated buffers of a freshly constructed one. + /// + /// `Vec::clone` keeps only the length, so a derived clone left the event and scratch + /// buffers without spare capacity and the first fill, forced cancel or stop event + /// panicked in `push_within_capacity`. `Clone` is cold, so restoring the bounds costs + /// one allocation per non-empty buffer and keeps every push path free of capacity + /// checks. `PendingStops` retains its own capacity in its `Clone`. + fn clone(&self) -> Self { + let mut cloned = Self { + config: self.config.clone(), + market_state: self.market_state.clone(), + risk_engine: self.risk_engine.clone(), + cross_risk_engine: self.cross_risk_engine.clone(), + next_order_id: self.next_order_id, + account: self.account.clone(), + limit_order_events: self.limit_order_events.clone(), + forced_cancel_scratch: self.forced_cancel_scratch.clone(), + liquidated_during_fills: self.liquidated_during_fills, + pending_stops: self.pending_stops.clone(), + stop_order_events: self.stop_order_events.clone(), + elected_stops_scratch: self.elected_stops_scratch.clone(), + ledger: self.ledger.clone(), + order_rate_limiter: self.order_rate_limiter.clone(), + }; + cloned.reserve_preallocated_capacities(); + cloned + } +} + +/// Capacity of the per-update buffers, derived from the maximum number of open orders. +/// +/// Shared by [`Exchange::new`] and [`Exchange::clone`] so the bounds cannot drift apart. +#[derive(Debug, Clone, Copy)] +struct BufferCapacities { + limit_order_events: usize, + forced_cancel_scratch: usize, + elected_stops_scratch: usize, + stop_order_events: usize, +} + +impl BufferCapacities { + fn for_orders(max_orders: NonZeroU16) -> Self { + let max = usize::from(max_orders.get()); + Self { + // Bids and asks each fill up to `max` times, and every fill can force-cancel + // as many orders again. + limit_order_events: max * 4, + // At most two forced cancellations per resting order, one elected stop and one + // stop event per order. + forced_cancel_scratch: max * 2, + elected_stops_scratch: max, + stop_order_events: max, + } + } +} + +/// Grow `vec` to hold at least `capacity` elements without dropping its contents. +/// +/// `Vec::clone` keeps only the length, while the event push paths +/// (`push_within_capacity`) rely on the spare capacity that [`Exchange::new`] +/// pre-allocates. Allocation-free once the bound is in place. +fn reserve_to_capacity(vec: &mut Vec, capacity: usize) { + if vec.capacity() >= capacity { + return; + } + assert!(vec.len() <= capacity); + vec.reserve_exact(capacity - vec.len()); + assert!(vec.capacity() >= capacity); +} + impl Exchange where I: Mon, @@ -263,10 +342,10 @@ where let balances = Balances::new(config.starting_wallet_balance()); let init_margin_req = config.contract_spec().init_margin_req(); let maker_fee = *config.contract_spec().fee_maker().as_ref(); - let pending_stops = PendingStops::with_capacity(max_active_orders); + let caps = BufferCapacities::for_orders(max_active_orders); // Every pending stop yields at most one event per public call (it is elected or // force-cancelled once), and the buffer is cleared at the start of every such call. - let stop_order_events = Vec::with_capacity(usize::from(max_active_orders.get())); + let stop_order_events = Vec::with_capacity(caps.stop_order_events); Self { config, market_state, @@ -274,19 +353,29 @@ where cross_risk_engine, next_order_id: OrderId::default(), account: Account::new(balances, max_active_orders, init_margin_req, maker_fee), - // Bids and asks each have a capacity of `max_active_orders`, so one update - // can emit at most `2 * max_active_orders` fills plus as many forced cancels. - limit_order_events: Vec::with_capacity(usize::from(max_active_orders.get()) * 4), - forced_cancel_scratch: Vec::with_capacity(usize::from(max_active_orders.get()) * 2), + limit_order_events: Vec::with_capacity(caps.limit_order_events), + forced_cancel_scratch: Vec::with_capacity(caps.forced_cancel_scratch), liquidated_during_fills: false, - pending_stops, + pending_stops: PendingStops::with_capacity(max_active_orders), stop_order_events, - elected_stops_scratch: Vec::with_capacity(usize::from(max_active_orders.get())), + elected_stops_scratch: Vec::with_capacity(caps.elected_stops_scratch), ledger: None, order_rate_limiter, } } + /// Give the per-update buffers the capacity of a freshly constructed exchange. + /// + /// [`Exchange::new`] allocates them up front, [`Exchange::clone`] restores them after + /// `Vec::clone` dropped the spare capacity. See [`reserve_to_capacity`]. + fn reserve_preallocated_capacities(&mut self) { + let caps = BufferCapacities::for_orders(self.config.max_num_open_orders()); + reserve_to_capacity(&mut self.limit_order_events, caps.limit_order_events); + reserve_to_capacity(&mut self.forced_cancel_scratch, caps.forced_cancel_scratch); + reserve_to_capacity(&mut self.elected_stops_scratch, caps.elected_stops_scratch); + reserve_to_capacity(&mut self.stop_order_events, caps.stop_order_events); + } + /// Enable the opt-in cashflow [`Ledger`] with initial capacity `capacity`, anchored at /// the current wallet equity. pub fn enable_ledger(&mut self, capacity: usize) { diff --git a/src/stop_orders/pending_stops.rs b/src/stop_orders/pending_stops.rs index e8c3617d..48b7ef0a 100644 --- a/src/stop_orders/pending_stops.rs +++ b/src/stop_orders/pending_stops.rs @@ -40,7 +40,7 @@ pub type ElectedStop = ( /// /// Capacity is pre-allocated at construction so admission and election never allocate /// on the hot path. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct PendingStops where @@ -51,6 +51,23 @@ where stops: Vec>, } +/// A clone impl which retains the capacity: admission uses it as the configured bound and +/// rejects with [`StopOrderError::MaxPendingStops`] instead of allocating. +impl Clone + for PendingStops +where + I: Mon, + BaseOrQuote: Currency, + UserOrderIdT: UserOrderId, +{ + fn clone(&self) -> Self { + let mut stops = self.stops.clone(); + stops.reserve_exact(self.stops.capacity() - self.stops.len()); + debug_assert_eq!(stops.capacity(), self.stops.capacity()); + Self { stops } + } +} + impl PendingStops where I: Mon, diff --git a/src/tests/stop_orders.rs b/src/tests/stop_orders.rs index 24c1e896..afed252d 100644 --- a/src/tests/stop_orders.rs +++ b/src/tests/stop_orders.rs @@ -1160,3 +1160,66 @@ fn trailing_stop_on_a_candle_trails_before_testing_the_adverse_extreme() { other => panic!("expected fill, got {other:?}"), } } + +#[test] +fn cloned_exchange_accepts_new_stop_orders() { + // A derived `Clone` kept only the length of the pre-allocated stop store, so admission + // failed with `MaxPendingStops(0)`. A clone must behave like a fresh exchange. + let ex = small_exchange(10, 1_000); + let mut cloned = ex.clone(); + cloned + .submit_stop_order( + StopOrder::stop_market( + Side::Sell, + QuoteCurrency::new(95, 0), + BaseCurrency::new(1, 0), + NoUserOrderId, + ) + .unwrap(), + ) + .unwrap(); + assert_eq!(cloned.pending_stops().len(), 1); +} + +#[test] +fn cloned_exchange_reports_a_triggered_stop() { + // Election pushes into the elected-stop and stop-event scratch buffers, which a + // derived `Clone` left without spare capacity. + let mut ex = small_exchange(10, 1_000); + ex.submit_market_order(MarketOrder::new(Side::Buy, BaseCurrency::new(2, 0)).unwrap()) + .unwrap(); + ex.submit_stop_order(reduce_only_sell_stop(95)).unwrap(); + + let mut cloned = ex.clone(); + cloned.update_state(&bba_94_95()).unwrap(); + + assert!(cloned.pending_stops().is_empty()); + assert!(cloned.account().position().quantity().is_zero()); + let events = cloned.stop_order_events(); + assert_eq!(events.len(), 1, "{events:?}"); + assert!(matches!(events[0], StopOrderEvent::Filled { .. })); +} + +#[test] +fn cloned_portfolio_accepts_new_stop_orders() { + // A portfolio clone shrinks each market's pre-allocated stop store to its length, so + // admission must not fail with `MaxPendingStops(0)`. + let pf = levered_portfolio(QuoteCurrency::new(200, 0)); + let mut cloned = pf.clone(); + cloned + .submit_stop_order( + MarketId::new(0), + StopOrder::stop_market( + Side::Sell, + QuoteCurrency::new(95, 0), + BaseCurrency::new(1, 0), + NoUserOrderId, + ) + .unwrap(), + ) + .unwrap(); + let stops = cloned + .pending_stops(MarketId::new(0)) + .expect("market exists"); + assert_eq!(stops.len(), 1); +} diff --git a/src/tests/update_state.rs b/src/tests/update_state.rs index a5a28b98..78b65db2 100644 --- a/src/tests/update_state.rs +++ b/src/tests/update_state.rs @@ -151,3 +151,37 @@ fn quote_update_of_flat_account_still_elects_pending_stops() { assert!(ex.pending_stops().is_empty()); assert_eq!(ex.account().position().quantity(), BaseCurrency::new(1, 0)); } + +#[test] +fn cloned_exchange_reports_a_fill() { + // A fill pushes into `limit_order_events`, which a derived `Clone` left without spare + // capacity. + let mut ex = mock_exchange_linear(); + ex.update_state(&bba(100, 101, 1)).unwrap(); + + let mut cloned = ex.clone(); + cloned + .submit_limit_order( + LimitOrder::new( + Side::Buy, + QuoteCurrency::new(100, 0), + BaseCurrency::new(1, 0), + ) + .unwrap(), + ) + .unwrap(); + // The trade prints strictly through the resting bid, which is the worst queue position. + let events = cloned + .update_state(&Trade { + price: QuoteCurrency::new(99, 0), + quantity: BaseCurrency::new(1, 0), + side: Side::Sell, + timestamp_exchange_ns: 2.into(), + }) + .unwrap(); + assert_eq!(events.len(), 1, "{events:?}"); + assert_eq!( + cloned.account().position().quantity(), + BaseCurrency::new(1, 0) + ); +} From 80f097cc0c034e49b8d65a8b232aaffc3276ee0d Mon Sep 17 00:00:00 2001 From: MathisWellmann Date: Wed, 25 Nov 2026 20:19:45 +0100 Subject: [PATCH 2/3] portfolio: keep pre-allocated buffer capacity through Clone The previous revision fixed `Exchange` and `PendingStops`, but `PortfolioExchange` still derived `Clone`. `Vec::clone` keeps only the length, so a cloned portfolio panicked in `push_within_capacity` on its first fill (`order_events`), stop election (`elected_stops_scratch`) or forced cancel (`forced_cancel_scratch`). Only `stop_events` was restored, lazily in `reset_stop_events`. `PortfolioExchange` now has a manual `Clone` that restores all four buffers through `reserve_preallocated_capacities`. Their sizes come from a new `BufferCapacities` shared by `new`, `add_market` and `clone`, so the bounds cannot drift apart. `add_market` grows to the absolute total instead of calling a relative `Vec::reserve`: the buffers are empty between calls, so `reserve(add)` only guaranteed `add`, not the old total plus `add`. `reserve_to_capacity` moves to `utils` so both exchanges share it. The `reset_stop_events` / `restore_stop_order_event_capacity` comments now say that only a deserialized exchange reaches the lazy path. Tests: a cloned portfolio (with a market added through `add_market`) reports a fill, a triggered stop and a forced cancel of a reduce-only order. All three panic without the new `Clone`. --- src/exchange.rs | 19 +---- src/portfolio/portfolio_exchange.rs | 115 +++++++++++++++++++++----- src/tests/portfolio.rs | 120 ++++++++++++++++++++++++++++ src/utils.rs | 18 +++++ 4 files changed, 235 insertions(+), 37 deletions(-) diff --git a/src/exchange.rs b/src/exchange.rs index 9952d239..c93e3862 100644 --- a/src/exchange.rs +++ b/src/exchange.rs @@ -81,6 +81,7 @@ use crate::{ TimestampNs, UserOrderId, }, + utils::reserve_to_capacity, }; /// Result of submitting a limit order via [`Exchange::submit_limit_order_with_execution`], @@ -303,20 +304,6 @@ impl BufferCapacities { } } -/// Grow `vec` to hold at least `capacity` elements without dropping its contents. -/// -/// `Vec::clone` keeps only the length, while the event push paths -/// (`push_within_capacity`) rely on the spare capacity that [`Exchange::new`] -/// pre-allocates. Allocation-free once the bound is in place. -fn reserve_to_capacity(vec: &mut Vec, capacity: usize) { - if vec.capacity() >= capacity { - return; - } - assert!(vec.len() <= capacity); - vec.reserve_exact(capacity - vec.len()); - assert!(vec.capacity() >= capacity); -} - impl Exchange where I: Mon, @@ -2055,8 +2042,8 @@ where /// Give `stop_order_events` enough spare capacity for the next event. /// - /// `#[derive(Clone)]` does not keep spare `Vec` capacity, so a cloned exchange has to - /// allocate on its first stop event. Every other exchange already has the bound. + /// `Clone` restores the bound, so only a deserialized exchange (serde cannot restore + /// spare `Vec` capacity) has to allocate on its first stop event. #[cold] #[inline(never)] fn restore_stop_order_event_capacity(&mut self) { diff --git a/src/portfolio/portfolio_exchange.rs b/src/portfolio/portfolio_exchange.rs index 6d4503d1..ec4cf02a 100644 --- a/src/portfolio/portfolio_exchange.rs +++ b/src/portfolio/portfolio_exchange.rs @@ -86,6 +86,7 @@ use crate::{ TimestampNs, UserOrderId, }, + utils::reserve_to_capacity, }; /// Internal per-market slot stored contiguously in [`PortfolioExchange::markets`]. @@ -246,7 +247,7 @@ where /// All registered markets share a single [`Balances`] wallet. Profits in winning /// positions offset losses in losing positions under cross-margin, and forced /// cancellations / liquidations reconcile across the entire portfolio. -#[derive(Debug, Clone, Getters)] +#[derive(Debug, Getters)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr( feature = "serde", @@ -308,6 +309,70 @@ where ledger: Option>, } +impl Clone + for PortfolioExchange +where + I: Mon, + BaseOrQuote: Currency, + BaseOrQuote::PairedCurrency: MarginCurrency, + UserOrderIdT: UserOrderId, +{ + /// Clone the portfolio with the pre-allocated buffers of a freshly constructed one. + /// + /// `Vec::clone` keeps only the length, so a derived clone left the event and scratch + /// buffers without spare capacity and the first fill, elected stop or forced cancel + /// panicked in `push_within_capacity`. `Clone` is cold, so restoring the bounds here + /// keeps every push path free of capacity checks. The per-market `ActiveLimitOrders` + /// and `PendingStops` retain their own capacity in their `Clone`. + fn clone(&self) -> Self { + let mut cloned = Self { + balances: self.balances.clone(), + markets: self.markets.clone(), + ticker_index: self.ticker_index.clone(), + next_order_id: self.next_order_id, + order_events: self.order_events.clone(), + stop_events: self.stop_events.clone(), + max_pending_stops: self.max_pending_stops, + elected_stops_scratch: self.elected_stops_scratch.clone(), + forced_cancel_scratch: self.forced_cancel_scratch.clone(), + liquidated_during_fills: self.liquidated_during_fills, + ledger: self.ledger.clone(), + }; + cloned.reserve_preallocated_capacities(); + cloned + } +} + +/// Capacity of the per-call buffers, derived from the summed `max_num_open_orders` of all +/// markets. +/// +/// Shared by [`PortfolioExchange::new`], [`PortfolioExchange::add_market`] and +/// [`PortfolioExchange::clone`] so the bounds cannot drift apart. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct BufferCapacities { + order_events: usize, + stop_events: usize, + elected_stops_scratch: usize, + forced_cancel_scratch: usize, +} + +impl BufferCapacities { + fn for_total_orders(total_order_cap: usize) -> Self { + // Every market's bids and asks each hold up to `max_num_open_orders`, so one call + // can fill or force-cancel twice the total. Order events cover the fills plus as + // many forced cancels. + let scratch_cap = (total_order_cap * 2).max(16); + Self { + order_events: scratch_cap * 2, + // `PendingStops` holds up to `max_num_open_orders` stops per market, and each + // yields at most one event per call. + stop_events: total_order_cap, + elected_stops_scratch: scratch_cap, + forced_cancel_scratch: scratch_cap, + } + } +} + impl PortfolioExchange where I: Mon, @@ -349,24 +414,37 @@ where .expect(EXPECT_CAPACITY); } - let scratch_cap = (total_order_cap * 2).max(16); - // `PendingStops` holds up to `max_num_open_orders` stops per market. - let max_pending_stops = total_order_cap; + let caps = BufferCapacities::for_total_orders(total_order_cap); Self { balances, markets, ticker_index, next_order_id: OrderId::default(), - order_events: Vec::with_capacity(scratch_cap * 2), - stop_events: Vec::with_capacity(max_pending_stops), - max_pending_stops, - elected_stops_scratch: Vec::with_capacity(scratch_cap), - forced_cancel_scratch: Vec::with_capacity(scratch_cap), + order_events: Vec::with_capacity(caps.order_events), + stop_events: Vec::with_capacity(caps.stop_events), + max_pending_stops: caps.stop_events, + elected_stops_scratch: Vec::with_capacity(caps.elected_stops_scratch), + forced_cancel_scratch: Vec::with_capacity(caps.forced_cancel_scratch), liquidated_during_fills: false, ledger: None, } } + /// Give the per-call buffers the capacity [`BufferCapacities`] prescribes for the + /// current set of markets. + /// + /// [`Self::new`] allocates them up front, [`Self::add_market`] grows them to the new + /// total and [`PortfolioExchange::clone`] restores them after `Vec::clone` dropped + /// the spare capacity. + fn reserve_preallocated_capacities(&mut self) { + let caps = BufferCapacities::for_total_orders(self.max_pending_stops); + assert_eq!(caps.stop_events, self.max_pending_stops); + reserve_to_capacity(&mut self.order_events, caps.order_events); + reserve_to_capacity(&mut self.stop_events, caps.stop_events); + reserve_to_capacity(&mut self.elected_stops_scratch, caps.elected_stops_scratch); + reserve_to_capacity(&mut self.forced_cancel_scratch, caps.forced_cancel_scratch); + } + /// Enable the opt-in portfolio cashflow [`Ledger`] anchored at current wallet equity. pub fn enable_ledger(&mut self, capacity: usize) { self.ledger = Some(Ledger::with_capacity(self.balances.equity(), capacity)); @@ -426,17 +504,12 @@ where } self.ticker_index.insert(ticker.clone(), market_id); } - let add_cap = usize::from(market_cfg.max_num_open_orders().get()) * 2; - self.forced_cancel_scratch.reserve(add_cap); - self.order_events.reserve(add_cap * 2); + // `max_pending_stops` is the summed order capacity of all markets, see + // `BufferCapacities`. Grow every buffer to the new total: a relative + // `Vec::reserve` only guarantees `len + additional`, and the buffers are empty + // between calls, so it would not grow them at all. self.max_pending_stops += usize::from(market_cfg.max_num_open_orders().get()); - // `reserve` is relative to `len`, so size against the total stop capacity instead. - self.stop_events.reserve( - self.max_pending_stops - .saturating_sub(self.stop_events.len()), - ); - assert!(self.stop_events.capacity() >= self.max_pending_stops); - self.elected_stops_scratch.reserve(add_cap); + self.reserve_preallocated_capacities(); #[allow( clippy::disallowed_methods, reason = "add_market is a cold-path dynamic market registration" @@ -2155,8 +2228,8 @@ where /// Clear `stop_events` at the start of a public call which can emit stop events. /// /// Also restores the capacity bound (one event per possible pending stop of every - /// market), because `#[derive(Clone)]` does not keep spare `Vec` capacity. - /// Allocation-free except on the first call after a clone. + /// market) if it is missing. `Clone` and `add_market` keep it, so only a deserialized + /// portfolio (serde cannot restore spare `Vec` capacity) takes that branch. #[inline] fn reset_stop_events(&mut self) { self.stop_events.clear(); diff --git a/src/tests/portfolio.rs b/src/tests/portfolio.rs index 2ee756b7..e3cc5b1c 100644 --- a/src/tests/portfolio.rs +++ b/src/tests/portfolio.rs @@ -804,3 +804,123 @@ fn portfolio_supports_one_market_per_market_id() { Err(PortfolioError::MaxMarketsReached(MarketId::COUNT)) ); } + +fn cloned_two_market_portfolio() -> (LinearPortfolio, MarketId) { + let cfg = PortfolioConfig::new( + QuoteCurrency::new(10_000, 0), + vec![make_linear_market_cfg("AAA", 2)], + ) + .unwrap(); + let mut pf = LinearPortfolio::new(cfg); + // Dynamic registration must leave the buffers sized for both markets as well. + let b = pf.add_market(make_linear_market_cfg("BBB", 2)).unwrap(); + pf.update_market(b, &bba(99, 100, 1)).unwrap(); + (pf.clone(), b) +} + +#[test] +fn cloned_portfolio_reports_a_fill() { + // A fill pushes into `order_events`, which a derived `Clone` left without spare + // capacity. + let (mut pf, b) = cloned_two_market_portfolio(); + rest_limit(&mut pf, b, Side::Buy, 98, 1); + let events = pf + .update_market( + b, + &Trade { + price: QuoteCurrency::new(97, 0), + quantity: BaseCurrency::new(1, 0), + side: Side::Sell, + timestamp_exchange_ns: 2.into(), + }, + ) + .unwrap(); + assert_eq!(events.len(), 1, "{events:?}"); + assert!(matches!(events[0].event, LimitOrderEvent::Fill(_))); + assert_eq!( + pf.market(b).unwrap().position.quantity(), + BaseCurrency::new(1, 0) + ); +} + +#[test] +fn cloned_portfolio_reports_a_triggered_stop() { + // Election pushes into the elected-stop scratch buffer, which a derived `Clone` left + // without spare capacity. + let (mut pf, b) = cloned_two_market_portfolio(); + pf.submit_market_order( + b, + MarketOrder::new(Side::Buy, BaseCurrency::new(1, 0)).unwrap(), + ) + .unwrap(); + pf.submit_stop_order( + b, + StopOrder::stop_market( + Side::Sell, + QuoteCurrency::new(95, 0), + BaseCurrency::new(1, 0), + NoUserOrderId, + ) + .unwrap() + .with_trigger_price_type(TriggerPriceType::Last), + ) + .unwrap(); + + let mut cloned = pf.clone(); + cloned + .update_market( + b, + &Trade { + price: QuoteCurrency::new(94, 0), + quantity: BaseCurrency::new(1, 0), + side: Side::Sell, + timestamp_exchange_ns: 2.into(), + }, + ) + .unwrap(); + + assert!(cloned.pending_stops(b).expect("market exists").is_empty()); + assert!(cloned.market(b).unwrap().position.quantity().is_zero()); + let events = cloned.stop_events(); + assert_eq!(events.len(), 1, "{events:?}"); + assert_eq!(events[0].market_id, b); + assert!(matches!(events[0].event, StopOrderEvent::Filled { .. })); +} + +#[test] +fn cloned_portfolio_reports_a_forced_cancel() { + // Shrinking the position below a resting reduce-only order force-cancels it through + // `forced_cancel_scratch`, which a derived `Clone` left without spare capacity. + let (mut pf, b) = cloned_two_market_portfolio(); + pf.submit_market_order( + b, + MarketOrder::new(Side::Buy, BaseCurrency::new(2, 0)).unwrap(), + ) + .unwrap(); + let reduce = pf + .submit_limit_order( + b, + LimitOrder::new( + Side::Sell, + QuoteCurrency::new(110, 0), + BaseCurrency::new(2, 0), + ) + .unwrap() + .with_reduce_only(true), + ) + .unwrap() + .id(); + + let mut cloned = pf.clone(); + let settlement = cloned + .submit_market_order( + b, + MarketOrder::new(Side::Sell, BaseCurrency::new(1, 0)).unwrap(), + ) + .unwrap(); + + assert_eq!(settlement.solvency, Solvency::Solvent); + assert_eq!(settlement.forced_cancels.len(), 1); + assert_eq!(settlement.forced_cancels[0].1.id(), reduce); + assert!(cloned.market(b).unwrap().active_limit_orders.is_empty()); +} diff --git a/src/utils.rs b/src/utils.rs index 6131db27..b02eea08 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -67,6 +67,24 @@ pub fn scale(from_min: F, from_max: F, to_min: F, to_max: F, valu to_min + ((value - from_min) * (to_max - to_min)) / (from_max - from_min) } +/// Grow `vec` to hold at least `capacity` elements without dropping its contents. +/// +/// `Vec::clone` keeps only the length, while the event push paths +/// (`push_within_capacity`) rely on the spare capacity that the exchange constructors +/// pre-allocate. Used by their `Clone` impls. Allocation-free once the bound is in place. +pub(crate) fn reserve_to_capacity(vec: &mut Vec, capacity: usize) { + let len_before = vec.len(); + if vec.capacity() < capacity { + vec.reserve_exact(capacity - len_before); + } + assert!(vec.capacity() >= capacity); + assert_eq!( + vec.len(), + len_before, + "reserving must not change the contents" + ); +} + /// The margin requirement for all the tracked orders. #[inline(always)] pub(crate) fn order_margin( From 4ab2733c07d1f9c02678a43d839ad962d2d608e4 Mon Sep 17 00:00:00 2001 From: MathisWellmann Date: Wed, 25 Nov 2026 20:47:11 +0100 Subject: [PATCH 3/3] execution_rules: share BufferCapacities between Exchange and PortfolioExchange Both exchanges sized their event and scratch buffers from the same input, the number of order slots (`max_num_open_orders`, or its sum over all markets), but each had its own private `BufferCapacities` with different formulas. A new event source would have needed the bound fixed in two places. `execution_rules::BufferCapacities::for_order_slots(n)` is now the only source: 4n order events, 2n forced cancels, n elected stops and n stop events. The field docs give the reason for each bound. `Exchange::new`/`clone` pass `max_num_open_orders`, `PortfolioExchange::new`/`add_market`/`clone` pass the summed slots. Portfolio sizes that change: - The `.max(16)` floor is gone. Nothing depended on it, and an empty portfolio now allocates nothing. - `elected_stops_scratch` shrinks from 2n to n. Elections are evaluated per market, so a single market's pending stops already bound it. This only changes memory use, not behavior. The push paths use `push_within_capacity`, so a bound that is too small would panic in the existing tests rather than allocate. Also drops the wrong "two forced cancellations per resting order" comment: each order is cancelled at most once. The 2n comes from bids and asks. Tests: unit test for the bounds, including 0 slots and the largest valid input, and a should_panic test for one slot more than any config allows. --- src/exchange.rs | 56 +++++---------------- src/execution_rules.rs | 76 +++++++++++++++++++++++++++++ src/portfolio/portfolio_exchange.rs | 60 +++++++---------------- 3 files changed, 106 insertions(+), 86 deletions(-) diff --git a/src/exchange.rs b/src/exchange.rs index c93e3862..29ad1441 100644 --- a/src/exchange.rs +++ b/src/exchange.rs @@ -1,5 +1,3 @@ -use std::num::NonZeroU16; - use assert2::assert; use getset::{ Getters, @@ -27,6 +25,7 @@ use crate::{ config::Config, execution_rules::{ self, + BufferCapacities, fill_flows, }, ledger::{ @@ -277,33 +276,6 @@ where } } -/// Capacity of the per-update buffers, derived from the maximum number of open orders. -/// -/// Shared by [`Exchange::new`] and [`Exchange::clone`] so the bounds cannot drift apart. -#[derive(Debug, Clone, Copy)] -struct BufferCapacities { - limit_order_events: usize, - forced_cancel_scratch: usize, - elected_stops_scratch: usize, - stop_order_events: usize, -} - -impl BufferCapacities { - fn for_orders(max_orders: NonZeroU16) -> Self { - let max = usize::from(max_orders.get()); - Self { - // Bids and asks each fill up to `max` times, and every fill can force-cancel - // as many orders again. - limit_order_events: max * 4, - // At most two forced cancellations per resting order, one elected stop and one - // stop event per order. - forced_cancel_scratch: max * 2, - elected_stops_scratch: max, - stop_order_events: max, - } - } -} - impl Exchange where I: Mon, @@ -329,10 +301,7 @@ where let balances = Balances::new(config.starting_wallet_balance()); let init_margin_req = config.contract_spec().init_margin_req(); let maker_fee = *config.contract_spec().fee_maker().as_ref(); - let caps = BufferCapacities::for_orders(max_active_orders); - // Every pending stop yields at most one event per public call (it is elected or - // force-cancelled once), and the buffer is cleared at the start of every such call. - let stop_order_events = Vec::with_capacity(caps.stop_order_events); + let caps = BufferCapacities::for_order_slots(usize::from(max_active_orders.get())); Self { config, market_state, @@ -340,12 +309,12 @@ where cross_risk_engine, next_order_id: OrderId::default(), account: Account::new(balances, max_active_orders, init_margin_req, maker_fee), - limit_order_events: Vec::with_capacity(caps.limit_order_events), - forced_cancel_scratch: Vec::with_capacity(caps.forced_cancel_scratch), + limit_order_events: Vec::with_capacity(caps.order_events()), + forced_cancel_scratch: Vec::with_capacity(caps.forced_cancels()), liquidated_during_fills: false, pending_stops: PendingStops::with_capacity(max_active_orders), - stop_order_events, - elected_stops_scratch: Vec::with_capacity(caps.elected_stops_scratch), + stop_order_events: Vec::with_capacity(caps.stop_events()), + elected_stops_scratch: Vec::with_capacity(caps.elected_stops()), ledger: None, order_rate_limiter, } @@ -354,13 +323,14 @@ where /// Give the per-update buffers the capacity of a freshly constructed exchange. /// /// [`Exchange::new`] allocates them up front, [`Exchange::clone`] restores them after - /// `Vec::clone` dropped the spare capacity. See [`reserve_to_capacity`]. + /// `Vec::clone` dropped the spare capacity. See [`BufferCapacities`]. fn reserve_preallocated_capacities(&mut self) { - let caps = BufferCapacities::for_orders(self.config.max_num_open_orders()); - reserve_to_capacity(&mut self.limit_order_events, caps.limit_order_events); - reserve_to_capacity(&mut self.forced_cancel_scratch, caps.forced_cancel_scratch); - reserve_to_capacity(&mut self.elected_stops_scratch, caps.elected_stops_scratch); - reserve_to_capacity(&mut self.stop_order_events, caps.stop_order_events); + let caps = + BufferCapacities::for_order_slots(usize::from(self.config.max_num_open_orders().get())); + reserve_to_capacity(&mut self.limit_order_events, caps.order_events()); + reserve_to_capacity(&mut self.forced_cancel_scratch, caps.forced_cancels()); + reserve_to_capacity(&mut self.elected_stops_scratch, caps.elected_stops()); + reserve_to_capacity(&mut self.stop_order_events, caps.stop_events()); } /// Enable the opt-in cashflow [`Ledger`] with initial capacity `capacity`, anchored at diff --git a/src/execution_rules.rs b/src/execution_rules.rs index f2e67d7f..ec74f092 100644 --- a/src/execution_rules.rs +++ b/src/execution_rules.rs @@ -4,6 +4,7 @@ //! Both venues implement the same order semantics on different account models. Keeping //! the rules here as pure functions means a fix cannot land in only one of them. +use getset::CopyGetters; use num_traits::Zero; use crate::{ @@ -17,6 +18,7 @@ use crate::{ Currency, LimitOrder, MarginCurrency, + MarketId, Mon, NewOrder, QuoteCurrency, @@ -330,6 +332,51 @@ where trade_range.is_some() && price_type == TriggerPriceType::Last } +/// Capacity of the per-call event and scratch buffers of both exchanges. +/// +/// The bounds depend only on the number of order slots `n`: the `max_num_open_orders` +/// of an [`crate::prelude::Exchange`], or the sum over all markets of a +/// [`crate::prelude::PortfolioExchange`]. Bids and asks each rest up to that many +/// orders, and the pending stops are capped at the same number. +/// `new`, `add_market` and `clone` of both exchanges size their buffers from here, so the +/// bounds cannot drift apart. The push paths use `push_within_capacity`, so a bound which +/// is too small panics instead of allocating. +#[derive(Debug, Clone, Copy, PartialEq, Eq, CopyGetters)] +pub(crate) struct BufferCapacities { + /// Fills and forced cancellations of one call: up to `2n` fills of the resting bids and + /// asks plus as many forced cancellations. + #[getset(get_copy = "pub(crate)")] + order_events: usize, + /// Orders force-cancelled between two drains: each of the at most `2n` resting + /// orders is cancelled at most once. + #[getset(get_copy = "pub(crate)")] + forced_cancels: usize, + /// Stops elected by one evaluation, which covers a single market's pending stops. + #[getset(get_copy = "pub(crate)")] + elected_stops: usize, + /// One event per pending stop per call; a portfolio liquidation drains every market. + #[getset(get_copy = "pub(crate)")] + stop_events: usize, +} + +impl BufferCapacities { + /// The capacities for `order_slots` slots, see the field docs for each bound. + #[must_use] + pub(crate) fn for_order_slots(order_slots: usize) -> Self { + // Both callers sum `NonZeroU16` limits over at most `MarketId::COUNT` markets. + assert!(order_slots <= MarketId::COUNT * usize::from(u16::MAX)); + let caps = Self { + order_events: order_slots * 4, + forced_cancels: order_slots * 2, + elected_stops: order_slots, + stop_events: order_slots, + }; + assert!(caps.order_events >= caps.forced_cancels); + assert!(caps.forced_cancels >= caps.elected_stops); + caps + } +} + #[cfg(test)] mod tests { use super::*; @@ -339,6 +386,35 @@ mod tests { PriceFilter, }; + #[test] + fn buffer_capacities_scale_with_order_slots() { + let caps = BufferCapacities::for_order_slots(10); + assert_eq!(caps.order_events(), 40); + assert_eq!(caps.forced_cancels(), 20); + assert_eq!(caps.elected_stops(), 10); + assert_eq!(caps.stop_events(), 10); + + // A portfolio without markets has no order slots and must not allocate. + let empty = BufferCapacities::for_order_slots(0); + assert_eq!(empty.order_events(), 0); + assert_eq!(empty.forced_cancels(), 0); + assert_eq!(empty.elected_stops(), 0); + assert_eq!(empty.stop_events(), 0); + + // The largest valid input: every market id with the largest order cap. + let max_slots = MarketId::COUNT * usize::from(u16::MAX); + assert_eq!( + BufferCapacities::for_order_slots(max_slots).order_events(), + max_slots * 4 + ); + } + + #[test] + #[should_panic] + fn buffer_capacities_reject_more_slots_than_any_config_allows() { + let _ = BufferCapacities::for_order_slots(MarketId::COUNT * usize::from(u16::MAX) + 1); + } + fn quoted_market(bid: i64, ask: i64) -> MarketState { let mut ms = MarketState::::default(); ms.update_state::<_, BaseCurrency>( diff --git a/src/portfolio/portfolio_exchange.rs b/src/portfolio/portfolio_exchange.rs index ec4cf02a..fddcdfdf 100644 --- a/src/portfolio/portfolio_exchange.rs +++ b/src/portfolio/portfolio_exchange.rs @@ -37,7 +37,10 @@ use crate::{ Position, }, contract_specification::ContractSpecification, - execution_rules::fill_flows, + execution_rules::{ + BufferCapacities, + fill_flows, + }, ledger::{ Ledger, LedgerEntryKind, @@ -343,36 +346,6 @@ where } } -/// Capacity of the per-call buffers, derived from the summed `max_num_open_orders` of all -/// markets. -/// -/// Shared by [`PortfolioExchange::new`], [`PortfolioExchange::add_market`] and -/// [`PortfolioExchange::clone`] so the bounds cannot drift apart. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -struct BufferCapacities { - order_events: usize, - stop_events: usize, - elected_stops_scratch: usize, - forced_cancel_scratch: usize, -} - -impl BufferCapacities { - fn for_total_orders(total_order_cap: usize) -> Self { - // Every market's bids and asks each hold up to `max_num_open_orders`, so one call - // can fill or force-cancel twice the total. Order events cover the fills plus as - // many forced cancels. - let scratch_cap = (total_order_cap * 2).max(16); - Self { - order_events: scratch_cap * 2, - // `PendingStops` holds up to `max_num_open_orders` stops per market, and each - // yields at most one event per call. - stop_events: total_order_cap, - elected_stops_scratch: scratch_cap, - forced_cancel_scratch: scratch_cap, - } - } -} - impl PortfolioExchange where I: Mon, @@ -414,17 +387,17 @@ where .expect(EXPECT_CAPACITY); } - let caps = BufferCapacities::for_total_orders(total_order_cap); + let caps = BufferCapacities::for_order_slots(total_order_cap); Self { balances, markets, ticker_index, next_order_id: OrderId::default(), - order_events: Vec::with_capacity(caps.order_events), - stop_events: Vec::with_capacity(caps.stop_events), - max_pending_stops: caps.stop_events, - elected_stops_scratch: Vec::with_capacity(caps.elected_stops_scratch), - forced_cancel_scratch: Vec::with_capacity(caps.forced_cancel_scratch), + order_events: Vec::with_capacity(caps.order_events()), + stop_events: Vec::with_capacity(caps.stop_events()), + max_pending_stops: total_order_cap, + elected_stops_scratch: Vec::with_capacity(caps.elected_stops()), + forced_cancel_scratch: Vec::with_capacity(caps.forced_cancels()), liquidated_during_fills: false, ledger: None, } @@ -437,12 +410,13 @@ where /// total and [`PortfolioExchange::clone`] restores them after `Vec::clone` dropped /// the spare capacity. fn reserve_preallocated_capacities(&mut self) { - let caps = BufferCapacities::for_total_orders(self.max_pending_stops); - assert_eq!(caps.stop_events, self.max_pending_stops); - reserve_to_capacity(&mut self.order_events, caps.order_events); - reserve_to_capacity(&mut self.stop_events, caps.stop_events); - reserve_to_capacity(&mut self.elected_stops_scratch, caps.elected_stops_scratch); - reserve_to_capacity(&mut self.forced_cancel_scratch, caps.forced_cancel_scratch); + // The summed pending-stop capacity is the summed order capacity of all markets. + let caps = BufferCapacities::for_order_slots(self.max_pending_stops); + assert_eq!(caps.stop_events(), self.max_pending_stops); + reserve_to_capacity(&mut self.order_events, caps.order_events()); + reserve_to_capacity(&mut self.stop_events, caps.stop_events()); + reserve_to_capacity(&mut self.elected_stops_scratch, caps.elected_stops()); + reserve_to_capacity(&mut self.forced_cancel_scratch, caps.forced_cancels()); } /// Enable the opt-in portfolio cashflow [`Ledger`] anchored at current wallet equity.