pricelevel 0.9.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
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
#[cfg(test)]
mod tests {
    use crate::execution::list::TradeList;
    use crate::execution::match_result::{MatchOutcome, MatchResult};
    use crate::execution::trade::Trade;
    use crate::orders::{Id, Side};
    use crate::utils::{Price, Quantity, TimestampMs};
    use std::str::FromStr;
    use uuid::Uuid;

    fn parse_uuid(input: &str) -> Uuid {
        match Uuid::parse_str(input) {
            Ok(value) => value,
            Err(error) => panic!("failed to parse uuid: {error}"),
        }
    }

    fn sample_trade(quantity: u64) -> Trade {
        sample_trade_with_maker(20, quantity)
    }

    fn sample_trade_with_maker(maker_id: u64, quantity: u64) -> Trade {
        Trade::with_timestamp(
            Id::from_uuid(parse_uuid("6ba7b810-9dad-11d1-80b4-00c04fd430c8")),
            Id::from_u64(10),
            Id::from_u64(maker_id),
            Price::new(1_000),
            Quantity::new(quantity),
            Side::Buy,
            TimestampMs::new(1_616_823_000_000),
        )
    }

    #[test]
    fn add_trade_updates_remaining_and_trades() {
        let mut result = MatchResult::new(Id::from_u64(10), Quantity::new(100));
        assert!(result.add_trade(sample_trade(25)).is_ok());

        assert_eq!(result.remaining_quantity().as_u64(), 75);
        assert_eq!(result.trades().len(), 1);
        assert!(!result.is_complete());
    }

    #[test]
    fn display_and_parse_use_trades_field() {
        let mut result = MatchResult::new(Id::from_u64(10), Quantity::new(100));
        assert!(result.add_trade(sample_trade(40)).is_ok());

        let rendered = result.to_string();
        assert!(rendered.contains(";trades=Trades:[Trade:"));

        let parsed = match MatchResult::from_str(&rendered) {
            Ok(value) => value,
            Err(error) => panic!("failed to parse match result: {error:?}"),
        };

        assert_eq!(parsed.trades().len(), 1);
        assert_eq!(parsed.remaining_quantity().as_u64(), 60);
    }

    #[test]
    fn add_trade_keeps_outcome_in_sync() {
        // No trades yet -> the default benign classification.
        let mut result = MatchResult::new(Id::from_u64(10), Quantity::new(100));
        assert_eq!(result.outcome(), MatchOutcome::NotFilled);

        // Partial fill.
        assert!(result.add_trade(sample_trade(40)).is_ok());
        assert_eq!(result.outcome(), MatchOutcome::PartiallyFilled);
        assert!(!result.was_killed());
        assert!(!result.was_rejected());

        // Complete fill.
        assert!(result.add_trade(sample_trade(60)).is_ok());
        assert_eq!(result.outcome(), MatchOutcome::Filled);
        assert!(result.is_complete());
    }

    #[test]
    fn outcome_survives_serde_json_roundtrip() {
        let mut result = MatchResult::new(Id::from_u64(10), Quantity::new(100));
        assert!(result.add_trade(sample_trade(40)).is_ok());

        let json = serde_json::to_string(&result).expect("serialize match result");
        let parsed: MatchResult = serde_json::from_str(&json).expect("deserialize match result");

        assert_eq!(parsed.outcome(), MatchOutcome::PartiallyFilled);
        assert_eq!(parsed.remaining_quantity().as_u64(), 60);
        assert_eq!(parsed.trades().len(), 1);
    }

    #[test]
    fn outcome_defaults_when_absent_from_json() {
        // A JSON payload written before the `outcome` field existed must still
        // deserialize (the field is `#[serde(default)]`). Build a current JSON,
        // then strip the `outcome` key to emulate the legacy shape.
        let result = MatchResult::new(Id::from_u64(10), Quantity::new(70));
        let mut value: serde_json::Value =
            serde_json::to_value(&result).expect("serialize match result");
        value
            .as_object_mut()
            .expect("object")
            .remove("outcome")
            .expect("current payload carries an outcome field");
        let legacy = serde_json::to_string(&value).expect("re-serialize legacy payload");

        let parsed: MatchResult =
            serde_json::from_str(&legacy).expect("legacy match result must deserialize");
        assert_eq!(parsed.outcome(), MatchOutcome::NotFilled);
        assert_eq!(parsed.remaining_quantity().as_u64(), 70);
    }

    #[test]
    fn from_str_rejects_old_transactions_field() {
        let old_payload = "MatchResult:order_id=1;remaining_quantity=1;is_complete=false;transactions=Transactions:[];filled_order_ids=[]";
        let parsed = MatchResult::from_str(old_payload);
        assert!(parsed.is_err());
    }

    #[test]
    fn add_trade_rejects_underflow() {
        let mut result = MatchResult::new(Id::from_u64(10), Quantity::new(10));
        let error = result.add_trade(sample_trade(11));
        assert!(error.is_err());
        assert_eq!(result.remaining_quantity().as_u64(), 10);
        assert_eq!(result.trades().len(), 0);
    }

