orderbook-rs 0.13.1

A high-performance, lock-free price level implementation for limit order books in Rust. This library provides the building blocks for creating efficient trading systems with support for multiple order types and concurrent access patterns.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
//! #230: `OrderBook::strandable_makers_resting`, the count that gates the
//! sweep's strandable-maker scan.
//!
//! The scan that captures makers whose hidden depth a sweep would strand has
//! to walk a level's resting orders, and `PriceLevel::iter_orders` is a
//! `DashMap` iterator that read-locks every shard of the map per level match.
//! Only a `ReserveOrder { auto_replenish: false, .. }` carrying hidden
//! quantity can ever be captured, so the book counts how many are resting
//! and the sweep skips the scan entirely while that count is zero.
//!
//! The count is exact: incremented at the two places an order is rested
//! (admission, snapshot-restore commit) and decremented at the three places
//! such a maker leaves a level (`cancel_order_with_reason`, the STP maker
//! cancel, the fill drain). These tests pin both directions, including the
//! gate closing again once the last one is gone.

#[cfg(test)]
mod tests {
    use crate::orderbook::book::OrderBook;
    use pricelevel::{Hash32, Id, OrderType, Price, Quantity, Side, TimeInForce, TimestampMs};
    use std::num::NonZeroU64;
    use std::sync::atomic::Ordering;

    const PRICE: u128 = 100;
    /// A GTD deadline far past any real clock reading, so the order is
    /// admitted and only the explicit eviction below expires it.
    const EXPIRY_DEADLINE_MS: u64 = 4_000_000_000_000;

    /// Read the count.
    fn count(book: &OrderBook<()>) -> usize {
        book.strandable_makers_resting.load(Ordering::Relaxed)
    }

    /// Is the sweep's scan armed?
    fn armed(book: &OrderBook<()>) -> bool {
        count(book) > 0
    }

    /// A reserve BUY at `PRICE` with the given tranches and replenishment
    /// policy.
    fn reserve_buy(
        id: Id,
        visible: u64,
        hidden: u64,
        replenish_amount: Option<u64>,
        auto_replenish: bool,
    ) -> OrderType<()> {
        OrderType::ReserveOrder {
            id,
            price: Price::new(PRICE),
            visible_quantity: Quantity::new(visible),
            hidden_quantity: Quantity::new(hidden),
            side: Side::Buy,
            user_id: Hash32::zero(),
            timestamp: TimestampMs::new(0),
            time_in_force: TimeInForce::Gtc,
            replenish_threshold: Quantity::new(0),
            replenish_amount: replenish_amount.and_then(NonZeroU64::new),
            auto_replenish,
            extra_fields: (),
        }
    }

    /// An iceberg BUY at `PRICE`.
    fn iceberg_buy(id: Id, visible: u64, hidden: u64) -> OrderType<()> {
        OrderType::IcebergOrder {
            id,
            price: Price::new(PRICE),
            visible_quantity: Quantity::new(visible),
            hidden_quantity: Quantity::new(hidden),
            side: Side::Buy,
            user_id: Hash32::zero(),
            timestamp: TimestampMs::new(0),
            time_in_force: TimeInForce::Gtc,
            extra_fields: (),
        }
    }

    /// A fresh book has nothing to scan for.
    #[test]
    fn test_strandable_makers_resting_starts_false() {
        let book: OrderBook<()> = OrderBook::new("FLAG-NEW");
        assert!(!armed(&book), "a fresh book has rested nothing");
    }

    /// Icebergs and auto-replenishing reserves both carry hidden depth, so
    /// they make levels the scan would have to walk — but neither can ever
    /// strand anything, so neither arms the gate, not even across a sweep
    /// that consumes them.
    #[test]
    fn test_strandable_makers_resting_stays_false_for_iceberg_and_auto_reserve() {
        let book: OrderBook<()> = OrderBook::new("FLAG-SAFE");
        let iceberg_id = Id::new();
        let auto_id = Id::new();

        assert!(
            book.add_order(iceberg_buy(iceberg_id, 10, 20)).is_ok(),
            "iceberg must rest"
        );
        assert!(
            book.add_order(reserve_buy(auto_id, 10, 20, Some(10), true))
                .is_ok(),
            "auto-replenishing reserve must rest"
        );
        assert!(!armed(&book), "neither kind can strand hidden depth");

        // A sweep across both leaves the gate closed as well.
        assert!(
            book.add_limit_order(Id::new(), PRICE, 15, Side::Sell, TimeInForce::Gtc, None)
                .is_ok(),
            "the crossing sell must be accepted"
        );
        assert!(!armed(&book), "matching does not arm the gate by itself");
    }

