Skip to main content

chronicle_core/
book.rs

1//! The book state machine (ARCHITECTURE.md section 7).
2//!
3//! Every mutating command runs validation, then preflight, then
4//! execution. Validation and preflight never mutate, so every rejection
5//! is atomic (INV-ORD-4). Execution cannot fail: all of its failure
6//! modes were excluded by the first two phases.
7//!
8//! Milestone 1 executed Limit orders (add and cancel), best price and
9//! L2 depth queries, and the structural invariant checker. Milestone 2
10//! executes the full command surface behind these same phases: `Ioc`,
11//! `Fok`, and `PostOnly` adds, amend, cancel-by-participant, and self-trade
12//! prevention in the match loop.
13
14use crate::arena::{Arena, NIL};
15use crate::bitmap::Bitmap;
16use crate::config::BookConfig;
17use crate::error::BookError;
18use crate::events::{CancelReason, EventBuffer, ExecutionEvent};
19use crate::level::Levels;
20use crate::lookup::Lookup;
21use crate::types::{OrderId, OrderType, ParticipantId, Side, StpPolicy};
22
23mod snapshot;
24
25/// One aggregated price level in an L2 depth snapshot.
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub struct DepthLevel {
28    /// Raw price in quote units.
29    pub price: u64,
30    /// Sum of remaining quantities resting at this price.
31    pub total_qty: u64,
32    /// Number of live orders at this price.
33    pub order_count: u32,
34}
35
36/// A single-instrument limit order book on one tick grid.
37pub struct Book {
38    /// The validated configuration this book was built with.
39    config: BookConfig,
40    /// One past the last tick on the grid, computed once at
41    /// construction from the validated config.
42    grid_end_tick: u64,
43    /// Order storage.
44    arena: Arena,
45    /// `OrderId` to (slot, generation) index.
46    lookup: Lookup,
47    /// Per-tick level aggregates and list ends.
48    levels: Levels,
49    /// Active bid levels.
50    bids: Bitmap,
51    /// Active ask levels.
52    asks: Bitmap,
53    /// Sequence number the next accepted command will take. Starts at
54    /// 1; rejected commands consume nothing.
55    next_seq: u64,
56}
57
58impl Book {
59    /// Build an empty book.
60    ///
61    /// # Examples
62    ///
63    /// ```
64    /// use chronicle_core::{Book, BookConfig, StpPolicy};
65    ///
66    /// let book = Book::new(BookConfig {
67    ///     max_orders: 16,
68    ///     grid_len: 640,
69    ///     tick_size: 1,
70    ///     grid_start_tick: 1,
71    ///     default_stp: StpPolicy::CancelIncoming,
72    /// })
73    /// .unwrap();
74    /// assert_eq!(book.live_order_count(), 0);
75    /// assert_eq!(book.best_bid(), None);
76    /// ```
77    ///
78    /// # Errors
79    ///
80    /// Returns [`BookError::InvalidConfig`] when the configuration
81    /// fails any rule in ARCHITECTURE.md section 3.2.
82    pub fn new(config: BookConfig) -> Result<Self, BookError> {
83        config.validate()?;
84        let grid_end_tick = config.grid_end_tick()?;
85        Ok(Self {
86            config,
87            grid_end_tick,
88            arena: Arena::new(config.max_orders),
89            lookup: Lookup::new(config.max_orders),
90            levels: Levels::new(config.grid_len),
91            bids: Bitmap::new(config.grid_len),
92            asks: Bitmap::new(config.grid_len),
93            next_seq: 1,
94        })
95    }
96
97    /// The configuration this book was built with.
98    #[must_use]
99    pub const fn config(&self) -> BookConfig {
100        self.config
101    }
102
103    /// Number of live orders.
104    #[must_use]
105    pub const fn live_order_count(&self) -> u32 {
106        self.arena.live_count()
107    }
108
109    /// Sequence number the next accepted command will take.
110    #[must_use]
111    pub const fn next_seq(&self) -> u64 {
112        self.next_seq
113    }
114
115    /// Best bid as `(price, aggregate qty)`, or `None` when no bid
116    /// rests.
117    #[must_use]
118    pub fn best_bid(&self) -> Option<(u64, u64)> {
119        self.bids
120            .highest()
121            .map(|idx| (self.price_of_idx(idx), self.levels.qty[idx as usize]))
122    }
123
124    /// Best ask as `(price, aggregate qty)`, or `None` when no ask
125    /// rests.
126    #[must_use]
127    pub fn best_ask(&self) -> Option<(u64, u64)> {
128        self.asks
129            .lowest()
130            .map(|idx| (self.price_of_idx(idx), self.levels.qty[idx as usize]))
131    }
132
133    /// Add an order. The order sweeps the opposite side in price-time
134    /// priority under its self-trade prevention policy (`stp`, falling
135    /// back to the book default when `None`), then the order type
136    /// decides the remainder: `Limit` rests it, `Ioc` expires it, `Fok` was
137    /// already proven fillable in preflight, and `PostOnly` rests in full
138    /// because preflight proved it does not cross.
139    ///
140    /// Returns the number of events written into `events`.
141    ///
142    /// # Examples
143    ///
144    /// ```
145    /// use chronicle_core::{
146    ///     Book, BookConfig, EventBuffer, ExecutionEvent, OrderId, OrderType, ParticipantId,
147    ///     Side, StpPolicy,
148    /// };
149    ///
150    /// let mut book = Book::new(BookConfig {
151    ///     max_orders: 16,
152    ///     grid_len: 640,
153    ///     tick_size: 1,
154    ///     grid_start_tick: 1,
155    ///     default_stp: StpPolicy::CancelIncoming,
156    /// })
157    /// .unwrap();
158    /// let mut storage = Vec::with_capacity(8);
159    /// let mut events = EventBuffer::new(&mut storage);
160    /// let written = book
161    ///     .add_order(
162    ///         OrderId(1),
163    ///         ParticipantId(1),
164    ///         Side::Bid,
165    ///         OrderType::Limit,
166    ///         100,
167    ///         10,
168    ///         None,
169    ///         &mut events,
170    ///     )
171    ///     .unwrap();
172    /// assert_eq!(written, 1);
173    /// assert!(matches!(storage[0], ExecutionEvent::Accepted { .. }));
174    /// assert_eq!(book.best_bid(), Some((100, 10)));
175    /// ```
176    ///
177    /// # Errors
178    ///
179    /// Returns a [`BookError`] before mutating anything when validation
180    /// or preflight fails: invalid or duplicate order id, zero
181    /// quantity, invalid price tick, capacity, a `PostOnly` price that
182    /// would cross, a `Fok` quantity the book cannot fill, or an event
183    /// buffer below the exact preflight bound.
184    #[allow(
185        clippy::too_many_arguments,
186        reason = "the signature is fixed verbatim by ARCHITECTURE.md section 7.1"
187    )]
188    pub fn add_order(
189        &mut self,
190        order_id: OrderId,
191        participant: ParticipantId,
192        side: Side,
193        order_type: OrderType,
194        price: u64,
195        qty: u64,
196        stp: Option<StpPolicy>,
197        events: &mut EventBuffer<'_>,
198    ) -> Result<usize, BookError> {
199        // Phase 1, validation. No mutation.
200        if order_id.0 == 0 {
201            return Err(BookError::InvalidOrderId { order_id });
202        }
203        if qty == 0 {
204            return Err(BookError::InvalidQuantity { qty });
205        }
206        let price_idx = self.price_to_idx(price)?;
207        if self.lookup.get(order_id.0).is_some() {
208            return Err(BookError::DuplicateOrderId { order_id });
209        }
210        let effective_stp = stp.unwrap_or(self.config.default_stp);
211        self.execute_add(
212            order_id,
213            participant,
214            side,
215            order_type,
216            price,
217            price_idx,
218            qty,
219            effective_stp,
220            events,
221        )
222    }
223
224    /// Cancel a live order by id.
225    ///
226    /// Returns the number of events written into `events` (one
227    /// `Cancelled` event on success).
228    ///
229    /// # Errors
230    ///
231    /// Returns [`BookError::OrderNotFound`] with no side effects when
232    /// the id is missing, filled, or already cancelled, and
233    /// [`BookError::EventBufferFull`] when the buffer has no free slot.
234    pub fn cancel_order(
235        &mut self,
236        order_id: OrderId,
237        events: &mut EventBuffer<'_>,
238    ) -> Result<usize, BookError> {
239        let (slot, generation) = self
240            .lookup
241            .get(order_id.0)
242            .ok_or(BookError::OrderNotFound { order_id })?;
243        if events.remaining() < 1 {
244            return Err(BookError::EventBufferFull {
245                needed: 1,
246                available: events.remaining(),
247            });
248        }
249        let seq = self.take_seq()?;
250        self.remove_live_order(slot, generation, CancelReason::Requested, seq, events);
251        Ok(1)
252    }
253
254    /// Cancel every live order belonging to one participant
255    /// (ARCHITECTURE.md section 7.8). Events are emitted in ascending
256    /// slot order, one `Cancelled` with reason
257    /// [`CancelReason::ByParticipant`] per order. A participant with no
258    /// live orders succeeds with zero events; the command still
259    /// consumes a sequence number, as every accepted command does.
260    ///
261    /// Returns the number of events written into `events`.
262    ///
263    /// # Errors
264    ///
265    /// Returns [`BookError::EventBufferFull`] before mutating anything
266    /// when the buffer holds fewer free slots than the participant has
267    /// live orders.
268    pub fn cancel_by_participant(
269        &mut self,
270        participant: ParticipantId,
271        events: &mut EventBuffer<'_>,
272    ) -> Result<usize, BookError> {
273        // Phase 1 and 2, preflight count (no mutation): the exact
274        // event bound is the participant's live order count.
275        let needed = self
276            .arena
277            .state
278            .iter()
279            .zip(self.arena.participant.iter())
280            .filter(|(state, owner)| {
281                **state == crate::arena::STATE_LIVE && **owner == participant.0
282            })
283            .count();
284        if events.remaining() < needed {
285            return Err(BookError::EventBufferFull {
286                needed,
287                available: events.remaining(),
288            });
289        }
290        // Phase 3, execution: ascending slot scan. Detaching the slot
291        // being visited cannot disturb the slots not yet visited, so
292        // the scan needs no scratch space.
293        let seq = self.take_seq()?;
294        let mut written = 0;
295        for slot in 0..self.config.max_orders {
296            let s = slot as usize;
297            if self.arena.state[s] == crate::arena::STATE_LIVE
298                && self.arena.participant[s] == participant.0
299            {
300                let generation = self.arena.generation[s];
301                self.remove_live_order(slot, generation, CancelReason::ByParticipant, seq, events);
302                written += 1;
303            }
304        }
305        debug_assert_eq!(written, needed, "preflight count and scan disagree");
306        Ok(written)
307    }
308
309    /// Amend a live order to a new price and a new remaining quantity
310    /// (ARCHITECTURE.md section 7.4). A smaller quantity at the same
311    /// price, or an identical price and quantity, preserves the order's
312    /// exact FIFO position; a larger quantity or any price change moves
313    /// it to the tail of the target level. An amend never triggers a
314    /// match. Every accepted amend emits one `Amended` event and
315    /// consumes one sequence number, including the identical no-op.
316    ///
317    /// Returns the number of events written into `events` (one on
318    /// success).
319    ///
320    /// # Errors
321    ///
322    /// Returns [`BookError::OrderNotFound`] when the id is not live,
323    /// [`BookError::InvalidPriceTick`] or [`BookError::InvalidQuantity`]
324    /// for an off-grid price or a zero quantity,
325    /// [`BookError::AmendWouldCross`] when the new price would leave
326    /// the book crossed, and [`BookError::EventBufferFull`] when the
327    /// buffer has no free slot. Every error is returned before any
328    /// mutation.
329    pub fn amend_order(
330        &mut self,
331        order_id: OrderId,
332        new_price: u64,
333        new_qty: u64,
334        events: &mut EventBuffer<'_>,
335    ) -> Result<usize, BookError> {
336        // Phase 1, validation. No mutation.
337        let (slot, _generation) = self
338            .lookup
339            .get(order_id.0)
340            .ok_or(BookError::OrderNotFound { order_id })?;
341        let new_idx = self.price_to_idx(new_price)?;
342        if new_qty == 0 {
343            return Err(BookError::InvalidQuantity { qty: new_qty });
344        }
345        let s = slot as usize;
346        let old_idx = self.arena.price_idx[s];
347        let old_qty = self.arena.qty[s];
348        let side = Side::from_u8(self.arena.side[s]);
349        // Phase 2, preflight. The crossing test comes first (an amend
350        // that would cross writes no events), then the one-event
351        // buffer bound, then the aggregate check on the target level.
352        if let Some(opposite_idx) = self.best_opposite_idx(side)
353            && crosses(side, new_idx, opposite_idx)
354        {
355            return Err(BookError::AmendWouldCross {
356                order_id,
357                new_price,
358                opposite_best: self.price_of_idx(opposite_idx),
359            });
360        }
361        if events.remaining() < 1 {
362            return Err(BookError::EventBufferFull {
363                needed: 1,
364                available: events.remaining(),
365            });
366        }
367        let target_base =
368            self.levels.qty[new_idx as usize] - if new_idx == old_idx { old_qty } else { 0 };
369        if target_base.checked_add(new_qty).is_none() {
370            return Err(BookError::ArithmeticOverflow {
371                what: "price level quantity",
372            });
373        }
374        // Phase 3, execution.
375        let seq = self.take_seq()?;
376        if new_idx == old_idx && new_qty == old_qty {
377            // Identical amend: a seq-consuming no-op (section 7.4).
378        } else if new_idx == old_idx && new_qty < old_qty {
379            // Reduce in place: position and priority are untouched.
380            let diff = old_qty - new_qty;
381            self.arena.qty[s] -= diff;
382            self.levels.qty[old_idx as usize] -= diff;
383        } else {
384            // Increase or reprice: the order loses its priority and
385            // rejoins at the tail of the target level.
386            self.unlink_from_level(slot);
387            self.arena.price_idx[s] = new_idx;
388            self.arena.qty[s] = new_qty;
389            self.link_at_tail(slot, side);
390        }
391        events.emit(ExecutionEvent::Amended {
392            seq,
393            order_id,
394            price: new_price,
395            qty: new_qty,
396        });
397        Ok(1)
398    }
399
400    /// Write up to `max_levels` aggregated levels for one side into
401    /// `out`, best price first, and return how many were written.
402    /// Mutates nothing and allocates nothing.
403    pub fn depth(&self, side: Side, max_levels: usize, out: &mut [DepthLevel]) -> usize {
404        let limit = max_levels.min(out.len());
405        let bitmap = match side {
406            Side::Bid => &self.bids,
407            Side::Ask => &self.asks,
408        };
409        let mut written = 0;
410        let mut cursor = match side {
411            Side::Bid => bitmap.highest(),
412            Side::Ask => bitmap.lowest(),
413        };
414        while written < limit {
415            let Some(idx) = cursor else { break };
416            out[written] = DepthLevel {
417                price: self.price_of_idx(idx),
418                total_qty: self.levels.qty[idx as usize],
419                order_count: self.levels.count[idx as usize],
420            };
421            written += 1;
422            cursor = match side {
423                Side::Bid => bitmap.highest_below(idx),
424                Side::Ask => bitmap.lowest_above(idx),
425            };
426        }
427        written
428    }
429
430    /// Full structural self-check (ARCHITECTURE.md section 11): crossed
431    /// book, per-level aggregates recomputed from the arena, bitmap
432    /// summaries recomputed from level counts, lookup reachability and
433    /// generation agreement for every live order, free list exactness,
434    /// and level list link symmetry. Intended for tests and debug
435    /// builds; it is O(capacity + grid).
436    ///
437    /// # Panics
438    ///
439    /// Panics on the first invariant violation found, with a message
440    /// naming the broken invariant and the offending slot or level.
441    /// That is the intended behaviour: this is a checker, and a failed
442    /// check must never be mistaken for a passing one.
443    pub fn debug_assert_invariants(&self) {
444        // Crossed book (INV-BOOK-1).
445        if let (Some((bid_price, _)), Some((ask_price, _))) = (self.best_bid(), self.best_ask()) {
446            assert!(
447                bid_price < ask_price,
448                "book is crossed: bid {bid_price} >= ask {ask_price}"
449            );
450        }
451        let seen_live = self.assert_levels();
452        // Bitmap summaries (INV-BITMAP-1) for both sides.
453        Self::assert_bitmap_summary(&self.bids);
454        Self::assert_bitmap_summary(&self.asks);
455        assert_eq!(self.bids.is_empty(), self.best_bid().is_none());
456        assert_eq!(self.asks.is_empty(), self.best_ask().is_none());
457        self.assert_free_list(&seen_live);
458    }
459
460    /// Per-level structure, aggregates, and lookup agreement. Returns
461    /// the set of slots seen live.
462    fn assert_levels(&self) -> Vec<bool> {
463        let mut seen_live = vec![false; self.config.max_orders as usize];
464        let mut total_live: u32 = 0;
465        assert_eq!(self.arena.capacity(), self.config.max_orders);
466        for idx in 0..self.config.grid_len {
467            let i = idx as usize;
468            let mut count: u32 = 0;
469            let mut sum: u64 = 0;
470            let mut prev = NIL;
471            let mut slot = self.levels.head[i];
472            let mut side_seen: Option<Side> = None;
473            while slot != NIL {
474                let s = slot as usize;
475                assert_eq!(
476                    self.arena.state[s],
477                    crate::arena::STATE_LIVE,
478                    "slot {slot} in a level list is not live"
479                );
480                assert_eq!(
481                    self.arena.price_idx[s], idx,
482                    "slot {slot} sits at the wrong level"
483                );
484                assert_eq!(
485                    self.arena.prev[s], prev,
486                    "slot {slot} prev link is asymmetric"
487                );
488                let side = Side::from_u8(self.arena.side[s]);
489                match side_seen {
490                    None => side_seen = Some(side),
491                    Some(existing) => {
492                        assert_eq!(existing, side, "level {idx} mixes sides");
493                    }
494                }
495                assert!(!seen_live[s], "slot {slot} appears in two level lists");
496                seen_live[s] = true;
497                assert_eq!(
498                    self.lookup.get(self.arena.order_id[s]),
499                    Some((slot, self.arena.generation[s])),
500                    "lookup disagrees with arena for slot {slot}"
501                );
502                assert!(self.arena.validate_handle(slot, self.arena.generation[s]));
503                count += 1;
504                sum = sum
505                    .checked_add(self.arena.qty[s])
506                    .expect("level quantity overflow in checker");
507                prev = slot;
508                slot = self.arena.next[s];
509            }
510            assert_eq!(
511                self.levels.count[i], count,
512                "level {idx} cached count is wrong"
513            );
514            assert_eq!(
515                self.levels.qty[i], sum,
516                "level {idx} cached quantity is wrong"
517            );
518            assert_eq!(
519                self.levels.tail[i], prev,
520                "level {idx} cached tail is wrong"
521            );
522            // Leaf bitmap bits agree with which side rests at the level.
523            assert_eq!(
524                self.bids.contains(idx),
525                side_seen == Some(Side::Bid),
526                "bid bitmap bit wrong at {idx}"
527            );
528            assert_eq!(
529                self.asks.contains(idx),
530                side_seen == Some(Side::Ask),
531                "ask bitmap bit wrong at {idx}"
532            );
533            total_live += count;
534        }
535        assert_eq!(
536            total_live,
537            self.arena.live_count(),
538            "arena live count disagrees with levels"
539        );
540        assert_eq!(
541            self.lookup.len(),
542            total_live as usize,
543            "lookup length disagrees with live count"
544        );
545        seen_live
546    }
547
548    /// Free list exactness (INV-ARENA-1): the chain from the head
549    /// visits exactly the free slots, each once, no cycles; every
550    /// other slot is live (seen by `assert_levels`) or retired.
551    fn assert_free_list(&self, seen_live: &[bool]) {
552        let mut free_walked: u32 = 0;
553        let mut slot = self.arena.free_head();
554        let mut free_seen = vec![false; self.config.max_orders as usize];
555        while slot != NIL {
556            let s = slot as usize;
557            assert_eq!(
558                self.arena.state[s],
559                crate::arena::STATE_FREE,
560                "slot {slot} on the free list is not free"
561            );
562            assert!(!free_seen[s], "free list cycle at slot {slot}");
563            free_seen[s] = true;
564            free_walked += 1;
565            slot = self.arena.next[s];
566        }
567        assert_eq!(
568            free_walked,
569            self.arena.free_count(),
570            "free list length disagrees with arena"
571        );
572        for s in 0..self.config.max_orders as usize {
573            if !seen_live[s] && !free_seen[s] {
574                assert_eq!(
575                    self.arena.state[s],
576                    crate::arena::STATE_RETIRED,
577                    "slot {s} is neither live, free, nor retired"
578                );
579            }
580        }
581    }
582
583    /// Recompute one bitmap hierarchy from its leaf words and compare
584    /// every summary bit (INV-BITMAP-1).
585    fn assert_bitmap_summary(bitmap: &Bitmap) {
586        for level in 1..bitmap.depth() {
587            for w in 0..bitmap.words_at(level) {
588                let word = bitmap.word(level, w);
589                for bit in 0..64usize {
590                    let child = w * 64 + bit;
591                    let expect = if child < bitmap.words_at(level - 1) {
592                        u64::from(bitmap.word(level - 1, child) != 0)
593                    } else {
594                        0
595                    };
596                    assert_eq!(
597                        (word >> bit) & 1,
598                        expect,
599                        "bitmap summary mismatch at level {level} word {w} bit {bit}"
600                    );
601                }
602            }
603        }
604    }
605
606    /// Convert a raw price to its dense tick index.
607    ///
608    /// # Errors
609    ///
610    /// Returns [`BookError::InvalidPriceTick`] on a zero price, an
611    /// unaligned price, or a tick outside the grid.
612    pub(crate) fn price_to_idx(&self, price: u64) -> Result<u32, BookError> {
613        let err = || BookError::InvalidPriceTick {
614            price,
615            tick_size: self.config.tick_size,
616            grid_start_tick: self.config.grid_start_tick,
617            grid_len: self.config.grid_len,
618        };
619        if price == 0 || !price.is_multiple_of(self.config.tick_size) {
620            return Err(err());
621        }
622        let tick = price / self.config.tick_size;
623        if tick < self.config.grid_start_tick || tick >= self.grid_end_tick {
624            return Err(err());
625        }
626        Ok(u32::try_from(tick - self.config.grid_start_tick).unwrap_or(0))
627    }
628
629    /// Convert a dense tick index back to its raw price.
630    pub(crate) fn price_of_idx(&self, idx: u32) -> u64 {
631        self.config
632            .price_of_tick(self.config.grid_start_tick + u64::from(idx))
633    }
634
635    /// Take the next sequence number for an accepted command.
636    ///
637    /// # Errors
638    ///
639    /// Returns [`BookError::ArithmeticOverflow`] at the unreachable
640    /// `u64` sequence ceiling, before any mutation.
641    fn take_seq(&mut self) -> Result<u64, BookError> {
642        let seq = self.next_seq;
643        self.next_seq = seq.checked_add(1).ok_or(BookError::ArithmeticOverflow {
644            what: "sequence number",
645        })?;
646        Ok(seq)
647    }
648
649    /// Preflight and execute an add of any order type. Validation
650    /// has already run; `stp` is the effective self-trade prevention
651    /// policy (the order's own, or the book default).
652    ///
653    /// Preflight is exact, per ARCHITECTURE.md section 7.2 as extended
654    /// by the Milestone 2 entry condition m3. A read-only simulation
655    /// of the sweep (`plan_sweep`) yields the exact event count, the
656    /// slots the sweep frees, and the taker remainder, so every
657    /// rejection is decided before the sequence number is taken:
658    ///
659    /// | Command | Exact event bound |
660    /// | --- | --- |
661    /// | `Limit` / `Ioc` / `Fok` add | sweep events (one `Trade` per trade, one `Filled` per maker filled, one `Cancelled` per resting order STP cancels) + 1 terminal event |
662    /// | `PostOnly` add | 1 (`Accepted`); the sweep never runs |
663    /// | `cancel_order` | 1 |
664    /// | `amend_order` | 1 |
665    /// | `cancel_by_participant` | the participant's live order count |
666    ///
667    /// Semantic preflight rejections (`PostOnly` crossing, `Fok`
668    /// shortfall) are decided before the event-buffer check, because
669    /// those commands would write no events at all; then the buffer
670    /// bound, then capacity and aggregate-overflow for a remainder
671    /// that would rest.
672    #[allow(
673        clippy::too_many_arguments,
674        reason = "mirrors the public add_order signature fixed by ARCHITECTURE.md section 7.1"
675    )]
676    fn execute_add(
677        &mut self,
678        order_id: OrderId,
679        participant: ParticipantId,
680        side: Side,
681        order_type: OrderType,
682        price: u64,
683        price_idx: u32,
684        qty: u64,
685        stp: StpPolicy,
686        events: &mut EventBuffer<'_>,
687    ) -> Result<usize, BookError> {
688        if order_type == OrderType::PostOnly {
689            return self.execute_post_only(
690                order_id,
691                participant,
692                side,
693                price,
694                price_idx,
695                qty,
696                events,
697            );
698        }
699        // ---- Preflight (no mutation) ----
700        let plan = self.plan_sweep(side, price_idx, qty, participant, stp);
701        if order_type == OrderType::Fok && plan.remaining > 0 {
702            return Err(BookError::FokInsufficientLiquidity {
703                requested: qty,
704                available: qty - plan.remaining,
705            });
706        }
707        let needed = plan.events + 1;
708        if events.remaining() < needed {
709            return Err(BookError::EventBufferFull {
710                needed,
711                available: events.remaining(),
712            });
713        }
714        let will_rest = order_type == OrderType::Limit && plan.remaining > 0 && !plan.stp_stopped;
715        if will_rest {
716            // A slot must exist once the sweep has freed the slots of
717            // the makers it filled or STP-cancelled.
718            if self.arena.free_count() as usize + plan.freed_slots == 0 {
719                return Err(BookError::CapacityFull {
720                    max_orders: self.config.max_orders,
721                });
722            }
723            // The resting aggregate must stay inside u64 (INV-MATH-1).
724            if self.levels.qty[price_idx as usize]
725                .checked_add(plan.remaining)
726                .is_none()
727            {
728                return Err(BookError::ArithmeticOverflow {
729                    what: "price level quantity",
730                });
731            }
732        }
733
734        // ---- Execution (cannot fail; the plan proved every step) ----
735        let seq = self.take_seq()?;
736        let written_before = events.written().len();
737        let (remaining, stp_stopped) = self.execute_sweep(
738            order_id,
739            participant,
740            side,
741            price_idx,
742            qty,
743            stp,
744            seq,
745            events,
746        );
747        debug_assert_eq!(
748            remaining, plan.remaining,
749            "execution diverged from the preflight plan"
750        );
751        debug_assert_eq!(stp_stopped, plan.stp_stopped);
752        if remaining == 0 {
753            events.emit(ExecutionEvent::Filled { seq, order_id });
754        } else if stp_stopped {
755            events.emit(ExecutionEvent::SelfTradePrevented { seq, order_id });
756        } else {
757            match order_type {
758                OrderType::Limit => {
759                    self.rest_order(order_id, participant, side, price_idx, remaining);
760                    events.emit(ExecutionEvent::Accepted { seq, order_id });
761                }
762                OrderType::Ioc => {
763                    events.emit(ExecutionEvent::Expired {
764                        seq,
765                        order_id,
766                        remaining_qty: remaining,
767                    });
768                }
769                OrderType::Fok | OrderType::PostOnly => {
770                    unreachable!("Fok remainders rejected in preflight; PostOnly never sweeps")
771                }
772            }
773        }
774        Ok(events.written().len() - written_before)
775    }
776
777    /// Run the sweep the preflight plan proved out, emitting sweep
778    /// events in order (section 7.6). Returns the taker remainder and
779    /// whether STP stopped the sweep at an own resting order.
780    #[allow(
781        clippy::too_many_arguments,
782        reason = "mirrors the public add_order signature fixed by ARCHITECTURE.md section 7.1"
783    )]
784    fn execute_sweep(
785        &mut self,
786        order_id: OrderId,
787        participant: ParticipantId,
788        side: Side,
789        price_idx: u32,
790        qty: u64,
791        stp: StpPolicy,
792        seq: u64,
793        events: &mut EventBuffer<'_>,
794    ) -> (u64, bool) {
795        let mut remaining = qty;
796        let mut stp_stopped = false;
797        while remaining > 0 {
798            let Some(maker_idx) = self.best_opposite_idx(side) else {
799                break;
800            };
801            if !crosses(side, price_idx, maker_idx) {
802                break;
803            }
804            let maker_slot = self.levels.head[maker_idx as usize];
805            debug_assert!(maker_slot != NIL, "active level has no head");
806            let ms = maker_slot as usize;
807            if self.arena.participant[ms] == participant.0 {
808                match stp {
809                    StpPolicy::CancelIncoming => {
810                        stp_stopped = true;
811                        break;
812                    }
813                    StpPolicy::CancelResting => {
814                        let generation = self.arena.generation[ms];
815                        self.remove_live_order(
816                            maker_slot,
817                            generation,
818                            CancelReason::SelfTradePrevention,
819                            seq,
820                            events,
821                        );
822                        continue;
823                    }
824                    StpPolicy::CancelBoth => {
825                        let generation = self.arena.generation[ms];
826                        self.remove_live_order(
827                            maker_slot,
828                            generation,
829                            CancelReason::SelfTradePrevention,
830                            seq,
831                            events,
832                        );
833                        stp_stopped = true;
834                        break;
835                    }
836                }
837            }
838            let maker_id = OrderId(self.arena.order_id[ms]);
839            let trade_qty = remaining.min(self.arena.qty[ms]);
840            let trade_price = self.price_of_idx(maker_idx);
841            self.arena.qty[ms] -= trade_qty;
842            self.levels.qty[maker_idx as usize] -= trade_qty;
843            remaining -= trade_qty;
844            events.emit(ExecutionEvent::Trade {
845                seq,
846                maker_order_id: maker_id,
847                taker_order_id: order_id,
848                price: trade_price,
849                qty: trade_qty,
850            });
851            if self.arena.qty[ms] == 0 {
852                self.detach(maker_slot);
853                events.emit(ExecutionEvent::Filled {
854                    seq,
855                    order_id: maker_id,
856                });
857            }
858        }
859        (remaining, stp_stopped)
860    }
861
862    /// Preflight and execute a `PostOnly` add: the sweep never runs, so
863    /// the whole preflight is the crossing test, the one-event buffer
864    /// bound, capacity, and the aggregate check.
865    #[allow(
866        clippy::too_many_arguments,
867        reason = "mirrors the public add_order signature fixed by ARCHITECTURE.md section 7.1"
868    )]
869    fn execute_post_only(
870        &mut self,
871        order_id: OrderId,
872        participant: ParticipantId,
873        side: Side,
874        price: u64,
875        price_idx: u32,
876        qty: u64,
877        events: &mut EventBuffer<'_>,
878    ) -> Result<usize, BookError> {
879        if let Some(opposite_idx) = self.best_opposite_idx(side)
880            && crosses(side, price_idx, opposite_idx)
881        {
882            return Err(BookError::PostOnlyWouldCross {
883                price,
884                opposite_best: self.price_of_idx(opposite_idx),
885            });
886        }
887        if events.remaining() < 1 {
888            return Err(BookError::EventBufferFull {
889                needed: 1,
890                available: events.remaining(),
891            });
892        }
893        if self.arena.free_count() == 0 {
894            return Err(BookError::CapacityFull {
895                max_orders: self.config.max_orders,
896            });
897        }
898        if self.levels.qty[price_idx as usize]
899            .checked_add(qty)
900            .is_none()
901        {
902            return Err(BookError::ArithmeticOverflow {
903                what: "price level quantity",
904            });
905        }
906        let seq = self.take_seq()?;
907        self.rest_order(order_id, participant, side, price_idx, qty);
908        events.emit(ExecutionEvent::Accepted { seq, order_id });
909        Ok(1)
910    }
911
912    /// Read-only simulation of the sweep an incoming order would
913    /// take, under its STP policy. This is the preflight plan: it
914    /// must agree with execution step for step, and the debug
915    /// assertions in `execute_add` check that it does.
916    fn plan_sweep(
917        &self,
918        side: Side,
919        price_idx: u32,
920        qty: u64,
921        participant: ParticipantId,
922        stp: StpPolicy,
923    ) -> SweepPlan {
924        let mut plan = SweepPlan {
925            events: 0,
926            freed_slots: 0,
927            remaining: qty,
928            stp_stopped: false,
929        };
930        let mut cursor = self.best_opposite_idx(side);
931        'levels: while plan.remaining > 0 {
932            let Some(idx) = cursor else { break };
933            if !crosses(side, price_idx, idx) {
934                break;
935            }
936            let mut slot = self.levels.head[idx as usize];
937            while slot != NIL {
938                let s = slot as usize;
939                if self.arena.participant[s] == participant.0 {
940                    match stp {
941                        StpPolicy::CancelIncoming => {
942                            plan.stp_stopped = true;
943                            break 'levels;
944                        }
945                        StpPolicy::CancelResting => {
946                            plan.events += 1;
947                            plan.freed_slots += 1;
948                        }
949                        StpPolicy::CancelBoth => {
950                            plan.events += 1;
951                            plan.freed_slots += 1;
952                            plan.stp_stopped = true;
953                            break 'levels;
954                        }
955                    }
956                } else {
957                    plan.events += 1; // Trade
958                    let maker_qty = self.arena.qty[s];
959                    if maker_qty <= plan.remaining {
960                        plan.remaining -= maker_qty;
961                        plan.events += 1; // Filled (maker)
962                        plan.freed_slots += 1;
963                    } else {
964                        plan.remaining = 0;
965                    }
966                }
967                if plan.remaining == 0 {
968                    break;
969                }
970                slot = self.arena.next[s];
971            }
972            cursor = self.next_opposite_idx(side, idx);
973        }
974        plan
975    }
976    /// Best level index on the side opposite to `side`.
977    fn best_opposite_idx(&self, side: Side) -> Option<u32> {
978        match side {
979            Side::Bid => self.asks.lowest(),
980            Side::Ask => self.bids.highest(),
981        }
982    }
983
984    /// Next level index on the opposite side beyond `idx`, moving away
985    /// from the best price.
986    fn next_opposite_idx(&self, side: Side, idx: u32) -> Option<u32> {
987        match side {
988            Side::Bid => self.asks.lowest_above(idx),
989            Side::Ask => self.bids.highest_below(idx),
990        }
991    }
992
993    /// Insert a resting remainder at the tail of its level, updating
994    /// arena, lookup, level aggregates, and the side bitmap.
995    fn rest_order(
996        &mut self,
997        order_id: OrderId,
998        participant: ParticipantId,
999        side: Side,
1000        price_idx: u32,
1001        qty: u64,
1002    ) {
1003        let (slot, generation) = self.arena.alloc().expect("preflight proved a free slot");
1004        let s = slot as usize;
1005        self.arena.order_id[s] = order_id.0;
1006        self.arena.participant[s] = participant.0;
1007        self.arena.price_idx[s] = price_idx;
1008        self.arena.qty[s] = qty;
1009        self.arena.side[s] = side.as_u8();
1010        self.lookup
1011            .insert(order_id.0, slot, generation)
1012            .expect("preflight proved lookup capacity");
1013        self.link_at_tail(slot, side);
1014    }
1015
1016    /// Link a slot whose arena columns are already set at the tail of
1017    /// its price level, updating level aggregates and the side bitmap.
1018    /// Shared by `rest_order` (fresh allocations) and `amend_order`
1019    /// (an order that lost its priority rejoins at the tail).
1020    fn link_at_tail(&mut self, slot: u32, side: Side) {
1021        let s = slot as usize;
1022        let idx = self.arena.price_idx[s];
1023        let i = idx as usize;
1024        let tail = self.levels.tail[i];
1025        self.arena.prev[s] = tail;
1026        self.arena.next[s] = NIL;
1027        if tail == NIL {
1028            self.levels.head[i] = slot;
1029            match side {
1030                Side::Bid => self.bids.set(idx),
1031                Side::Ask => self.asks.set(idx),
1032            }
1033        } else {
1034            self.arena.next[tail as usize] = slot;
1035        }
1036        self.levels.tail[i] = slot;
1037        self.levels.qty[i] += self.arena.qty[s];
1038        self.levels.count[i] += 1;
1039    }
1040
1041    /// Unlink a live order from its level list and aggregates without
1042    /// releasing its slot or its lookup entry. The mirror of
1043    /// `link_at_tail`; `detach` is this plus deregistration and
1044    /// release. Used by amend, where the order keeps its identity and
1045    /// its slot and only its position changes.
1046    fn unlink_from_level(&mut self, slot: u32) {
1047        let s = slot as usize;
1048        let idx = self.arena.price_idx[s];
1049        let i = idx as usize;
1050        let side = Side::from_u8(self.arena.side[s]);
1051        let prev = self.arena.prev[s];
1052        let next = self.arena.next[s];
1053        if prev == NIL {
1054            self.levels.head[i] = next;
1055        } else {
1056            self.arena.next[prev as usize] = next;
1057        }
1058        if next == NIL {
1059            self.levels.tail[i] = prev;
1060        } else {
1061            self.arena.prev[next as usize] = prev;
1062        }
1063        self.levels.qty[i] -= self.arena.qty[s];
1064        self.levels.count[i] -= 1;
1065        if self.levels.count[i] == 0 {
1066            match side {
1067                Side::Bid => self.bids.clear(idx),
1068                Side::Ask => self.asks.clear(idx),
1069            }
1070        }
1071        self.arena.prev[s] = NIL;
1072        self.arena.next[s] = NIL;
1073    }
1074
1075    /// Detach a live order from its level list, level aggregates, the
1076    /// side bitmap, and the lookup, and release its slot. Emits no
1077    /// event; callers emit the lifecycle event that fits their path.
1078    fn detach(&mut self, slot: u32) {
1079        let s = slot as usize;
1080        let idx = self.arena.price_idx[s];
1081        let i = idx as usize;
1082        let side = Side::from_u8(self.arena.side[s]);
1083        let order_id = self.arena.order_id[s];
1084        let prev = self.arena.prev[s];
1085        let next = self.arena.next[s];
1086        if prev == NIL {
1087            self.levels.head[i] = next;
1088        } else {
1089            self.arena.next[prev as usize] = next;
1090        }
1091        if next == NIL {
1092            self.levels.tail[i] = prev;
1093        } else {
1094            self.arena.prev[next as usize] = prev;
1095        }
1096        self.levels.qty[i] -= self.arena.qty[s];
1097        self.levels.count[i] -= 1;
1098        if self.levels.count[i] == 0 {
1099            match side {
1100                Side::Bid => self.bids.clear(idx),
1101                Side::Ask => self.asks.clear(idx),
1102            }
1103        }
1104        let removed = self.lookup.remove(order_id);
1105        debug_assert_eq!(
1106            removed.map(|(sl, _)| sl),
1107            Some(slot),
1108            "lookup and arena disagree"
1109        );
1110        self.arena.release(slot);
1111    }
1112
1113    /// Unlink, deregister, and release one live order, emitting its
1114    /// `Cancelled` event. Shared by cancel and (from Milestone 2)
1115    /// mass cancel and self-trade prevention.
1116    fn remove_live_order(
1117        &mut self,
1118        slot: u32,
1119        generation: u32,
1120        reason: CancelReason,
1121        seq: u64,
1122        events: &mut EventBuffer<'_>,
1123    ) {
1124        debug_assert!(self.arena.validate_handle(slot, generation));
1125        let order_id = OrderId(self.arena.order_id[slot as usize]);
1126        self.detach(slot);
1127        events.emit(ExecutionEvent::Cancelled {
1128            seq,
1129            order_id,
1130            reason,
1131        });
1132    }
1133}
1134
1135/// The preflight plan for one sweep (see `Book::plan_sweep`): the
1136/// exact event count before the terminal event, the number of arena
1137/// slots the sweep frees (makers filled plus resting orders STP
1138/// cancels), the taker remainder the sweep leaves, and whether STP
1139/// stopped the sweep at an own order.
1140struct SweepPlan {
1141    /// Sweep events only; the caller adds one terminal event.
1142    events: usize,
1143    /// Slots freed by the sweep.
1144    freed_slots: usize,
1145    /// Taker quantity left when the sweep stops.
1146    remaining: u64,
1147    /// True when STP stopped the sweep at an own resting order.
1148    stp_stopped: bool,
1149}
1150
1151/// Crossing test in dense tick index space: an incoming bid crosses an
1152/// ask level at or below its own index; an incoming ask crosses a bid
1153/// level at or above its own index.
1154const fn crosses(side: Side, taker_idx: u32, maker_idx: u32) -> bool {
1155    match side {
1156        Side::Bid => maker_idx <= taker_idx,
1157        Side::Ask => maker_idx >= taker_idx,
1158    }
1159}
1160
1161#[cfg(test)]
1162mod tests {
1163    use super::*;
1164
1165    fn test_config() -> BookConfig {
1166        BookConfig {
1167            max_orders: 64,
1168            grid_len: 4096,
1169            tick_size: 1,
1170            grid_start_tick: 1,
1171            default_stp: crate::types::StpPolicy::CancelIncoming,
1172        }
1173    }
1174
1175    fn book() -> Book {
1176        Book::new(test_config()).expect("valid config")
1177    }
1178
1179    fn buffer() -> Vec<ExecutionEvent> {
1180        Vec::with_capacity(1024)
1181    }
1182
1183    /// Run one Limit add against a fresh buffer and return its events.
1184    fn add(
1185        b: &mut Book,
1186        id: u64,
1187        participant: u32,
1188        side: Side,
1189        price: u64,
1190        qty: u64,
1191    ) -> Vec<ExecutionEvent> {
1192        add_typed(b, id, participant, side, OrderType::Limit, price, qty, None)
1193    }
1194
1195    /// Run one add of any type against a fresh buffer, with an explicit
1196    /// STP policy (`None` exercises the book default), and return its
1197    /// events.
1198    #[allow(
1199        clippy::too_many_arguments,
1200        reason = "test helper mirrors the public add_order parameter list"
1201    )]
1202    fn add_typed(
1203        b: &mut Book,
1204        id: u64,
1205        participant: u32,
1206        side: Side,
1207        order_type: OrderType,
1208        price: u64,
1209        qty: u64,
1210        stp: Option<StpPolicy>,
1211    ) -> Vec<ExecutionEvent> {
1212        let mut storage = Vec::with_capacity(64);
1213        {
1214            let mut events = EventBuffer::new(&mut storage);
1215            b.add_order(
1216                OrderId(id),
1217                ParticipantId(participant),
1218                side,
1219                order_type,
1220                price,
1221                qty,
1222                stp,
1223                &mut events,
1224            )
1225            .expect("add");
1226        }
1227        storage
1228    }
1229
1230    /// Run one amend against a fresh buffer and return its events.
1231    fn amend(b: &mut Book, id: u64, new_price: u64, new_qty: u64) -> Vec<ExecutionEvent> {
1232        let mut storage = Vec::with_capacity(4);
1233        {
1234            let mut events = EventBuffer::new(&mut storage);
1235            b.amend_order(OrderId(id), new_price, new_qty, &mut events)
1236                .expect("amend");
1237        }
1238        storage
1239    }
1240
1241    /// Full observable state, for atomicity assertions: sequence,
1242    /// liveness, best prices, and complete depth on both sides.
1243    type StateSnapshot = (
1244        u64,
1245        u32,
1246        Option<(u64, u64)>,
1247        Option<(u64, u64)>,
1248        Vec<(u64, u64, u32)>,
1249        Vec<(u64, u64, u32)>,
1250    );
1251
1252    fn snapshot(b: &Book) -> StateSnapshot {
1253        fn depth_of(b: &Book, side: Side) -> Vec<(u64, u64, u32)> {
1254            let mut out = [DepthLevel {
1255                price: 0,
1256                total_qty: 0,
1257                order_count: 0,
1258            }; 64];
1259            let n = b.depth(side, 64, &mut out);
1260            out[..n]
1261                .iter()
1262                .map(|d| (d.price, d.total_qty, d.order_count))
1263                .collect()
1264        }
1265        (
1266            b.next_seq(),
1267            b.live_order_count(),
1268            b.best_bid(),
1269            b.best_ask(),
1270            depth_of(b, Side::Bid),
1271            depth_of(b, Side::Ask),
1272        )
1273    }
1274
1275    #[test]
1276    fn guard_zero_order_id() {
1277        let mut b = book();
1278        let mut storage = buffer();
1279        let mut events = EventBuffer::new(&mut storage);
1280        let err = b
1281            .add_order(
1282                OrderId(0),
1283                ParticipantId(1),
1284                Side::Bid,
1285                OrderType::Limit,
1286                100,
1287                5,
1288                None,
1289                &mut events,
1290            )
1291            .expect_err("zero id must be rejected");
1292        assert_eq!(
1293            err,
1294            BookError::InvalidOrderId {
1295                order_id: OrderId(0)
1296            }
1297        );
1298        assert_eq!(b.live_order_count(), 0);
1299        assert_eq!(b.next_seq(), 1);
1300    }
1301
1302    #[test]
1303    fn guard_zero_qty() {
1304        let mut b = book();
1305        let mut storage = buffer();
1306        let mut events = EventBuffer::new(&mut storage);
1307        let err = b
1308            .add_order(
1309                OrderId(1),
1310                ParticipantId(1),
1311                Side::Bid,
1312                OrderType::Limit,
1313                100,
1314                0,
1315                None,
1316                &mut events,
1317            )
1318            .expect_err("zero qty must be rejected");
1319        assert_eq!(err, BookError::InvalidQuantity { qty: 0 });
1320        assert_eq!(b.live_order_count(), 0);
1321    }
1322
1323    #[test]
1324    fn guard_duplicate_order_id() {
1325        let mut b = book();
1326        let mut storage = buffer();
1327        let mut events = EventBuffer::new(&mut storage);
1328        b.add_order(
1329            OrderId(7),
1330            ParticipantId(1),
1331            Side::Bid,
1332            OrderType::Limit,
1333            100,
1334            5,
1335            None,
1336            &mut events,
1337        )
1338        .expect("first add");
1339        let err = b
1340            .add_order(
1341                OrderId(7),
1342                ParticipantId(2),
1343                Side::Ask,
1344                OrderType::Limit,
1345                101,
1346                5,
1347                None,
1348                &mut events,
1349            )
1350            .expect_err("duplicate id must be rejected");
1351        assert_eq!(
1352            err,
1353            BookError::DuplicateOrderId {
1354                order_id: OrderId(7)
1355            }
1356        );
1357        assert_eq!(b.live_order_count(), 1);
1358    }
1359
1360    #[test]
1361    fn guard_invalid_price_tick_each_rule() {
1362        let mut cfg = test_config();
1363        cfg.tick_size = 5;
1364        cfg.grid_start_tick = 100;
1365        cfg.grid_len = 640;
1366        let mut b = Book::new(cfg).expect("valid config");
1367        let mut storage = buffer();
1368        let mut events = EventBuffer::new(&mut storage);
1369        let cases = [
1370            0u64,  // zero price
1371            502,   // unaligned: 502 is not a multiple of 5
1372            495,   // aligned tick 99, below grid start 100
1373            3_700, // aligned tick 740, grid end is 100 + 640 = 740, excluded
1374        ];
1375        for price in cases {
1376            let err = b
1377                .add_order(
1378                    OrderId(1),
1379                    ParticipantId(1),
1380                    Side::Bid,
1381                    OrderType::Limit,
1382                    price,
1383                    5,
1384                    None,
1385                    &mut events,
1386                )
1387                .expect_err("each tick rule must reject");
1388            assert!(
1389                matches!(err, BookError::InvalidPriceTick { .. }),
1390                "price {price} gave {err:?}"
1391            );
1392        }
1393        assert_eq!(b.live_order_count(), 0);
1394        assert_eq!(b.next_seq(), 1);
1395    }
1396
1397    #[test]
1398    fn limit_orders_rest_and_report_best_prices() {
1399        let mut b = book();
1400        let mut storage = buffer();
1401        let mut events = EventBuffer::new(&mut storage);
1402        b.add_order(
1403            OrderId(1),
1404            ParticipantId(1),
1405            Side::Bid,
1406            OrderType::Limit,
1407            100,
1408            5,
1409            None,
1410            &mut events,
1411        )
1412        .expect("bid 1");
1413        b.add_order(
1414            OrderId(2),
1415            ParticipantId(1),
1416            Side::Bid,
1417            OrderType::Limit,
1418            101,
1419            3,
1420            None,
1421            &mut events,
1422        )
1423        .expect("bid 2");
1424        b.add_order(
1425            OrderId(3),
1426            ParticipantId(2),
1427            Side::Ask,
1428            OrderType::Limit,
1429            105,
1430            4,
1431            None,
1432            &mut events,
1433        )
1434        .expect("ask");
1435        assert_eq!(b.best_bid(), Some((101, 3)));
1436        assert_eq!(b.best_ask(), Some((105, 4)));
1437        let mut out = [DepthLevel {
1438            price: 0,
1439            total_qty: 0,
1440            order_count: 0,
1441        }; 4];
1442        let n = b.depth(Side::Bid, 4, &mut out);
1443        assert_eq!(n, 2);
1444        assert_eq!(
1445            out[0],
1446            DepthLevel {
1447                price: 101,
1448                total_qty: 3,
1449                order_count: 1
1450            }
1451        );
1452        assert_eq!(
1453            out[1],
1454            DepthLevel {
1455                price: 100,
1456                total_qty: 5,
1457                order_count: 1
1458            }
1459        );
1460        b.debug_assert_invariants();
1461    }
1462
1463    #[test]
1464    fn fifo_partial_fill_keeps_head_and_residual_rests_at_tail() {
1465        let mut b = book();
1466        // Two makers at the same ask price; arrival order 1 then 2.
1467        add(&mut b, 1, 1, Side::Ask, 100, 10);
1468        add(&mut b, 2, 1, Side::Ask, 100, 10);
1469        // A third maker at a worse ask price.
1470        add(&mut b, 3, 1, Side::Ask, 101, 5);
1471        // Taker buys 15: fills maker 1 fully, maker 2 partially.
1472        let stream = add(&mut b, 9, 2, Side::Bid, 100, 15);
1473        assert_eq!(
1474            stream,
1475            [
1476                ExecutionEvent::Trade {
1477                    seq: 4,
1478                    maker_order_id: OrderId(1),
1479                    taker_order_id: OrderId(9),
1480                    price: 100,
1481                    qty: 10,
1482                },
1483                ExecutionEvent::Filled {
1484                    seq: 4,
1485                    order_id: OrderId(1)
1486                },
1487                ExecutionEvent::Trade {
1488                    seq: 4,
1489                    maker_order_id: OrderId(2),
1490                    taker_order_id: OrderId(9),
1491                    price: 100,
1492                    qty: 5,
1493                },
1494                ExecutionEvent::Filled {
1495                    seq: 4,
1496                    order_id: OrderId(9)
1497                },
1498            ]
1499        );
1500        // Maker 2 still rests at the head of the 100 level with 5 left.
1501        assert_eq!(b.best_ask(), Some((100, 5)));
1502        // A small taker now hits maker 2 (still head), not maker 3.
1503        add(&mut b, 10, 2, Side::Bid, 101, 5);
1504        assert_eq!(b.best_ask(), Some((101, 5)));
1505        b.debug_assert_invariants();
1506    }
1507
1508    #[test]
1509    fn level_aggregates_track_fill_cancel_amend() {
1510        let mut b = book();
1511        let mut storage = buffer();
1512        let mut events = EventBuffer::new(&mut storage);
1513        b.add_order(
1514            OrderId(1),
1515            ParticipantId(1),
1516            Side::Bid,
1517            OrderType::Limit,
1518            100,
1519            10,
1520            None,
1521            &mut events,
1522        )
1523        .expect("add 1");
1524        b.add_order(
1525            OrderId(2),
1526            ParticipantId(1),
1527            Side::Bid,
1528            OrderType::Limit,
1529            100,
1530            6,
1531            None,
1532            &mut events,
1533        )
1534        .expect("add 2");
1535        assert_eq!(b.best_bid(), Some((100, 16)));
1536        b.add_order(
1537            OrderId(3),
1538            ParticipantId(2),
1539            Side::Ask,
1540            OrderType::Limit,
1541            100,
1542            4,
1543            None,
1544            &mut events,
1545        )
1546        .expect("crossing ask fills 4 from the head bid");
1547        assert_eq!(b.best_bid(), Some((100, 12)));
1548        b.cancel_order(OrderId(2), &mut events).expect("cancel");
1549        assert_eq!(b.best_bid(), Some((100, 6)));
1550        // Amend legs (Milestone 2): reduce, increase, reprice. Order 1
1551        // is the only order left, holding 6 at price 100.
1552        amend(&mut b, 1, 100, 4);
1553        assert_eq!(b.best_bid(), Some((100, 4)), "reduce drops the aggregate");
1554        amend(&mut b, 1, 100, 9);
1555        assert_eq!(
1556            b.best_bid(),
1557            Some((100, 9)),
1558            "increase raises the aggregate"
1559        );
1560        amend(&mut b, 1, 99, 9);
1561        assert_eq!(b.best_bid(), Some((99, 9)), "reprice moves the aggregate");
1562        let mut out = [DepthLevel {
1563            price: 0,
1564            total_qty: 0,
1565            order_count: 0,
1566        }; 4];
1567        assert_eq!(b.depth(Side::Bid, 4, &mut out), 1);
1568        assert_eq!(
1569            out[0],
1570            DepthLevel {
1571                price: 99,
1572                total_qty: 9,
1573                order_count: 1
1574            }
1575        );
1576        b.debug_assert_invariants();
1577    }
1578
1579    #[test]
1580    fn cancel_missing_order_is_an_error_without_side_effects() {
1581        let mut b = book();
1582        let mut storage = buffer();
1583        let mut events = EventBuffer::new(&mut storage);
1584        let err = b
1585            .cancel_order(OrderId(42), &mut events)
1586            .expect_err("missing order");
1587        assert_eq!(
1588            err,
1589            BookError::OrderNotFound {
1590                order_id: OrderId(42)
1591            }
1592        );
1593        assert_eq!(b.next_seq(), 1, "rejected cancel consumes no seq");
1594    }
1595
1596    #[test]
1597    fn best_prices_clear_after_last_cancel() {
1598        let mut b = book();
1599        let mut storage = buffer();
1600        let mut events = EventBuffer::new(&mut storage);
1601        b.add_order(
1602            OrderId(1),
1603            ParticipantId(1),
1604            Side::Bid,
1605            OrderType::Limit,
1606            100,
1607            5,
1608            None,
1609            &mut events,
1610        )
1611        .expect("add");
1612        b.cancel_order(OrderId(1), &mut events).expect("cancel");
1613        assert_eq!(b.best_bid(), None);
1614        assert_eq!(b.live_order_count(), 0);
1615        b.debug_assert_invariants();
1616    }
1617
1618    #[test]
1619    fn capacity_full_rejects_an_order_that_would_rest() {
1620        let mut cfg = test_config();
1621        cfg.max_orders = 2;
1622        let mut b = Book::new(cfg).expect("valid config");
1623        let mut storage = buffer();
1624        let mut events = EventBuffer::new(&mut storage);
1625        b.add_order(
1626            OrderId(1),
1627            ParticipantId(1),
1628            Side::Bid,
1629            OrderType::Limit,
1630            100,
1631            5,
1632            None,
1633            &mut events,
1634        )
1635        .expect("add 1");
1636        b.add_order(
1637            OrderId(2),
1638            ParticipantId(1),
1639            Side::Bid,
1640            OrderType::Limit,
1641            99,
1642            5,
1643            None,
1644            &mut events,
1645        )
1646        .expect("add 2");
1647        let err = b
1648            .add_order(
1649                OrderId(3),
1650                ParticipantId(1),
1651                Side::Bid,
1652                OrderType::Limit,
1653                98,
1654                5,
1655                None,
1656                &mut events,
1657            )
1658            .expect_err("third resting order exceeds capacity");
1659        assert_eq!(err, BookError::CapacityFull { max_orders: 2 });
1660        assert_eq!(b.live_order_count(), 2);
1661    }
1662
1663    #[test]
1664    fn math_checked_paths_at_u64_edges() {
1665        // INV-MATH-1: aggregate arithmetic is checked at the boundary.
1666        // A level already holding u64::MAX cannot take one more unit:
1667        // the add fails in preflight with a typed error, atomically.
1668        let mut b = book();
1669        let mut storage = buffer();
1670        let mut events = EventBuffer::new(&mut storage);
1671        b.add_order(
1672            OrderId(1),
1673            ParticipantId(1),
1674            Side::Bid,
1675            OrderType::Limit,
1676            100,
1677            u64::MAX,
1678            None,
1679            &mut events,
1680        )
1681        .expect("one maximal order rests");
1682        assert_eq!(b.best_bid(), Some((100, u64::MAX)));
1683        let err = b
1684            .add_order(
1685                OrderId(2),
1686                ParticipantId(1),
1687                Side::Bid,
1688                OrderType::Limit,
1689                100,
1690                1,
1691                None,
1692                &mut events,
1693            )
1694            .expect_err("level aggregate would overflow u64");
1695        assert_eq!(
1696            err,
1697            BookError::ArithmeticOverflow {
1698                what: "price level quantity"
1699            }
1700        );
1701        assert_eq!(
1702            b.best_bid(),
1703            Some((100, u64::MAX)),
1704            "book unchanged after overflow rejection"
1705        );
1706        assert_eq!(b.live_order_count(), 1);
1707        assert_eq!(b.next_seq(), 2, "rejected command consumed no seq");
1708        // Amend leg (Milestone 2): repricing a second order onto the
1709        // maximal level would overflow the same aggregate, and is
1710        // rejected the same way, before any mutation.
1711        b.add_order(
1712            OrderId(3),
1713            ParticipantId(1),
1714            Side::Bid,
1715            OrderType::Limit,
1716            101,
1717            5,
1718            None,
1719            &mut events,
1720        )
1721        .expect("second order rests at its own level");
1722        let before = snapshot(&b);
1723        let mut storage2 = buffer();
1724        let mut events2 = EventBuffer::new(&mut storage2);
1725        let err = b
1726            .amend_order(OrderId(3), 100, 5, &mut events2)
1727            .expect_err("amend onto a maximal level overflows the aggregate");
1728        assert_eq!(
1729            err,
1730            BookError::ArithmeticOverflow {
1731                what: "price level quantity"
1732            }
1733        );
1734        assert_eq!(snapshot(&b), before, "overflowing amend mutated nothing");
1735        b.debug_assert_invariants();
1736    }
1737
1738    #[test]
1739    fn event_buffer_full_is_atomic() {
1740        let mut b = book();
1741        let mut big_storage: Vec<ExecutionEvent> = Vec::with_capacity(64);
1742        let mut big = EventBuffer::new(&mut big_storage);
1743        b.add_order(
1744            OrderId(1),
1745            ParticipantId(1),
1746            Side::Ask,
1747            OrderType::Limit,
1748            100,
1749            5,
1750            None,
1751            &mut big,
1752        )
1753        .expect("maker rests");
1754        // A crossing taker emits Trade + Filled(maker) + Filled(taker) =
1755        // 3 events. Offer a buffer with room for 2.
1756        let mut small_storage: Vec<ExecutionEvent> = Vec::with_capacity(2);
1757        let err = {
1758            let mut small = EventBuffer::new(&mut small_storage);
1759            b.add_order(
1760                OrderId(2),
1761                ParticipantId(2),
1762                Side::Bid,
1763                OrderType::Limit,
1764                100,
1765                5,
1766                None,
1767                &mut small,
1768            )
1769            .expect_err("buffer below the preflight bound")
1770        };
1771        assert_eq!(
1772            err,
1773            BookError::EventBufferFull {
1774                needed: 3,
1775                available: 2
1776            }
1777        );
1778        assert_eq!(b.best_ask(), Some((100, 5)), "maker untouched");
1779        assert_eq!(b.next_seq(), 2, "rejected command consumed no seq");
1780        assert_eq!(small_storage.len(), 0, "no partial events written");
1781        // Milestone 2 legs: the same bound discipline for the new
1782        // command types, each with its exact per-command bound
1783        // (ARCHITECTURE.md section 7.2).
1784        //
1785        // Amend bound is exactly 1.
1786        let mut zero_storage: Vec<ExecutionEvent> = Vec::new();
1787        let err = {
1788            let mut zero = EventBuffer::new(&mut zero_storage);
1789            b.amend_order(OrderId(1), 100, 3, &mut zero)
1790                .expect_err("amend needs exactly one event slot")
1791        };
1792        assert_eq!(
1793            err,
1794            BookError::EventBufferFull {
1795                needed: 1,
1796                available: 0
1797            }
1798        );
1799        assert_eq!(b.best_ask(), Some((100, 5)), "amend left the order alone");
1800        // Ioc bound for this sweep is the same 3 events.
1801        let mut two_storage: Vec<ExecutionEvent> = Vec::with_capacity(2);
1802        let err = {
1803            let mut two = EventBuffer::new(&mut two_storage);
1804            b.add_order(
1805                OrderId(2),
1806                ParticipantId(2),
1807                Side::Bid,
1808                OrderType::Ioc,
1809                100,
1810                5,
1811                None,
1812                &mut two,
1813            )
1814            .expect_err("ioc sweep needs three event slots")
1815        };
1816        assert_eq!(
1817            err,
1818            BookError::EventBufferFull {
1819                needed: 3,
1820                available: 2
1821            }
1822        );
1823        assert_eq!(b.best_ask(), Some((100, 5)), "maker still untouched");
1824        b.debug_assert_invariants();
1825    }
1826
1827    #[test]
1828    fn event_buffer_full_cancel_by_participant_bound() {
1829        let mut b = book();
1830        let mut storage = buffer();
1831        let mut setup = EventBuffer::new(&mut storage);
1832        b.add_order(
1833            OrderId(1),
1834            ParticipantId(1),
1835            Side::Bid,
1836            OrderType::Limit,
1837            100,
1838            5,
1839            None,
1840            &mut setup,
1841        )
1842        .expect("setup bid rests");
1843        b.add_order(
1844            OrderId(3),
1845            ParticipantId(1),
1846            Side::Bid,
1847            OrderType::Limit,
1848            99,
1849            5,
1850            None,
1851            &mut setup,
1852        )
1853        .expect("setup bid rests");
1854        let mut tiny_storage: Vec<ExecutionEvent> = Vec::with_capacity(1);
1855        let mut tiny = EventBuffer::new(&mut tiny_storage);
1856        let err = b
1857            .cancel_by_participant(ParticipantId(1), &mut tiny)
1858            .expect_err("bound is the live order count");
1859        assert_eq!(
1860            err,
1861            BookError::EventBufferFull {
1862                needed: 2,
1863                available: 1
1864            }
1865        );
1866        assert_eq!(b.live_order_count(), 2, "nothing was cancelled");
1867        b.debug_assert_invariants();
1868    }
1869
1870    #[test]
1871    fn ioc_expires_remainder_and_never_rests() {
1872        let mut b = book();
1873        add(&mut b, 1, 2, Side::Ask, 100, 5);
1874        let stream = add_typed(&mut b, 2, 3, Side::Bid, OrderType::Ioc, 100, 8, None);
1875        assert_eq!(
1876            stream,
1877            [
1878                ExecutionEvent::Trade {
1879                    seq: 2,
1880                    maker_order_id: OrderId(1),
1881                    taker_order_id: OrderId(2),
1882                    price: 100,
1883                    qty: 5,
1884                },
1885                ExecutionEvent::Filled {
1886                    seq: 2,
1887                    order_id: OrderId(1)
1888                },
1889                ExecutionEvent::Expired {
1890                    seq: 2,
1891                    order_id: OrderId(2),
1892                    remaining_qty: 3
1893                },
1894            ]
1895        );
1896        assert_eq!(b.live_order_count(), 0, "an Ioc order never rests");
1897        // The expired id is terminal: cancelling it finds nothing.
1898        let mut storage = buffer();
1899        let mut events = EventBuffer::new(&mut storage);
1900        let err = b
1901            .cancel_order(OrderId(2), &mut events)
1902            .expect_err("expired order is not live");
1903        assert_eq!(
1904            err,
1905            BookError::OrderNotFound {
1906                order_id: OrderId(2)
1907            }
1908        );
1909        // An Ioc order that crosses nothing expires in full.
1910        let stream = add_typed(&mut b, 3, 3, Side::Bid, OrderType::Ioc, 100, 4, None);
1911        assert_eq!(
1912            stream,
1913            [ExecutionEvent::Expired {
1914                seq: 3,
1915                order_id: OrderId(3),
1916                remaining_qty: 4
1917            }]
1918        );
1919        assert_eq!(b.best_bid(), None);
1920        b.debug_assert_invariants();
1921    }
1922
1923    #[test]
1924    fn ioc_fills_fully_when_liquidity_covers() {
1925        let mut b = book();
1926        add(&mut b, 1, 2, Side::Ask, 100, 5);
1927        let stream = add_typed(&mut b, 2, 3, Side::Bid, OrderType::Ioc, 100, 5, None);
1928        assert_eq!(
1929            stream,
1930            [
1931                ExecutionEvent::Trade {
1932                    seq: 2,
1933                    maker_order_id: OrderId(1),
1934                    taker_order_id: OrderId(2),
1935                    price: 100,
1936                    qty: 5,
1937                },
1938                ExecutionEvent::Filled {
1939                    seq: 2,
1940                    order_id: OrderId(1)
1941                },
1942                ExecutionEvent::Filled {
1943                    seq: 2,
1944                    order_id: OrderId(2)
1945                },
1946            ]
1947        );
1948        assert_eq!(b.live_order_count(), 0);
1949        b.debug_assert_invariants();
1950    }
1951
1952    #[test]
1953    fn ioc_and_fok_do_not_need_a_slot_on_a_full_book() {
1954        let mut cfg = test_config();
1955        cfg.max_orders = 1;
1956        let mut b = Book::new(cfg).expect("valid config");
1957        add(&mut b, 1, 2, Side::Ask, 100, 5);
1958        assert_eq!(b.live_order_count(), 1, "the book is full");
1959        // Neither order rests, so neither needs the slot the filled
1960        // maker is about to free.
1961        let stream = add_typed(&mut b, 2, 3, Side::Bid, OrderType::Ioc, 100, 5, None);
1962        assert_eq!(stream.len(), 3);
1963        add(&mut b, 3, 2, Side::Ask, 100, 5);
1964        let stream = add_typed(&mut b, 4, 3, Side::Bid, OrderType::Fok, 100, 5, None);
1965        assert_eq!(stream.len(), 3);
1966        assert_eq!(b.live_order_count(), 0);
1967        b.debug_assert_invariants();
1968    }
1969
1970    #[test]
1971    fn fok_fills_fully_or_not_at_all() {
1972        let mut b = book();
1973        add(&mut b, 1, 2, Side::Ask, 100, 5);
1974        add(&mut b, 2, 2, Side::Ask, 101, 5);
1975        let before = snapshot(&b);
1976        let mut storage = buffer();
1977        let err = {
1978            let mut events = EventBuffer::new(&mut storage);
1979            b.add_order(
1980                OrderId(3),
1981                ParticipantId(3),
1982                Side::Bid,
1983                OrderType::Fok,
1984                101,
1985                11,
1986                None,
1987                &mut events,
1988            )
1989            .expect_err("eleven requested, ten available")
1990        };
1991        assert_eq!(
1992            err,
1993            BookError::FokInsufficientLiquidity {
1994                requested: 11,
1995                available: 10
1996            }
1997        );
1998        assert_eq!(snapshot(&b), before, "a failed Fok mutates nothing");
1999        let stream = add_typed(&mut b, 3, 3, Side::Bid, OrderType::Fok, 101, 10, None);
2000        assert_eq!(
2001            stream,
2002            [
2003                ExecutionEvent::Trade {
2004                    seq: 3,
2005                    maker_order_id: OrderId(1),
2006                    taker_order_id: OrderId(3),
2007                    price: 100,
2008                    qty: 5,
2009                },
2010                ExecutionEvent::Filled {
2011                    seq: 3,
2012                    order_id: OrderId(1)
2013                },
2014                ExecutionEvent::Trade {
2015                    seq: 3,
2016                    maker_order_id: OrderId(2),
2017                    taker_order_id: OrderId(3),
2018                    price: 101,
2019                    qty: 5,
2020                },
2021                ExecutionEvent::Filled {
2022                    seq: 3,
2023                    order_id: OrderId(2)
2024                },
2025                ExecutionEvent::Filled {
2026                    seq: 3,
2027                    order_id: OrderId(3)
2028                },
2029            ]
2030        );
2031        assert_eq!(b.live_order_count(), 0);
2032        b.debug_assert_invariants();
2033    }
2034
2035    /// Resting layout for the STP Fok cases: the taker (participant 1)
2036    /// owns the middle ask.
2037    fn fok_stp_layout(b: &mut Book) {
2038        add(b, 1, 9, Side::Ask, 100, 5);
2039        add(b, 2, 1, Side::Ask, 100, 5);
2040        add(b, 3, 9, Side::Ask, 101, 5);
2041    }
2042
2043    #[test]
2044    fn fok_available_accounts_for_stp() {
2045        // INV-ORD-1: `available` is the exact STP-adjusted executable
2046        // quantity of ARCHITECTURE.md section 7.5, per policy.
2047        for (stp, available) in [
2048            (StpPolicy::CancelIncoming, 5),
2049            (StpPolicy::CancelResting, 10),
2050            (StpPolicy::CancelBoth, 5),
2051        ] {
2052            let mut b = book();
2053            fok_stp_layout(&mut b);
2054            let before = snapshot(&b);
2055            let mut storage = buffer();
2056            let err = {
2057                let mut events = EventBuffer::new(&mut storage);
2058                b.add_order(
2059                    OrderId(9),
2060                    ParticipantId(1),
2061                    Side::Bid,
2062                    OrderType::Fok,
2063                    101,
2064                    12,
2065                    Some(stp),
2066                    &mut events,
2067                )
2068                .expect_err("twelve is not executable under any policy")
2069            };
2070            assert_eq!(
2071                err,
2072                BookError::FokInsufficientLiquidity {
2073                    requested: 12,
2074                    available
2075                },
2076                "policy {stp:?}"
2077            );
2078            assert_eq!(
2079                snapshot(&b),
2080                before,
2081                "policy {stp:?}: a failed Fok mutates nothing, not even STP cancels"
2082            );
2083        }
2084        // Under CancelResting the same layout fills ten: the own order
2085        // is cancelled in the sweep and the deeper order completes it.
2086        let mut b = book();
2087        fok_stp_layout(&mut b);
2088        let stream = add_typed(
2089            &mut b,
2090            9,
2091            1,
2092            Side::Bid,
2093            OrderType::Fok,
2094            101,
2095            10,
2096            Some(StpPolicy::CancelResting),
2097        );
2098        assert_eq!(
2099            stream,
2100            [
2101                ExecutionEvent::Trade {
2102                    seq: 4,
2103                    maker_order_id: OrderId(1),
2104                    taker_order_id: OrderId(9),
2105                    price: 100,
2106                    qty: 5,
2107                },
2108                ExecutionEvent::Filled {
2109                    seq: 4,
2110                    order_id: OrderId(1)
2111                },
2112                ExecutionEvent::Cancelled {
2113                    seq: 4,
2114                    order_id: OrderId(2),
2115                    reason: CancelReason::SelfTradePrevention
2116                },
2117                ExecutionEvent::Trade {
2118                    seq: 4,
2119                    maker_order_id: OrderId(3),
2120                    taker_order_id: OrderId(9),
2121                    price: 101,
2122                    qty: 5,
2123                },
2124                ExecutionEvent::Filled {
2125                    seq: 4,
2126                    order_id: OrderId(3)
2127                },
2128                ExecutionEvent::Filled {
2129                    seq: 4,
2130                    order_id: OrderId(9)
2131                },
2132            ]
2133        );
2134        assert_eq!(b.live_order_count(), 0);
2135        b.debug_assert_invariants();
2136    }
2137
2138    #[test]
2139    fn post_only_rejection_is_atomic() {
2140        let mut b = book();
2141        add(&mut b, 1, 2, Side::Ask, 100, 5);
2142        let before = snapshot(&b);
2143        let mut storage = buffer();
2144        let err = {
2145            let mut events = EventBuffer::new(&mut storage);
2146            b.add_order(
2147                OrderId(2),
2148                ParticipantId(1),
2149                Side::Bid,
2150                OrderType::PostOnly,
2151                100,
2152                5,
2153                None,
2154                &mut events,
2155            )
2156            .expect_err("priced exactly at the best ask, a PostOnly buy crosses")
2157        };
2158        assert_eq!(
2159            err,
2160            BookError::PostOnlyWouldCross {
2161                price: 100,
2162                opposite_best: 100
2163            }
2164        );
2165        assert_eq!(snapshot(&b), before, "a rejected PostOnly mutates nothing");
2166        // One tick below the ask it rests in full.
2167        let stream = add_typed(&mut b, 2, 1, Side::Bid, OrderType::PostOnly, 99, 5, None);
2168        assert_eq!(
2169            stream,
2170            [ExecutionEvent::Accepted {
2171                seq: 2,
2172                order_id: OrderId(2)
2173            }]
2174        );
2175        assert_eq!(b.best_bid(), Some((99, 5)));
2176        // Equality crosses on the sell side too.
2177        let mut storage = buffer();
2178        let err = {
2179            let mut events = EventBuffer::new(&mut storage);
2180            b.add_order(
2181                OrderId(4),
2182                ParticipantId(2),
2183                Side::Ask,
2184                OrderType::PostOnly,
2185                99,
2186                5,
2187                None,
2188                &mut events,
2189            )
2190            .expect_err("priced exactly at the best bid, a PostOnly sell crosses")
2191        };
2192        assert_eq!(
2193            err,
2194            BookError::PostOnlyWouldCross {
2195                price: 99,
2196                opposite_best: 99
2197            }
2198        );
2199        b.debug_assert_invariants();
2200    }
2201
2202    /// Three asks at one price: other, own, other, in arrival order.
2203    fn stp_layout(b: &mut Book) {
2204        add(b, 1, 9, Side::Ask, 100, 5);
2205        add(b, 2, 1, Side::Ask, 100, 5);
2206        add(b, 3, 9, Side::Ask, 100, 5);
2207    }
2208
2209    #[test]
2210    fn stp_cancel_incoming_stops_at_own_order() {
2211        let mut b = book();
2212        stp_layout(&mut b);
2213        let stream = add_typed(
2214            &mut b,
2215            9,
2216            1,
2217            Side::Bid,
2218            OrderType::Limit,
2219            100,
2220            20,
2221            Some(StpPolicy::CancelIncoming),
2222        );
2223        assert_eq!(
2224            stream,
2225            [
2226                ExecutionEvent::Trade {
2227                    seq: 4,
2228                    maker_order_id: OrderId(1),
2229                    taker_order_id: OrderId(9),
2230                    price: 100,
2231                    qty: 5,
2232                },
2233                ExecutionEvent::Filled {
2234                    seq: 4,
2235                    order_id: OrderId(1)
2236                },
2237                ExecutionEvent::SelfTradePrevented {
2238                    seq: 4,
2239                    order_id: OrderId(9)
2240                },
2241            ]
2242        );
2243        // The own order is untouched and the third maker was never
2244        // reached; the taker remainder was cancelled, not rested.
2245        assert_eq!(b.best_ask(), Some((100, 10)));
2246        assert_eq!(b.best_bid(), None);
2247        assert_eq!(b.live_order_count(), 2);
2248        b.debug_assert_invariants();
2249    }
2250
2251    #[test]
2252    fn stp_cancel_resting_skips_own_orders() {
2253        let mut b = book();
2254        stp_layout(&mut b);
2255        let stream = add_typed(
2256            &mut b,
2257            9,
2258            1,
2259            Side::Bid,
2260            OrderType::Limit,
2261            100,
2262            12,
2263            Some(StpPolicy::CancelResting),
2264        );
2265        assert_eq!(
2266            stream,
2267            [
2268                ExecutionEvent::Trade {
2269                    seq: 4,
2270                    maker_order_id: OrderId(1),
2271                    taker_order_id: OrderId(9),
2272                    price: 100,
2273                    qty: 5,
2274                },
2275                ExecutionEvent::Filled {
2276                    seq: 4,
2277                    order_id: OrderId(1)
2278                },
2279                ExecutionEvent::Cancelled {
2280                    seq: 4,
2281                    order_id: OrderId(2),
2282                    reason: CancelReason::SelfTradePrevention
2283                },
2284                ExecutionEvent::Trade {
2285                    seq: 4,
2286                    maker_order_id: OrderId(3),
2287                    taker_order_id: OrderId(9),
2288                    price: 100,
2289                    qty: 5,
2290                },
2291                ExecutionEvent::Filled {
2292                    seq: 4,
2293                    order_id: OrderId(3)
2294                },
2295                ExecutionEvent::Accepted {
2296                    seq: 4,
2297                    order_id: OrderId(9)
2298                },
2299            ]
2300        );
2301        // Both other makers filled, the own order was cancelled without
2302        // consuming taker quantity, and the remainder of 2 rests.
2303        assert_eq!(b.best_bid(), Some((100, 2)));
2304        assert_eq!(b.best_ask(), None);
2305        b.debug_assert_invariants();
2306    }
2307
2308    #[test]
2309    fn stp_cancel_both_cancels_each_side() {
2310        let mut b = book();
2311        stp_layout(&mut b);
2312        let stream = add_typed(
2313            &mut b,
2314            9,
2315            1,
2316            Side::Bid,
2317            OrderType::Limit,
2318            100,
2319            20,
2320            Some(StpPolicy::CancelBoth),
2321        );
2322        assert_eq!(
2323            stream,
2324            [
2325                ExecutionEvent::Trade {
2326                    seq: 4,
2327                    maker_order_id: OrderId(1),
2328                    taker_order_id: OrderId(9),
2329                    price: 100,
2330                    qty: 5,
2331                },
2332                ExecutionEvent::Filled {
2333                    seq: 4,
2334                    order_id: OrderId(1)
2335                },
2336                ExecutionEvent::Cancelled {
2337                    seq: 4,
2338                    order_id: OrderId(2),
2339                    reason: CancelReason::SelfTradePrevention
2340                },
2341                ExecutionEvent::SelfTradePrevented {
2342                    seq: 4,
2343                    order_id: OrderId(9)
2344                },
2345            ]
2346        );
2347        assert_eq!(b.best_ask(), Some((100, 5)), "the third maker survives");
2348        assert_eq!(b.best_bid(), None);
2349        b.debug_assert_invariants();
2350    }
2351
2352    #[test]
2353    fn stp_default_applies_when_order_names_none() {
2354        let mut cfg = test_config();
2355        cfg.default_stp = StpPolicy::CancelResting;
2356        let mut b = Book::new(cfg).expect("valid config");
2357        stp_layout(&mut b);
2358        let stream = add(&mut b, 9, 1, Side::Bid, 100, 12);
2359        assert!(
2360            stream.contains(&ExecutionEvent::Cancelled {
2361                seq: 4,
2362                order_id: OrderId(2),
2363                reason: CancelReason::SelfTradePrevention
2364            }),
2365            "the book default CancelResting policy cancelled the own order: {stream:?}"
2366        );
2367        assert_eq!(b.best_bid(), Some((100, 2)));
2368        b.debug_assert_invariants();
2369    }
2370
2371    #[test]
2372    fn amend_reduce_preserves_priority() {
2373        let mut b = book();
2374        add(&mut b, 1, 1, Side::Bid, 100, 10);
2375        add(&mut b, 2, 1, Side::Bid, 100, 10);
2376        let stream = amend(&mut b, 1, 100, 4);
2377        assert_eq!(
2378            stream,
2379            [ExecutionEvent::Amended {
2380                seq: 3,
2381                order_id: OrderId(1),
2382                price: 100,
2383                qty: 4
2384            }]
2385        );
2386        // Order 1 is still the head: a sell of 5 fills it first.
2387        let stream = add(&mut b, 3, 2, Side::Ask, 100, 5);
2388        assert_eq!(
2389            stream,
2390            [
2391                ExecutionEvent::Trade {
2392                    seq: 4,
2393                    maker_order_id: OrderId(1),
2394                    taker_order_id: OrderId(3),
2395                    price: 100,
2396                    qty: 4,
2397                },
2398                ExecutionEvent::Filled {
2399                    seq: 4,
2400                    order_id: OrderId(1)
2401                },
2402                ExecutionEvent::Trade {
2403                    seq: 4,
2404                    maker_order_id: OrderId(2),
2405                    taker_order_id: OrderId(3),
2406                    price: 100,
2407                    qty: 1,
2408                },
2409                ExecutionEvent::Filled {
2410                    seq: 4,
2411                    order_id: OrderId(3)
2412                },
2413            ]
2414        );
2415        b.debug_assert_invariants();
2416    }
2417
2418    #[test]
2419    fn amend_identical_is_noop() {
2420        let mut b = book();
2421        add(&mut b, 1, 1, Side::Bid, 100, 10);
2422        add(&mut b, 2, 1, Side::Bid, 100, 10);
2423        let before = snapshot(&b);
2424        let stream = amend(&mut b, 1, 100, 10);
2425        assert_eq!(
2426            stream,
2427            [ExecutionEvent::Amended {
2428                seq: 3,
2429                order_id: OrderId(1),
2430                price: 100,
2431                qty: 10
2432            }]
2433        );
2434        let after = snapshot(&b);
2435        assert_eq!(after.0, before.0 + 1, "the no-op amend consumed one seq");
2436        assert_eq!(after.1, before.1, "live count unchanged");
2437        assert_eq!(after.2, before.2, "best bid unchanged");
2438        assert_eq!(after.4, before.4, "depth unchanged");
2439        // Position is untouched: order 1 still fills first.
2440        let stream = add(&mut b, 3, 2, Side::Ask, 100, 10);
2441        assert_eq!(
2442            stream[0],
2443            ExecutionEvent::Trade {
2444                seq: 4,
2445                maker_order_id: OrderId(1),
2446                taker_order_id: OrderId(3),
2447                price: 100,
2448                qty: 10
2449            }
2450        );
2451        b.debug_assert_invariants();
2452    }
2453
2454    #[test]
2455    fn amend_increase_or_reprice_goes_to_tail() {
2456        // Increase at the same price.
2457        let mut b = book();
2458        add(&mut b, 1, 1, Side::Bid, 100, 5);
2459        add(&mut b, 2, 1, Side::Bid, 100, 5);
2460        amend(&mut b, 1, 100, 8);
2461        let stream = add(&mut b, 3, 2, Side::Ask, 100, 6);
2462        assert_eq!(
2463            stream,
2464            [
2465                ExecutionEvent::Trade {
2466                    seq: 4,
2467                    maker_order_id: OrderId(2),
2468                    taker_order_id: OrderId(3),
2469                    price: 100,
2470                    qty: 5,
2471                },
2472                ExecutionEvent::Filled {
2473                    seq: 4,
2474                    order_id: OrderId(2)
2475                },
2476                ExecutionEvent::Trade {
2477                    seq: 4,
2478                    maker_order_id: OrderId(1),
2479                    taker_order_id: OrderId(3),
2480                    price: 100,
2481                    qty: 1,
2482                },
2483                ExecutionEvent::Filled {
2484                    seq: 4,
2485                    order_id: OrderId(3)
2486                },
2487            ],
2488            "the increased order fills behind the order that was behind it"
2489        );
2490        // Reprice onto another level: tail of the target level.
2491        let mut b = book();
2492        add(&mut b, 1, 1, Side::Bid, 100, 5);
2493        add(&mut b, 2, 1, Side::Bid, 99, 5);
2494        amend(&mut b, 1, 99, 5);
2495        let stream = add(&mut b, 3, 2, Side::Ask, 99, 6);
2496        assert_eq!(
2497            stream[0],
2498            ExecutionEvent::Trade {
2499                seq: 4,
2500                maker_order_id: OrderId(2),
2501                taker_order_id: OrderId(3),
2502                price: 99,
2503                qty: 5
2504            },
2505            "the repriced order sits behind the order already at 99"
2506        );
2507        assert_eq!(
2508            stream[2],
2509            ExecutionEvent::Trade {
2510                seq: 4,
2511                maker_order_id: OrderId(1),
2512                taker_order_id: OrderId(3),
2513                price: 99,
2514                qty: 1
2515            }
2516        );
2517        b.debug_assert_invariants();
2518    }
2519
2520    #[test]
2521    fn amend_that_would_cross_is_rejected() {
2522        let mut b = book();
2523        add(&mut b, 9, 2, Side::Ask, 105, 5);
2524        add(&mut b, 1, 1, Side::Bid, 100, 5);
2525        let before = snapshot(&b);
2526        let mut storage = buffer();
2527        let err = {
2528            let mut events = EventBuffer::new(&mut storage);
2529            b.amend_order(OrderId(1), 105, 5, &mut events)
2530                .expect_err("amending a bid to the best ask locks the book")
2531        };
2532        assert_eq!(
2533            err,
2534            BookError::AmendWouldCross {
2535                order_id: OrderId(1),
2536                new_price: 105,
2537                opposite_best: 105
2538            }
2539        );
2540        assert_eq!(snapshot(&b), before, "a crossing amend mutates nothing");
2541        // One tick below the ask is fine.
2542        let stream = amend(&mut b, 1, 104, 5);
2543        assert_eq!(
2544            stream,
2545            [ExecutionEvent::Amended {
2546                seq: 3,
2547                order_id: OrderId(1),
2548                price: 104,
2549                qty: 5
2550            }]
2551        );
2552        assert_eq!(b.best_bid(), Some((104, 5)));
2553        b.debug_assert_invariants();
2554    }
2555
2556    #[test]
2557    fn amend_missing_and_terminal_ids_are_not_found() {
2558        let mut b = book();
2559        let mut storage = buffer();
2560        let mut events = EventBuffer::new(&mut storage);
2561        let err = b
2562            .amend_order(OrderId(42), 100, 5, &mut events)
2563            .expect_err("never-seen id");
2564        assert_eq!(
2565            err,
2566            BookError::OrderNotFound {
2567                order_id: OrderId(42)
2568            }
2569        );
2570        // A filled order is terminal.
2571        add(&mut b, 1, 1, Side::Bid, 100, 5);
2572        add(&mut b, 2, 2, Side::Ask, 100, 5);
2573        let mut storage = buffer();
2574        let mut events = EventBuffer::new(&mut storage);
2575        let err = b
2576            .amend_order(OrderId(1), 100, 3, &mut events)
2577            .expect_err("filled order");
2578        assert_eq!(
2579            err,
2580            BookError::OrderNotFound {
2581                order_id: OrderId(1)
2582            }
2583        );
2584        // A cancelled order is terminal.
2585        add(&mut b, 3, 1, Side::Bid, 100, 5);
2586        let mut storage = buffer();
2587        let mut events = EventBuffer::new(&mut storage);
2588        b.cancel_order(OrderId(3), &mut events).expect("cancel");
2589        let err = b
2590            .amend_order(OrderId(3), 100, 3, &mut events)
2591            .expect_err("cancelled order");
2592        assert_eq!(
2593            err,
2594            BookError::OrderNotFound {
2595                order_id: OrderId(3)
2596            }
2597        );
2598        b.debug_assert_invariants();
2599    }
2600
2601    #[test]
2602    fn amend_zero_qty_and_bad_price_are_rejected() {
2603        let mut b = book();
2604        add(&mut b, 1, 1, Side::Bid, 100, 5);
2605        let before = snapshot(&b);
2606        let mut storage = buffer();
2607        let mut events = EventBuffer::new(&mut storage);
2608        let err = b
2609            .amend_order(OrderId(1), 100, 0, &mut events)
2610            .expect_err("zero quantity");
2611        assert_eq!(err, BookError::InvalidQuantity { qty: 0 });
2612        let err = b
2613            .amend_order(OrderId(1), 0, 5, &mut events)
2614            .expect_err("zero price");
2615        assert!(matches!(err, BookError::InvalidPriceTick { .. }));
2616        assert_eq!(snapshot(&b), before);
2617        b.debug_assert_invariants();
2618    }
2619
2620    #[test]
2621    fn cancel_by_participant_event_order_is_slot_order() {
2622        // INV-CANCEL-1: the snapshot format relies on this order.
2623        // Slots are allocated 0, 1, 2, ... and freed slots are reused
2624        // LIFO, so after cancelling order 1 (slot 0) the next add
2625        // (order 5) takes slot 0, ahead of orders 3 and 4.
2626        let mut b = book();
2627        add(&mut b, 1, 1, Side::Bid, 100, 5);
2628        add(&mut b, 2, 2, Side::Bid, 100, 5);
2629        add(&mut b, 3, 1, Side::Bid, 99, 5);
2630        add(&mut b, 4, 1, Side::Ask, 105, 5);
2631        let mut storage = buffer();
2632        let mut events = EventBuffer::new(&mut storage);
2633        b.cancel_order(OrderId(1), &mut events).expect("cancel");
2634        add(&mut b, 5, 1, Side::Bid, 98, 5);
2635        let mut storage = Vec::with_capacity(16);
2636        let written = {
2637            let mut events = EventBuffer::new(&mut storage);
2638            b.cancel_by_participant(ParticipantId(1), &mut events)
2639                .expect("mass cancel")
2640        };
2641        assert_eq!(written, 3);
2642        assert_eq!(
2643            storage,
2644            [
2645                ExecutionEvent::Cancelled {
2646                    seq: 7,
2647                    order_id: OrderId(5),
2648                    reason: CancelReason::ByParticipant
2649                },
2650                ExecutionEvent::Cancelled {
2651                    seq: 7,
2652                    order_id: OrderId(3),
2653                    reason: CancelReason::ByParticipant
2654                },
2655                ExecutionEvent::Cancelled {
2656                    seq: 7,
2657                    order_id: OrderId(4),
2658                    reason: CancelReason::ByParticipant
2659                },
2660            ],
2661            "ascending slot order: slot 0 (order 5), slot 2 (order 3), slot 3 (order 4)"
2662        );
2663        // Only participant 2's order survives.
2664        assert_eq!(b.live_order_count(), 1);
2665        assert_eq!(b.best_bid(), Some((100, 5)));
2666        assert_eq!(b.best_ask(), None);
2667        b.debug_assert_invariants();
2668    }
2669
2670    #[test]
2671    fn cancel_by_participant_with_no_orders_succeeds_empty() {
2672        let mut b = book();
2673        add(&mut b, 1, 2, Side::Bid, 100, 5);
2674        let mut storage = Vec::with_capacity(4);
2675        let written = {
2676            let mut events = EventBuffer::new(&mut storage);
2677            b.cancel_by_participant(ParticipantId(7), &mut events)
2678                .expect("an empty mass cancel is an accepted command")
2679        };
2680        assert_eq!(written, 0);
2681        assert_eq!(storage.len(), 0);
2682        assert_eq!(b.next_seq(), 3, "the accepted command consumed a seq");
2683        assert_eq!(b.best_bid(), Some((100, 5)), "other participants untouched");
2684        b.debug_assert_invariants();
2685    }
2686
2687    #[test]
2688    fn event_shape_golden() {
2689        // INV-EVENT-3: one scripted session exercising every command
2690        // type, with the complete event stream pinned.
2691        let mut b = book();
2692        let mut storage = buffer();
2693        run_golden_session(&mut b, &mut storage);
2694        assert_eq!(storage, golden_expected());
2695
2696        assert_eq!(
2697            b.live_order_count(),
2698            0,
2699            "every order reached a terminal state"
2700        );
2701        assert_eq!(b.next_seq(), 10);
2702        b.debug_assert_invariants();
2703    }
2704
2705    /// The scripted nine-command session for `event_shape_golden`:
2706    /// every command type once, against one shared event storage.
2707    fn run_golden_session(b: &mut Book, storage: &mut Vec<ExecutionEvent>) {
2708        let mut run = |b: &mut Book, f: &dyn Fn(&mut Book, &mut EventBuffer<'_>)| {
2709            let mut events = EventBuffer::new(storage);
2710            f(b, &mut events);
2711        };
2712        run(b, &|b, e| {
2713            b.add_order(
2714                OrderId(1),
2715                ParticipantId(1),
2716                Side::Bid,
2717                OrderType::Limit,
2718                100,
2719                10,
2720                None,
2721                e,
2722            )
2723            .expect("bid rests");
2724        });
2725        run(b, &|b, e| {
2726            b.add_order(
2727                OrderId(2),
2728                ParticipantId(2),
2729                Side::Ask,
2730                OrderType::Limit,
2731                105,
2732                10,
2733                None,
2734                e,
2735            )
2736            .expect("ask rests");
2737        });
2738        run(b, &|b, e| {
2739            b.amend_order(OrderId(2), 103, 10, e).expect("amend");
2740        });
2741        run(b, &|b, e| {
2742            b.add_order(
2743                OrderId(3),
2744                ParticipantId(3),
2745                Side::Bid,
2746                OrderType::Limit,
2747                103,
2748                4,
2749                None,
2750                e,
2751            )
2752            .expect("crossing bid fills");
2753        });
2754        run(b, &|b, e| {
2755            b.add_order(
2756                OrderId(4),
2757                ParticipantId(3),
2758                Side::Ask,
2759                OrderType::Ioc,
2760                100,
2761                15,
2762                None,
2763                e,
2764            )
2765            .expect("ioc sweeps and expires");
2766        });
2767        run(b, &|b, e| {
2768            b.add_order(
2769                OrderId(5),
2770                ParticipantId(1),
2771                Side::Ask,
2772                OrderType::Limit,
2773                102,
2774                7,
2775                None,
2776                e,
2777            )
2778            .expect("ask rests");
2779        });
2780        run(b, &|b, e| {
2781            b.add_order(
2782                OrderId(6),
2783                ParticipantId(1),
2784                Side::Bid,
2785                OrderType::Limit,
2786                102,
2787                7,
2788                Some(StpPolicy::CancelIncoming),
2789                e,
2790            )
2791            .expect("self-trade prevented");
2792        });
2793        run(b, &|b, e| {
2794            b.cancel_by_participant(ParticipantId(1), e)
2795                .expect("mass cancel");
2796        });
2797        run(b, &|b, e| {
2798            b.cancel_order(OrderId(2), e).expect("cancel");
2799        });
2800    }
2801
2802    /// The pinned event stream for `event_shape_golden` (INV-EVENT-3):
2803    /// every variant, in order, with exact seqs and payloads.
2804    fn golden_expected() -> Vec<ExecutionEvent> {
2805        vec![
2806            ExecutionEvent::Accepted {
2807                seq: 1,
2808                order_id: OrderId(1),
2809            },
2810            ExecutionEvent::Accepted {
2811                seq: 2,
2812                order_id: OrderId(2),
2813            },
2814            ExecutionEvent::Amended {
2815                seq: 3,
2816                order_id: OrderId(2),
2817                price: 103,
2818                qty: 10,
2819            },
2820            ExecutionEvent::Trade {
2821                seq: 4,
2822                maker_order_id: OrderId(2),
2823                taker_order_id: OrderId(3),
2824                price: 103,
2825                qty: 4,
2826            },
2827            ExecutionEvent::Filled {
2828                seq: 4,
2829                order_id: OrderId(3),
2830            },
2831            ExecutionEvent::Trade {
2832                seq: 5,
2833                maker_order_id: OrderId(1),
2834                taker_order_id: OrderId(4),
2835                price: 100,
2836                qty: 10,
2837            },
2838            ExecutionEvent::Filled {
2839                seq: 5,
2840                order_id: OrderId(1),
2841            },
2842            ExecutionEvent::Expired {
2843                seq: 5,
2844                order_id: OrderId(4),
2845                remaining_qty: 5,
2846            },
2847            ExecutionEvent::Accepted {
2848                seq: 6,
2849                order_id: OrderId(5),
2850            },
2851            ExecutionEvent::SelfTradePrevented {
2852                seq: 7,
2853                order_id: OrderId(6),
2854            },
2855            ExecutionEvent::Cancelled {
2856                seq: 8,
2857                order_id: OrderId(5),
2858                reason: CancelReason::ByParticipant,
2859            },
2860            ExecutionEvent::Cancelled {
2861                seq: 9,
2862                order_id: OrderId(2),
2863                reason: CancelReason::Requested,
2864            },
2865        ]
2866    }
2867}