    #[test]
    fn executed_value_rejects_overflow() {
        let mut result = MatchResult::new(Id::from_u64(10), Quantity::new(4));

        let trade = Trade::with_timestamp(
            Id::from_uuid(parse_uuid("6ba7b810-9dad-11d1-80b4-00c04fd430c8")),
            Id::from_u64(10),
            Id::from_u64(20),
            Price::new(u128::MAX),
            Quantity::new(2),
            Side::Buy,
            TimestampMs::new(1_616_823_000_000),
        );

        assert!(result.add_trade(trade).is_ok());
        assert!(result.executed_value().is_err());
    }

    // ----- average_price edge cases -----
    //
    // `average_price()` returns `Result<Option<f64>, PriceLevelError>` and
    // computes `executed_value as f64 / executed_quantity as f64`, guarding
    // the zero-quantity case so it never divides by zero. These tests pin the
    // zero-quantity, precision-loss, and never-NaN/Inf behavior. The
    // happy-path (exact) average is covered by
    // `test_average_price_exact_small_values_is_precise` below.

    /// No trades have been added, so executed quantity is zero and there is no
    /// average price to report: `average_price()` must return `Ok(None)`
    /// (never an error, never a division by zero, never NaN).
    #[test]
    fn test_average_price_zero_executed_quantity_returns_none() {
        let result = MatchResult::new(Id::from_u64(10), Quantity::new(100));

        match result.average_price() {
            Ok(None) => {}
            other => panic!("expected Ok(None) for zero executed quantity, got {other:?}"),
        }
    }

    /// A single trade whose `price` and `quantity` are exactly representable in
    /// `f64` yields an exact average. Pins that the common case is precise and
    /// never NaN/Inf.
    #[test]
    fn test_average_price_exact_small_values_is_precise() {
        let mut result = MatchResult::new(Id::from_u64(10), Quantity::new(100));

        // price 1000, quantity 30 -> value 30_000, avg 1000.0 exactly.
        assert!(result.add_trade(sample_trade(30)).is_ok());

        match result.average_price() {
            Ok(Some(avg)) => {
                assert!(avg.is_finite(), "average price must be finite");
                assert!((avg - 1000.0_f64).abs() < f64::EPSILON);
            }
            other => panic!("expected Ok(Some(1000.0)), got {other:?}"),
        }
    }

    /// Large value/quantity case where `f64`'s 53-bit integer mantissa cannot
    /// represent the exact integer average.
    ///
    /// A single trade with `price = 2^53 + 1` and `quantity = 1` has an exact
    /// integer average of `9_007_199_254_740_993`, but `average_price()`
    /// returns `9_007_199_254_740_992.0` because `2^53 + 1` is not
    /// representable as an `f64` (it rounds to `2^53`). This is a documented,
    /// intrinsic limitation of using `f64` for the analytics average — the
    /// matching path itself keeps exact integer `Price`/`Quantity` math and
    /// only `average_price` drops to `f64`.
    ///
    /// We therefore do NOT assert exact equality with the integer average.
    /// Instead we assert the result is finite and within a small absolute
    /// tolerance (well under 1 ULP-worth of drift at this magnitude, here a
    /// fixed difference of exactly 1).
    #[test]
    fn test_average_price_large_values_loses_f64_precision_but_stays_finite() {
        const PRICE: u128 = (1_u128 << 53) + 1; // 9_007_199_254_740_993
        const EXACT_INT_AVG: u128 = PRICE; // quantity == 1, so average == price

        let mut result = MatchResult::new(Id::from_u64(10), Quantity::new(1));
        let trade = Trade::with_timestamp(
            Id::from_uuid(parse_uuid("6ba7b810-9dad-11d1-80b4-00c04fd430c8")),
            Id::from_u64(10),
            Id::from_u64(20),
            Price::new(PRICE),
            Quantity::new(1),
            Side::Buy,
            TimestampMs::new(1_616_823_000_000),
        );
        assert!(result.add_trade(trade).is_ok());

        match result.average_price() {
            Ok(Some(avg)) => {
                // Never NaN/Inf for a valid, in-range input.
                assert!(avg.is_finite(), "average price must be finite");
                assert!(!avg.is_nan(), "average price must not be NaN");
                assert!(!avg.is_infinite(), "average price must not be Inf");

                // Document the observed drift: the exact integer average is
                // 2^53 + 1, but f64 has only a 53-bit mantissa and the division
                // rounds it down to 2^53.
                assert_eq!(
                    avg, 9_007_199_254_740_992.0_f64,
                    "observed f64 average rounds 2^53 + 1 down to 2^53"
                );

                // Show the loss in INTEGER space. Comparing `EXACT_INT_AVG as
                // f64` would round the same way and hide the drift (abs_err
                // would be 0), so convert the f64 result back to an integer and
                // prove it is short of the exact integer average by exactly 1.
                let avg_as_int = avg as u128;
                assert_eq!(
                    EXACT_INT_AVG - avg_as_int,
                    1,
                    "f64 average loses exactly 1 vs the exact integer average (2^53 + 1)"
                );
            }
            other => panic!("expected Ok(Some(_)), got {other:?}"),
        }
    }