    /// Resting a non-auto reserve with hidden depth arms the gate.
    #[test]
    fn test_strandable_makers_resting_set_by_resting_non_auto_reserve() {
        let book: OrderBook<()> = OrderBook::new("FLAG-ARM");
        assert!(
            book.add_order(reserve_buy(Id::new(), 10, 20, None, false))
                .is_ok(),
            "the reserve must rest"
        );
        assert!(armed(&book), "a strandable maker is now on the book");
    }

    /// Without hidden depth there is nothing to strand, so the same
    /// non-auto reserve leaves the gate closed.
    #[test]
    fn test_strandable_makers_resting_stays_false_without_hidden_depth() {
        let book: OrderBook<()> = OrderBook::new("FLAG-NO-HIDDEN");
        assert!(
            book.add_order(reserve_buy(Id::new(), 10, 0, None, false))
                .is_ok(),
            "the reserve must rest"
        );
        assert!(!armed(&book), "no hidden tranche, nothing to strand");
    }

    /// The residual-resting path arms the gate too: a partially filled
    /// non-auto reserve that keeps a positive visible tranche rests with its
    /// hidden depth intact and can strand it later.
    #[test]
    fn test_strandable_makers_resting_set_by_rested_residual() {
        let book: OrderBook<()> = OrderBook::new("FLAG-RESIDUAL");
        assert!(
            book.add_limit_order(Id::new(), PRICE, 5, Side::Sell, TimeInForce::Gtc, None)
                .is_ok(),
            "contra depth must rest"
        );
        let taker_id = Id::new();
        assert!(
            book.add_order(reserve_buy(taker_id, 10, 20, None, false))
                .is_ok(),
            "the aggressive reserve must rest its residual"
        );
        assert!(
            book.get_order(taker_id).is_some(),
            "5 of the visible tranche was taken, so the residual rests"
        );
        assert!(armed(&book), "the rested residual is strandable");
    }

    /// The flag is not part of the snapshot format; a restore re-derives it
    /// from the orders it installs, so a package carrying a strandable maker
    /// arms the gate on the restored book.
    #[test]
    fn test_strandable_makers_resting_rederived_by_snapshot_package_restore() {
        let source: OrderBook<()> = OrderBook::new("FLAG-RESTORE");
        let order_id = Id::new();
        assert!(
            source
                .add_order(reserve_buy(order_id, 10, 20, None, false))
                .is_ok(),
            "the reserve must rest on the source book"
        );
        assert!(armed(&source), "the source book is armed");
        let package = match source.create_snapshot_package(usize::MAX) {
            Ok(package) => package,
            Err(error) => panic!("snapshot package must build: {error}"),
        };

        let mut restored: OrderBook<()> = OrderBook::new("FLAG-RESTORE");
        assert!(!armed(&restored), "the destination starts closed");
        assert!(
            restored.restore_from_snapshot_package(package).is_ok(),
            "the package must restore"
        );

        assert!(
            restored.get_order(order_id).is_some(),
            "the strandable maker is on the restored book"
        );
        assert!(
            armed(&restored),
            "restore must re-derive the gate from the installed orders"
        );
    }

    /// A package with no strandable maker leaves the gate closed, so the
    /// re-derivation is not a blanket `true` on every restore.
    #[test]
    fn test_strandable_makers_resting_stays_false_restoring_a_safe_package() {
        let source: OrderBook<()> = OrderBook::new("FLAG-RESTORE-SAFE");
        assert!(
            source.add_order(iceberg_buy(Id::new(), 10, 20)).is_ok(),
            "the iceberg must rest on the source book"
        );
        let package = match source.create_snapshot_package(usize::MAX) {
            Ok(package) => package,
            Err(error) => panic!("snapshot package must build: {error}"),
        };

        let mut restored: OrderBook<()> = OrderBook::new("FLAG-RESTORE-SAFE");
        assert!(
            restored.restore_from_snapshot_package(package).is_ok(),
            "the package must restore"
        );
        assert!(!armed(&restored), "nothing installed can strand anything");
    }

