Skip to main content

nautilus_kraken/websocket/dispatch/
mod.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//! WebSocket execution dispatch for the Kraken Spot and Futures clients.
17//!
18//! Implements the two-tier execution dispatch contract from
19//! `docs/developer_guide/adapters.md#tracked-and-external-execution-updates`:
20//!
21//! 1. The execution client registers an [`OrderIdentity`] in [`WsDispatchState`]
22//!    when it submits an order.
23//! 2. WebSocket execution messages are routed through the per-product dispatch
24//!    functions in [`futures`] and [`spot`]. For tracked orders the dispatch
25//!    builds typed [`OrderEventAny`] events and emits them directly via
26//!    [`ExecutionEventEmitter::send_order_event`]. For untracked / external
27//!    orders the dispatch falls back to `OrderStatusReport` / `FillReport`
28//!    so the engine can reconcile.
29//!
30//! The dispatch state lives in an `Arc<WsDispatchState>` shared between the
31//! main client thread (which registers identities at submission time) and the
32//! spawned WebSocket consumer task. `DashMap`/`DashSet` provide lock-free
33//! concurrent access.
34
35pub mod futures;
36pub mod spot;
37pub mod spot_orders;
38
39use std::sync::{
40    Arc,
41    atomic::{AtomicBool, Ordering},
42};
43
44use dashmap::{DashMap, DashSet};
45use indexmap::IndexSet;
46use nautilus_core::{AtomicMap, UUID4, UnixNanos};
47use nautilus_live::ExecutionEventEmitter;
48use nautilus_model::{
49    enums::{OrderSide, OrderType},
50    events::{OrderAccepted, OrderEventAny, OrderFilled},
51    identifiers::{
52        AccountId, ClientOrderId, InstrumentId, StrategyId, TradeId, TraderId, VenueOrderId,
53    },
54    reports::FillReport,
55    types::{Currency, Quantity},
56};
57use parking_lot::Mutex;
58use rust_decimal::Decimal;
59
60const DEDUP_CAPACITY: usize = 10_000;
61
62/// A terminal open-orders removal whose fills have not all arrived yet.
63///
64/// The venue's cumulative filled quantity on an `is_cancel=true` order delta
65/// is parked here until the fills feed accounts it, so cancellation of the remainder
66/// cannot overtake its fills.
67#[derive(Debug, Clone)]
68pub struct PendingRemoval {
69    /// Cumulative filled quantity reported by the venue on the removal delta.
70    pub venue_filled: Quantity,
71    /// Venue reason carried by the removal delta.
72    pub reason: Option<String>,
73    /// Venue event time of the removal delta.
74    pub ts_event: UnixNanos,
75}
76
77/// Snapshot of the mutable fields seen on a tracked `OpenOrdersDelta`.
78///
79/// Used by the futures delta path to discriminate partial fills (filled
80/// increased), modify acknowledgements (qty / price / trigger_price changed),
81/// and no-op deltas (nothing changed) when a follow-up delta arrives.
82#[derive(Debug, Clone, Copy, PartialEq)]
83pub struct DeltaSnapshot {
84    pub qty: Quantity,
85    pub filled: Quantity,
86    pub limit_price: Option<Decimal>,
87    pub stop_price: Option<Decimal>,
88}
89
90impl DeltaSnapshot {
91    pub(crate) fn new(
92        qty: Quantity,
93        filled: Quantity,
94        limit_price: Option<Decimal>,
95        stop_price: Option<Decimal>,
96    ) -> Self {
97        Self {
98            qty,
99            filled,
100            limit_price,
101            stop_price,
102        }
103    }
104
105    pub(crate) fn non_fill_fields_match(&self, other: &Self) -> bool {
106        self.qty == other.qty
107            && self.limit_price == other.limit_price
108            && self.stop_price == other.stop_price
109    }
110}
111
112/// Identity metadata captured when an order is submitted through this client.
113///
114/// Stored in [`WsDispatchState::order_identities`] keyed by the full Nautilus
115/// [`ClientOrderId`]. The dispatch functions use the identity to build typed
116/// order events for tracked orders without needing access to the engine cache
117/// (which is `!Send` and unreachable from the spawned WebSocket task).
118#[derive(Debug, Clone)]
119pub struct OrderIdentity {
120    /// Strategy that owns the order.
121    pub strategy_id: StrategyId,
122    /// Instrument the order targets.
123    pub instrument_id: InstrumentId,
124    /// Order side captured at submission.
125    pub order_side: OrderSide,
126    /// Order type captured at submission.
127    pub order_type: OrderType,
128    /// Order quantity captured at submission. Used to detect terminal fills.
129    pub quantity: Quantity,
130}
131
132/// Per-client dispatch state shared between order submission and the
133/// WebSocket consumer task.
134///
135/// Tracks which orders were submitted through this client (so we can route
136/// venue events to typed [`OrderEventAny`] emissions for tracked orders, and
137/// fall back to reports for external orders), and provides cross-stream
138/// dedup for `OrderAccepted` and `OrderFilled` emissions.
139#[derive(Debug)]
140pub struct WsDispatchState {
141    /// Tracked orders keyed by full Nautilus [`ClientOrderId`].
142    pub order_identities: DashMap<ClientOrderId, OrderIdentity>,
143    /// Client order IDs for which an `OrderAccepted` event has been emitted.
144    pub emitted_accepted: DashSet<ClientOrderId>,
145    /// Client order IDs that have reached the filled terminal state.
146    pub filled_orders: DashSet<ClientOrderId>,
147    /// Symbol captured from execution frames for a venue order id.
148    ///
149    /// Kraken's spot v2 executions channel sends a `pending_new` frame with
150    /// full order details, then follow-up frames (`new`, `amended`,
151    /// `restated`, `status`) that omit fields which have not changed -
152    /// Kraken's docs show `symbol` omitted on the `new` delta. The dispatch
153    /// needs the symbol to resolve the instrument, so we cache it here from
154    /// any frame that carries it (first writer wins). Keyed by venue
155    /// `order_id` because delta frames often lack `cl_ord_id` as well.
156    ///
157    /// Known limitation: the live spot execution client currently subscribes
158    /// with `snap_orders=false` (see `execution/spot.rs`). Orders that were
159    /// already open at the venue before this process connected therefore do
160    /// not receive an in-session `pending_new`, and if their next delta
161    /// frame omits `symbol` it is dropped at symbol resolution. State for
162    /// such orders is recovered via REST reconciliation
163    /// (`request_order_status_reports`). Enabling `snap_orders=true` would
164    /// allow the executions snapshot to seed the cache for pre-existing
165    /// orders.
166    ///
167    /// Steady-state eviction happens on terminal exec types
168    /// (`Canceled`/`Filled`/`Expired`). Bounded by `DEDUP_CAPACITY` as a
169    /// safety net so missed terminal frames (reconnects, partial replays)
170    /// cannot leak entries indefinitely.
171    pub order_symbol_cache: DashMap<String, String>,
172    /// `ClientOrderId` captured from execution frames for a venue order id.
173    ///
174    /// Kraken's `pending_new` echoes our submitted `cl_ord_id`, but follow-up
175    /// delta frames (`new`, `amended`, `restated`, `status`) routinely omit
176    /// it. Without this mapping the dispatch cannot resolve the tracked
177    /// order from a delta and falls back to the untracked report path,
178    /// which loses the typed `OrderAccepted` event - the symptom behind
179    /// issue #4051.
180    ///
181    /// Populated whenever a frame resolves a `cl_ord_id` (first writer
182    /// wins, keyed by venue `order_id`). Consulted when `exec.cl_ord_id`
183    /// is `None`. Mirrors the `venue_client_map` used by the futures
184    /// dispatch path.
185    ///
186    /// Eviction policy matches `order_symbol_cache`: cleared on terminal
187    /// exec types and bounded by `DEDUP_CAPACITY` as a safety net.
188    pub order_client_id_cache: DashMap<String, ClientOrderId>,
189    /// Last snapshot of qty / filled / price / trigger_price seen on a
190    /// tracked `OpenOrdersDelta`.
191    ///
192    /// The futures delta path uses this map to discriminate partial-fill
193    /// notifications (the new delta carries `filled` greater than the
194    /// previously seen value), modify acknowledgements (a non-fill field
195    /// changed), and pure no-op deltas (nothing changed). It is updated only
196    /// by the delta path so that the fill path's own cumulative is not
197    /// double-counted.
198    pub delta_snapshots: DashMap<ClientOrderId, DeltaSnapshot>,
199    /// Cumulative filled quantity per tracked client order id, populated by
200    /// the fill side of dispatch.
201    ///
202    /// Compared against `OrderIdentity::quantity` to decide when to clean up
203    /// tracked state on a terminal fill.
204    pub order_filled_qty: DashMap<ClientOrderId, Quantity>,
205    /// Terminal cancellations waiting for their fills to be accounted,
206    /// populated by the futures delta side of dispatch and resolved by the
207    /// fill side.
208    pub pending_removals: DashMap<ClientOrderId, PendingRemoval>,
209    /// Trade IDs for which an `OrderFilled` event has been emitted.
210    ///
211    /// Bounded FIFO dedup: when capacity is reached, the oldest entry is
212    /// evicted on the next insert. A simple `clear()` at the threshold would
213    /// drop all recent trade IDs at once, opening a window where a reconnect
214    /// or replay immediately after the rollover could re-emit duplicate
215    /// `OrderFilled` events.
216    pub emitted_trades: Mutex<IndexSet<TradeId>>,
217    clearing: AtomicBool,
218}
219
220impl Default for WsDispatchState {
221    fn default() -> Self {
222        Self {
223            order_identities: DashMap::new(),
224            emitted_accepted: DashSet::default(),
225            filled_orders: DashSet::default(),
226            order_symbol_cache: DashMap::new(),
227            order_client_id_cache: DashMap::new(),
228            delta_snapshots: DashMap::new(),
229            order_filled_qty: DashMap::new(),
230            pending_removals: DashMap::new(),
231            emitted_trades: Mutex::new(IndexSet::with_capacity(DEDUP_CAPACITY)),
232            clearing: AtomicBool::new(false),
233        }
234    }
235}
236
237impl WsDispatchState {
238    /// Creates a new empty dispatch state.
239    #[must_use]
240    pub fn new() -> Self {
241        Self::default()
242    }
243
244    /// Registers an order identity. Called by the execution client at order
245    /// submission time, before any WebSocket events for the order can arrive.
246    pub fn register_identity(&self, client_order_id: ClientOrderId, identity: OrderIdentity) {
247        self.order_identities.insert(client_order_id, identity);
248    }
249
250    /// Returns a clone of the identity for the given client order id, if any.
251    #[must_use]
252    pub fn lookup_identity(&self, client_order_id: &ClientOrderId) -> Option<OrderIdentity> {
253        self.order_identities
254            .get(client_order_id)
255            .map(|r| r.clone())
256    }
257
258    /// Atomically marks an `OrderAccepted` event as emitted for this order.
259    ///
260    /// Returns `true` when the entry was newly inserted (caller should emit the
261    /// event), and `false` when an entry was already present (caller should
262    /// skip emission). Replaces the racier "contains-then-insert" pattern,
263    /// which allowed concurrent emitters to both observe `false` from
264    /// `contains` and then both insert + emit duplicate `OrderAccepted` events.
265    pub fn insert_accepted(&self, cid: ClientOrderId) -> bool {
266        self.evict_if_full(&self.emitted_accepted);
267        self.emitted_accepted.insert(cid)
268    }
269
270    /// Marks an order as having reached the filled terminal state.
271    pub fn insert_filled(&self, cid: ClientOrderId) {
272        self.evict_if_full(&self.filled_orders);
273        self.filled_orders.insert(cid);
274    }
275
276    /// Caches the symbol for a venue `order_id` if not already present.
277    ///
278    /// Atomic via [`DashMap::entry`] so concurrent callers cannot overwrite an
279    /// existing cached value - first writer wins, all later writers no-op.
280    /// The cheap `contains_key` fast path skips the key allocation when the
281    /// entry already exists; the `or_insert_with` covers the race that opens
282    /// between that check and the insert.
283    pub fn cache_order_symbol(&self, order_id: &str, symbol: &str) {
284        if self.order_symbol_cache.contains_key(order_id) {
285            return;
286        }
287        self.evict_map_if_full(&self.order_symbol_cache);
288        self.order_symbol_cache
289            .entry(order_id.to_string())
290            .or_insert_with(|| symbol.to_string());
291    }
292
293    /// Returns the symbol previously cached for a venue `order_id`, if any.
294    #[must_use]
295    pub fn lookup_order_symbol(&self, order_id: &str) -> Option<String> {
296        self.order_symbol_cache
297            .get(order_id)
298            .map(|r| r.value().clone())
299    }
300
301    /// Removes any cached symbol for a venue `order_id`. Called when the order
302    /// reaches a terminal state on the executions stream.
303    pub fn forget_order_symbol(&self, order_id: &str) {
304        self.order_symbol_cache.remove(order_id);
305    }
306
307    /// Caches the resolved `ClientOrderId` for a venue `order_id` if not
308    /// already present.
309    ///
310    /// Atomic via [`DashMap::entry`] so concurrent callers cannot overwrite an
311    /// existing cached value - first writer wins. The cheap `contains_key`
312    /// fast path skips the key allocation when the entry already exists.
313    pub fn cache_order_client_id(&self, order_id: &str, client_order_id: ClientOrderId) {
314        if self.order_client_id_cache.contains_key(order_id) {
315            return;
316        }
317        self.evict_map_if_full(&self.order_client_id_cache);
318        self.order_client_id_cache
319            .entry(order_id.to_string())
320            .or_insert(client_order_id);
321    }
322
323    /// Returns the `ClientOrderId` previously cached for a venue `order_id`,
324    /// if any.
325    #[must_use]
326    pub fn lookup_order_client_id(&self, order_id: &str) -> Option<ClientOrderId> {
327        self.order_client_id_cache.get(order_id).map(|r| *r)
328    }
329
330    /// Removes any cached `ClientOrderId` for a venue `order_id`. Called when
331    /// the order reaches a terminal state on the executions stream.
332    pub fn forget_order_client_id(&self, order_id: &str) {
333        self.order_client_id_cache.remove(order_id);
334    }
335
336    /// Atomically inserts a trade id into the dedup set.
337    ///
338    /// Returns `true` when the trade was already present (i.e. it is a
339    /// duplicate), `false` otherwise. When the dedup set is at capacity the
340    /// oldest entry is evicted to make room, preserving the `DEDUP_CAPACITY`
341    /// most recently seen trade IDs.
342    pub fn check_and_insert_trade(&self, trade_id: TradeId) -> bool {
343        let mut set = self.emitted_trades.lock();
344
345        if set.contains(&trade_id) {
346            return true;
347        }
348
349        if set.len() >= DEDUP_CAPACITY {
350            set.shift_remove_index(0);
351        }
352
353        set.insert(trade_id);
354        false
355    }
356
357    /// Removes all dispatch state for an order that has reached a terminal state.
358    pub fn cleanup_terminal(&self, client_order_id: &ClientOrderId) {
359        self.order_identities.remove(client_order_id);
360        self.emitted_accepted.remove(client_order_id);
361        self.order_filled_qty.remove(client_order_id);
362        self.delta_snapshots.remove(client_order_id);
363        self.pending_removals.remove(client_order_id);
364    }
365
366    /// Records cumulative filled quantity for a tracked order. Used by the
367    /// fill side of dispatch only.
368    pub fn record_filled_qty(&self, client_order_id: ClientOrderId, qty: Quantity) {
369        self.order_filled_qty.insert(client_order_id, qty);
370    }
371
372    /// Returns the previously recorded cumulative filled quantity, if any.
373    #[must_use]
374    pub fn previous_filled_qty(&self, client_order_id: &ClientOrderId) -> Option<Quantity> {
375        self.order_filled_qty.get(client_order_id).map(|r| *r)
376    }
377
378    /// Parks a terminal cancellation until the fills feed accounts its cumulative filled quantity.
379    pub fn insert_pending_removal(&self, client_order_id: ClientOrderId, removal: PendingRemoval) {
380        self.evict_map_if_full(&self.pending_removals);
381        self.pending_removals.insert(client_order_id, removal);
382    }
383
384    /// Returns a clone of the parked removal for the order, if any.
385    #[must_use]
386    pub fn pending_removal(&self, client_order_id: &ClientOrderId) -> Option<PendingRemoval> {
387        self.pending_removals
388            .get(client_order_id)
389            .map(|r| r.clone())
390    }
391
392    /// Removes the parked removal for the order, if any.
393    pub fn remove_pending_removal(&self, client_order_id: &ClientOrderId) {
394        self.pending_removals.remove(client_order_id);
395    }
396
397    /// Records the latest delta snapshot for a tracked order. Used by the
398    /// delta side of dispatch only.
399    pub fn record_delta_snapshot(&self, client_order_id: ClientOrderId, snapshot: DeltaSnapshot) {
400        self.delta_snapshots.insert(client_order_id, snapshot);
401    }
402
403    /// Returns the previously recorded delta snapshot, if any.
404    #[must_use]
405    pub fn previous_delta_snapshot(
406        &self,
407        client_order_id: &ClientOrderId,
408    ) -> Option<DeltaSnapshot> {
409        self.delta_snapshots.get(client_order_id).map(|r| *r)
410    }
411
412    /// Updates the tracked `quantity` for an order following a successful
413    /// modify acknowledgement, leaving all other identity fields untouched.
414    pub fn update_identity_quantity(&self, client_order_id: &ClientOrderId, quantity: Quantity) {
415        if let Some(mut entry) = self.order_identities.get_mut(client_order_id) {
416            entry.quantity = quantity;
417        }
418    }
419
420    fn evict_if_full(&self, set: &DashSet<ClientOrderId>) {
421        if set.len() >= DEDUP_CAPACITY
422            && self
423                .clearing
424                .compare_exchange(false, true, Ordering::AcqRel, Ordering::Relaxed)
425                .is_ok()
426        {
427            set.clear();
428            self.clearing.store(false, Ordering::Release);
429        }
430    }
431
432    fn evict_map_if_full<K, V>(&self, map: &DashMap<K, V>)
433    where
434        K: Eq + std::hash::Hash,
435    {
436        if map.len() >= DEDUP_CAPACITY
437            && self
438                .clearing
439                .compare_exchange(false, true, Ordering::AcqRel, Ordering::Relaxed)
440                .is_ok()
441        {
442            map.clear();
443            self.clearing.store(false, Ordering::Release);
444        }
445    }
446}
447
448/// Resolves a shortened client order id to its full Nautilus form.
449///
450/// An order sent with its client order id shortened by `truncate_cl_ord_id` is
451/// echoed in that form; the truncation map, populated when such an order is
452/// submitted, lets the WebSocket consumer recover the original id. Falls back
453/// to constructing a fresh `ClientOrderId` from the echoed string when no
454/// mapping exists (the order is then treated as external by downstream lookup).
455pub(crate) fn resolve_client_order_id(
456    truncated: &str,
457    truncated_id_map: &Arc<AtomicMap<String, ClientOrderId>>,
458) -> ClientOrderId {
459    truncated_id_map
460        .load()
461        .get(truncated)
462        .copied()
463        .unwrap_or_else(|| ClientOrderId::new(truncated))
464}
465
466/// Synthesizes and emits an `OrderAccepted` event when one has not yet been
467/// emitted for the given order.
468///
469/// Used before emitting non-Accepted events (Filled, Canceled, Expired,
470/// Updated) so that strategies always observe the canonical
471/// `Submitted -> Accepted -> ...` lifecycle even when the venue compresses
472/// the acceptance and follow-up event into a single message (fast fills).
473#[expect(clippy::too_many_arguments)]
474pub(crate) fn ensure_accepted_emitted(
475    client_order_id: ClientOrderId,
476    venue_order_id: VenueOrderId,
477    account_id: AccountId,
478    identity: &OrderIdentity,
479    state: &WsDispatchState,
480    emitter: &ExecutionEventEmitter,
481    ts_event: UnixNanos,
482    ts_init: UnixNanos,
483) {
484    if !state.insert_accepted(client_order_id) {
485        return;
486    }
487    let accepted = OrderAccepted::new(
488        emitter.trader_id(),
489        identity.strategy_id,
490        identity.instrument_id,
491        client_order_id,
492        venue_order_id,
493        account_id,
494        UUID4::new(),
495        ts_event,
496        ts_init,
497        false,
498    );
499    emitter.send_order_event(OrderEventAny::Accepted(accepted));
500}
501
502/// Builds an [`OrderFilled`] event from a [`FillReport`] and tracked
503/// [`OrderIdentity`].
504pub(crate) fn fill_report_to_order_filled(
505    report: &FillReport,
506    trader_id: TraderId,
507    identity: &OrderIdentity,
508    quote_currency: Currency,
509    client_order_id: ClientOrderId,
510) -> OrderFilled {
511    OrderFilled::new(
512        trader_id,
513        identity.strategy_id,
514        identity.instrument_id,
515        client_order_id,
516        report.venue_order_id,
517        report.account_id,
518        report.trade_id,
519        identity.order_side,
520        identity.order_type,
521        report.last_qty,
522        report.last_px,
523        quote_currency,
524        report.liquidity_side,
525        UUID4::new(),
526        report.ts_event,
527        report.ts_init,
528        false,
529        report.venue_position_id,
530        Some(report.commission),
531        None,
532    )
533}
534
535#[cfg(test)]
536mod tests {
537    use nautilus_model::{
538        enums::{OrderSide, OrderType},
539        identifiers::{ClientOrderId, InstrumentId, StrategyId, TradeId},
540    };
541    use rstest::rstest;
542
543    use super::*;
544
545    fn make_identity() -> OrderIdentity {
546        OrderIdentity {
547            strategy_id: StrategyId::new("EXEC_TESTER-001"),
548            instrument_id: InstrumentId::from("PF_XBTUSD.KRAKEN"),
549            order_side: OrderSide::Buy,
550            order_type: OrderType::Limit,
551            quantity: Quantity::from("0.0001"),
552        }
553    }
554
555    #[rstest]
556    fn test_register_and_lookup_identity() {
557        let state = WsDispatchState::new();
558        let cid = ClientOrderId::new("uuid-1");
559        state.register_identity(cid, make_identity());
560
561        let found = state.lookup_identity(&cid);
562        assert!(found.is_some());
563        let identity = found.unwrap();
564        assert_eq!(identity.strategy_id.as_str(), "EXEC_TESTER-001");
565        assert_eq!(identity.order_side, OrderSide::Buy);
566    }
567
568    #[rstest]
569    fn test_lookup_identity_missing_returns_none() {
570        let state = WsDispatchState::new();
571        let cid = ClientOrderId::new("not-tracked");
572        assert!(state.lookup_identity(&cid).is_none());
573    }
574
575    #[rstest]
576    fn test_insert_accepted_dedup() {
577        let state = WsDispatchState::new();
578        let cid = ClientOrderId::new("uuid-2");
579        assert!(!state.emitted_accepted.contains(&cid));
580        state.insert_accepted(cid);
581        assert!(state.emitted_accepted.contains(&cid));
582        // Second insert is a no-op.
583        state.insert_accepted(cid);
584        assert!(state.emitted_accepted.contains(&cid));
585    }
586
587    #[rstest]
588    fn test_insert_accepted_returns_true_on_first_insert_false_on_repeat() {
589        let state = WsDispatchState::new();
590        let cid = ClientOrderId::new("uuid-atomic");
591
592        assert!(
593            state.insert_accepted(cid),
594            "first insert must report newly inserted",
595        );
596        assert!(
597            !state.insert_accepted(cid),
598            "second insert must report already present (atomic dedup)",
599        );
600    }
601
602    #[rstest]
603    fn test_cache_order_symbol_first_write_wins() {
604        let state = WsDispatchState::new();
605        state.cache_order_symbol("v-order-1", "BTC/USD");
606        state.cache_order_symbol("v-order-1", "ETH/USD");
607
608        assert_eq!(
609            state.lookup_order_symbol("v-order-1").as_deref(),
610            Some("BTC/USD"),
611            "later writes must not overwrite the original cached symbol",
612        );
613    }
614
615    #[rstest]
616    fn test_cache_order_symbol_bounded_by_capacity() {
617        let state = WsDispatchState::new();
618        for i in 0..DEDUP_CAPACITY {
619            state.cache_order_symbol(format!("v-order-{i}").as_str(), "BTC/USD");
620        }
621        // At capacity; the next insert triggers a `clear()` before insertion.
622        state.cache_order_symbol("v-order-overflow", "BTC/USD");
623
624        assert!(
625            state.order_symbol_cache.len() <= DEDUP_CAPACITY,
626            "cache must stay within DEDUP_CAPACITY after overflow",
627        );
628        assert_eq!(
629            state.lookup_order_symbol("v-order-overflow").as_deref(),
630            Some("BTC/USD"),
631            "the overflow entry was inserted after eviction",
632        );
633    }
634
635    #[rstest]
636    fn test_check_and_insert_trade_detects_duplicates() {
637        let state = WsDispatchState::new();
638        let trade = TradeId::new("trade-1");
639        // First insert: not a duplicate.
640        assert!(!state.check_and_insert_trade(trade));
641        // Second insert: duplicate.
642        assert!(state.check_and_insert_trade(trade));
643    }
644
645    #[rstest]
646    fn test_check_and_insert_trade_fifo_eviction_preserves_recent_ids() {
647        // Verifies the dedup window slides rather than collapsing to zero at
648        // the capacity threshold. Overshooting by one entry must evict only
649        // the oldest (`trade-0`), leaving every other ID still deduped.
650        let state = WsDispatchState::new();
651        for i in 0..DEDUP_CAPACITY {
652            let trade = TradeId::new(format!("trade-{i}").as_str());
653            assert!(!state.check_and_insert_trade(trade));
654        }
655        // At capacity; the next insert evicts `trade-0`.
656        let overflow = TradeId::new(format!("trade-{DEDUP_CAPACITY}").as_str());
657        assert!(!state.check_and_insert_trade(overflow));
658
659        // Inspect the dedup set directly to confirm FIFO behavior without
660        // perturbing state via another `check_and_insert_trade` call.
661        let set = state.emitted_trades.lock();
662        assert_eq!(set.len(), DEDUP_CAPACITY);
663        assert!(
664            !set.contains(&TradeId::new("trade-0")),
665            "oldest entry should have been evicted",
666        );
667        assert!(
668            set.contains(&TradeId::new("trade-1")),
669            "second-oldest remains"
670        );
671        assert!(
672            set.contains(&TradeId::new(
673                format!("trade-{}", DEDUP_CAPACITY - 1).as_str(),
674            )),
675            "most-recent pre-overflow entry remains",
676        );
677        assert!(
678            set.contains(&overflow),
679            "the overflow entry was inserted after eviction",
680        );
681    }
682
683    #[rstest]
684    fn test_cleanup_terminal_removes_state() {
685        let state = WsDispatchState::new();
686        let cid = ClientOrderId::new("uuid-3");
687        state.register_identity(cid, make_identity());
688        state.insert_accepted(cid);
689        state.record_filled_qty(cid, Quantity::from("0.0001"));
690        state.insert_pending_removal(
691            cid,
692            PendingRemoval {
693                venue_filled: Quantity::from("0.0001"),
694                reason: Some("partial_fill".to_string()),
695                ts_event: UnixNanos::default(),
696            },
697        );
698
699        assert!(state.lookup_identity(&cid).is_some());
700        assert!(state.emitted_accepted.contains(&cid));
701        assert!(state.pending_removal(&cid).is_some());
702
703        state.cleanup_terminal(&cid);
704
705        assert!(state.lookup_identity(&cid).is_none());
706        assert!(!state.emitted_accepted.contains(&cid));
707        assert!(state.previous_filled_qty(&cid).is_none());
708        assert!(state.pending_removal(&cid).is_none());
709    }
710
711    #[rstest]
712    fn test_resolve_client_order_id_via_truncated_map() {
713        let map: Arc<AtomicMap<String, ClientOrderId>> = Arc::new(AtomicMap::new());
714        let full = ClientOrderId::new("full-uuid-12345");
715        map.insert("trunc-id".to_string(), full);
716
717        let resolved = resolve_client_order_id("trunc-id", &map);
718        assert_eq!(resolved, full);
719    }
720
721    #[rstest]
722    fn test_resolve_client_order_id_falls_back_to_input() {
723        let map: Arc<AtomicMap<String, ClientOrderId>> = Arc::new(AtomicMap::new());
724        let resolved = resolve_client_order_id("unknown", &map);
725        assert_eq!(resolved.as_str(), "unknown");
726    }
727}