    /// For valid inputs producing trades, `average_price()` must never yield a
    /// NaN or infinite value. Sweeps a handful of (price, quantity) inputs and
    /// asserts finiteness on each.
    #[test]
    fn test_average_price_valid_inputs_never_nan_or_inf() {
        let cases: [(u128, u64); 4] = [
            (1, 1),
            (1_000, 7),
            (u64::MAX as u128, 3),
            ((1_u128 << 60) + 5, 11),
        ];

        for (idx, (price, quantity)) in cases.into_iter().enumerate() {
            let mut result = MatchResult::new(Id::from_u64(10), Quantity::new(quantity));
            let trade = Trade::with_timestamp(
                Id::from_uuid(parse_uuid("6ba7b810-9dad-11d1-80b4-00c04fd430c8")),
                Id::from_u64(10),
                Id::from_u64(20),
                Price::new(price),
                Quantity::new(quantity),
                Side::Buy,
                TimestampMs::new(1_616_823_000_000),
            );
            assert!(result.add_trade(trade).is_ok());

            match result.average_price() {
                Ok(Some(avg)) => {
                    assert!(
                        avg.is_finite(),
                        "case {idx}: average must be finite (price={price}, qty={quantity})"
                    );
                }
                other => panic!("case {idx}: expected Ok(Some(_)), got {other:?}"),
            }
        }
    }

    // ----- issue #114: malformed UTF-8 must parse to Err, never panic -----
    //
    // `MatchResult::from_str` accepts untrusted text and must return a
    // `Result`, so a multibyte Unicode scalar sitting before the next ASCII
    // delimiter must not make an internal byte offset land inside the scalar
    // and panic on a non-char-boundary slice. Each case below simply calls
    // `from_str` and asserts `Err`: a plain call is enough to prove no panic,
    // because a panic would unwind the test rather than reach the assertion.

    /// Every field position that the byte scanners walk — a plain field value,
    /// a value that runs to the end of the string with no trailing `;`, a
    /// field name, the `trades` bracket body, and the `filled_order_ids`
    /// bracket body — must reject 2-, 3-, and 4-byte scalars deterministically.
    #[test]
    fn from_str_rejects_multibyte_without_panicking() {
        // 'é' = 2 bytes, '→' = 3 bytes, '😀' = 4 bytes: cover every UTF-8 width
        // and a scalar straddling each delimiter position.
        let malformed = [
            // Multibyte in a field value immediately before the ';' delimiter.
            "MatchResult:order_id=é;remaining_quantity=60;is_complete=false;\
             trades=Trades:[];filled_order_ids=[]",
            "MatchResult:order_id=→;remaining_quantity=60;is_complete=false;\
             trades=Trades:[];filled_order_ids=[]",
            // Multibyte in the LAST-scanned value that runs to end-of-string
            // (no trailing ';'): exercises the find-to-end branch.
            "MatchResult:order_id=10😀",
            // Multibyte in a field NAME (before the '=').
            "MatchResult:é=10;remaining_quantity=60;is_complete=false;\
             trades=Trades:[];filled_order_ids=[]",
            // Multibyte inside the trades bracket body.
            "MatchResult:order_id=10;remaining_quantity=60;is_complete=false;\
             trades=Trades:[é];filled_order_ids=[]",
            "MatchResult:order_id=10;remaining_quantity=60;is_complete=false;\
             trades=Trades:[😀];filled_order_ids=[]",
            // Multibyte inside the filled_order_ids bracket list.
            "MatchResult:order_id=10;remaining_quantity=60;is_complete=false;\
             trades=Trades:[];filled_order_ids=[é]",
            "MatchResult:order_id=10;remaining_quantity=60;is_complete=false;\
             trades=Trades:[];filled_order_ids=[1,→,2]",
            // Multibyte right where the '=' after a field name is expected.
            "MatchResult:order_idé=10;remaining_quantity=60;is_complete=false;\
             trades=Trades:[];filled_order_ids=[]",
        ];

        for input in malformed {
            let parsed = MatchResult::from_str(input);
            assert!(
                parsed.is_err(),
                "malformed multibyte input must parse to Err, got Ok for {input:?}"
            );
        }
    }

    /// A multibyte scalar that lands exactly on the byte offset where the
    /// scanner probes for the closing `]` of each bracket must not panic — the
    /// bracket depth stays unbalanced and the parse fails cleanly.
    #[test]
    fn from_str_rejects_unterminated_multibyte_bracket() {
        let inputs = [
            // trades bracket opened, then a multibyte scalar, then end.
            "MatchResult:order_id=10;remaining_quantity=60;is_complete=false;\
             trades=Trades:[é",
            // filled_order_ids bracket opened, then a multibyte scalar, then end.
            "MatchResult:order_id=10;remaining_quantity=60;is_complete=false;\
             trades=Trades:[];filled_order_ids=[😀",
        ];
        for input in inputs {
            assert!(
                MatchResult::from_str(input).is_err(),
                "unterminated multibyte bracket must parse to Err for {input:?}"
            );
        }
    }