    /// The count falls back to zero when the last strandable maker is
    /// **cancelled**, closing the gate again.
    #[test]
    fn test_strandable_makers_resting_returns_to_zero_on_cancel() {
        let book: OrderBook<()> = OrderBook::new("COUNT-CANCEL");
        let first = Id::new();
        let second = Id::new();
        assert!(
            book.add_order(reserve_buy(first, 10, 20, None, false))
                .is_ok()
        );
        assert!(
            book.add_order(reserve_buy(second, 10, 20, None, false))
                .is_ok()
        );
        assert_eq!(count(&book), 2, "both strandable makers are counted");

        assert!(book.cancel_order(first).is_ok(), "first cancel");
        assert_eq!(count(&book), 1, "one decrement per removal");
        assert!(book.cancel_order(second).is_ok(), "second cancel");
        assert_eq!(count(&book), 0, "the gate closes again");
        assert!(!armed(&book), "no scan is armed once none rest");
    }

    /// Mass cancel funnels through the same helper, so the count follows.
    #[test]
    fn test_strandable_makers_resting_returns_to_zero_on_mass_cancel() {
        let book: OrderBook<()> = OrderBook::new("COUNT-MASS");
        assert!(
            book.add_order(reserve_buy(Id::new(), 10, 20, None, false))
                .is_ok()
        );
        assert!(
            book.add_order(reserve_buy(Id::new(), 10, 20, None, false))
                .is_ok()
        );
        // An iceberg is not counted and must not disturb the tally.
        assert!(book.add_order(iceberg_buy(Id::new(), 10, 20)).is_ok());
        assert_eq!(count(&book), 2, "only the reserves are counted");

        let cancelled = book.cancel_all_orders();
        assert_eq!(cancelled.cancelled_count(), 3, "every maker is cancelled");
        assert_eq!(
            count(&book),
            0,
            "mass cancel decrements through the same funnel"
        );
    }

    /// Consuming the last strandable maker through a sweep decrements it in
    /// the fill drain, which is the third removal path.
    #[test]
    fn test_strandable_makers_resting_returns_to_zero_when_consumed() {
        let book: OrderBook<()> = OrderBook::new("COUNT-CONSUMED");
        let maker_id = Id::new();
        assert!(
            book.add_order(reserve_buy(maker_id, 10, 20, None, false))
                .is_ok()
        );
        assert_eq!(count(&book), 1, "the maker is counted");

        assert!(
            book.add_limit_order(Id::new(), PRICE, 10, Side::Sell, TimeInForce::Gtc, None)
                .is_ok(),
            "the sweep takes the whole visible tranche"
        );

        assert!(book.get_order(maker_id).is_none(), "the maker is removed");
        assert_eq!(count(&book), 0, "the fill drain decrements the count");
        assert!(
            !armed(&book),
            "the gate closes after the last one is consumed"
        );
    }

    /// Cancellation versus matching of the same maker: whichever removes
    /// it, the count falls to zero exactly once and never twice.
    #[test]
    fn test_strandable_makers_resting_decrements_exactly_once_per_maker() {
        // Removed by cancel: the later sweep must not decrement again.
        let cancelled: OrderBook<()> = OrderBook::new("COUNT-ONCE-CANCEL");
        let maker = Id::new();
        assert!(
            cancelled
                .add_order(reserve_buy(maker, 10, 20, None, false))
                .is_ok()
        );
        assert_eq!(count(&cancelled), 1);
        assert!(cancelled.cancel_order(maker).is_ok(), "cancel removes it");
        assert_eq!(count(&cancelled), 0, "one decrement");
        assert!(
            cancelled
                .add_limit_order(Id::new(), PRICE, 10, Side::Sell, TimeInForce::Gtc, None)
                .is_ok(),
            "a later sweep finds nothing to consume"
        );
        assert_eq!(count(&cancelled), 0, "no second decrement");

        // Removed by matching: a later cancel must not decrement again.
        let matched: OrderBook<()> = OrderBook::new("COUNT-ONCE-MATCH");
        let consumed = Id::new();
        assert!(
            matched
                .add_order(reserve_buy(consumed, 10, 20, None, false))
                .is_ok()
        );
        assert_eq!(count(&matched), 1);
        assert!(
            matched
                .add_limit_order(Id::new(), PRICE, 10, Side::Sell, TimeInForce::Gtc, None)
                .is_ok(),
            "the sweep consumes it"
        );
        assert_eq!(count(&matched), 0, "one decrement");
        assert!(
            matches!(matched.cancel_order(consumed), Ok(None)),
            "the order is already gone"
        );
        assert_eq!(count(&matched), 0, "no second decrement");
    }