    /// Canonical ASCII output from `Display` — including a populated
    /// `filled_order_ids` list and multiple trades — must keep round-tripping
    /// unchanged through `FromStr`.
    #[test]
    fn display_round_trips_with_filled_ids_and_trades() {
        // Two makers (20 and 21) each fully consumed, so each is both a trade
        // maker and a filled id — the shape the engine actually produces.
        let mut result = MatchResult::new(Id::from_u64(10), Quantity::new(100));
        assert!(result.add_trade(sample_trade_with_maker(20, 30)).is_ok());
        assert!(result.add_trade(sample_trade_with_maker(21, 20)).is_ok());
        result.add_filled_order_id(Id::from_u64(20));
        result.add_filled_order_id(Id::from_u64(21));

        let rendered = result.to_string();
        let parsed = match MatchResult::from_str(&rendered) {
            Ok(value) => value,
            Err(error) => panic!("valid canonical output must round-trip: {error:?}"),
        };

        assert_eq!(parsed.order_id(), Id::from_u64(10));
        assert_eq!(parsed.remaining_quantity().as_u64(), 50);
        assert!(!parsed.is_complete());
        assert_eq!(parsed.trades().len(), 2);
        assert_eq!(
            parsed.filled_order_ids(),
            &[Id::from_u64(20), Id::from_u64(21)]
        );
        // Rendering the parsed result reproduces the exact canonical text.
        assert_eq!(parsed.to_string(), rendered);
    }

    // ----- issue #116: invariants enforced during decoding -----
    //
    // Private fields protect Rust-API construction, but `Deserialize` and
    // `FromStr` reconstruct fields directly. Both now route through
    // `MatchResult::validated`, so a self-contradictory payload is rejected
    // (serde error / `PriceLevelError`) instead of minting an impossible value.
    // Every payload a public-API-built result can produce still decodes.

    /// A valid `MatchResult` carrying trades and filled ids round-trips through
    /// serde JSON with all fields (including `outcome`) intact.
    #[test]
    fn valid_result_with_filled_ids_round_trips_serde_json() {
        let mut result = MatchResult::new(Id::from_u64(10), Quantity::new(100));
        assert!(result.add_trade(sample_trade_with_maker(20, 40)).is_ok());
        result.add_filled_order_id(Id::from_u64(20));

        let json = serde_json::to_string(&result).expect("serialize");
        let parsed: MatchResult = serde_json::from_str(&json).expect("valid payload must decode");

        assert_eq!(parsed.order_id(), Id::from_u64(10));
        assert_eq!(parsed.remaining_quantity().as_u64(), 60);
        assert!(!parsed.is_complete());
        assert_eq!(parsed.outcome(), MatchOutcome::PartiallyFilled);
        assert_eq!(parsed.trades().len(), 1);
        assert_eq!(parsed.filled_order_ids(), &[Id::from_u64(20)]);
    }

    /// A genuinely killed / rejected result (no trades, no filled ids) still
    /// decodes — the outcome invariant only forbids a *populated* kill/reject.
    #[test]
    fn valid_killed_and_rejected_round_trip_serde_json() {
        for build in [
            MatchResult::mark_killed as fn(&mut MatchResult, u64),
            MatchResult::mark_rejected,
        ] {
            let mut result = MatchResult::new(Id::from_u64(10), Quantity::new(100));
            build(&mut result, 100);

            let json = serde_json::to_string(&result).expect("serialize");
            let parsed: MatchResult =
                serde_json::from_str(&json).expect("empty kill/reject must decode");

            assert_eq!(parsed.remaining_quantity().as_u64(), 100);
            assert!(!parsed.is_complete());
            assert!(parsed.trades().is_empty());
            assert!(parsed.filled_order_ids().is_empty());
            assert!(parsed.was_killed() || parsed.was_rejected());
        }
    }

    /// Helper: serialize a valid result, mutate the JSON object, and return the
    /// mutated JSON string so a negative test can feed it back to `from_str`.
    fn mutated_json(base: &MatchResult, mutate: impl FnOnce(&mut serde_json::Value)) -> String {
        let mut value = serde_json::to_value(base).expect("serialize base");
        mutate(&mut value);
        serde_json::to_string(&value).expect("re-serialize mutated payload")
    }

    /// Invariant 1: `is_complete == true` with a positive remainder is rejected.
    #[test]
    fn deserialize_rejects_complete_with_remainder() {
        // new(0) is complete with remainder 0; force a positive remainder.
        let base = MatchResult::new(Id::from_u64(10), Quantity::new(0));
        let json = mutated_json(&base, |v| {
            v["remaining_quantity"] = serde_json::json!(5);
        });
        assert!(serde_json::from_str::<MatchResult>(&json).is_err());
    }