    /// An id reused by a plain order after its strandable reserve was
    /// cancelled never decrements again and is never reported: the count
    /// follows the order body, not the id.
    #[test]
    fn test_strandable_makers_resting_ignores_a_reused_id() {
        let book: OrderBook<()> = OrderBook::new("COUNT-ID-REUSE");
        let shared_id = Id::new();
        assert!(
            book.add_order(reserve_buy(shared_id, 10, 20, None, false))
                .is_ok()
        );
        assert_eq!(count(&book), 1);
        assert!(book.cancel_order(shared_id).is_ok());
        assert_eq!(count(&book), 0, "the reserve is gone");

        // The same id, now a plain order.
        assert!(
            book.add_limit_order(shared_id, PRICE, 10, Side::Buy, TimeInForce::Gtc, None)
                .is_ok(),
            "the freed id is reusable"
        );
        assert_eq!(count(&book), 0, "a Standard order is not strandable");

        assert!(
            book.add_limit_order(Id::new(), PRICE, 10, Side::Sell, TimeInForce::Gtc, None)
                .is_ok(),
            "a sweep consumes the plain order"
        );
        assert_eq!(count(&book), 0, "consuming it decrements nothing");
    }

    /// Every scoped mass-cancel entry point and TIF expiry eviction funnel
    /// through `cancel_order_with_reason`, so each decrements exactly.
    #[test]
    fn test_strandable_makers_resting_follows_every_mass_cancel_entry_point() {
        for label in ["by_side", "by_user", "by_price_range", "expiry"] {
            let book: OrderBook<()> = OrderBook::new("COUNT-MASS-PATHS");
            let user = pricelevel::Hash32::from([5u8; 32]);
            let mut order = reserve_buy(Id::new(), 10, 20, None, false);
            if let OrderType::ReserveOrder {
                user_id,
                time_in_force,
                ..
            } = &mut order
            {
                *user_id = user;
                if label == "expiry" {
                    // Far enough ahead that admission accepts it against
                    // the book's real clock; the eviction below steps past
                    // it explicitly.
                    *time_in_force = TimeInForce::Gtd(EXPIRY_DEADLINE_MS);
                }
            }
            assert!(book.add_order(order).is_ok(), "{label}: the reserve rests");
            assert_eq!(count(&book), 1, "{label}: counted");

            match label {
                "by_side" => {
                    let removed = book.cancel_orders_by_side(Side::Buy);
                    assert_eq!(removed.cancelled_count(), 1, "{label}: one order cancelled");
                }
                "by_user" => {
                    let removed = book.cancel_orders_by_user(user);
                    assert_eq!(removed.cancelled_count(), 1, "{label}: one order cancelled");
                }
                "by_price_range" => {
                    let removed =
                        book.cancel_orders_by_price_range(Side::Buy, PRICE - 1, PRICE + 1);
                    assert_eq!(removed.cancelled_count(), 1, "{label}: one order cancelled");
                }
                _ => {
                    book.evict_expired_orders(TimestampMs::new(EXPIRY_DEADLINE_MS + 1));
                }
            }

            assert_eq!(count(&book), 0, "{label}: the count returns to zero");
        }
    }

    /// A cancel-then-add modify removes the maker and re-adds it, so the
    /// count is decremented and incremented and lands back at one.
    #[test]
    fn test_strandable_makers_resting_survives_a_cancel_then_add_modify() {
        let book: OrderBook<()> = OrderBook::new("COUNT-MODIFY");
        let maker = Id::new();
        assert!(
            book.add_order(reserve_buy(maker, 10, 20, None, false))
                .is_ok()
        );
        assert_eq!(count(&book), 1);

        let repriced = book.update_order(pricelevel::OrderUpdate::UpdatePrice {
            order_id: maker,
            new_price: Price::new(PRICE - 1),
        });
        assert!(repriced.is_ok(), "the re-price succeeds: {repriced:?}");

        assert_eq!(
            count(&book),
            1,
            "the cancel decremented and the re-add incremented"
        );
        match book.get_order(maker) {
            Some(order) => assert_eq!(order.price().as_u128(), PRICE - 1, "re-priced"),
            None => panic!("the re-priced maker must rest"),
        }
    }

    /// #230 / restore: a legacy package carrying the one shape `pricelevel`
    /// cannot execute — a non-auto reserve with no visible tranche — is
    /// rejected in the prepare phase, before any book state is touched, so
    /// the live book survives the failed restore untouched.
    /// Build a source book holding the ghost shape, the way a pre-#230 book
    /// could come to hold one: empty an admitted reserve's visible tranche
    /// through the level itself.
    fn book_holding_a_ghost(symbol: &str, ghost_id: Id) -> OrderBook<()> {
        let source: OrderBook<()> = OrderBook::new(symbol);
        assert!(
            source
                .add_order(reserve_buy(ghost_id, 10, 20, None, false))
                .is_ok(),
            "the reserve rests with a visible tranche"
        );
        {
            let level = source.bids.get(&PRICE).expect("the bid level exists");
            let emptied = level
                .value()
                .update_order(pricelevel::OrderUpdate::UpdateQuantity {
                    order_id: ghost_id,
                    new_quantity: Quantity::new(0),
                });
            assert!(
                emptied.is_ok(),
                "the level accepts the zero update: {emptied:?}"
            );
        }
        source
    }

    /// A destination book with state and configuration that a rejected
    /// restore must leave untouched.
    fn destination_with_state(symbol: &str, survivor: Id) -> OrderBook<()> {
        let mut destination: OrderBook<()> = OrderBook::new(symbol);
        destination.set_lot_size(5);
        destination.set_min_order_size(5);
        assert!(
            destination
                .add_limit_order(survivor, PRICE, 5, Side::Buy, TimeInForce::Gtc, None)
                .is_ok(),
            "the destination has state to protect"
        );
        destination
    }

    /// Assert a rejected restore left the destination exactly as it was.
    fn assert_destination_intact(book: &OrderBook<()>, survivor: Id, ghost_id: Id) {
        assert!(
            book.get_order(survivor).is_some(),
            "a rejected restore must leave the live book untouched"
        );
        assert!(
            book.get_order(ghost_id).is_none(),
            "nothing from the rejected package may land"
        );
        assert_eq!(
            book.best_bid(),
            Some(PRICE),
            "the destination's level survives"
        );
        assert_eq!(book.lot_size(), Some(5), "configuration survives");
        assert_eq!(book.min_order_size(), Some(5), "configuration survives");
    }

    /// The **direct** `restore_from_snapshot(&self)` path rejects the ghost
    /// in its prepare phase, before any state change.
    #[test]
    fn test_direct_restore_rejects_a_zero_visible_non_auto_reserve() {
        let ghost_id = Id::new();
        let source = book_holding_a_ghost("GHOST-DIRECT", ghost_id);
        let snapshot = source.create_snapshot(usize::MAX);

        let survivor = Id::new();
        let destination = destination_with_state("GHOST-DIRECT", survivor);

        match destination.restore_from_snapshot(snapshot) {
            Err(crate::orderbook::error::OrderBookError::ZeroVisibleTranche {
                order_id,
                hidden_quantity,
            }) => {
                assert_eq!(order_id, ghost_id);
                assert_eq!(hidden_quantity, 20);
            }
            other => panic!("expected ZeroVisibleTranche from the direct restore, got {other:?}"),
        }
        assert_destination_intact(&destination, survivor, ghost_id);
    }