    /// Invariant 3: a `Rejected` / `Killed` outcome may not carry trades.
    #[test]
    fn deserialize_rejects_trades_on_killed_or_rejected() {
        let mut base = MatchResult::new(Id::from_u64(10), Quantity::new(100));
        assert!(base.add_trade(sample_trade_with_maker(20, 40)).is_ok());

        for outcome in ["killed", "rejected"] {
            let json = mutated_json(&base, |v| {
                v["outcome"] = serde_json::json!(outcome);
            });
            assert!(
                serde_json::from_str::<MatchResult>(&json).is_err(),
                "{outcome} with trades must be rejected"
            );
        }
    }

    /// Invariant 3 (filled ids variant): a `Killed` outcome may not carry
    /// filled order ids either.
    #[test]
    fn deserialize_rejects_filled_ids_on_killed() {
        let mut base = MatchResult::new(Id::from_u64(10), Quantity::new(100));
        base.mark_killed(100);
        let json = mutated_json(&base, |v| {
            // Killed carries no trades; inject a filled id with no backing trade.
            v["filled_order_ids"] = serde_json::json!(["20"]);
        });
        assert!(serde_json::from_str::<MatchResult>(&json).is_err());
    }

    /// Invariant 2: trade quantities whose sum overflows `u64` are rejected.
    #[test]
    fn deserialize_rejects_executed_quantity_sum_overflow() {
        let mut base = MatchResult::new(Id::from_u64(10), Quantity::new(100));
        assert!(base.add_trade(sample_trade_with_maker(20, 40)).is_ok());
        assert!(base.add_trade(sample_trade_with_maker(21, 20)).is_ok());
        // Two trades each at u64::MAX overflow the checked sum.
        let json = mutated_json(&base, |v| {
            v["trades"]["trades"][0]["quantity"] = serde_json::json!(u64::MAX);
            v["trades"]["trades"][1]["quantity"] = serde_json::json!(u64::MAX);
        });
        assert!(serde_json::from_str::<MatchResult>(&json).is_err());
    }

    /// Invariant 2 (implied initial): executed quantity + remaining overflowing
    /// `u64` (an impossible initial taker quantity) is rejected.
    #[test]
    fn deserialize_rejects_executed_plus_remaining_overflow() {
        let mut base = MatchResult::new(Id::from_u64(10), Quantity::new(100));
        assert!(base.add_trade(sample_trade_with_maker(20, 40)).is_ok());
        let json = mutated_json(&base, |v| {
            v["trades"]["trades"][0]["quantity"] = serde_json::json!(u64::MAX);
            // Keep is_complete consistent with a positive remainder.
            v["remaining_quantity"] = serde_json::json!(5);
            v["is_complete"] = serde_json::json!(false);
        });
        assert!(serde_json::from_str::<MatchResult>(&json).is_err());
    }

    /// Invariant 4: a filled order id with no backing trade maker is rejected.
    #[test]
    fn deserialize_rejects_filled_id_absent_from_trades() {
        let mut base = MatchResult::new(Id::from_u64(10), Quantity::new(100));
        assert!(base.add_trade(sample_trade_with_maker(20, 40)).is_ok());
        base.add_filled_order_id(Id::from_u64(20));
        let json = mutated_json(&base, |v| {
            // 99 never traded.
            v["filled_order_ids"] = serde_json::json!(["20", "99"]);
        });
        assert!(serde_json::from_str::<MatchResult>(&json).is_err());
    }

    // ----- issue #116: the same invariants via FromStr -----

    /// `FromStr` rejects a structurally-valid text whose `is_complete` claim
    /// contradicts the remainder.
    #[test]
    fn from_str_rejects_complete_with_remainder() {
        let text = "MatchResult:order_id=10;remaining_quantity=5;is_complete=true;\
                    trades=Trades:[];filled_order_ids=[]";
        assert!(MatchResult::from_str(text).is_err());
    }

    /// `FromStr` rejects text whose trade quantities sum past `u64::MAX`.
    #[test]
    fn from_str_rejects_executed_quantity_sum_overflow() {
        let trades = TradeList::from_vec(vec![
            sample_trade_with_maker(20, u64::MAX),
            sample_trade_with_maker(21, u64::MAX),
        ]);
        let text = format!(
            "MatchResult:order_id=10;remaining_quantity=1;is_complete=false;\
             trades={trades};filled_order_ids=[]"
        );
        assert!(MatchResult::from_str(&text).is_err());
    }

    /// `FromStr` rejects text listing a filled id that is not a trade maker.
    #[test]
    fn from_str_rejects_filled_id_absent_from_trades() {
        let trades = TradeList::from_vec(vec![sample_trade_with_maker(20, 40)]);
        let text = format!(
            "MatchResult:order_id=10;remaining_quantity=60;is_complete=false;\
             trades={trades};filled_order_ids=[20,99]"
        );
        assert!(MatchResult::from_str(&text).is_err());
    }

    /// Structural tightening (#114 review follow-up): trailing content after the
    /// `filled_order_ids` closing `]` is now rejected, symmetric with the
    /// `trades` branch. Previously the `filled_order_ids` branch silently
    /// tolerated a missing `;` separator and parsed the trailing text as another
    /// field.
    #[test]
    fn from_str_rejects_trailing_content_after_filled_ids() {
        // A second `order_id=...` glued directly to the closing `]` with no `;`.
        let text = "MatchResult:order_id=10;remaining_quantity=0;is_complete=true;\
                    trades=Trades:[];filled_order_ids=[]order_id=10";
        assert!(
            MatchResult::from_str(text).is_err(),
            "trailing content after filled_order_ids ']' must be rejected"
        );
        // The canonical form (nothing after the ']') still parses.
        let ok = "MatchResult:order_id=10;remaining_quantity=0;is_complete=true;\
                  trades=Trades:[];filled_order_ids=[]";
        assert!(MatchResult::from_str(ok).is_ok());
    }

    // ----- property: from_str never panics on arbitrary UTF-8 -----
    //
    // A co-located `proptest` block (the `tests/proptest/` harness is reserved
    // for the nine matching invariants and drives `PriceLevel`, not the
    // parser, so a parser-robustness property does not fit there). `proptest`
    // reports any panic in the closure as a failing, shrinking case, so the
    // bodies just call `from_str` and drop the result.
    use proptest::prelude::*;

    /// Concatenate the format's structural delimiters with arbitrary Unicode
    /// scalars so multibyte characters land adjacent to (and straddling) every
    /// delimiter the byte scanners probe — the worst case for boundary safety.
    fn structural_fuzz() -> impl Strategy<Value = String> {
        let token = prop_oneof![
            Just("=".to_string()),
            Just(";".to_string()),
            Just("[".to_string()),
            Just("]".to_string()),
            Just("Trades:".to_string()),
            Just("order_id".to_string()),
            Just("remaining_quantity".to_string()),
            Just("is_complete".to_string()),
            Just("trades".to_string()),
            Just("filled_order_ids".to_string()),
            any::<char>().prop_map(|c| c.to_string()),
        ];
        prop::collection::vec(token, 0..24)
            .prop_map(|parts| format!("MatchResult:{}", parts.concat()))
    }

    proptest! {
        #![proptest_config(ProptestConfig { cases: 1024, ..ProptestConfig::default() })]

        /// Arbitrary UTF-8 strings (with the required prefix and bare) never
        /// panic; they either parse or return `Err`.
        #[test]
        fn from_str_never_panics_on_arbitrary_utf8(suffix in any::<String>()) {
            let with_prefix = format!("MatchResult:{suffix}");
            // The result is deliberately ignored — a panic (not an Err) is the
            // only way this can fail.
            let _ = MatchResult::from_str(&with_prefix);
            let _ = MatchResult::from_str(&suffix);
        }

        /// Delimiter-dense fuzz: multibyte scalars adjacent to every structural
        /// delimiter still never panic.
        #[test]
        fn from_str_never_panics_on_structural_fuzz(input in structural_fuzz()) {
            let _ = MatchResult::from_str(&input);
        }
    }

    /// An explicit outcome that contradicts the decoded fields is rejected:
    /// `Filled` with a positive remainder, `PartiallyFilled` with a zero
    /// remainder or without trades, `NotFilled` with trades, and a complete
    /// (zero-remainder) `Killed` / `Rejected`.
    #[test]
    fn deserialize_rejects_contradictory_explicit_outcome() {
        let mut partial = MatchResult::new(Id::from_u64(10), Quantity::new(100));
        assert!(partial.add_trade(sample_trade_with_maker(20, 40)).is_ok());
        let empty = MatchResult::new(Id::from_u64(10), Quantity::new(100));
        let complete = MatchResult::new(Id::from_u64(10), Quantity::new(0));

        // Filled with a positive remainder.
        let json = mutated_json(&partial, |v| {
            v["outcome"] = serde_json::json!("filled");
        });
        assert!(serde_json::from_str::<MatchResult>(&json).is_err());
        // PartiallyFilled with zero remainder / no trades.
        let json = mutated_json(&complete, |v| {
            v["outcome"] = serde_json::json!("partially_filled");
        });
        assert!(serde_json::from_str::<MatchResult>(&json).is_err());
        let json = mutated_json(&empty, |v| {
            v["outcome"] = serde_json::json!("partially_filled");
        });
        assert!(serde_json::from_str::<MatchResult>(&json).is_err());
        // NotFilled with trades present.
        let json = mutated_json(&partial, |v| {
            v["outcome"] = serde_json::json!("not_filled");
        });
        assert!(serde_json::from_str::<MatchResult>(&json).is_err());
        // A complete, empty Killed / Rejected (turned-away takers keep their
        // full quantity).
        for outcome in ["killed", "rejected"] {
            let json = mutated_json(&complete, |v| {
                v["outcome"] = serde_json::json!(outcome);
            });
            assert!(serde_json::from_str::<MatchResult>(&json).is_err());
        }
    }