    /// The **JSON** path rejects it too, through the same prepare phase.
    #[test]
    fn test_json_restore_rejects_a_zero_visible_non_auto_reserve() {
        let ghost_id = Id::new();
        let source = book_holding_a_ghost("GHOST-JSON", ghost_id);
        let json = match source.snapshot_to_json(usize::MAX) {
            Ok(json) => json,
            Err(error) => panic!("snapshot json must build: {error}"),
        };

        let survivor = Id::new();
        let mut destination = destination_with_state("GHOST-JSON", survivor);

        match destination.restore_from_snapshot_json(&json) {
            Err(crate::orderbook::error::OrderBookError::ZeroVisibleTranche {
                order_id,
                hidden_quantity,
            }) => {
                assert_eq!(order_id, ghost_id);
                assert_eq!(hidden_quantity, 20);
            }
            other => panic!("expected ZeroVisibleTranche from the json restore, got {other:?}"),
        }
        assert_destination_intact(&destination, survivor, ghost_id);
    }

    #[test]
    fn test_restore_rejects_a_package_holding_a_zero_visible_non_auto_reserve() {
        // Build the ghost on a source book by emptying the visible tranche
        // of an already-admitted reserve through the level itself, which is
        // how a pre-#230 book could come to hold one.
        let source: OrderBook<()> = OrderBook::new("GHOST-RESTORE");
        let ghost_id = Id::new();
        assert!(
            source
                .add_order(reserve_buy(ghost_id, 10, 20, None, false))
                .is_ok(),
            "the reserve rests with a visible tranche"
        );
        let level = source.bids.get(&PRICE).expect("the bid level exists");
        let emptied = level
            .value()
            .update_order(pricelevel::OrderUpdate::UpdateQuantity {
                order_id: ghost_id,
                new_quantity: Quantity::new(0),
            });
        assert!(
            emptied.is_ok(),
            "the level accepts the zero update: {emptied:?}"
        );
        let package = match source.create_snapshot_package(usize::MAX) {
            Ok(package) => package,
            Err(error) => panic!("snapshot package must build: {error}"),
        };

        // The destination holds a healthy order that must survive.
        let mut destination: OrderBook<()> = OrderBook::new("GHOST-RESTORE");
        let survivor = Id::new();
        assert!(
            destination
                .add_limit_order(survivor, PRICE, 5, Side::Buy, TimeInForce::Gtc, None)
                .is_ok(),
            "the destination has state to protect"
        );

        match destination.restore_from_snapshot_package(package) {
            Err(crate::orderbook::error::OrderBookError::ZeroVisibleTranche {
                order_id,
                hidden_quantity,
            }) => {
                assert_eq!(order_id, ghost_id, "the offending order is named");
                assert_eq!(hidden_quantity, 20, "the stranded tranche is reported");
            }
            other => panic!("expected ZeroVisibleTranche from the restore, got {other:?}"),
        }

        assert!(
            destination.get_order(survivor).is_some(),
            "a rejected restore must leave the live book untouched"
        );
        assert!(
            destination.get_order(ghost_id).is_none(),
            "nothing from the rejected package may land"
        );
        assert_eq!(
            destination.best_bid(),
            Some(PRICE),
            "the destination's own level survives"
        );
    }

    /// The two self-trade-prevention pre-match arms capture too (#230,
    /// coverage): under `CancelTaker`, a same-user taker sweeping a level
    /// that holds a strandable maker fills the non-self depth ahead of it,
    /// is cancelled at the same-user maker, and leaves that maker intact —
    /// so the count does not move and no discard is reported.
    #[test]
    fn test_stp_cancel_taker_arm_captures_without_removing_the_maker() {
        use crate::orderbook::stp::STPMode;

        let user = pricelevel::Hash32::from([7u8; 32]);
        let book: OrderBook<()> = OrderBook::with_stp_mode("STP-CAPTURE", STPMode::CancelTaker);

        // A strandable maker owned by the same user as the incoming taker,
        // resting behind a foreign maker at the same price.
        let foreign = Id::new();
        assert!(
            book.add_limit_order_with_user(
                foreign,
                PRICE,
                3,
                Side::Buy,
                TimeInForce::Gtc,
                pricelevel::Hash32::from([9u8; 32]),
                None,
            )
            .is_ok(),
            "the foreign maker rests first"
        );
        let mut strandable = reserve_buy(Id::new(), 10, 20, None, false);
        let strandable_id = strandable.id();
        if let OrderType::ReserveOrder { user_id, .. } = &mut strandable {
            *user_id = user;
        }
        assert!(book.add_order(strandable).is_ok(), "the reserve rests");
        assert_eq!(count(&book), 1, "the strandable maker is counted");

        // The same user sells into the level: it may take the foreign depth,
        // then STP cancels it at its own maker.
        let taker = book.add_limit_order_with_user(
            Id::new(),
            PRICE,
            8,
            Side::Sell,
            TimeInForce::Gtc,
            user,
            None,
        );
        assert!(
            taker.is_err(),
            "CancelTaker must cancel the self-crossing taker: {taker:?}"
        );

        match book.get_order(strandable_id) {
            Some(order) => assert_eq!(
                (
                    order.visible_quantity().as_u64(),
                    order.hidden_quantity().as_u64()
                ),
                (10, 20),
                "the same-user maker is untouched by its own taker"
            ),
            None => panic!("the strandable maker must survive the STP cancel"),
        }
        assert_eq!(
            count(&book),
            1,
            "nothing was discarded, so the count does not move"
        );
    }

    /// The gate only controls *reporting*, never matching: a book whose
    /// flag was never armed still discards a non-auto reserve maker's
    /// hidden tranche exactly as before. (It cannot actually happen — the
    /// maker could not be resting without arming the gate — so this pins
    /// that the two concerns stay separate.)
    #[test]
    fn test_strandable_scan_gate_does_not_change_matching_outcome() {
        let book: OrderBook<()> = OrderBook::new("FLAG-SEMANTICS");
        let maker_id = Id::new();
        assert!(
            book.add_order(reserve_buy(maker_id, 10, 20, None, false))
                .is_ok(),
            "the maker must rest"
        );
        // Close the gate behind the maker's back, then sweep it.
        book.strandable_makers_resting.store(0, Ordering::Relaxed);
        assert!(
            book.add_limit_order(Id::new(), PRICE, 10, Side::Sell, TimeInForce::Gtc, None)
                .is_ok(),
            "the crossing sell must be accepted"
        );

        assert!(
            book.get_order(maker_id).is_none(),
            "the depleted non-replenishing maker leaves the book either way"
        );
        assert!(
            book.best_bid().is_none(),
            "the emptied level is removed either way"
        );
    }

    /// `UpdateQuantity { new_quantity: 0 }` is a removal, not a resize
    /// (#223), and it funnels through the same `cancel_order_with_reason`
    /// a user cancel does — so it decrements the count on the counted path,
    /// once per maker and never twice. Two strandable makers make the
    /// "once" observable: a double decrement on the first would close the
    /// gate while the second is still resting.
    #[test]
    fn test_strandable_makers_resting_returns_to_zero_on_a_zero_quantity_update() {
        let book: OrderBook<()> = OrderBook::new("COUNT-ZERO-UPDATE");
        let first = Id::new();
        let second = Id::new();
        assert!(
            book.add_order(reserve_buy(first, 10, 20, None, false))
                .is_ok()
        );
        assert!(
            book.add_order(reserve_buy(second, 10, 20, None, false))
                .is_ok()
        );
        assert_eq!(count(&book), 2, "both strandable makers are counted");

        let zero_update = |order_id: Id| {
            book.update_order(pricelevel::OrderUpdate::UpdateQuantity {
                order_id,
                new_quantity: Quantity::new(0),
            })
        };

        assert!(
            matches!(zero_update(first), Ok(Some(_))),
            "the zero update removes the first maker"
        );
        assert_eq!(count(&book), 1, "exactly one decrement");
        assert!(
            armed(&book),
            "the second maker still rests, so the scan stays armed"
        );

        assert!(
            matches!(zero_update(second), Ok(Some(_))),
            "the zero update removes the second maker"
        );
        assert_eq!(count(&book), 0, "the gate closes again");
        assert!(!armed(&book), "no scan is armed once none rest");

        // Nothing is left to consume, so a later sweep cannot decrement a
        // second time for makers this path already removed.
        assert!(
            book.add_limit_order(Id::new(), PRICE, 10, Side::Sell, TimeInForce::Gtc, None)
                .is_ok(),
            "a later sweep finds nothing to consume"
        );
        assert_eq!(count(&book), 0, "no second decrement");
    }
}