    /// A legacy payload without an outcome key derives the benign
    /// classification from the other fields instead of being rejected.
    #[test]
    fn deserialize_legacy_payload_without_outcome_derives() {
        let mut partial = MatchResult::new(Id::from_u64(10), Quantity::new(100));
        assert!(partial.add_trade(sample_trade_with_maker(20, 40)).is_ok());
        let json = mutated_json(&partial, |v| {
            if let Some(obj) = v.as_object_mut() {
                obj.remove("outcome");
            }
        });
        let decoded = match serde_json::from_str::<MatchResult>(&json) {
            Ok(decoded) => decoded,
            Err(err) => panic!("legacy payload must decode: {err}"),
        };
        assert_eq!(decoded.outcome(), MatchOutcome::PartiallyFilled);
    }

    /// A trade whose taker order id differs from the result's incoming order id
    /// is rejected at decode time and by `add_trade`.
    #[test]
    fn taker_identity_enforced_on_decode_and_add_trade() {
        let mut base = MatchResult::new(Id::from_u64(10), Quantity::new(100));
        assert!(base.add_trade(sample_trade_with_maker(20, 40)).is_ok());

        let json = mutated_json(&base, |v| {
            v["order_id"] = serde_json::json!(Id::from_u64(999));
        });
        assert!(serde_json::from_str::<MatchResult>(&json).is_err());

        // add_trade mirrors the guard: sample trades carry taker id 10.
        let mut mismatched = MatchResult::new(Id::from_u64(999), Quantity::new(100));
        assert!(
            mismatched
                .add_trade(sample_trade_with_maker(20, 40))
                .is_err()
        );
    }

    /// Duplicate or out-of-order filled ids are rejected: the engine records
    /// each fully-consumed maker exactly once, in trade order.
    #[test]
    fn deserialize_rejects_duplicate_or_out_of_order_filled_ids() {
        let mut base = MatchResult::new(Id::from_u64(10), Quantity::new(100));
        assert!(base.add_trade(sample_trade_with_maker(20, 40)).is_ok());
        assert!(base.add_trade(sample_trade_with_maker(21, 60)).is_ok());
        base.add_filled_order_id(Id::from_u64(20));
        base.add_filled_order_id(Id::from_u64(21));

        let json = mutated_json(&base, |v| {
            v["filled_order_ids"] = serde_json::json!([Id::from_u64(20), Id::from_u64(20)]);
        });
        assert!(serde_json::from_str::<MatchResult>(&json).is_err());

        let json = mutated_json(&base, |v| {
            v["filled_order_ids"] = serde_json::json!([Id::from_u64(21), Id::from_u64(20)]);
        });
        assert!(serde_json::from_str::<MatchResult>(&json).is_err());
    }

    /// Build a valid `MatchResult` purely through the public API from a seed, so
    /// every invariant `validated` checks holds by construction: `add_trade`
    /// keeps `is_complete` / `remaining` / `outcome` in lockstep, and each
    /// filled id is a maker that just traded.
    fn build_valid_result(initial: u64, specs: &[(u64, u64, bool)]) -> MatchResult {
        let mut result = MatchResult::new(Id::from_u64(10), Quantity::new(initial));
        let mut remaining = initial;
        // A fully-consumed maker is recorded in filled_order_ids exactly once
        // (the engine removes it from the queue), so the generator must not
        // fill the same maker twice — the validator rejects duplicates.
        let mut filled = std::collections::HashSet::new();
        for &(maker, raw_qty, fill) in specs {
            if remaining == 0 {
                break;
            }
            // A trade of 1..=remaining keeps add_trade from underflowing.
            let qty = raw_qty % remaining + 1;
            if result
                .add_trade(sample_trade_with_maker(maker, qty))
                .is_ok()
            {
                remaining -= qty;
                if fill && filled.insert(maker) {
                    result.add_filled_order_id(Id::from_u64(maker));
                }
            }
        }
        result
    }

    /// #135 regression: the `Serialize` shape must be symmetric with the
    /// validated wire struct. Before the fix the bare `outcome` variant index
    /// landed where the wire's `Option` tag was expected and bincode decode
    /// failed with `UnexpectedVariant` on every payload 0.9.0 produced.
    #[test]
    fn bincode_round_trip_is_symmetric_issue_135() {
        // Empty result (NotFilled) — the minimal shape that 0.9.0 failed on.
        let empty = MatchResult::new(Id::from_u64(10), Quantity::new(100));
        let bytes = match bincode::serde::encode_to_vec(&empty, bincode::config::standard()) {
            Ok(bytes) => bytes,
            Err(error) => panic!("bincode encode failed: {error}"),
        };
        let decoded: MatchResult =
            match bincode::serde::decode_from_slice(&bytes, bincode::config::standard()) {
                Ok((value, _)) => value,
                Err(error) => panic!("bincode decode failed: {error}"),
            };
        assert_eq!(decoded.outcome(), MatchOutcome::NotFilled);
        assert_eq!(decoded.remaining_quantity().as_u64(), 100);

        // Partially filled result with a trade — outcome variant index 1.
        let mut partial = MatchResult::new(Id::from_u64(10), Quantity::new(100));
        assert!(partial.add_trade(sample_trade(25)).is_ok());
        let bytes = match bincode::serde::encode_to_vec(&partial, bincode::config::standard()) {
            Ok(bytes) => bytes,
            Err(error) => panic!("bincode encode failed: {error}"),
        };
        let decoded: MatchResult =
            match bincode::serde::decode_from_slice(&bytes, bincode::config::standard()) {
                Ok((value, _)) => value,
                Err(error) => panic!("bincode decode failed: {error}"),
            };
        assert_eq!(decoded.outcome(), MatchOutcome::PartiallyFilled);
        assert_eq!(decoded.remaining_quantity().as_u64(), 75);
        assert_eq!(decoded.trades().len(), 1);
    }

    /// #135 guard: wrapping `outcome` in `Some` on the serialize side must
    /// not change the JSON payload — serde flattens the option away, so the
    /// key still carries the bare snake_case value.
    #[test]
    fn json_payload_keeps_bare_outcome_issue_135() {
        let result = MatchResult::new(Id::from_u64(10), Quantity::new(100));
        let json = match serde_json::to_string(&result) {
            Ok(json) => json,
            Err(error) => panic!("json encode failed: {error}"),
        };
        assert!(
            json.contains("\"outcome\":\"not_filled\""),
            "outcome must stay a bare value in JSON, got: {json}"
        );
    }

    proptest! {
        #![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })]

        /// Any valid result built through the public API round-trips serde
        /// JSON (outcome preserved), bincode (positional, non-self-describing
        /// — pins the encode/decode shape symmetry of #135), and
        /// Display/FromStr (benign outcome re-derived identically) with no
        /// field drift — the validator never rejects a
        /// legitimately-constructed value.
        #[test]
        fn valid_result_round_trips_both_encodings(
            initial in 1u64..=100_000,
            specs in prop::collection::vec((20u64..=40, 1u64..=100_000, any::<bool>()), 0..12),
        ) {
            let original = build_valid_result(initial, &specs);

            // bincode is positional: it only decodes if the Serialize shape
            // matches the wire struct field-for-field (#135).
            let bytes = bincode::serde::encode_to_vec(&original, bincode::config::standard())
                .map_err(|e| TestCaseError::fail(format!("bincode encode: {e}")))?;
            let (bin_decoded, _): (MatchResult, usize) =
                bincode::serde::decode_from_slice(&bytes, bincode::config::standard())
                    .map_err(|e| TestCaseError::fail(format!("valid bincode must decode: {e}")))?;
            prop_assert_eq!(bin_decoded.order_id(), original.order_id());
            prop_assert_eq!(
                bin_decoded.remaining_quantity().as_u64(),
                original.remaining_quantity().as_u64()
            );
            prop_assert_eq!(bin_decoded.is_complete(), original.is_complete());
            prop_assert_eq!(bin_decoded.outcome(), original.outcome());
            prop_assert_eq!(bin_decoded.trades().len(), original.trades().len());
            prop_assert_eq!(bin_decoded.filled_order_ids(), original.filled_order_ids());

            // serde JSON must decode and preserve every field, outcome included.
            let json = serde_json::to_string(&original)
                .map_err(|e| TestCaseError::fail(format!("serialize: {e}")))?;
            let decoded: MatchResult = serde_json::from_str(&json)
                .map_err(|e| TestCaseError::fail(format!("valid json must decode: {e}")))?;
            prop_assert_eq!(decoded.order_id(), original.order_id());
            prop_assert_eq!(
                decoded.remaining_quantity().as_u64(),
                original.remaining_quantity().as_u64()
            );
            prop_assert_eq!(decoded.is_complete(), original.is_complete());
            prop_assert_eq!(decoded.outcome(), original.outcome());
            prop_assert_eq!(decoded.trades().len(), original.trades().len());
            prop_assert_eq!(decoded.filled_order_ids(), original.filled_order_ids());

            // Display / FromStr must reparse and preserve the text-carried fields.
            let text = original.to_string();
            let reparsed = MatchResult::from_str(&text)
                .map_err(|e| TestCaseError::fail(format!("valid text must reparse: {e}")))?;
            prop_assert_eq!(
                reparsed.remaining_quantity().as_u64(),
                original.remaining_quantity().as_u64()
            );
            prop_assert_eq!(reparsed.is_complete(), original.is_complete());
            prop_assert_eq!(reparsed.trades().len(), original.trades().len());
            prop_assert_eq!(reparsed.filled_order_ids(), original.filled_order_ids());
        }
    }
}