orderbook-py 0.16.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (225) hide show
  1. orderbook_py-0.16.0/CHANGELOG.md +4272 -0
  2. orderbook_py-0.16.0/Cargo.toml +285 -0
  3. orderbook_py-0.16.0/LICENSE +21 -0
  4. orderbook_py-0.16.0/Makefile +269 -0
  5. orderbook_py-0.16.0/PKG-INFO +61 -0
  6. orderbook_py-0.16.0/README.md +1997 -0
  7. orderbook_py-0.16.0/benches/concurrent/contention.rs +249 -0
  8. orderbook_py-0.16.0/benches/concurrent/mod.rs +14 -0
  9. orderbook_py-0.16.0/benches/concurrent/register.rs +260 -0
  10. orderbook_py-0.16.0/benches/mod.rs +56 -0
  11. orderbook_py-0.16.0/benches/order_book/add_only_hdr.rs +50 -0
  12. orderbook_py-0.16.0/benches/order_book/add_only_risk_hdr.rs +124 -0
  13. orderbook_py-0.16.0/benches/order_book/add_orders.rs +172 -0
  14. orderbook_py-0.16.0/benches/order_book/aggressive_walk_hdr.rs +123 -0
  15. orderbook_py-0.16.0/benches/order_book/alloc_count.rs +373 -0
  16. orderbook_py-0.16.0/benches/order_book/best_price_read_hdr.rs +119 -0
  17. orderbook_py-0.16.0/benches/order_book/cancel_only_hdr.rs +71 -0
  18. orderbook_py-0.16.0/benches/order_book/cancel_single_owner_hdr.rs +75 -0
  19. orderbook_py-0.16.0/benches/order_book/fill_single_owner_hdr.rs +70 -0
  20. orderbook_py-0.16.0/benches/order_book/hdr_common.rs +258 -0
  21. orderbook_py-0.16.0/benches/order_book/mass_cancel.rs +131 -0
  22. orderbook_py-0.16.0/benches/order_book/mass_cancel_burst_hdr.rs +62 -0
  23. orderbook_py-0.16.0/benches/order_book/mass_cancel_by_user_hdr.rs +68 -0
  24. orderbook_py-0.16.0/benches/order_book/match_orders.rs +133 -0
  25. orderbook_py-0.16.0/benches/order_book/matching.rs +67 -0
  26. orderbook_py-0.16.0/benches/order_book/mixed_70_20_10_hdr.rs +103 -0
  27. orderbook_py-0.16.0/benches/order_book/mixed_operations.rs +159 -0
  28. orderbook_py-0.16.0/benches/order_book/mod.rs +24 -0
  29. orderbook_py-0.16.0/benches/order_book/notional_walk_hdr.rs +123 -0
  30. orderbook_py-0.16.0/benches/order_book/pegged_reprice.rs +111 -0
  31. orderbook_py-0.16.0/benches/order_book/pending_stops.rs +274 -0
  32. orderbook_py-0.16.0/benches/order_book/pending_stops_hdr.rs +235 -0
  33. orderbook_py-0.16.0/benches/order_book/replay.rs +136 -0
  34. orderbook_py-0.16.0/benches/order_book/reserve_sweep_hdr.rs +354 -0
  35. orderbook_py-0.16.0/benches/order_book/snapshot.rs +150 -0
  36. orderbook_py-0.16.0/benches/order_book/stp_contention_hdr.rs +279 -0
  37. orderbook_py-0.16.0/benches/order_book/stp_sweep_hdr.rs +149 -0
  38. orderbook_py-0.16.0/benches/order_book/thin_book_sweep_hdr.rs +106 -0
  39. orderbook_py-0.16.0/benches/order_book/update_orders.rs +111 -0
  40. orderbook_py-0.16.0/benches/serialization.rs +91 -0
  41. orderbook_py-0.16.0/benches/simple/basic.rs +26 -0
  42. orderbook_py-0.16.0/benches/simple/mod.rs +1 -0
  43. orderbook_py-0.16.0/doc/README.md +66 -0
  44. orderbook_py-0.16.0/orderbook-go/README.md +46 -0
  45. orderbook_py-0.16.0/orderbook-py/Cargo.lock +826 -0
  46. orderbook_py-0.16.0/orderbook-py/Cargo.toml +21 -0
  47. orderbook_py-0.16.0/orderbook-py/README.md +37 -0
  48. orderbook_py-0.16.0/orderbook-py/src/lib.rs +466 -0
  49. orderbook_py-0.16.0/orderbook-py/tests/test_orderbook.py +86 -0
  50. orderbook_py-0.16.0/pyproject.toml +36 -0
  51. orderbook_py-0.16.0/python/orderbook_py/__init__.py +13 -0
  52. orderbook_py-0.16.0/python/orderbook_py/_orderbook.pyi +79 -0
  53. orderbook_py-0.16.0/python/orderbook_py/py.typed +0 -0
  54. orderbook_py-0.16.0/rust-toolchain.toml +2 -0
  55. orderbook_py-0.16.0/src/lib.rs +1900 -0
  56. orderbook_py-0.16.0/src/orderbook/book.rs +7307 -0
  57. orderbook_py-0.16.0/src/orderbook/book_change_event.rs +128 -0
  58. orderbook_py-0.16.0/src/orderbook/cache.rs +502 -0
  59. orderbook_py-0.16.0/src/orderbook/clock.rs +286 -0
  60. orderbook_py-0.16.0/src/orderbook/emission.rs +1401 -0
  61. orderbook_py-0.16.0/src/orderbook/error.rs +1304 -0
  62. orderbook_py-0.16.0/src/orderbook/fees.rs +702 -0
  63. orderbook_py-0.16.0/src/orderbook/implied_volatility/black_scholes.rs +810 -0
  64. orderbook_py-0.16.0/src/orderbook/implied_volatility/error.rs +216 -0
  65. orderbook_py-0.16.0/src/orderbook/implied_volatility/integration.rs +960 -0
  66. orderbook_py-0.16.0/src/orderbook/implied_volatility/mod.rs +53 -0
  67. orderbook_py-0.16.0/src/orderbook/implied_volatility/solver.rs +859 -0
  68. orderbook_py-0.16.0/src/orderbook/implied_volatility/types.rs +316 -0
  69. orderbook_py-0.16.0/src/orderbook/iterators.rs +420 -0
  70. orderbook_py-0.16.0/src/orderbook/manager.rs +1145 -0
  71. orderbook_py-0.16.0/src/orderbook/market_impact.rs +316 -0
  72. orderbook_py-0.16.0/src/orderbook/mass_cancel.rs +2168 -0
  73. orderbook_py-0.16.0/src/orderbook/matching.rs +3314 -0
  74. orderbook_py-0.16.0/src/orderbook/metrics.rs +289 -0
  75. orderbook_py-0.16.0/src/orderbook/mod.rs +129 -0
  76. orderbook_py-0.16.0/src/orderbook/modifications.rs +4011 -0
  77. orderbook_py-0.16.0/src/orderbook/nats.rs +1371 -0
  78. orderbook_py-0.16.0/src/orderbook/nats_book_change.rs +1477 -0
  79. orderbook_py-0.16.0/src/orderbook/nats_common.rs +1392 -0
  80. orderbook_py-0.16.0/src/orderbook/operations.rs +541 -0
  81. orderbook_py-0.16.0/src/orderbook/order_state.rs +1541 -0
  82. orderbook_py-0.16.0/src/orderbook/pool.rs +161 -0
  83. orderbook_py-0.16.0/src/orderbook/private.rs +650 -0
  84. orderbook_py-0.16.0/src/orderbook/reject_reason.rs +923 -0
  85. orderbook_py-0.16.0/src/orderbook/repricing.rs +938 -0
  86. orderbook_py-0.16.0/src/orderbook/risk.rs +3020 -0
  87. orderbook_py-0.16.0/src/orderbook/sequencer/error.rs +208 -0
  88. orderbook_py-0.16.0/src/orderbook/sequencer/file_journal.rs +2888 -0
  89. orderbook_py-0.16.0/src/orderbook/sequencer/in_memory_journal.rs +397 -0
  90. orderbook_py-0.16.0/src/orderbook/sequencer/journal.rs +119 -0
  91. orderbook_py-0.16.0/src/orderbook/sequencer/mod.rs +54 -0
  92. orderbook_py-0.16.0/src/orderbook/sequencer/replay.rs +3923 -0
  93. orderbook_py-0.16.0/src/orderbook/sequencer/types.rs +592 -0
  94. orderbook_py-0.16.0/src/orderbook/serialization.rs +1337 -0
  95. orderbook_py-0.16.0/src/orderbook/snapshot.rs +1096 -0
  96. orderbook_py-0.16.0/src/orderbook/statistics.rs +177 -0
  97. orderbook_py-0.16.0/src/orderbook/stop_orders.rs +1836 -0
  98. orderbook_py-0.16.0/src/orderbook/stop_protection.rs +264 -0
  99. orderbook_py-0.16.0/src/orderbook/stp.rs +599 -0
  100. orderbook_py-0.16.0/src/orderbook/tests/analytics_overflow.rs +509 -0
  101. orderbook_py-0.16.0/src/orderbook/tests/book.rs +1954 -0
  102. orderbook_py-0.16.0/src/orderbook/tests/concurrent_crossing_adds.rs +666 -0
  103. orderbook_py-0.16.0/src/orderbook/tests/core_boundaries.rs +408 -0
  104. orderbook_py-0.16.0/src/orderbook/tests/depth_analysis.rs +275 -0
  105. orderbook_py-0.16.0/src/orderbook/tests/enriched_snapshot_tests.rs +295 -0
  106. orderbook_py-0.16.0/src/orderbook/tests/error.rs +228 -0
  107. orderbook_py-0.16.0/src/orderbook/tests/fee_overflow.rs +680 -0
  108. orderbook_py-0.16.0/src/orderbook/tests/fixtures/book_serde_0_13_1.json +1 -0
  109. orderbook_py-0.16.0/src/orderbook/tests/fixtures/journal_0_13_1/segment-00000000000000000000.journal +0 -0
  110. orderbook_py-0.16.0/src/orderbook/tests/fixtures/snapshot_v3_0_13_1.json +1 -0
  111. orderbook_py-0.16.0/src/orderbook/tests/fixtures/snapshot_v4_0_14_pre286.json +1 -0
  112. orderbook_py-0.16.0/src/orderbook/tests/fixtures/snapshot_v4_resting_trailing_stop.json +1 -0
  113. orderbook_py-0.16.0/src/orderbook/tests/fixtures/snapshot_v5_0_14_0_pending_stops.json +1 -0
  114. orderbook_py-0.16.0/src/orderbook/tests/fixtures/trade_result_0_13_1.bincode +0 -0
  115. orderbook_py-0.16.0/src/orderbook/tests/fixtures/trade_result_0_13_1.json +1 -0
  116. orderbook_py-0.16.0/src/orderbook/tests/iterator_tests.rs +400 -0
  117. orderbook_py-0.16.0/src/orderbook/tests/journal_compat_0_13.rs +207 -0
  118. orderbook_py-0.16.0/src/orderbook/tests/level_removal_race.rs +194 -0
  119. orderbook_py-0.16.0/src/orderbook/tests/listener_emission.rs +1123 -0
  120. orderbook_py-0.16.0/src/orderbook/tests/lot_size_validation.rs +393 -0
  121. orderbook_py-0.16.0/src/orderbook/tests/market_impact_tests.rs +301 -0
  122. orderbook_py-0.16.0/src/orderbook/tests/market_metrics.rs +277 -0
  123. orderbook_py-0.16.0/src/orderbook/tests/mass_cancel_failures.rs +678 -0
  124. orderbook_py-0.16.0/src/orderbook/tests/match_abort.rs +1007 -0
  125. orderbook_py-0.16.0/src/orderbook/tests/matching.rs +382 -0
  126. orderbook_py-0.16.0/src/orderbook/tests/mod.rs +42 -0
  127. orderbook_py-0.16.0/src/orderbook/tests/modification_failures.rs +871 -0
  128. orderbook_py-0.16.0/src/orderbook/tests/modifications.rs +1290 -0
  129. orderbook_py-0.16.0/src/orderbook/tests/operations.rs +794 -0
  130. orderbook_py-0.16.0/src/orderbook/tests/order.rs +399 -0
  131. orderbook_py-0.16.0/src/orderbook/tests/order_placement_tests.rs +298 -0
  132. orderbook_py-0.16.0/src/orderbook/tests/post_trade_risk.rs +487 -0
  133. orderbook_py-0.16.0/src/orderbook/tests/repricing.rs +557 -0
  134. orderbook_py-0.16.0/src/orderbook/tests/restore_validation.rs +730 -0
  135. orderbook_py-0.16.0/src/orderbook/tests/reused_taker_id.rs +171 -0
  136. orderbook_py-0.16.0/src/orderbook/tests/serialize_tests.rs +132 -0
  137. orderbook_py-0.16.0/src/orderbook/tests/snapshot.rs +1155 -0
  138. orderbook_py-0.16.0/src/orderbook/tests/snapshot_walk.rs +118 -0
  139. orderbook_py-0.16.0/src/orderbook/tests/statistics_tests.rs +333 -0
  140. orderbook_py-0.16.0/src/orderbook/tests/stop_protection.rs +1128 -0
  141. orderbook_py-0.16.0/src/orderbook/tests/stp.rs +1481 -0
  142. orderbook_py-0.16.0/src/orderbook/tests/stp_concurrency.rs +1017 -0
  143. orderbook_py-0.16.0/src/orderbook/tests/strandable_gate_concurrency.rs +711 -0
  144. orderbook_py-0.16.0/src/orderbook/tests/strandable_maker_count.rs +796 -0
  145. orderbook_py-0.16.0/src/orderbook/tests/test_helpers.rs +19 -0
  146. orderbook_py-0.16.0/src/orderbook/tests/time_in_force.rs +118 -0
  147. orderbook_py-0.16.0/src/orderbook/tests/trailing_stops.rs +2065 -0
  148. orderbook_py-0.16.0/src/orderbook/tests/uuid.rs +128 -0
  149. orderbook_py-0.16.0/src/orderbook/tests/wire_compat_0_13.rs +115 -0
  150. orderbook_py-0.16.0/src/orderbook/trade.rs +945 -0
  151. orderbook_py-0.16.0/src/orderbook/user_orders.rs +287 -0
  152. orderbook_py-0.16.0/src/prelude.rs +95 -0
  153. orderbook_py-0.16.0/src/utils/counting_allocator.rs +248 -0
  154. orderbook_py-0.16.0/src/utils/mod.rs +12 -0
  155. orderbook_py-0.16.0/src/utils/tests/mod.rs +1 -0
  156. orderbook_py-0.16.0/src/utils/tests/time.rs +147 -0
  157. orderbook_py-0.16.0/src/utils/time.rs +127 -0
  158. orderbook_py-0.16.0/src/wire/bytes.rs +139 -0
  159. orderbook_py-0.16.0/src/wire/error.rs +48 -0
  160. orderbook_py-0.16.0/src/wire/framing.rs +234 -0
  161. orderbook_py-0.16.0/src/wire/inbound/cancel.rs +98 -0
  162. orderbook_py-0.16.0/src/wire/inbound/cancel_replace.rs +109 -0
  163. orderbook_py-0.16.0/src/wire/inbound/mass_cancel.rs +163 -0
  164. orderbook_py-0.16.0/src/wire/inbound/mod.rs +33 -0
  165. orderbook_py-0.16.0/src/wire/inbound/new_order.rs +462 -0
  166. orderbook_py-0.16.0/src/wire/mod.rs +194 -0
  167. orderbook_py-0.16.0/src/wire/outbound/book_update.rs +219 -0
  168. orderbook_py-0.16.0/src/wire/outbound/exec_report.rs +345 -0
  169. orderbook_py-0.16.0/src/wire/outbound/mod.rs +22 -0
  170. orderbook_py-0.16.0/src/wire/outbound/trade_print.rs +187 -0
  171. orderbook_py-0.16.0/tests/alloc_budget.rs +142 -0
  172. orderbook_py-0.16.0/tests/bincode_decode_bounds.rs +268 -0
  173. orderbook_py-0.16.0/tests/fee_tests.rs +471 -0
  174. orderbook_py-0.16.0/tests/metrics/metrics_tests.rs +508 -0
  175. orderbook_py-0.16.0/tests/metrics/mod.rs +26 -0
  176. orderbook_py-0.16.0/tests/unit/atomic_postonly_fok_tests.rs +347 -0
  177. orderbook_py-0.16.0/tests/unit/best_price_race_tests.rs +168 -0
  178. orderbook_py-0.16.0/tests/unit/book_coverage_tests.rs +701 -0
  179. orderbook_py-0.16.0/tests/unit/book_manager_cross_cancel_tests.rs +221 -0
  180. orderbook_py-0.16.0/tests/unit/clock_determinism_tests.rs +174 -0
  181. orderbook_py-0.16.0/tests/unit/common/mod.rs +7 -0
  182. orderbook_py-0.16.0/tests/unit/common/strategies.rs +126 -0
  183. orderbook_py-0.16.0/tests/unit/concurrent_level_statistics_tests.rs +195 -0
  184. orderbook_py-0.16.0/tests/unit/engine_seq_monotonic_tests.rs +99 -0
  185. orderbook_py-0.16.0/tests/unit/evict_expired_tests.rs +284 -0
  186. orderbook_py-0.16.0/tests/unit/filejournal_edge_case_tests.rs +605 -0
  187. orderbook_py-0.16.0/tests/unit/implied_volatility_tests.rs +261 -0
  188. orderbook_py-0.16.0/tests/unit/integration_workflow_tests.rs +541 -0
  189. orderbook_py-0.16.0/tests/unit/kill_switch_tests.rs +351 -0
  190. orderbook_py-0.16.0/tests/unit/manager_coverage_tests.rs +344 -0
  191. orderbook_py-0.16.0/tests/unit/manager_lifecycle_tests.rs +484 -0
  192. orderbook_py-0.16.0/tests/unit/market_order_by_amount_tests.rs +424 -0
  193. orderbook_py-0.16.0/tests/unit/mass_cancel_determinism_tests.rs +246 -0
  194. orderbook_py-0.16.0/tests/unit/mass_cancel_tests.rs +779 -0
  195. orderbook_py-0.16.0/tests/unit/matching_coverage_tests.rs +411 -0
  196. orderbook_py-0.16.0/tests/unit/matching_coverage_tests_extended.rs +269 -0
  197. orderbook_py-0.16.0/tests/unit/mod.rs +71 -0
  198. orderbook_py-0.16.0/tests/unit/modifications_coverage_tests.rs +336 -0
  199. orderbook_py-0.16.0/tests/unit/modify_atomic_tests.rs +234 -0
  200. orderbook_py-0.16.0/tests/unit/mutation_failure_atomicity_tests.rs +383 -0
  201. orderbook_py-0.16.0/tests/unit/operations_coverage_tests.rs +389 -0
  202. orderbook_py-0.16.0/tests/unit/operations_coverage_tests_extended.rs +388 -0
  203. orderbook_py-0.16.0/tests/unit/order_state_tests.rs +639 -0
  204. orderbook_py-0.16.0/tests/unit/private_coverage_tests.rs +658 -0
  205. orderbook_py-0.16.0/tests/unit/props_quantity_update_priority.rs +306 -0
  206. orderbook_py-0.16.0/tests/unit/reject_reason_tests.rs +195 -0
  207. orderbook_py-0.16.0/tests/unit/replay_config_tests.rs +613 -0
  208. orderbook_py-0.16.0/tests/unit/replay_coverage_tests.rs +643 -0
  209. orderbook_py-0.16.0/tests/unit/replay_determinism.rs +124 -0
  210. orderbook_py-0.16.0/tests/unit/replay_submit_error_tests.rs +1118 -0
  211. orderbook_py-0.16.0/tests/unit/repricing_determinism_tests.rs +646 -0
  212. orderbook_py-0.16.0/tests/unit/reserve_lot_size_tests.rs +544 -0
  213. orderbook_py-0.16.0/tests/unit/reserve_residual_policy_tests.rs +1346 -0
  214. orderbook_py-0.16.0/tests/unit/reserve_residual_replay_tests.rs +185 -0
  215. orderbook_py-0.16.0/tests/unit/restore_user_orders_determinism_tests.rs +201 -0
  216. orderbook_py-0.16.0/tests/unit/risk_layer_tests.rs +956 -0
  217. orderbook_py-0.16.0/tests/unit/sequencer_types_tests.rs +636 -0
  218. orderbook_py-0.16.0/tests/unit/snapshot_concurrency_tests.rs +152 -0
  219. orderbook_py-0.16.0/tests/unit/snapshot_restore_tests.rs +560 -0
  220. orderbook_py-0.16.0/tests/unit/special_order_restore_tests.rs +260 -0
  221. orderbook_py-0.16.0/tests/unit/stp_reachability_tests.rs +1352 -0
  222. orderbook_py-0.16.0/tests/unit/two_tranche_conservation_tests.rs +299 -0
  223. orderbook_py-0.16.0/tests/unit/update_price_and_quantity_two_tranche_tests.rs +294 -0
  224. orderbook_py-0.16.0/tests/unit/update_quantity_zero_tests.rs +827 -0
  225. orderbook_py-0.16.0/tests/unit/validation_tests.rs +823 -0
@@ -0,0 +1,4272 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ### Fixed
11
+
12
+ - **A pegged re-price sweep no longer trades on a stale touch (#328).** The
13
+ sweep read the best bid, best ask and mid once and priced every peg from
14
+ that copy, so a peg moved earlier in the sweep could make a later
15
+ opposite-side peg cross and trade: a taker fill at a price its owner never
16
+ sent, a wash trade between one user's pegs with STP off, a silent cancel
17
+ under `CancelMaker`, or a peg stuck on every sweep under `CancelTaker` /
18
+ `CancelBoth`. Each peg now reads the touch as it stands when it is
19
+ re-priced, and a peg does not count its own order: on its own side, a best
20
+ level holding only the peg is skipped for the next level (a mid peg no
21
+ longer ratchets, e.g. 150 then 175, on an unchanged book). A target that
22
+ would still cross is not sent: it is reported in
23
+ `RepricingResult::failed_orders` and the peg stays where it was. The cross
24
+ check and the re-insert run under the exclusive submit gate, so a
25
+ concurrent submit cannot move the touch in between and the no-trade
26
+ guarantee holds without serializing sweeps with submits.
27
+ Passive clamp, tick snap, price floor, #174 failure reporting, id-order
28
+ iteration (#106) and the #291 stale-registration release are unchanged.
29
+ New Criterion rows `pegged_reprice/sweep_moves/1000` and
30
+ `pegged_reprice/sweep_steady/1000`.
31
+
32
+ Compatibility: behaviour change only, no API, snapshot or wire format
33
+ change. A peg alone at the best level now prices off the next level
34
+ instead of its own quote, so repriced prices can differ from 0.16.0. A
35
+ re-price that would cross now appears in `failed_orders` instead of
36
+ trading.
37
+
38
+ ## [0.16.0] - 2026-11-13
39
+
40
+ A feature release: `tokio` becomes an optional dependency behind a `tokio`
41
+ feature, on by default (#324). Default builds are unchanged; a build with
42
+ `default-features = false` no longer has Tokio or `BookManagerTokio`, hence
43
+ the minor bump. Dependencies move to their latest stable releases. No
44
+ snapshot or wire format change.
45
+
46
+ ### Changed
47
+
48
+ - **Dependencies at their latest stable releases, declared as `X.Y`.**
49
+ Notably `async-nats` 0.50 → 0.52 (its `jetstream::Context` is what
50
+ `NatsTradePublisher::new` and `NatsBookChangePublisher::new` take, so users
51
+ of the `nats` feature need `async-nats` 0.52 too), `tokio` 1.54, `uuid`
52
+ 1.29, `either` 1.19, `proptest` 1.12 (dev); every other entry is written as
53
+ `X.Y` of its current release. No code change was needed. `bincode` stays at
54
+ 2.0: the 3.0.0 release on crates.io is a placeholder that does not compile.
55
+ - **`.codex/` and `.agents/` are no longer tracked** and are listed in
56
+ `.gitignore`. They hold local tooling configuration, never shipped in the
57
+ published crate (`Cargo.toml` `include` already left them out).
58
+
59
+ - **`tokio` is now an optional dependency behind a `tokio` feature (#324).**
60
+ Only `BookManagerTokio` and the `nats` publishers use it; the core order
61
+ book (matching, levels, snapshots) does not. The feature is in `default`,
62
+ so existing builds are unchanged. Build with `default-features = false` to
63
+ drop Tokio from the dependency graph; `BookManagerTokio` and its
64
+ re-exports in `prelude` and the crate root are then unavailable. The `nats`
65
+ feature enables `tokio`. A new CI job builds and lints the crate with
66
+ `--no-default-features` and checks that `cargo tree -e normal` shows no
67
+ Tokio.
68
+
69
+ ## [0.15.4] - 2026-11-05
70
+
71
+ A fix release: a match or market taker reusing a live id is refused (#321).
72
+ No public API or snapshot format change.
73
+
74
+ ### Fixed
75
+
76
+ - **A match or market taker reusing a live id is refused instead of trading
77
+ through the best price (#321).** `match_order*`, `match_limit_order*`,
78
+ `match_market_order*`, `match_market_order_by_amount*`, the
79
+ `submit_market_order*` wrappers and `match_orders_batch` now return
80
+ `DuplicateOrderId` when a resting order or pending stop owns the taker's id,
81
+ as `add_order` already did. Before, the level holding the id refused it as a
82
+ self-match and the sweep moved on: the taker filled at a worse price, every
83
+ order at the skipped level lost its priority, and the id was live twice. The
84
+ check runs under the submit gate ahead of the #240 and #244 checks, so nothing
85
+ trades and the resting order's state is unchanged. Compatibility: callers that
86
+ reused an id now get an error where they got fills; fresh ids match as before.
87
+
88
+ ## [0.15.3] - 2026-11-02
89
+
90
+ A concurrency fix release: snapshots taken during a cancel or sweep no
91
+ longer show emptied levels or gaps (#313), and `best_bid()` / `best_ask()`
92
+ no longer serve a stale or phantom price after a racing read (#309). No
93
+ public API or snapshot format change.
94
+
95
+ ### Fixed
96
+
97
+ - **`create_snapshot` no longer reports emptied levels or leaves gaps
98
+ under concurrent cancels and sweeps (#313).** Each side is now built by
99
+ walking the price-ordered level map (asks ascending, bids descending),
100
+ skipping any level with no orders and stopping after `depth` kept
101
+ levels. Before, a snapshot taken while a shared-gate cancel or sweep ran
102
+ could list a level at zero quantity (its last order gone, the level not
103
+ yet removed), or drop a level removed between key collection and read,
104
+ returning fewer than `depth` levels while more were resting.
105
+ `enriched_snapshot` / `enriched_snapshot_with_metrics` had the
106
+ zero-count half of the same bug and use the same walk. Levels holding
107
+ only hidden or reserve quantity still have orders and are kept.
108
+ Compatibility: on a quiescent book the output is identical (same levels,
109
+ same order), so `create_snapshot_package` checksums and replay
110
+ determinism are unchanged; no snapshot format change. Per-level
111
+ statistics stay advisory under concurrent sweeps.
112
+ - **`best_bid()` / `best_ask()` no longer serve a stale or phantom price
113
+ after a write that raced a read (#309).** The best-price cache was a
114
+ validity flag that every write cleared *before* its level change
115
+ completed, so a reader that walked the skiplist inside that window
116
+ stored the pre-write price as valid, and it stayed valid until the next
117
+ write; after a cancel it could name a level that no longer existed. The
118
+ post-only check, the headroom prechecks (`will_cross_market`),
119
+ `mid_price` and `spread` read the same value, so a non-crossing
120
+ post-only order could be refused with `PriceCrossing`. The cache is now
121
+ generation-tagged per side: each side's generation is bumped *after*
122
+ every level insert or removal completes (new level on admission,
123
+ emptied-level removal on cancel, fill or modify, `cancel_all_orders`,
124
+ snapshot restore), a reader loads it *before* walking and publishes
125
+ `(generation, price)` through a lock-free seqlock, and a hit requires
126
+ the published generation to be the current one. The price is now held
127
+ in two `AtomicU64` halves instead of a `crossbeam` `AtomicCell<u128>`,
128
+ which is not lock-free on stable Rust (it falls back to a global
129
+ striped lock). Adding to or leaving a level that stays linked no longer
130
+ clears the cache. Removing the cache outright was prototyped and
131
+ benchmarked too and rejected: with `scripts/bench_compare.sh --rounds 5`
132
+ against `main`, one `best_bid()` + `best_ask()` pair on a quiet
133
+ 10 000-order book went from 7 ns to 13 ns p50 without a cache and to
134
+ 5 ns with the generation-tagged one; with one writer moving the best
135
+ ask it went from 14 ns (main, serving stale values) to 53 ns p50 /
136
+ 384 ns p99 without a cache and to 6 ns / 13 ns with it. Every write
137
+ scenario (`add_only`, `mixed_70_20_10`, `cancel_only`,
138
+ `aggressive_walk`, `contended_add_4t` / `_8t`, `stp_cancel_maker`) is
139
+ within noise of `main` for both. New bench `best_price_read_hdr`
140
+ (`best_price_read` and `best_price_read_1w`, also in
141
+ `benches/compare`). Compatibility: no public API, snapshot format or
142
+ event change; `PriceLevelCache` stays private and is still not
143
+ serialized. The cache unit tests were rewritten for the new type; the
144
+ #310 high-price test is kept as a `u128::MAX` round trip through the
145
+ two halves.
146
+
147
+ ## [0.15.2] - 2026-11-02
148
+
149
+ A patch release: the fully deterministic constructor no longer derives a
150
+ default trade-ID namespace. The crate now declares its minimum Rust
151
+ version, 1.95. No public API or snapshot format change.
152
+
153
+ ### Fixed
154
+
155
+ - **`OrderBook::with_clock_and_namespace` no longer reads the wall clock.**
156
+ It used to build the book through `with_clock`, which derives the default
157
+ trade-ID namespace (wall-clock nanoseconds, the process id and the
158
+ process-wide construction counter) and then threw that namespace away.
159
+ It now assembles the book directly with the injected clock and namespace,
160
+ so it no longer derives the default namespace: building the book does not
161
+ read the wall clock or the process id and leaves the construction counter
162
+ untouched. (The `DashMap` indexes still seed std `RandomState`, which only
163
+ affects lookups.) `with_clock`, `new`,
164
+ `with_trade_listener` and `with_trade_and_price_level_listener` behave as
165
+ before: all four share one private constructor and still derive the
166
+ default namespace.
167
+ - `ReplayEngine::replay_from_with_clock_and_config` with a
168
+ `trade_id_namespace` builds the replayed book with
169
+ `with_clock_and_namespace`, so it no longer derives a default namespace
170
+ either.
171
+
172
+ ### Changed
173
+
174
+ - `Cargo.toml` declares `rust-version = "1.95"`, the oldest toolchain the
175
+ crate already needed (`AtomicU64::try_update`); older toolchains now get
176
+ a clear MSRV error instead of `E0658`.
177
+
178
+ ## [0.15.1] - 2026-11-02
179
+
180
+ A performance patch release: user-index removal no longer scans the
181
+ owner's resting orders (#311). No public API or snapshot format change.
182
+
183
+ ### Changed
184
+
185
+ - CI and `make coverage*` now require cargo-tarpaulin >= 0.37.5, the first
186
+ release that reads Rust 1.99 coverage data.
187
+ - **Performance: user-index removal no longer scans the owner's orders
188
+ (#311).** Each `user_orders` entry is an append-only list of
189
+ `(sequence, id)` slots, and `OrderLocation` carries the order's
190
+ sequence, so a cancel, filled maker or modify finds its slot by binary
191
+ search and marks it removed instead of shifting the owner's whole
192
+ list. One owner with `n` resting orders paid O(n) per removal, and
193
+ `cancel_orders_by_user` / `cancel_orders_by_side` O(n²); every
194
+ `add_limit_order` caller is that one owner (`Hash32::zero()`). Adds
195
+ stay a single push, admission order for `cancel_orders_by_user` (#252)
196
+ and location-last release (#288) are kept. Single-owner cancel and fill
197
+ go from about 24 µs to 1 µs at 100 000 resting orders, and
198
+ `cancel_orders_by_user` over 10 000 orders from 29.5 ms to 3.8 ms; new
199
+ benches `cancel_single_owner_hdr`, `fill_single_owner_hdr` and
200
+ `mass_cancel_by_user_hdr` cover that case.
201
+ - `PriceLevelCache` gains tests for the default state, the empty bid side,
202
+ serialization, and prices at or above 2^127, which must round trip
203
+ unchanged (#310, follow-up to the #308 review).
204
+
205
+ ## [0.15.0] - 2026-09-30
206
+
207
+ The stop-protection release. Elected trailing stops (#286) can be bounded
208
+ by a per-book protection collar (#302): with a collar configured, an
209
+ elected stop's child is an immediate-or-cancel limit order at the trailed
210
+ stop price minus (sell) or plus (buy) the collar, instead of an unpriced
211
+ market order. Without a collar, behaviour is unchanged from 0.14.0.
212
+ Breaking: new public fields on `OrderBookSnapshotPackage`,
213
+ `ReplayBookConfig` and `OrderStatus::Triggered`, a new
214
+ `CancelReason::StopProtectionBand` variant, and snapshot format 6.
215
+
216
+ ### Added
217
+
218
+ - **Protection collar for elected stop orders (#302).** `StopProtection`
219
+ (`try_new(collar)`, `new(NonZeroU128)`, `collar()`, `limit_price(side,
220
+ stop)`, `check_tick_size`) and `OrderBook::set_stop_protection` /
221
+ `stop_protection`. With a collar, an elected trailing stop
222
+ (`special_orders`) executes as an immediate-or-cancel limit order at
223
+ `stop - collar` (sell) or `stop + collar` (buy), `stop` being its trailed
224
+ stop price at election and the collar an absolute offset in price units
225
+ (like CME protection points, except that the remainder is cancelled,
226
+ not rested: a stop whose band is exhausted leaves its position
227
+ unprotected); nothing rests. A remainder the collar cut (liquidity left
228
+ beyond the limit, including an empty band) ends `Cancelled { reason:
229
+ StopProtectionBand }`; one left because the side ran out within the band
230
+ keeps `InsufficientLiquidity`. `OrderStatus::Triggered` records the
231
+ child's `limit_price`. `StopProtection` is re-exported from the prelude.
232
+ The collar must be a multiple of the
233
+ tick size (`InvalidTickSize`; a later `set_tick_size` does not
234
+ re-validate it) and cannot be zero (new
235
+ `OrderBookError::InvalidStopProtection`, reject code `Other(0)`: a
236
+ configuration error). A band that reaches or passes the representable
237
+ bound (sell `collar >= stop`, buy `stop + collar >= u128::MAX`) has the
238
+ bound, `0` / `u128::MAX`, as its limit. Unset (the default) keeps the 0.14.0 unpriced IOC
239
+ market child. The type is available without `special_orders`, so
240
+ snapshots and replay configurations are identical in every build.
241
+ `ReplayBookConfig::with_stop_protection` carries it into replay. The
242
+ `pending_stops_hdr` bench gains `*_collar_*` elect and cascade
243
+ scenarios; `special_orders_demo` shows a collar.
244
+
245
+ ### Changed (breaking)
246
+
247
+ - **Snapshot format 6 (#302).** `ORDERBOOK_SNAPSHOT_FORMAT_VERSION` is `6`
248
+ and `OrderBookSnapshotPackage::validate` reads `2..=6`. Packages carry
249
+ `stop_protection: Option<StopProtection>` (`#[serde(default)]`),
250
+ written by `create_snapshot_package` and installed by
251
+ `restore_from_snapshot_package` (as captured, without the tick-size
252
+ check). The snapshot payload and its checksum are unchanged from
253
+ version 5; config fields are not checksummed, as before.
254
+ - Migration: version-5 packages (0.14.0) keep verifying and restore with
255
+ no collar (covered by a verbatim 0.14.0 fixture); a package below
256
+ version 6 that carries a collar is rejected. A 0.14 reader rejects
257
+ every version-6 package ("Unsupported snapshot version") instead of
258
+ silently dropping the collar, so upgrade readers before writers. A
259
+ zero collar does not deserialize.
260
+ - **`ReplayBookConfig::stop_protection` (#302).** New public field; code
261
+ building the struct with an exhaustive literal must set it (or use
262
+ `..Default::default()`). `ReplayBookConfig::new` leaves it `None`.
263
+ - **`OrderBookSnapshotPackage::stop_protection` (#302).** New public
264
+ field; exhaustive literals must set it.
265
+ - **`CancelReason::StopProtectionBand` (#302).** New variant, appended
266
+ (bincode index 10, JSON `"StopProtectionBand"`); exhaustive matches need
267
+ the arm. The collared child's terminal reason when the collar cut its
268
+ sweep; `InsufficientLiquidity` otherwise.
269
+ - **`OrderStatus::Triggered::limit_price` (#302).** New field
270
+ (`Option<u128>`, `#[serde(default)]`): the child's collar limit, `None`
271
+ for a market child. 0.14 JSON decodes with `None`; bincode `Triggered`
272
+ payloads do not decode across 0.14 / 0.15. Patterns and literals naming
273
+ every field must add it. `Display` appends `, limit=<price>` when set.
274
+ Nothing journaled or on the wire carries `OrderStatus` (`ExecReport`
275
+ keeps status code 5).
276
+
277
+ ### Known limitations
278
+
279
+ - **Stop protection collar (#302).** A gap of more than one collar through
280
+ a stop's price always consumes the stop with zero fill
281
+ (`StopProtectionBand`), leaving the position unprotected. The collar
282
+ bounds each child, not the cascade: a ladder of stops spaced one collar
283
+ apart still walks the book `k × collar` in one call (no cascade depth
284
+ limit or velocity pause). A sell collar that reaches or exceeds the stop
285
+ price (limit 0), or a buy `stop + collar` that reaches or exceeds
286
+ `u128::MAX`, does not protect that stop. Replay needs the
287
+ source book's collar, constant over the replayed range. A mismatch is
288
+ not an `OutcomeMismatch`, and `snapshots_match` catches it only when it
289
+ changed an outcome (the snapshot does not carry the collar; with no
290
+ election in the range, or coinciding fills, the snapshots match while
291
+ future elections differ): compare the replayed book's
292
+ `stop_protection()` with the source book's (or the snapshot package's
293
+ `stop_protection`).
294
+
295
+ ## [0.14.0] - 2026-09-30
296
+
297
+ The panic-policy release. `pricelevel` is upgraded to 0.10.2; the
298
+ Production Panic Policy (crate-owned code no longer initiates a panic)
299
+ is enforced mechanically by a `[lints.clippy]` deny set plus
300
+ `scripts/check_panic_policy.py`, with no allowlist left. The audit that
301
+ policy required surfaced a long list of engine and state failures that
302
+ used to be clamped, ignored or silently recovered (matching, fees and
303
+ notionals, risk, modifies, mass cancels, snapshots and restore, journals
304
+ and replay, wire and bincode decoding); every one now returns a typed
305
+ error instead. Off-book trailing stops (#286) land on top: a
306
+ `TrailingStop` is held as a pending stop rather than resting as visible
307
+ liquidity, trailing the last trade price and executing as an
308
+ immediate-or-cancel market order when it elects. Performance is measured
309
+ against the last release, `v0.13.1`, and re-measured after #286 merged;
310
+ see `BENCHMARKS.md` / `BENCH.md`. It is a breaking release: see "Changed
311
+ (breaking)" and the migration table in `src/lib.rs`.
312
+
313
+ ### Added
314
+
315
+ - **Off-book trailing stops (#286, `special_orders`).**
316
+ `OrderBook::stop_trigger_order_id(stop_id)` (and the pure
317
+ `orderbook::stop_orders::stop_trigger_order_id(namespace, stop_id)`)
318
+ names the market order an elected stop executes as;
319
+ `OrderStatus::Triggered { child_id, trigger_price }` (wire `ExecReport`
320
+ status 5) and `TradeResult::origin_stop_id` link a stop and its market
321
+ order; `OrderBookError::StopOrdersUnsupported` / `StopWouldTrigger` /
322
+ `InvalidStopTerms` with reject codes 23 / 24 / 25; the Criterion group
323
+ "OrderBook - Pending Stops" (controls, trailing / elect / cascade at
324
+ N = 10 and 1000, contended adds with 0 or 1 stop) and the
325
+ `pending_stops_hdr` bench (both with `--features special_orders`). See
326
+ Changed (breaking). JSON `TradeResult`s without `origin_stop_id` decode
327
+ with `None`; bincode `TradeResult`s written without it (0.13, or 0.14
328
+ pre-releases) do not decode, and vice versa.
329
+ - **Production Panic Policy CI gate (#242).** `[lints.clippy]` in
330
+ `Cargo.toml` denies `unwrap_used`, `expect_used`, `panic`, `unreachable`,
331
+ `todo`, `unimplemented`, `indexing_slicing`, `string_slice`,
332
+ `arithmetic_side_effects`, `cast_possible_truncation`, `cast_sign_loss`,
333
+ `cast_possible_wrap`, `manual_assert`, `panic_in_result_fn`, `get_unwrap`
334
+ and `exit` package-wide (the `examples` member does not inherit it);
335
+ `clippy.toml` exempts real tests. `scripts/check_panic_policy.py` (`make
336
+ lint-panic`, part of `make lint` and `make pre-push`) catches what clippy
337
+ cannot: the `assert!` / `debug_assert!` family, `saturating_*` /
338
+ `wrapping_*`, `std::process::exit` / `abort`, `catch_unwind` /
339
+ `panic_any` / `resume_unwind` (tests may still use all three), and
340
+ production-reachable `#[cfg(test)]` seams. `doc/panic-boundaries.md`
341
+ documents irreducible dependency limits, the two documented `unsafe`
342
+ exceptions (`memmap2` under feature `journal`, `CountingAllocator` under
343
+ feature `alloc-counters`) and the no-panic obligations of
344
+ caller-supplied code. The temporary ratchet ledgers used during the
345
+ cycle were removed (#260); the gate is absolute (see Changed).
346
+ - `rules/global_rules.md` is now tracked; the policy script and fixtures
347
+ are un-ignored in `.gitignore` (not part of the published package).
348
+ - `OrderBook::risk_accounting_anomalies()` and
349
+ `RiskState::accounting_anomalies()`, plus the
350
+ `orderbook_risk_accounting_anomalies_total` counter under the `metrics`
351
+ feature (#243): the number of pre-trade risk accounting anomalies (a
352
+ release larger than an account counter, a fill larger than a maker's
353
+ tracked remainder, a post-trade counter increment that would overflow).
354
+ Expected to stay at zero; every anomaly is also logged.
355
+
356
+ ### Changed (breaking)
357
+
358
+ - **Trailing stops are pending off-book stops (#286).** A
359
+ `OrderType::TrailingStop` used to be admitted as an ordinary limit order
360
+ at its stop price: it rested as visible liquidity, traded as soon as it
361
+ was marketable, and `reprice_trailing_stops` could only move it on a
362
+ crossed book (its watermark never advanced). With `special_orders` it is
363
+ now held off book and driven by the book's prints:
364
+ - never on a level: not liquidity, not depth, not in any analytics or
365
+ snapshot level list; `get_order` still finds it and
366
+ `trailing_stop_ids()` lists pending stops in admission order;
367
+ - its watermark (`last_reference_price`, taken as given at admission)
368
+ follows the prints in its favour and its stop price trails it by
369
+ `trail_amount`, only tightening;
370
+ - a print at or through the stop price elects it: it leaves the book,
371
+ releases its risk and executes as an immediate-or-cancel, unpriced
372
+ market order for its quantity, side and user (STP, fees and the market
373
+ preflights apply; the remainder is cancelled; no protection collar and
374
+ no price band), under the id `OrderBook::stop_trigger_order_id(stop_id)`
375
+ (UUIDv5 of the trade-id namespace, which should stay private);
376
+ - evaluation is automatic, under the submit gate the call already holds,
377
+ before every call that traded returns, along each sweep's price path
378
+ (its first print, then its last: stops trail, then the print elects),
379
+ iterative (a stop's market order is a new sweep, bounded by the pending
380
+ stops) and deterministic (one print's stops in trigger order, sell
381
+ highest / buy lowest first, then admission order);
382
+ - at election the stop records the new `OrderStatus::Triggered
383
+ { child_id, trigger_price }` and the market order's `TradeResult`s
384
+ carry `origin_stop_id`; then the stop takes the market order's
385
+ terminal state (`Filled`, `Cancelled { InsufficientLiquidity |
386
+ SelfTradePrevention | MatchAborted }`, or `Rejected` when it was
387
+ refused untouched, including a market-order id already in use);
388
+ - while the kill switch is engaged elections are suspended (prints still
389
+ trail), so protective stops are not consumed by rejected market orders;
390
+ - admission accepts `GTC` / `GTD` / `DAY` only and requires a positive
391
+ quantity and trail (a multiple of the tick size) and a stop price not
392
+ beyond its watermark (`InvalidStopTerms`, code 25); a stop the last
393
+ trade already crosses is rejected untouched (`StopWouldTrigger`, code
394
+ 24), at admission and on modify; the risk open-order slot and notional
395
+ are reserved at the stop price (no price band) and follow the stop as
396
+ it trails, without enforcing limits (a trailing sell stop can lift its
397
+ account above `max_notional_per_account`); a modify re-books in place;
398
+ - cancel, `update_order` (quantity, stop price, replace; a zero quantity
399
+ on `UpdatePriceAndQuantity` / `Replace` is `InvalidStopTerms`), every
400
+ mass cancel scope (pending stops follow the resting orders in the
401
+ result; the price range matches the current, trailed stop price),
402
+ `cancel_all_orders` and `evict_expired_orders` cover pending stops;
403
+ - while a stop is pending, calls that can trade and calls that target a
404
+ stop take the exclusive submit gate; post-only adds and the cancels
405
+ and quantity updates of other orders keep the shared side;
406
+ `create_snapshot` captures under the shared side.
407
+ Without `special_orders` a trailing stop is rejected untouched with the
408
+ new `OrderBookError::StopOrdersUnsupported { order_id }` (reject code
409
+ `StopOrdersUnsupported` = 23, journaled as never mutating).
410
+ `SpecialOrderTracker` loses its trailing-stop methods
411
+ (`register_trailing_stop`, `unregister_trailing_stop`,
412
+ `trailing_stop_count`, `trailing_stop_ids`); `reprice_trailing_stops`
413
+ returns `0` (every call that trades evaluates its own prints).
414
+ Compatibility: code that relied on a trailing stop resting or trading at
415
+ its stop price must treat it as a stop order now, and a stop the last
416
+ trade already crosses is now a rejection; exhaustive matches on
417
+ `OrderStatus` need a `Triggered` arm; a journal written before 0.14 that
418
+ holds trailing stops does not replay (the stop no longer rests), and
419
+ replay of a live book's stops needs the recorded trade-id namespace for
420
+ identical market-order ids (`snapshots_match` holds either way). A
421
+ command's journaled `TradeResult` holds its own trades only; a stop it
422
+ elected reaches the trade listener as a separate `TradeResult`.
423
+ Cost, measured against main (5925a7a) with `special_orders` on a loaded
424
+ host (1-minute load 5 to 13): with no stop pending,
425
+ `match_market_against_limit` / `_iceberg` stay within -1.5 % / +1.0 %
426
+ of main (five interleaved rounds over every commit of this change; an
427
+ earlier six-round run at load 11 read +10 to +16 % and did not
428
+ reproduce once the load dropped), `add_limit_orders` +1.3 % and the
429
+ contended `concurrent_add_limit_orders` rows within their noise, HDR
430
+ `aggressive_walk` and the `benches/compare` rows NOISY with no
431
+ consistent direction (a book without stops never allocates the store).
432
+ With stops pending, a quiet print costs about 70 ns more than the
433
+ `_0_stops` control, independent of the stop count; trailing costs
434
+ about 220 ns and an election about 630 ns per stop (see
435
+ `pending_stops_hdr` in `BENCH.md`); with one stop pending, 4-thread
436
+ limit adds (which can trade) serialize on the exclusive gate (7.9 us
437
+ per add in Criterion against 2.8 us without a stop), while post-only
438
+ adds match their control.
439
+ - **Snapshot package format v5 (#286).** `ORDERBOOK_SNAPSHOT_FORMAT_VERSION`
440
+ goes from 4 to 5: `OrderBookSnapshot` gains `pending_stops:
441
+ Vec<OrderType<()>>` (admission order, stop price and watermark included)
442
+ and `last_trade_price: Option<u128>`, both `#[serde(default)]`, and the
443
+ checksum of a v5 package covers them. Restore installs the last trade
444
+ price (a restored book used to come back with none) and the pending
445
+ stops after validating them (trailing-stop kind, `GTC` / `GTD` / `DAY`,
446
+ positive quantity, consistent terms, unique ids; a stop the last trade
447
+ crosses is legal, see the kill switch above), and
448
+ rebuilds their risk at the stop price. `snapshots_match` compares both
449
+ fields. Migration: none needed on read; v2, v3 and v4 packages validate
450
+ with their original checksum and restore with no pending stop and no
451
+ last trade price (pinned by a verbatim v4 fixture written on `main`
452
+ before #286). A v2-v4 package that carries either field is rejected
453
+ (its checksum would not cover it). A package holding a trailing stop on
454
+ a price level (written by 0.13 or by a 0.14 pre-release) is refused with
455
+ `StopOrdersUnsupported`: cancel trailing stops on the old version before
456
+ snapshotting, and re-submit them after the upgrade. Packages written by
457
+ 0.14 are v5 and are rejected by older readers; upgrade readers before
458
+ writers. `OrderBookSnapshot` literals need the two new fields.
459
+ - **`ReplayError` is `#[non_exhaustive]` (#260).** 0.14 already adds
460
+ `JournalTruncated` and `MassCancelMismatch`; marking the enum now, in the
461
+ breaking window, lets later failure modes land without another break.
462
+ Compatibility: a `match` on `ReplayError` outside this crate needs a
463
+ wildcard arm. No behaviour change.
464
+ - **Core boundary tightening (#294).** Compatibility:
465
+ - `OrderBook::place_order_in_book` is removed. It was a public raw
466
+ placement that bypassed the submit gate, the kill switch, risk,
467
+ crossing checks, self-trade prevention, the strandable-maker rule and
468
+ order-state tracking, contradicting the gate's documented boundary; it
469
+ had no production caller. Use `add_order` (or the `add_*` helpers).
470
+ - `PriceSource::LastTrade` IV extraction on a two-sided book that has
471
+ not traded yet returns `Err(IVError::NoPriceAvailable)` instead of
472
+ silently pricing from the mid. Use `PriceSource::MidPrice` as an
473
+ explicit fallback. One-sided books are priced from their only side,
474
+ as before.
475
+ - A panic under the shared submit gate now engages the kill switch and
476
+ latches `submit_gate_poisoned()`; after an unwind under the exclusive
477
+ side the kill switch is engaged at the unwind rather than at the next
478
+ acquisition, so a market order submitted right after the panic is
479
+ rejected too. `release_kill_switch` resumes flow as before.
480
+ - `OrderStateTracker::transition` (standalone tracker) runs the
481
+ terminal-id eviction before its listener, so a listener that reads
482
+ the tracker can find an older terminal id already evicted.
483
+
484
+ - **Listeners run after commit and outside the submit gate (#249,
485
+ decision D3).** Behaviour change, no signature change. Compatibility:
486
+ - `TradeListener`, `PriceLevelChangedListener` and the book's
487
+ `OrderStateListener` used to run inline, often while the submit gate
488
+ was held and in several places before the mutation finished. Events
489
+ are now buffered during the mutation, stamped with `engine_seq` under
490
+ the gate at commit, and delivered after the gate is released by one
491
+ active dispatcher per book.
492
+ - Ordering guarantee: per book, one total order consistent with commit
493
+ order; `engine_seq` strictly increases across the delivered trade and
494
+ price-level stream, now also with concurrent submitters (previously
495
+ two shared-gate submitters could interleave their mints and deliver out
496
+ of sequence). A single submitting thread sees exactly the same events
497
+ in exactly the same order as before (pinned by a recorded-stream test).
498
+ - Timing: delivery happens on whichever thread is dispatching. Single
499
+ threaded, a call's events are still delivered before it returns; under
500
+ concurrency a submit can return before another thread's dispatcher has
501
+ delivered its events. A listener may observe a book state newer than
502
+ its event.
503
+ - Emission scopes nest per book: caller code running inside one book's
504
+ mutation (a `Clock`, `T::clone`) that drives another book gets that
505
+ book's events delivered after its own gate is released.
506
+ - Re-entrant calls are now allowed: a listener may submit, cancel,
507
+ modify or mass-cancel on the same book (previously a deadlock under
508
+ the exclusive gate). The nested call's events are delivered after the
509
+ current batch.
510
+ - Panicking listener: book state is consistent (the mutation committed
511
+ first) and the gate is not poisoned; the rest of the batch being
512
+ delivered is dropped and counted. New diagnostics:
513
+ `OrderBook::dropped_listener_events()`, `OrderBook::listener_panics()`,
514
+ and `OrderBook::flush_listener_events()` to deliver batches left
515
+ queued after such a panic (call it when `listener_panics()` grows).
516
+ A snapshot-package restore discards (and counts) batches still queued
517
+ from before it, since it rewinds `engine_seq` below them.
518
+ - Backlog: the listener outbox is unbounded; a slow or stalled listener
519
+ grows it (caller contract: listeners return quickly). New gauge
520
+ `OrderBook::pending_listener_events()`.
521
+ - Submit-gate poisoning is no longer recovered silently. It can now only
522
+ follow an engine (or `T::default()` / `T::clone()`) panic under the
523
+ exclusive gate; the acquisition that detects it engages the kill switch
524
+ (new flow and modifies return `KillSwitchActive`, cancels still run),
525
+ logs once at `ERROR` and latches `OrderBook::submit_gate_poisoned()`.
526
+ - `OrderStateTracker::transition` on a standalone tracker still calls its
527
+ listener inline; only a tracker owned by a book defers it.
528
+ - `match_market_order*` / `match_limit_order*` now publish their trades
529
+ before releasing the gate (they used to publish after it), so the
530
+ trade's `engine_seq` is stamped at commit with the sweep's level events;
531
+ the listener itself still runs after the gate is released.
532
+ - `add_order_with_result` / `*_with_committed` with a trade listener
533
+ installed clone the `TradeResult` once (caller copy + deferred listener
534
+ copy; same fills, fees and `engine_seq`). Journal and replay do not go
535
+ through listeners and are unaffected.
536
+ - **Measured cost of the total-order guarantee** (Criterion, 3 to 5
537
+ interleaved rounds against main c59d74f, Apple M-series). The one
538
+ workload over the 5% budget is `concurrent_add_limit_orders` **with a
539
+ no-op trade + price-level listener installed**: +3.8% / +6.7% / +3.7%
540
+ at 2 / 8 / 16 threads (4 threads within noise). Why: a strictly
541
+ increasing `engine_seq` in commit order needs each commit's stamp and
542
+ publish to be one atomic step under the submit gate, which is one
543
+ outbox lock acquisition per commit (measured 1.23 per add at 8
544
+ threads, dispatcher drains included); on main the listeners ran
545
+ inline, concurrently and unordered. The workload maximises that cost:
546
+ every thread adds at one price for one account, so all of them
547
+ serialise on the same level and index anyway, and a no-op listener
548
+ makes delivery free, leaving the lock handoff as the whole difference.
549
+ Everything else is within budget. Without listeners every path is
550
+ unchanged within noise: `add_limit_orders` +0.1%,
551
+ `concurrent_add_limit_orders` -1.0% to +0.7%,
552
+ `concurrent_mixed_operations` -1.2% to +1.1%, HDR `add_only` and
553
+ `mixed_70_20_10` p50 0.0%, `aggressive_walk` p50 +2.4% over 10 rounds
554
+ (one 1 ns histogram bucket). With listeners, `add_limit_orders` is
555
+ +2.4%, `concurrent_mixed_operations` -0.9% to +4.9% and
556
+ `match_market_against_limit` +3% to +4%. Tried and kept: a
557
+ spin flag in front of the outbox mutex (the contended `std` mutex
558
+ parked waiters in the kernel; 8 threads went from +9.3% to about +6%).
559
+ Tried and reverted: cache-line co-location of the outbox's hot fields,
560
+ appending events into a shared buffer in place (slower at every thread
561
+ count), backoff tuning. Evaluated and not pursued: dropping
562
+ readiness tracking (at most about 2 points, and it would deliver
563
+ before the owner's gate release), a lock-free ring keyed by
564
+ `engine_seq` (state-only batches and externally minted sequence
565
+ numbers leave gaps that can only be closed by stalling delivery).
566
+
567
+ - **`OrderBook::peek_match` returns `Result` (#246).** Compatibility:
568
+ `peek_match(side, quantity, price_limit)`: `u64` →
569
+ `Result<u64, OrderBookError>`. A level whose `visible + hidden` overflows
570
+ `u64` used to be read as empty (`total_quantity().unwrap_or(0)`) and the
571
+ running total was saturated; the overflowing level is now
572
+ `OrderBookError::PriceLevelError`, and the accounting is checked. Values
573
+ are unchanged for every book whose levels fit `u64`; add `?` or handle
574
+ the error.
575
+
576
+ - **Checked fee / trade arithmetic API (#244).** Compatibility:
577
+ - `FeeSchedule::calculate_fee(notional, is_maker)`: `i128` →
578
+ `Result<i128, FeeOverflow>`. The clamping variant is gone; add `?` or
579
+ handle the error. Values are unchanged wherever the old call did not
580
+ clamp.
581
+ - `FeeSchedule::try_calculate_fee` is deprecated (same behaviour as
582
+ `calculate_fee`). New `FeeSchedule::check_notional(notional)` checks
583
+ both legs at once.
584
+ - `TradeResult::new` and `TradeResult::with_fees`: `TradeResult` →
585
+ `Result<TradeResult, TradeArithmeticError>`; `TradeResult::total_fees`:
586
+ `i128` → `Result<i128, TradeArithmeticError>`;
587
+ `TradeInfo::from_trade_result`: `TradeInfo` →
588
+ `Result<TradeInfo, TradeArithmeticError>`. `TradeArithmeticError` is
589
+ new, `#[non_exhaustive]`, and re-exported at the root and in the
590
+ prelude.
591
+ - `OrderBookError` gains `FeeOverflow` and `NotionalOverflow`;
592
+ `RejectReason` gains `FeeOverflow` (18) and `NotionalOverflow` (19).
593
+ Existing codes do not move. Exhaustive matches on `OrderBookError`
594
+ inside a consumer crate were already impossible (`#[non_exhaustive]`).
595
+ - Behaviour: a taker whose worst-case notional × fee rate overflowed
596
+ used to trade with a clamped or dropped fee (or a saturated
597
+ `quote_notional`); it is now rejected untouched. No snapshot, journal
598
+ or wire format changes; `ORDERBOOK_SNAPSHOT_FORMAT_VERSION` stays 4.
599
+ A journal recorded by 0.13 in which such a clamped trade was accepted
600
+ replays as a `FeeOverflow` / `NotionalOverflow` rejection
601
+ (`ReplayError::OutcomeMismatch`).
602
+ - Replay: because the fee schedule now decides verdicts (code 18),
603
+ `ReplayBookConfig::fee_schedule` must match the source book's schedule;
604
+ replaying with a different one can flip a fill into a rejection or the
605
+ reverse and stops with `ReplayError::OutcomeMismatch`.
606
+
607
+ - **Journal trait and `InMemoryJournal` surface (#252).**
608
+ - `Journal::last_sequence(&self) -> Option<u64>` becomes
609
+ `-> Result<Option<u64>, JournalError>` (approved trait break):
610
+ implementors return `Ok(None)` for an empty journal and an error when
611
+ it cannot be read; callers add `?`. `ReplayEngine` maps the error to
612
+ `ReplayError::JournalError` instead of `EmptyJournal`.
613
+ - `Journal::append` must reject a non-increasing sequence with
614
+ `JournalError::NonMonotonicSequence`; a custom implementation should
615
+ do the same. Journals that rely on duplicate sequences no longer
616
+ append.
617
+ - `InMemoryJournal::with_capacity(n)` returns
618
+ `Result<Self, JournalError>` (`AllocationFailed`); `len()` and
619
+ `is_empty()` return `Result<_, JournalError>` instead of reporting 0 /
620
+ `true` on a poisoned lock.
621
+ - `JournalError` is now derived with `thiserror` (Display text
622
+ unchanged) and gains `NonMonotonicSequence`, `SegmentExists` and
623
+ `AllocationFailed` (it is `#[non_exhaustive]`). `ReplayError` gains
624
+ `MassCancelMismatch` (the enum is `#[non_exhaustive]` as of 0.14, #260,
625
+ so downstream matches need a wildcard arm); new public
626
+ `MassCancelDivergence`.
627
+ - Behaviour: a journaled `MassCancelled` whose ids do not match the
628
+ replay (for example a placeholder `MassCancelResult::default()` for a
629
+ cancel that removed orders) now fails replay; journal the result the
630
+ mass cancel returned. A journaled eviction the replay book cannot
631
+ reproduce is `MassCancelMismatch` rather than
632
+ `OrderBookError(OrderNotFound)`.
633
+ - Compatibility: no on-disk format change. Valid journals written by
634
+ 0.13 and earlier 0.14 builds open, verify and replay unchanged (pinned
635
+ by the 0.13.1 fixture). A journal holding mid-segment corruption in its
636
+ latest segment now fails to open instead of being silently truncated at
637
+ the damage, and a journal with duplicate stored sequences fails
638
+ `verify_integrity`. Reopen can take longer on large segments: it reads
639
+ the unused tail once to zero stale bytes.
640
+ - Journals written before 0.10.2 (#190), when the id order inside a
641
+ journaled `MassCancelled` was not reproducible across processes, now
642
+ fail replay loudly with `ReplayError::MassCancelMismatch` at the first
643
+ such mass cancel instead of passing on equal counts. Re-record them, or
644
+ replay them with a build before 0.14.
645
+
646
+ - **Modification error contract (#247).** Compatibility:
647
+ - `OrderQuantity::total_quantity()`: `u64` (saturating) →
648
+ `Result<u64, OrderBookError>` (`QuantityOverflow` for an
649
+ unrepresentable two-tranche total). Values are unchanged for every
650
+ representable order; add `?` or handle the error.
651
+ `checked_total_quantity()` is unchanged.
652
+ - `OrderBookError::PriceCrossing::opposite_price`: `u128` →
653
+ `Option<u128>`; `None` where `0` used to stand for an opposite side
654
+ that emptied before the error was built.
655
+ - `OrderBookError` gains `ModifyRolledBack`, `ModifyOrderLost` and
656
+ `OrderChangedDuringModify` (only ever the source of the first two);
657
+ `RejectReason` gains `ModifyRolledBack` (20) and `ModifyOrderLost`
658
+ (21); `CancelReason` gains `RestFailed`, appended last so the bincode
659
+ index of every earlier variant is unchanged (exhaustive matches on
660
+ `CancelReason` need a new arm). Existing codes do not move.
661
+ - `InsufficientLiquidity` from an IOC remainder now carries the taker's
662
+ total as `requested` and its executed quantity as `available`; both
663
+ were read off the visible tranche before, so only two-tranche IOC
664
+ takers see different numbers.
665
+ - Behaviour: `update_order(Cancel)` now records `Cancelled
666
+ { UserRequested }` and releases the order's risk contribution, like
667
+ `cancel_order`. A re-priced order keeps its fill history: its state is
668
+ `PartiallyFilled` with cumulative quantities instead of resetting to
669
+ `Open`. A modify re-add is no longer rejected by a kill switch
670
+ engaged, or a risk limit consumed, after the modify's own checks
671
+ passed.
672
+ - Replay: `SequencerResult::from(&err)` records both new variants as
673
+ `RejectedWithCode` with `may_have_mutated: true`, and replay
674
+ re-executes an `UpdateOrder` journaled under code 20 or 21 (as it does
675
+ under `MatchAborted`) instead of skipping it. Their causes are not in
676
+ the journal, so replay normally stops with
677
+ `ReplayError::OutcomeMismatch`: loud, never a silent divergence. No
678
+ snapshot, journal or wire format change;
679
+ `ORDERBOOK_SNAPSHOT_FORMAT_VERSION` stays 4.
680
+
681
+ - **pricelevel upgraded to 0.10 (#239).** The crate version moves to
682
+ 0.14.0. pricelevel 0.10 makes level snapshots, queue views, dry runs and
683
+ match-result growth fallible; every such result is now propagated as
684
+ `OrderBookError::PriceLevelError` instead of being ignored. Signature
685
+ changes (callers add `?` or handle the error):
686
+ - `OrderBook::create_snapshot(depth)`: `OrderBookSnapshot` →
687
+ `Result<OrderBookSnapshot, OrderBookError>`.
688
+ - `OrderBook::enriched_snapshot(depth)` and
689
+ `OrderBook::enriched_snapshot_with_metrics(depth, flags)`:
690
+ `EnrichedSnapshot` → `Result<EnrichedSnapshot, OrderBookError>`.
691
+ - `OrderBook::evict_expired_orders(now_ms)`: `Vec<Arc<OrderType<T>>>` →
692
+ `Result<EvictionResult<T>, OrderBookError>` (the `EvictionResult` is
693
+ from #248, see below). The read phase runs before any eviction, so
694
+ `Err` means nothing was evicted.
695
+ - `BookManagerStd` / `BookManagerTokio`: `evict_expired_orders(symbol,
696
+ now_ms)` returns `Option<Result<EvictionResult<T>, OrderBookError>>`
697
+ and `evict_expired_across_books(now_ms)` returns
698
+ `HashMap<String, Result<EvictionResult<T>, OrderBookError>>` (one
699
+ failing book does not stop the others). Both managers stay in parity.
700
+ - `OrderBookError` now derives `Clone` (the hand-written impl is gone,
701
+ since `PriceLevelError` derives `Clone` upstream); behaviour unchanged.
702
+ - Re-exported pricelevel items follow pricelevel 0.10: `PriceLevel::snapshot`
703
+ returns `Result`, `Trade::new` is removed (use `Trade::with_timestamp`),
704
+ `UuidGenerator::next` becomes `try_next`, `OrderType::match_against` /
705
+ `refresh_iceberg` return `Result`, `MatchResult` gains `error()`, and
706
+ `PriceLevelError` gains `CapacityExceeded`, `CounterExhausted` and
707
+ `EntropyUnavailable` (exhaustive matches need new arms).
708
+ - **Mass cancels report failures instead of swallowing them (#239).**
709
+ `MassCancelResult` gains `failures()` / `has_failures()` and the new
710
+ `#[non_exhaustive]` `MassCancelFailure` enum (re-exported at the root).
711
+ `cancel_all_orders`, `cancel_orders_by_side` and
712
+ `cancel_orders_by_price_range` read every level in scope before cancelling
713
+ anything; a level whose orders cannot be read refuses the whole call:
714
+ nothing is cancelled and `MassCancelFailure::LevelUnreadable { side,
715
+ price, error }` is recorded (logged at `WARN`). Signatures are unchanged.
716
+ Code that treats an empty result as "nothing to cancel" should check
717
+ `has_failures()`. The field is `#[serde(default)]`, so JSON (including
718
+ journaled `MassCancelled` entries) written by 0.13 decodes with no
719
+ failures. Replay turns a refused mass cancel or eviction into
720
+ `ReplayError::OrderBookError` instead of continuing on a diverged book.
721
+ Replay applies a mass cancel journaled as refused as a no-op instead of
722
+ re-executing it, so a replay book that happens to be readable cannot
723
+ cancel orders the live book kept.
724
+ - **Mass cancels are failure-aware and gate-safe (#248).**
725
+ - `cancel_all_orders` now holds the **exclusive** submit gate. Under the
726
+ shared gate it collected the resting ids, then cleared
727
+ `order_locations` / `user_orders` and drained the levels wholesale, so
728
+ an order admitted in between was dropped with no cancel event, no
729
+ order-state transition and no risk release, and the risk reset wiped
730
+ the reservations of in-flight submits. Its price-level and order-state
731
+ events are now emitted **after** the book is cleared (same events, same
732
+ order: levels bids then asks ascending, then one `Cancelled
733
+ { MassCancelAll }` per order), so a listener never sees an event ahead
734
+ of the mutation.
735
+ - `cancel_orders_by_side`, `cancel_orders_by_user`,
736
+ `cancel_orders_by_price_range` and `evict_expired_orders` also take the
737
+ exclusive gate: they collect their scope before cancelling it id by id,
738
+ and under the shared gate an id cancelled and re-admitted out of scope
739
+ in between (other side, price, user, or not expired) was cancelled by
740
+ the bulk call. Cost: submits, cancels and modifies on that book wait
741
+ for the bulk operation. Single-order `cancel_order` keeps the shared
742
+ gate.
743
+ - `cancel_orders_by_user` no longer removes the user's `user_orders`
744
+ entry up front: each successful cancel untracks its own id, a failed
745
+ order stays indexed, and stale ids (no longer resting) are still
746
+ purged.
747
+ - Per-order failures are recorded instead of swallowed:
748
+ `MassCancelFailure` gains `OrderCancelFailed { order_id, error }`. A
749
+ scoped mass cancel carries on past a failed order, so a result can
750
+ hold cancelled ids **and** failures, both in the deterministic
751
+ traversal order; the failed order stays resting and fully tracked
752
+ (location, user index, risk, order state). New
753
+ `MassCancelResult::is_refused()` / `MassCancelFailure::is_refusal()`
754
+ tell a refused call (`LevelUnreadable`, nothing cancelled) from a
755
+ partial one.
756
+ - `OrderBook::cancel_order` (and every internal cancel) resolves a failed
757
+ level removal by what the level still holds. If the order still rests
758
+ it returns `Err(OrderBookError::PriceLevelError(_))` with nothing
759
+ mutated; before, that case returned `Ok(None)`, indistinguishable from
760
+ an absent order. If the level removed the order and then failed
761
+ (pricelevel can commit a removal and then report a broken invariant),
762
+ the book completes the removal like a successful cancel (level event,
763
+ `Cancelled` state, location, user index, risk, special-order tracking,
764
+ empty level) and returns the new
765
+ `OrderBookError::OrderRemovedWithLevelFault { order_id, source }`
766
+ (reject code `Other(0)`; logged at `ERROR`), so no index goes stale.
767
+ Mass cancels list such an order as cancelled and record
768
+ `MassCancelFailure::LevelFaultAfterRemoval`. The strandable-maker count
769
+ is not decremented in that case (no order body), which errs on the
770
+ safe side.
771
+ - `evict_expired_orders` returns the new `EvictionResult<T>` (evicted
772
+ orders, their ids and per-order failures, in sweep order;
773
+ `mass_cancel_result()` gives the `MassCancelResult` to journal as
774
+ `SequencerResult::MassCancelled`). It carries on past a failed order,
775
+ which stays resting; a later sweep retries it. New
776
+ `MassCancelResult::failed_order_ids()`.
777
+ - Replay of an `EvictExpiredOrders` event journaled as `MassCancelled`
778
+ evicts exactly the journaled ids instead of re-running the sweep, so
779
+ an order the live sweep failed to evict keeps resting; a journaled id
780
+ the replay book cannot evict is reported as
781
+ `ReplayError::MassCancelMismatch` (#252).
782
+ Without a journaled result the sweep is re-run and any failure is
783
+ reported.
784
+ - `SequencerResult::from(&OrderBookError)` records
785
+ `OrderRemovedWithLevelFault` as `OrderCancelled { order_id }` (the
786
+ outcome the book took), not as a rejection, so replay removes the
787
+ order too; an `UpdateOrder` journaled as `OrderCancelled` is replayed
788
+ as that cancel rather than by re-executing the update (whose re-add
789
+ the live book never performed).
790
+ - Replay skips only a **refused** journaled mass cancel
791
+ (`is_refused()`), not every result with failures; a mass cancel
792
+ journaled with per-order failures is re-executed and reconciled by
793
+ identity (#252, see Fixed).
794
+ - Compatibility: `evict_expired_orders` (and the manager pass-throughs)
795
+ change their success type to `EvictionResult<T>`, a second change in
796
+ the 0.14 cycle: `len()`, `is_empty()`, `iter()` and `for order in
797
+ &result` keep working, indexing becomes `evicted_orders()[i]`. No
798
+ other signature changes. `MassCancelFailure` and
799
+ `OrderBookError` are `#[non_exhaustive]`, so downstream matches already
800
+ carry a wildcard arm. JSON `MassCancelResult`s written by 0.13 (no
801
+ `failures`) and by 0.14 builds before #248 (`level_unreadable` only)
802
+ decode unchanged; a JSON result carrying `order_cancel_failed` or
803
+ `level_fault_after_removal` does not decode on those older readers. No snapshot or journal format
804
+ change. Callers that treated `cancel_order`'s `Ok(None)` as "gone"
805
+ should also handle `Err`.
806
+ - **Snapshot package format v4.** `ORDERBOOK_SNAPSHOT_FORMAT_VERSION` goes
807
+ from 3 to 4 because a level's `value_executed` statistic is a `u128` in
808
+ pricelevel 0.10 and may exceed `u64::MAX`. Migration: none needed on read;
809
+ v2 (0.11) and v3 (0.12 / 0.13) packages validate with their original
810
+ checksum and restore (pinned by a verbatim 0.13.1 v3 fixture next to the
811
+ 0.8.4 v2 fixture). Packages written by 0.14 (v4 here, v5 since #286,
812
+ above) are rejected by 0.13 and earlier (version check, or a decode error when a
813
+ `value_executed` exceeds `u64::MAX`); upgrade readers before writers.
814
+ - **Wire break: bincode `TradeResult` (NATS + `bincode`).** pricelevel 0.10
815
+ appended a positional `error` field to `MatchResult`, so a bincode
816
+ `TradeResult` written by 0.13 does not decode under 0.14 and vice versa.
817
+ Mixed-version NATS consumers using `BincodeEventSerializer` must upgrade
818
+ producers and consumers together. The JSON serializer and the
819
+ `FileJournal` (JSON payloads) stay compatible: a 0.13.1 JSON
820
+ `TradeResult` and a verbatim 0.13.1 journal segment (trades, a coded
821
+ rejection, a mass cancel) decode, verify and replay under 0.14 (pinned by
822
+ fixture tests). A bincode-encoded `MassCancelResult` from 0.13 does not
823
+ decode either (new `failures` field).
824
+ - **Aborted sweeps surface as `OrderBookError::MatchAborted` (#240).**
825
+ pricelevel 0.10 reports a mid-sweep failure (`CounterExhausted`,
826
+ `CapacityExceeded`, e.g. an exhausted trade-id sequence) in
827
+ `MatchResult::error()` while keeping the prefix it committed. The sweep
828
+ now stops at the failed level and never walks on to a worse price; the
829
+ committed prefix is real and is published exactly like a partial fill
830
+ (trade listener, price-level listener, risk `on_fill`, maker order state
831
+ and location cleanup); the remainder never rests, whatever the
832
+ time-in-force; and every submission path (`add_order*`,
833
+ `add_limit_order*`, `submit_market_order*`, `match_market_order*`,
834
+ `match_limit_order*`, the raw `match_order*`, modify re-adds) returns
835
+ `Err(OrderBookError::MatchAborted { order_id, executed_quantity,
836
+ trade_count, source: Box<PriceLevelError> })` (boxed, so
837
+ `OrderBookError` stays 96 bytes). Each level's worst case
838
+ (`min(resting makers, quantity cap)`) is reserved in the result before the
839
+ level is touched; a refused reservation aborts before that level. The taker's terminal state is
840
+ `OrderStatus::Cancelled { filled_quantity: executed_quantity, reason:
841
+ CancelReason::MatchAborted }`. A failed STP queue view, or a refused
842
+ worst-case reservation for a level (taken before the STP arms touch it),
843
+ aborts the same way before that level is touched, with the prefix of the
844
+ earlier levels (empty only at the first level). A failed post-only probe
845
+ is a clean rejection instead: the book is provably untouched, so it
846
+ returns `PriceLevelError` with `Rejected { CapacityExceeded |
847
+ CounterExhausted }` rather than `PriceCrossing` or an abort.
848
+ Compatibility:
849
+ - `OrderBookError::MatchAborted` is a new variant; `OrderBookError` is
850
+ `#[non_exhaustive]`, so downstream matches keep compiling. Code that
851
+ matched `PriceLevelError` to detect a sweep failure matches
852
+ `MatchAborted` now. `std::error::Error::source` returns the
853
+ `PriceLevelError` for it.
854
+ - `CancelReason::MatchAborted` is appended (bincode index 8). The enum is
855
+ not `#[non_exhaustive]`: exhaustive downstream matches need a new arm.
856
+ - `RejectReason` gains `MatchAborted` (15), `CapacityExceeded` (16) and
857
+ `CounterExhausted` (17), appended; existing codes do not move. A
858
+ `PriceLevelError::CapacityExceeded` / `CounterExhausted` now maps to 16 /
859
+ 17 instead of `Other(0)`; other `PriceLevelError`s stay `Other(0)`. Older
860
+ readers decode the new codes as `Other(n)`.
861
+ - `SequencerResult::MatchAborted { reason, code, committed:
862
+ CommittedPrefix }` is appended (additive, `#[non_exhaustive]` enum):
863
+ existing JSON and bincode journals decode unchanged; journals carrying
864
+ it fail to decode against older binaries. Build it with
865
+ `SequencerResult::from_submit_failure` from the new `SubmitFailure`
866
+ returned by `add_order_with_committed`,
867
+ `submit_market_order_with_committed` and
868
+ `submit_market_order_by_amount_with_committed` (the plain APIs keep
869
+ their signatures). `From<&OrderBookError>` records a `MatchAborted`
870
+ error as `RejectedWithCode` (code 15, `may_have_mutated: true`).
871
+ - Replay re-executes a journaled `MatchAborted` submit and requires the
872
+ same committed prefix (makers, prices, quantities, executed quantity;
873
+ trade ids are recorded but not compared); anything else is
874
+ `ReplayError::OutcomeMismatch`. An `UpdateOrder` journaled as
875
+ `RejectedWithCode` under code 15 is re-executed and reconciled by code
876
+ instead of being skipped. Aborts come from exhausted resources a fresh
877
+ replay book does not normally reproduce, so such a journal stops replay
878
+ loudly rather than diverging.
879
+ - No snapshot format change (`ORDERBOOK_SNAPSHOT_FORMAT_VERSION` stays 4).
880
+ - **Fill-or-kill preflight (#240).** Before any mutation a fill-or-kill
881
+ taker now checks the book's trade-id headroom against an upper bound on
882
+ the trades its sweep can emit and reserves the result buffers for its
883
+ maker steps; a shortfall rejects it untouched with
884
+ `OrderBookError::PriceLevelError(CapacityExceeded)` (reject code 16,
885
+ `OrderStatus::Rejected`). A failed feasibility dry run is a kill
886
+ (`Rejected` with the resource code), never zero depth. Made exact by
887
+ pricelevel 0.10.1 (#293, below): per-level counters are checked and the
888
+ trade-id check and reservation use exact counts.
889
+ A partial `MatchAborted` from a `*_with_committed` call is the only
890
+ failure that boxes the committed `TradeResult`; the plain APIs never box
891
+ it.
892
+ - **Exhausted trade-id generator and dead-book signal (#240).** A crossing
893
+ submit (`add_order*`, `submit_market_order*`, `match_market_order*`,
894
+ `match_limit_order*`) or a crossing modify (in its validate-first phase,
895
+ before the original is cancelled, which keeps resting) is rejected
896
+ untouched with `PriceLevelError(CapacityExceeded { IdSequence })`, code
897
+ 16, once the book's trade-id generator is exhausted; post-only and
898
+ non-crossing orders (a limit that does not cross the best opposite price)
899
+ are unaffected. The check runs under the gate the sweep holds and is exact
900
+ under the exclusive gate or a single writer; under the shared gate,
901
+ concurrent takers racing for the last ids may still abort with
902
+ `MatchAborted` (pricelevel 0.10 has no public atomic id reservation). New `OrderBook::match_aborts()`,
903
+ `OrderBook::match_fold_failures()` and `OrderBook::trade_ids_exhausted()`
904
+ (latched on the first exhaustion, logged once at `ERROR`, cleared by
905
+ `set_trade_id_namespace`); with `metrics`, the counters
906
+ `orderbook_match_aborts_total`, `orderbook_match_fold_failures_total` and
907
+ `orderbook_trade_ids_exhausted_total`. No automatic kill switch. An
908
+ abort during a modify's re-add for any other cause still destroys the
909
+ original (documented on `update_order`).
910
+ The residuals, including why a journaled abort usually stops replay with
911
+ `OutcomeMismatch`, are documented in `doc/panic-boundaries.md`; poisoned
912
+ levels are handled since #293 (below).
913
+ - **pricelevel 0.10.2 (#293, #259).** The `pricelevel` floor is raised to
914
+ `0.10.2`. 0.10.1 closes three residuals of the #240 sweep-abort work
915
+ (below); 0.10.2 fixes the two allocation costs filed from #259: a fixed
916
+ 32 `DashMap` shards per level instead of a host-sized map
917
+ (PriceLevel#224) and a bounded up-front trade reservation in
918
+ `match_order` (PriceLevel#225). Compatibility:
919
+ - **Poisoned levels stop the sweep (PriceLevel#217).** A poisoned level
920
+ used to return an empty result without an error, so the sweep walked
921
+ on to a worse price. It now reports `InvalidOperation` through
922
+ `MatchResult::error()`: the sweep stops there and returns
923
+ `MatchAborted` with the earlier levels' prefix (taker
924
+ `Cancelled { MatchAborted }`); a post-only probe on it is rejected
925
+ untouched with that error.
926
+ - **Exact fill-or-kill preflight (PriceLevel#218).** Every level a FOK
927
+ will reach is dry-run with `PriceLevel::match_requirements` for the
928
+ quantity the sweep will ask of it, under the exclusive submit gate the
929
+ FOK already holds. A poisoned level, a per-level counter without
930
+ headroom or a maker step that would stop the sweep now rejects the FOK
931
+ untouched with `PriceLevelError` (`InvalidOperation`, reject reason
932
+ `Other(0)`; `CounterExhausted`, code 17) instead of aborting it
933
+ mid-sweep. The trade-id check uses the exact
934
+ `MatchRequirements::trade_ids_required` instead of an upper bound, so
935
+ a FOK that fits the remaining trade ids is no longer refused (for
936
+ example two trades against two remaining ids, previously refused as
937
+ needing three), and replenishment trades are reserved up front. An
938
+ STP `CancelTaker` / `CancelBoth` pre-match counts what the dry run
939
+ fills for it, not the visible depth counted ahead of the same-user
940
+ maker, so a maker that cannot deliver its counted depth no longer lets
941
+ a FOK fill an earlier level and then be cancelled. Levels where STP
942
+ `CancelMaker` cancels makers first keep the conservative bound (see
943
+ `doc/panic-boundaries.md`).
944
+ - **Level fold with `MatchResult::try_absorb` (PriceLevel#219).** A
945
+ level asked for exactly the aggregate's remaining quantity is absorbed;
946
+ when the aggregate holds no trades or filled ids yet, the absorb adopts
947
+ the level's own buffers without reserving or allocating (or
948
+ over-reserving `min(makers, quantity)` on a deep level). In practice
949
+ that is the first traded level of a non-FOK base-quantity sweep. A FOK
950
+ reserves its whole sweep up front; quote-notional levels and STP
951
+ pre-matches asked for less than the remainder are copied into a
952
+ reserved aggregate; later levels reserve trades and filled ids
953
+ separately. Allocation counts
954
+ (`cargo bench --features alloc-counters --bench alloc_count`, new
955
+ crossing scenarios): a one-level crossing add that partially fills a
956
+ maker drops from 6.00 to 4.00 allocs/op (2,080 to 1,200 B/op); a 500-unit
957
+ taker against a 1,000-maker level from 6.00 to 4.00 allocs/op (176,320
958
+ to 88,320 B/op). The trades, their order and every event are unchanged.
959
+ A failed level absorbed into the prefix hands its error to the
960
+ aggregate; the abort path rebuilds the published prefix without it, so
961
+ the committed `TradeResult` still has an empty error slot.
962
+ - No public API change: the preflight types are crate-internal. No
963
+ snapshot or journal format change.
964
+
965
+ - **Implied-volatility inputs are validated; Black-Scholes and Greeks
966
+ return `Result` (#256).** `f64::clamp(min_iv, max_iv)` in the solver
967
+ panicked when `min_iv > max_iv` or a bound was NaN, reachable through the
968
+ public `SolverConfig` fields and `with_bounds`. New
969
+ `SolverConfig::validate()` (all fields finite, `0 < min_iv <= max_iv`,
970
+ `tolerance > 0`, `min_vega >= 0`, `max_iterations > 0`) and
971
+ `IVConfig::validate()` (`price_scale` finite and `> 0`, `max_spread_bps`
972
+ finite and `>= 0`, plus the solver check) run at the top of `solve_iv`,
973
+ `solve_iv_bisection`, `OrderBook::implied_volatility` and
974
+ `implied_volatility_with_config`, before the book is read. Signature
975
+ changes (callers add `?` or handle the error):
976
+ - `BlackScholes::{price, vega, delta, gamma, theta}(params, vol)`,
977
+ `BlackScholes::d1(..)` and `BlackScholes::d2(..)`: `f64` →
978
+ `Result<f64, IVError>`. Inputs must be finite with `spot > 0` and
979
+ `strike > 0`; `time_to_expiry` and `vol` must be `>= 0` (zero selects
980
+ the documented degenerate limit) and `> 0` for `d1` / `d2`. A
981
+ non-finite output from in-domain input (for example an overflowing
982
+ discount factor) is `IVError::NonFiniteResult`. `erf`, `norm_cdf` and
983
+ `norm_pdf` stay infallible: they are total on finite input.
984
+ - `OrderBook::{theoretical_price, option_vega, option_delta,
985
+ option_gamma, option_theta}`: `f64` → `Result<f64, IVError>`.
986
+ - `IVError` is `#[non_exhaustive]` (exhaustive matches outside the crate
987
+ need a wildcard arm), is now derived with `thiserror` (Display strings
988
+ unchanged), and gains `InvalidConfig { field, message }`,
989
+ `NonFiniteResult { operation, value }`, `ArithmeticOverflow { operation }`
990
+ and `PriceLevel(PriceLevelError)`.
991
+
992
+ Behaviour changes: a configuration that used to panic or silently
993
+ misbehave (NaN `max_spread_bps` disabled the spread gate; a zero or NaN
994
+ `price_scale` produced inf / NaN prices) now returns
995
+ `IVError::InvalidConfig`. `PriceSource::WeightedMid` sums the two
996
+ best-level quantities in `u128` (the `u64` sum could overflow), and a
997
+ level whose `total_quantity()` fails now returns `IVError::PriceLevel`
998
+ instead of being treated as empty; a level that disappears between the
999
+ best-price read and the quantity read still counts as `0`. With
1000
+ `vol == 0` and `time_to_expiry > 0`, `theta` returns the carry term of
1001
+ the discounted intrinsic value instead of `0.0`, and `delta` is the step
1002
+ on spot versus the discounted strike (previously NaN exactly at the
1003
+ forward). A Black-Scholes overflow mid-iteration surfaces as
1004
+ `NonFiniteResult` instead of `InvalidParams`. `IVParams::is_atm` returns
1005
+ `false` for a non-finite or non-positive strike instead of dividing by
1006
+ it. Results for valid inputs are unchanged.
1007
+ - **NATS publishers validate configuration and surface task failures
1008
+ (#253).** Applies to `NatsTradePublisher` and `NatsBookChangePublisher`.
1009
+ - `shutdown()` returns `Result<(), NatsPublisherError>` instead of `()`.
1010
+ The new `#[non_exhaustive]` `NatsPublisherError` (re-exported at the
1011
+ root, in the prelude and from `orderbook::nats`) has `TaskPanicked {
1012
+ message }` (for example a panicking caller-supplied serializer, or a
1013
+ runtime without the time driver) and `TaskCancelled` (the runtime shut
1014
+ down first). It converts into `OrderBookError::NatsPublishError`. Only
1015
+ the call that joins the task reports the outcome; repeated calls return
1016
+ `Ok(())`. Callers add `?` or handle the result.
1017
+ - Builder values are clamped with a `tracing::warn!` instead of panicking
1018
+ later: `with_batch_window_ms` and `with_min_publish_interval_ms` to
1019
+ 60,000 ms (`MAX_BATCH_WINDOW_MS`, `MAX_MIN_PUBLISH_INTERVAL_MS`),
1020
+ `with_max_batch_size` into `1..=65_536` (`MAX_BATCH_SIZE`) and
1021
+ `with_channel_capacity` into `1..=MAX_CHANNEL_CAPACITY` (Tokio's
1022
+ `Semaphore::MAX_PERMITS`). Configurations inside those ranges behave
1023
+ as before. `max_batch_size(0)` previously dropped buffered events on
1024
+ shutdown; it now means `1`.
1025
+ - Retries use capped exponential backoff with jitter: retry `n` waits a
1026
+ delay in `[c / 2, c]` with `c = min(10 ms * 2^n, 5 s)`
1027
+ (`BASE_RETRY_DELAY_MS`, `MAX_RETRY_DELAY_MS`); the old delay doubled
1028
+ without a cap (up to `u64::MAX` ms). The jitter is a hash of a
1029
+ per-publisher seed, the message sequence and the retry index; no new
1030
+ dependency.
1031
+ - Shutdown is observed while a batch window is open or a
1032
+ `min_publish_interval_ms` throttle wait is running (not only when
1033
+ idle), closes the channel before draining so the drain terminates, and
1034
+ skips the publish throttle. Events sent after shutdown, or after the
1035
+ task died, are counted in `dropped_events`; a closed channel logs one
1036
+ `WARN` instead of one per event, and a full channel one `WARN` per
1037
+ overload episode.
1038
+ - Counters and sequences never wrap: a sequence that would overflow
1039
+ refuses the publish (counted in `error_count`, logged at `ERROR`). A
1040
+ book-change batch reserves the sequences for all of its subjects
1041
+ (`changes`, `bid`, `ask`) in one step, so it is published on every
1042
+ subject or refused whole, never partially.
1043
+ Poisoned task-lifecycle locks are recovered instead of detaching the
1044
+ task. Connect / disconnect transitions of the publish path are logged
1045
+ at `INFO`.
1046
+ - The runtime handed to `new` must have its time driver enabled; this is
1047
+ now documented (module docs, `doc/panic-boundaries.md`).
1048
+ - Wire format and subjects are unchanged.
1049
+ - **Book managers are runtime-safe, stoppable and observable (#255).**
1050
+ `BookManagerTokio::start_trade_processor` called `tokio::spawn`, which
1051
+ panics outside a Tokio runtime, and `BookManagerStd` used
1052
+ `std::thread::spawn`, which panics if the OS refuses a thread. Neither
1053
+ processor had a shutdown path and a failed trade-event send was only
1054
+ logged, once per event. Both managers, in parity:
1055
+ - `start_trade_processor()` now returns `Result<(), ManagerError>`
1056
+ instead of handing out the thread / task `JoinHandle`; the manager
1057
+ keeps it. `BookManagerTokio` uses `Handle::try_current()` and returns
1058
+ `ManagerError::NoRuntime` outside a runtime; `BookManagerStd` spawns a
1059
+ named thread (`orderbook-trade-processor`) through
1060
+ `std::thread::Builder` and returns `ManagerError::ThreadSpawn { kind,
1061
+ message }` if the OS refuses. A failed start consumes nothing and can
1062
+ be retried.
1063
+ - New `start_trade_processor_with(handler)` runs a caller-supplied
1064
+ `FnMut(TradeEvent)` for every trade event instead of the built-in
1065
+ `INFO` logger; `BookManagerTokio::start_trade_processor_on(&Handle,
1066
+ handler)` starts it from any thread on an explicit runtime.
1067
+ - New `stop_trade_processor()` (blocking on `BookManagerStd`, `async` on
1068
+ `BookManagerTokio`) signals the processor, lets it handle every event
1069
+ already queued, then joins the thread / awaits the task. A panicked
1070
+ processor is `ManagerError::ProcessorPanicked { message }`, a cancelled
1071
+ Tokio task `ManagerError::ProcessorCancelled`, and a call with nothing
1072
+ running `ManagerError::ProcessorNotRunning`. A stopped processor cannot
1073
+ be restarted (`ProcessorAlreadyStarted`). Trading that overlaps the
1074
+ stop (a removed book on another thread) loses nothing: every trade
1075
+ event is either handled or counted as dropped. `BookManagerStd` closes
1076
+ producer admission and waits for in-flight sends before the final
1077
+ drain; `BookManagerTokio` closes its receiver first.
1078
+ - New `dropped_trade_events()` counts trade events a listener could not
1079
+ deliver because the processor is gone; with the `metrics` feature each
1080
+ one also increments `orderbook_manager_trade_events_dropped_total`. The
1081
+ first drop is logged at `ERROR` once per manager, not once per event.
1082
+ - `ManagerError` (already `#[non_exhaustive]`) gains `NoRuntime`,
1083
+ `ThreadSpawn`, `ProcessorNotRunning`, `ProcessorPanicked` and
1084
+ `ProcessorCancelled`.
1085
+
1086
+ Compatibility: code that bound or joined the returned handle (`let h =
1087
+ mgr.start_trade_processor()?; ... h.join()` / `h.await`) calls
1088
+ `mgr.stop_trade_processor()` (`.await` on Tokio) instead; code that
1089
+ ignored the handle compiles unchanged. Calling `start_trade_processor`
1090
+ on `BookManagerTokio` outside a runtime is an `Err` instead of a panic.
1091
+ Dropping a manager without stopping still ends the processor once every
1092
+ book's listener is dropped, as before. The default processor's log lines
1093
+ now use structured fields (`symbol`, `trades`, `executed_quantity`;
1094
+ `quantity`, `price`, `trade_id`) instead of formatted messages. No
1095
+ change to matching, trade events or snapshots.
1096
+ `doc/panic-boundaries.md` lists the trade handler's no-panic obligation and the `crossbeam::channel` / `tokio`
1097
+ surface the processors use.
1098
+
1099
+ - **Wire encoders return `Result` (#254).** `encode_exec_report`, `encode_trade_print` and
1100
+ `encode_book_update` (feature `wire`) reserved their fixed payload with
1101
+ `Vec::reserve`, which panics with "capacity overflow" when the caller's
1102
+ buffer cannot grow. They now reserve with `Vec::try_reserve` and return
1103
+ `Result<(), WireError>`; the new `WireError::CapacityOverflow` variant
1104
+ reports the failure and leaves the buffer unchanged. Decoders (`decode_frame`,
1105
+ `decode_exec_report`, `decode_trade_print`, `decode_book_update`) read
1106
+ through a shared checked-offset helper (`checked_add` +
1107
+ `slice::get` + `<[u8; N]>::try_from`) instead of `copy_from_slice` and
1108
+ raw `offset + N`; the frame length prefix converts with
1109
+ `usize::try_from`. `NewOrderWire` to `OrderType` converts the price with
1110
+ `u64::try_from` instead of an `as` cast and fills the STP user bytes
1111
+ without `copy_from_slice`. The inbound layout size guards are now a
1112
+ compile-time type equality (`[(); N] = [(); size_of::<T>()]`) instead of
1113
+ `const _: () = assert!(..)`: still rejected at compile time, no
1114
+ `assert!` form. `src/orderbook/metrics.rs` documents the caller-installed
1115
+ `metrics` recorder boundary (must not panic; owns its counter overflow
1116
+ semantics); it needed no code change.
1117
+
1118
+ **Compatibility:** the wire format is unchanged: every frame and payload
1119
+ encodes and decodes byte-for-byte as before, and malformed input returns
1120
+ the same `WireError` variants (`Truncated` / `InvalidPayload`) as
1121
+ before. Callers of the three encoders add `?` (or handle the error).
1122
+ `WireError` is `#[non_exhaustive]`, so downstream matches already carry
1123
+ a wildcard arm for `CapacityOverflow`. Metrics names, labels and values are
1124
+ unchanged.
1125
+
1126
+ - **Book analytics return `Result` with checked aggregates (#245).**
1127
+ The read-only analytics used raw `price * qty` (`vwap`, `market_impact`,
1128
+ `simulate_market_order`), `.sum()` (`buy_sell_pressure`, the snapshot
1129
+ totals, the enriched-snapshot depth) and saturating folds, so type-valid
1130
+ extreme inputs panicked in debug and wrapped or clamped in release; about
1131
+ 30 sites also read a level whose `visible + hidden` total overflows as
1132
+ `0` (`total_quantity().unwrap_or(0)`), or as `u64::MAX` in
1133
+ `total_quantity_at_price`. Every level read now goes through one helper
1134
+ that returns the level's `PriceLevelError`, `u128` notionals and `u64`
1135
+ depth sums use checked arithmetic, and the analytics return
1136
+ `Result<_, OrderBookError>`:
1137
+ - `OrderBook`: `vwap`, `micro_price`, `order_book_imbalance`,
1138
+ `market_impact`, `simulate_market_order`, `price_at_depth`,
1139
+ `price_at_depth_adjusted`, `cumulative_depth_to_target`,
1140
+ `total_depth_at_levels`, `liquidity_in_range`, `total_quantity_at_price`,
1141
+ `get_volume_by_price`, `depth_statistics`, `buy_sell_pressure`,
1142
+ `is_thin_book`, `depth_distribution`, `find_level`.
1143
+ - `levels_with_cumulative_depth`, `levels_until_depth` and
1144
+ `levels_in_range` yield `Result<LevelInfo, OrderBookError>`; the first
1145
+ `Err` (level overflow or cumulative-depth overflow) is yielded once and
1146
+ the iterator is then exhausted (`FusedIterator`), so no depth is
1147
+ reported past a failed level.
1148
+ - `OrderBookSnapshot::{total_bid_volume, total_ask_volume,
1149
+ total_bid_value, total_ask_value}`, `EnrichedSnapshot::{new,
1150
+ with_metrics}`, `OrderSimulation::total_cost` and
1151
+ `DistributionBin::width`.
1152
+ - New `OrderBookError::ArithmeticOverflow { operation: &'static str }`
1153
+ and `OrderBookError::AllocationFailed { operation, requested }`, both
1154
+ mapped to wire code `RejectReason::Other(0)` and classified as
1155
+ non-mutating by the sequencer (they are never raised by a submit).
1156
+ `OrderBookError` stays within its 96-byte size budget.
1157
+ - `depth_distribution` caps `bins` at the new
1158
+ `MAX_DEPTH_DISTRIBUTION_BINS` (4096), reserves with
1159
+ `Vec::try_reserve_exact`, computes bin bounds with checked arithmetic,
1160
+ reads the price range from the two ends of the level map and bins only
1161
+ that observed band, and indexes with `get_mut`. A level at `u128::MAX`
1162
+ (whose exclusive last-bin bound `u128::MAX + 1` is not representable)
1163
+ returns `ArithmeticOverflow`.
1164
+ Bin bounds are clamped to `max_price + 1`, so bins are contiguous and
1165
+ never inverted (`DistributionBin::width` is always `Ok` for them): when
1166
+ `bins` exceeds the observed price span, the surplus trailing bins are
1167
+ empty zero-width bins at `max_price + 1` (0.13 let them run past the
1168
+ range, ending with an inverted last bin).
1169
+ - Pegged orders referencing `MidPrice` (feature `special_orders`) use the
1170
+ exact integer midpoint (`u128::midpoint`, rounded down) instead of
1171
+ `mid_price() as u128`, which lost precision above 2^53. The `Mid` risk
1172
+ reference price shares the same helper (unchanged result).
1173
+ - `market_impact` reports `slippage` as `worst.abs_diff(best)`: equal to
1174
+ the previous value on a settled book, the true distance (instead of `0`)
1175
+ if the best price moves between the cache read and the walk.
1176
+
1177
+ **Compatibility:** source-breaking for callers of the listed functions:
1178
+ add `?` (or handle the error) and handle each iterator item (`level?`,
1179
+ or `collect::<Result<Vec<_>, _>>()?`). Values are unchanged for every
1180
+ book whose aggregates fit their types; the only visible differences are
1181
+ that an overflow is now an `Err` instead of a panic / wrapped / clamped
1182
+ value, `total_quantity_at_price` no longer returns `Some(u64::MAX)` for an
1183
+ overflowed level, a `depth_distribution` request above 4096 bins returns
1184
+ 4096 bins, and a pegged mid-price order above 2^53 reprices to the exact
1185
+ midpoint. The matching path (`peek_match`, sweeps, fill-or-kill
1186
+ feasibility) is untouched: no trade, event, journal or snapshot format
1187
+ changes. `OrderBookError` is `#[non_exhaustive]`, so downstream matches
1188
+ already carry a wildcard arm for the two new variants.
1189
+
1190
+ ### Changed
1191
+
1192
+ - **Performance: measured and recovered for 0.14.0 (#259).** Two engine
1193
+ fixes, no behaviour or format change:
1194
+ - A fully filled maker is removed from the `user_orders` index by its
1195
+ owner, which the order-location index now carries
1196
+ (`OrderLocation { price, side, user_id }`), instead of a scan over every
1197
+ user's entry (O(active users) per filled maker, one shard guard
1198
+ allocated per shard visited, hash-seed dependent). Order-preserving
1199
+ removal (#252) and location-last release (#288) are kept.
1200
+ `get_order_locations_arc` and the `Serialize` output keep their
1201
+ `(price, side)` shape.
1202
+ - A passive add to an existing price level no longer builds and drops a
1203
+ whole `PriceLevel` (`SkipMap::get_or_insert` evaluated its value
1204
+ eagerly; a pricelevel 0.10 level owns a DashMap whose shard array is
1205
+ about 16 KB on an 18-core host). `get_or_insert_with` builds a level
1206
+ only for a new price.
1207
+
1208
+ Allocation profile (`alloc_count`): passive add on one level 6.3 allocs /
1209
+ 18.3 KB per op to 3.3 / 0.95 KB; full-fill cross 18 to 128 allocs per op
1210
+ (seed dependent) to 3.0; one-level market sweep 44 to 119 to 2.0;
1211
+ mixed 70/20/10 16.5 to 32.4 allocs / 9.4 KB to 3.35 / 3.3 KB.
1212
+
1213
+ The release head (`b8e2337`, pricelevel 0.10.2) against v0.13.1
1214
+ (`scripts/bench_compare.sh`, 5 interleaved rounds, same harness on both
1215
+ sides, p50 median, verdicts generated by the summarizer): `add_only`
1216
+ -43 %, `mixed_70_20_10` -48 %, `stp_cancel_maker` -68 %,
1217
+ `snapshot_create_10k` -51 %, `snapshot_restore_10k` -67 %,
1218
+ `replay_10k` -59 %, `mass_cancel_burst` -40 %, `contended_add_4t`
1219
+ -40 %. The one regression, `contended_add_listeners_8t` +16.5 % (#247
1220
+ level stripes, #249 ordered outbox), and the slower cancel-miss path
1221
+ (+8 ns: #249, #294) are accepted by the maintainer as the cost of the
1222
+ 0.14.0 guarantees
1223
+ ([decision on #259](https://github.com/joaquinbejar/OrderBook-rs/issues/259#issuecomment-5896324957)); #259's "no unresolved regression"
1224
+ criterion is scoped by that decision. The `snapshot_create_10k` +6.2 %
1225
+ seen on the #259 branch with pricelevel 0.10.1 is gone on the release
1226
+ head. Full tables, bisections and raw rounds: `BENCHMARKS.md`,
1227
+ `BENCH.md` "0.13.1 → 0.14.0 delta" and `doc/bench/0.14.0/`.
1228
+ - **Benchmark harness (#259).** `benches/compare` covers fourteen
1229
+ scenarios on both versions (adds, cancels, walks, mixed, thin book,
1230
+ mass cancel, STP, snapshot create / restore, replay, contended adds with
1231
+ and without listeners), draws every input before the clock and drops
1232
+ every output after it, and seeds the cancel scenarios with a
1233
+ non-crossing book whose size it asserts. `scripts/bench_compare.sh`
1234
+ records per-run load and reports p50 / p99 with a generated verdict
1235
+ (+3 % uncontended, +5 % contended, NOISY above 10 pp spread, one-tick
1236
+ rule for single-op timing, separation rule for disjoint 5+-round
1237
+ ranges). HDR benches: `aggressive_walk_hdr` / `notional_walk_hdr` keep
1238
+ their ask ladder stocked (before, about 98 % of their samples timed a
1239
+ market order rejected by an empty book) and inspect results after the
1240
+ clock; `cancel_only_hdr` / `mass_cancel_burst_hdr` seed a non-crossing
1241
+ book (before, most timed cancels were misses). Their numbers are not
1242
+ comparable with earlier runs.
1243
+ - **The Production Panic Policy gate is absolute (#260).** The temporary
1244
+ ratchet ledgers used during the cycle (`scripts/panic_policy_allowlist.txt`,
1245
+ `scripts/clippy_ratchet.txt`, `scripts/check_clippy_ratchet.py`, the
1246
+ `make lint-clippy-ratchet` target and the per-file
1247
+ `// panic-policy-ratchet` allows) were removed once every entry was fixed.
1248
+ `scripts/check_panic_policy.py` has no allowlist any more (its
1249
+ `--write-allowlist` / `--ratchet-report` modes are gone): any finding
1250
+ fails, and it now also fails on a production `#[allow]` / `#[expect]`
1251
+ (inner, outer or inside `cfg_attr`) of a lint `[lints.clippy]` denies,
1252
+ or of a group containing one (`clippy::restriction`, `clippy::pedantic`,
1253
+ and `clippy::all` as a catch-all).
1254
+ The inline `panic-policy-allow-saturating` marker is the only exception
1255
+ form. Tooling only: no public API or behaviour change.
1256
+ - `tests/alloc_budget.rs` (feature `alloc-counters`) now asserts the median
1257
+ over seven independent measured windows against a ceiling of 15.0
1258
+ allocs/op, derived from the measured per-process range (about 6.5 to
1259
+ 10.4) instead of a single window against 10.0, which flipped on noise.
1260
+ CI now runs it (#262). Test-only change.
1261
+ - **Behaviour from pricelevel 0.10.** `PriceLevel::new` starts
1262
+ `first_arrival_time` at `0` (unstamped) instead of the wall clock, so
1263
+ identical input yields identical level snapshot checksums.
1264
+ `matchable_quantity` replays the queue in sweep (insertion) order, so a
1265
+ fill-or-kill verdict involving iceberg / reserve replenishment follows
1266
+ what the sweep actually executes. No existing test expectation changed.
1267
+ - `impl Serialize for OrderBook` maps a failed level snapshot to a serde
1268
+ error; the JSON shape is unchanged (no `Ok` wrapper), pinned against a
1269
+ 0.13.1 capture.
1270
+ - Snapshot restore materializes every level's orders in its validation
1271
+ phase, so the commit phase stays infallible.
1272
+ - Dependency floors raised to the latest semver-compatible releases: uuid
1273
+ 1.26.1, serde_json 1.0.151, serde 1.0.229, crossbeam 0.8.5, bitflags
1274
+ 2.13.2, thiserror 2.0.21, bytes 1.12.1, crc32fast 1.5.2, memmap2 0.9.11,
1275
+ metrics 0.24.6, zerocopy 0.8.59; dev-dependency hdrhistogram 7.6; examples
1276
+ metrics-exporter-prometheus 0.18.3 (#237). `bincode` stays on 2.0.1: the
1277
+ 3.0.0 release on crates.io is a tombstone whose library is a single
1278
+ `compile_error!`. No new dependencies and no feature changes.
1279
+
1280
+ ### Fixed
1281
+
1282
+ - **Core boundary gaps found by the final audit (#294).** Engine
1283
+ consistency around caller-supplied code; no panic was reachable with
1284
+ valid input.
1285
+ - An unwind under the **shared** side of the submit gate left no trace
1286
+ (a `RwLockReadGuard` never poisons): a panicking `Clock`, metrics
1287
+ recorder, `tracing` subscriber or `T::default()` running mid-mutation
1288
+ in an ordinary submit, cancel or modify left the book possibly
1289
+ inconsistent and still accepting flow. `SubmitGateGuard`'s drop now
1290
+ checks `std::thread::panicking()` (once per drop, against the value
1291
+ at acquisition, like std's own poison flag) and, on either side,
1292
+ engages the kill switch and latches `submit_gate_poisoned()` before
1293
+ the gate is released, logging once at `ERROR`.
1294
+ - The sweep drain ran the per-maker caller code (`track_state`'s
1295
+ `Clock` and `record_reject`, the strandable-maker `INFO`,
1296
+ `record_reserve_hidden_discarded`) before each maker's index cleanup,
1297
+ so an unwind left ghost locations and user-index entries for every
1298
+ maker not cleaned yet. A drop guard now releases the indices of every
1299
+ maker not released yet while the drain unwinds. The per-maker order
1300
+ (state recorded, then location released) is kept on purpose: the
1301
+ location is the id's ownership token (#288), and releasing it first
1302
+ would let a same-id order admitted meanwhile have its resting state
1303
+ overwritten by the old order's `Filled`. Event order is unchanged.
1304
+ - The rest path claims an order's location and publishes its
1305
+ user-index entry, risk reservation and resting state before the level
1306
+ admits it (#288), running caller code in between (`Clock`, metrics,
1307
+ `T::default()`). A panic there left all of them, and possibly a new
1308
+ empty level, behind for an order no level holds. A drop guard now
1309
+ withdraws them: the recorded state first (clock-free), then in #288's
1310
+ release order the user index and reservation, then the location, so
1311
+ every rollback happens while the attempt still owns the id and a
1312
+ same-id order admitted concurrently cannot have its own transition
1313
+ popped; it then removes the empty level. Review follow-up (PR #297):
1314
+ `T::default()` (the unit conversion) now runs before the level stripe
1315
+ is taken; and a panic raised by the gate guard's own commit phase
1316
+ (caller `tracing` code under the held gate, inside the guard's drop)
1317
+ is caught by a commit sentinel that engages the kill switch and
1318
+ latches `submit_gate_poisoned()`.
1319
+ - A standalone `OrderStateTracker::transition` invoked its listener
1320
+ before queuing a terminal id for eviction, so a panicking listener
1321
+ left the id retained forever. The id is queued first.
1322
+ - The listener dispatcher could spin forever when its delivery buffer
1323
+ persistently refused to grow (`try_reserve`): the head batch stayed
1324
+ ready and was never taken. It is now delivered in place.
1325
+ - Dead code: the unused `next_order_id` counter is gone and the
1326
+ drop-only submit-gate guard fields are `_`-prefixed instead of
1327
+ `#[allow(dead_code)]`.
1328
+
1329
+ Cost, measured against main 4567530 with interleaved rounds (medians,
1330
+ on a loaded machine): one `thread::panicking()` read per gate
1331
+ acquisition and per drop, and no allocation in the drain.
1332
+ `aggressive_walk_hdr` p50 / p99 / p99.9 +0.0% / -1.4% / +1.6% (10
1333
+ rounds); `add_limit_orders` +0.6%, `add_limit_orders_with_listeners`
1334
+ +0.6%, `match_market_against_limit` -2.3%,
1335
+ `match_market_against_limit_with_listeners` +0.6%,
1336
+ `match_market_against_iceberg` -0.9% (5 rounds). The rest-path claim
1337
+ guard, against main e0762f4: `add_only_hdr` p50 / p99 / p99.9
1338
+ +1.9% / -3.4% / -3.7% (8 rounds); `add_limit_orders` +0.7%,
1339
+ `add_limit_orders_with_listeners` +1.1%, `match_market_against_limit`
1340
+ +0.8% (4 rounds). All within noise.
1341
+
1342
+ - **Panic-free matching, STP and matching pool (#246).** The last
1343
+ panicking forms in `matching.rs`, `stp.rs` and `pool.rs` are gone:
1344
+ - The `STPMode::CancelMaker` fill-or-kill walk summed the non-self depth
1345
+ with `.sum()`: resting depth past `u64::MAX` (legal with a large
1346
+ visible tranche plus an iceberg's hidden tranche) panicked in debug
1347
+ and, in release, wrapped into a false kill. It now accumulates
1348
+ `min(cap, depth)` with checked adds, so such a level reads as exactly
1349
+ the taker's cap and the FOK fills. The STP `safe_quantity` scan uses
1350
+ the same bounded accumulator (`min(Σ visible, u64::MAX)`), exact for
1351
+ every consumer.
1352
+ - The thread-local matching pool is reached with `LocalKey::try_with`
1353
+ and `RefCell::try_borrow_mut`: a sweep run from a thread-local
1354
+ destructor after the pool was torn down, or a reentrant pool access,
1355
+ uses fresh buffers instead of panicking.
1356
+ - The three `debug_assert!`s on the #225 STP snapshot invariant are now
1357
+ a debug-build check that logs at `ERROR` (maker id, price, site)
1358
+ instead of panicking; release builds still skip it.
1359
+ - The per-level budget (`remaining - executed`, the quote-notional
1360
+ `price × executed` deduction, lot rounding, the `u128` to `u64` level
1361
+ cap) uses checked forms and `u64::try_from`. These invariants cannot
1362
+ fail on a valid book (the level cap is derived from the same budget
1363
+ the deduction checks against), so valid traffic and existing journals
1364
+ replay unchanged; a breach, which can only come from already corrupt
1365
+ state, aborts the sweep with its committed prefix
1366
+ (`OrderBookError::MatchAborted`) instead of being clamped.
1367
+ - Quote-notional normalization no longer returns the un-normalized
1368
+ result, with its `u64::MAX` working bound in `remaining_quantity()`,
1369
+ as a success when the rebuild fails: the committed trades are
1370
+ reported as `MatchAborted` and the failure is logged.
1371
+
1372
+ Compatibility: identical trades, fees, events and order states for
1373
+ every valid input; no snapshot, journal or wire format change
1374
+ (`ORDERBOOK_SNAPSHOT_FORMAT_VERSION` stays 4) and no replay impact. The
1375
+ only behaviour changes are on the overflow and invariant-breach paths
1376
+ above, which used to panic, wrap or clamp. `peek_match` changes
1377
+ signature (see "Changed (breaking)").
1378
+
1379
+ - **Journals hardened against corruption and misuse (#252).**
1380
+ - `FileJournal` rotation created segments with `create(true).truncate(true)`
1381
+ and `append` never checked sequences, so a duplicate or restarted
1382
+ sequence at a rotation boundary truncated an existing segment (and
1383
+ could `SIGBUS` a reader that had it mapped). Segments are now created
1384
+ with `create_new`; an existing file fails the append with the new
1385
+ `JournalError::SegmentExists { path }` and is left untouched. Both
1386
+ `FileJournal` and `InMemoryJournal` refuse a `sequence_num` that is not
1387
+ strictly greater than the last one with the new
1388
+ `JournalError::NonMonotonicSequence { last, attempted }`, before
1389
+ anything is written. On reopen `FileJournal` recovers the last sequence
1390
+ from the newest non-empty segment, so the check survives a restart.
1391
+ - A malformed entry header ended a segment silently, so replay
1392
+ "succeeded" on a prefix. Only a zero `entry_length` is now the end of
1393
+ data; any other bad header (below the 20-byte minimum, past the end of
1394
+ the segment, a truncated non-zero length field) is
1395
+ `Some(Err(JournalError::InvalidEntryHeader { .. }))` from reads, after
1396
+ which the iterator stops, and the same error from `verify_integrity`,
1397
+ which also reports stored sequences that do not strictly increase
1398
+ (`NonMonotonicSequence`). A header sequence that disagrees with the
1399
+ CRC-valid payload is a `DeserializationError`.
1400
+ - Torn-tail recovery left the torn bytes in place, so a later, shorter
1401
+ append left stale bytes that decoded as the next header. Reopen now
1402
+ zeroes every non-zero byte past the recovered write position (only
1403
+ dirty 4 KiB chunks are written, so the sparse tail is not
1404
+ materialised) and flushes them. A damaged entry followed by a valid
1405
+ one is corruption inside committed data, not a torn tail: reopen scans
1406
+ every offset after the damage (skipping zero runs), and if any valid
1407
+ entry follows, even behind several damaged ones, `open` refuses with
1408
+ `JournalError::CorruptEntry` (or `InvalidEntryHeader`) and leaves the
1409
+ file unchanged instead of truncating and later overwriting the valid
1410
+ entries. Readers never read past the committed write position of the
1411
+ active segment, and an active segment whose file is shorter than that
1412
+ position (an external truncation, even on an entry boundary) is
1413
+ `InvalidEntryHeader` instead of a silently shorter replay.
1414
+ - The writer's segment, `last_seq` and active segment start now live
1415
+ under one mutex, so `last_seq` is updated under the same guard as the
1416
+ durable write and cannot be left behind by a poisoned second lock;
1417
+ `archive_segments_before` holds it so a rotation cannot race the
1418
+ renames. A poisoned lock is `JournalError::MutexPoisoned` on every
1419
+ method of both journals (it was `Io` in `InMemoryJournal`, and `None`
1420
+ from `last_sequence`, which `ReplayEngine` reported as `EmptyJournal`).
1421
+ - Capacity comes from the mapping length instead of file metadata; the
1422
+ write slice, the 32-bit `entry_length` (`u32::try_from`, a payload over
1423
+ ~4 GiB is `EntryTooLarge`), the encode buffer (`try_reserve_exact`,
1424
+ new `JournalError::AllocationFailed { what, requested }`) and every
1425
+ byte decode use checked forms. The `memmap2` mapping stays a
1426
+ documented `unsafe` exception.
1427
+ - **Replay reconciles mass cancels by identity (#252).** A journaled
1428
+ non-refused `MassCancelled` for `CancelAll` / `CancelBySide` /
1429
+ `CancelByUser` / `CancelByPriceRange` is re-executed and the replayed
1430
+ cancelled ids must equal the journaled ones **in order**, the orders
1431
+ left resting by per-order failures (`failed_order_ids()`) must match in
1432
+ order, and the replay must not refuse. A journaled eviction must evict
1433
+ exactly its journaled ids in order. Disagreements are the new
1434
+ `ReplayError::MassCancelMismatch { sequence_num, divergence, recorded,
1435
+ replayed }` (`MassCancelDivergence::{Refusal, CancelledIds, FailedIds}`)
1436
+ instead of passing on equal counts or surfacing as a generic
1437
+ `OrderBookError`. `LevelFaultAfterRemoval` entries are fault reports, not
1438
+ book outcomes, and are not compared. A live mass cancel with per-order
1439
+ failures normally stops replay here by design (a fresh replay book does
1440
+ not reproduce the level fault).
1441
+ - **A fill no longer reorders a user's resting orders (#252).** Removing a
1442
+ filled maker from the `user_orders` index used `swap_remove`, which moved
1443
+ the user's last order into the filled one's slot, so
1444
+ `cancel_orders_by_user` did not follow admission order as documented. The
1445
+ removal now preserves order (`Vec::remove`; still linear in that user's
1446
+ list, as the lookup already was). Replay was consistent with the live
1447
+ book either way; with identity reconciliation the documented order
1448
+ matters wherever the index is rebuilt differently.
1449
+
1450
+ - **Checked counters, snapshot restore validation and remaining core forms
1451
+ (#250).** `engine_seq` was minted with a wrapping `fetch_add` and is
1452
+ restored verbatim from an untrusted snapshot package, so a package
1453
+ carrying `u64::MAX` made the next event wrap to `0`.
1454
+ `OrderBook::next_engine_seq()` now returns `Result<u64, OrderBookError>`
1455
+ and refuses with the new `OrderBookError::EngineSeqExhausted { engine_seq }`
1456
+ instead of wrapping (the last mintable value is `u64::MAX - 1`). The
1457
+ engine's own emission paths run after the mutation, so on exhaustion they
1458
+ suppress the listener `TradeResult` / `PriceLevelChangedEvent` (logged
1459
+ once at `ERROR`, reported by the new `OrderBook::engine_seq_exhausted()`)
1460
+ instead of stamping a wrapped sequence; the book keeps matching. A
1461
+ caller-owned result is never affected: `add_order_with_result` and the
1462
+ `*_with_committed` APIs still return their committed fills, stamped with
1463
+ the new `UNSTAMPED_ENGINE_SEQ` (`u64::MAX`, never minted). All
1464
+ `PriceLevelChangedEvent` emissions now go through one helper.
1465
+ Snapshot restore, both `restore_from_snapshot` and
1466
+ `restore_from_snapshot_package`, now rejects in the prepare phase, before
1467
+ any live state is touched: a crossed or locked book (best bid >= best ask,
1468
+ new `OrderBookError::SnapshotCrossed { best_bid, best_ask }`); an order
1469
+ whose `visible + hidden` does not fit `u64` (`QuantityOverflow`, now
1470
+ checked for every order, not only when risk is rebuilt; pricelevel's level
1471
+ validation already refuses it first as `PriceLevelError`); and, on the
1472
+ package path, `engine_seq == u64::MAX` (`EngineSeqExhausted`). A package
1473
+ restore clears the exhaustion latch. `OrderBookSnapshot::refresh_aggregates`
1474
+ returns `Result` and `OrderBookSnapshotPackage::new` propagates its error
1475
+ instead of checksumming stale aggregates. `spread()` (book and snapshot)
1476
+ and `spread_bps()` return `None` for a crossed read instead of a clamped
1477
+ `0`. The strandable-maker count, `StubClock`, the order-state tracker's
1478
+ purge cutoff and purge count, the repricing counters and the trade /
1479
+ depth metric casts use checked forms: the strandable count refuses (and
1480
+ logs at `WARN`) an increment past `usize::MAX` or a decrement at zero;
1481
+ `StubClock` stops at its last representable value instead of wrapping
1482
+ (`StubClock::is_exhausted()`, logged once); a retention window reaching
1483
+ before the clock's epoch purges nothing. The order-state tracker
1484
+ recovers a poisoned terminal-queue mutex (the queue is an eviction hint,
1485
+ re-checked per id) instead of silently skipping eviction forever. Each
1486
+ order's status and history now live in one map entry, so a transition
1487
+ updates both atomically and an eviction (`DashMap::remove_if` on that
1488
+ entry) removes exactly the lifecycle it checked: an id re-activated or
1489
+ re-terminated concurrently is never evicted or split from its history.
1490
+ The eviction queue lock is never held while a map lock is taken.
1491
+ Compatibility: `next_engine_seq()` and
1492
+ `OrderBookSnapshot::refresh_aggregates()` change signature (see the
1493
+ migration table). `OrderBookError` gains `EngineSeqExhausted` and
1494
+ `SnapshotCrossed` (wire code `RejectReason::Other(0)`; the enum is
1495
+ `#[non_exhaustive]`). Restore now rejects packages and snapshots that
1496
+ earlier versions accepted: crossed or locked books (a live book never
1497
+ rests one; such a state only came from hand-merged or corrupted
1498
+ snapshots, including the #194 recovery fixture with a trailing stop
1499
+ inside the market) and packages with `engine_seq == u64::MAX`. Tick and
1500
+ lot alignment is deliberately not enforced on restore, because a live
1501
+ book keeps orders admitted under a previous tick or lot size (see
1502
+ `set_lot_size`), and its snapshot must keep restoring. `spread()` /
1503
+ `spread_bps()` can return `None` where they used to return `Some(0)`.
1504
+ An `OrderStateTracker::purge_terminal_older_than` window longer
1505
+ than the clock's current value no longer purges entries stamped at `0`.
1506
+ No snapshot, journal or wire format change:
1507
+ `ORDERBOOK_SNAPSHOT_FORMAT_VERSION` is unchanged.
1508
+
1509
+ - **Default trade-id namespace no longer reads panicking OS entropy
1510
+ (#265).** `OrderBook::new`, `with_clock`, `with_trade_listener`,
1511
+ `with_trade_and_price_level_listener` (and every constructor built on
1512
+ them) minted the trade-id namespace with `Uuid::new_v4()`, which panics
1513
+ through `getrandom` when the OS RNG fails. The namespace is now a UUIDv5
1514
+ derived from the symbol, the process id, the wall clock in nanoseconds
1515
+ (`0` before the epoch) and a process-wide `checked_add` construction
1516
+ counter: distinct for every book in a process, across concurrent
1517
+ processes and across restarts (argument in the function docs and
1518
+ `doc/panic-boundaries.md`). No `Uuid::new_v4()` remains in production
1519
+ code; std's `RandomState` seeding (behind `HashMap` / `DashMap`) is the
1520
+ documented remaining OS-entropy read.
1521
+ Compatibility: constructor signatures are unchanged and still
1522
+ infallible. Default namespaces are UUID version 5 instead of version 4
1523
+ and are still unique per book; trade ids keep their format (UUIDv5 over
1524
+ namespace + counter). `set_trade_id_namespace`,
1525
+ `with_clock_and_namespace` and `ReplayBookConfig` injection are
1526
+ unchanged, so replay is unaffected. No wire, journal or snapshot format
1527
+ change.
1528
+
1529
+ - **Checked time and allocation-counter helpers (#257).**
1530
+ `current_time_millis()` narrowed the `u128` millisecond count to `u64`
1531
+ with `as` and silently returned `0` for a clock set before the UNIX
1532
+ epoch. The new `try_current_time_millis() -> Result<u64, TimeError>`
1533
+ converts with `u64::try_from` and reports `TimeError::ClockBeforeEpoch`
1534
+ or `TimeError::MillisOverflow`. `current_time_millis()` stays infallible
1535
+ (its production callers, `MonotonicClock::now_millis`, the book-manager
1536
+ trade listeners and the NATS book-change batch timestamp, have no error
1537
+ channel) and now documents its fallback: `0` before the epoch, `u64::MAX`
1538
+ on overflow (instead of a truncated value), each logged once per process
1539
+ with `tracing::warn!`. Matching still takes time only from the injected
1540
+ `Clock`; no wall-clock read was added. `AllocSnapshot::since` (feature
1541
+ `alloc-counters`) uses `checked_sub` and returns `Option<AllocSnapshot>`,
1542
+ `None` when the snapshots are out of order, instead of clamping to zero.
1543
+ `src/utils/mod.rs` gates its test module with `#[cfg(test)]`.
1544
+ Compatibility: `current_time_millis()` keeps its signature and returns
1545
+ the same value on any sane clock; `try_current_time_millis` and
1546
+ `TimeError` are additive (re-exported from the crate root and the
1547
+ prelude). `AllocSnapshot::since` is source-breaking for
1548
+ `alloc-counters` users: add `.expect(..)` or handle `None`. No wire,
1549
+ journal or snapshot format change.
1550
+ - **Fee and notional arithmetic on the trade path is checked (#244).**
1551
+ Fees and trade notionals used to clamp or vanish on overflow:
1552
+ `FeeSchedule::calculate_fee` clamped the fee, `TradeResult::with_fees`
1553
+ dropped a fee whose running total overflowed, `TradeResult::total_fees`
1554
+ clamped even a negative overflow to `+i128::MAX`, `quote_notional`
1555
+ saturated, and `TradeInfo::from_trade_result` reported a failed
1556
+ `executed_quantity()` as `0`. Every one of them is now checked and
1557
+ typed. Fee representability is validated **before** the book is
1558
+ touched: each taker's worst-case notional (worst reachable price ×
1559
+ quantity; for a limit buy the limit, else the highest ask it can reach; for a
1560
+ sell the best bid; for a `*_by_amount` order the amount) must fit `u128`
1561
+ and be priced exactly by both fee legs, or the taker is rejected
1562
+ untouched with `OrderBookError::FeeOverflow` (reject code 18) or
1563
+ `OrderBookError::NotionalOverflow` (code 19), state
1564
+ `Rejected { FeeOverflow | NotionalOverflow }`. The check runs under the
1565
+ submit gate next to the #240 trade-id check, on every submission API
1566
+ (`add_order*`, `submit_market_order*`, `submit_market_order_by_amount*`,
1567
+ `match_market_order*`, `match_limit_order*`, the raw `match_order*`, and
1568
+ `update_order` before the original is cancelled), with or without a
1569
+ trade listener. Under the shared submit gate it is best effort, like the
1570
+ #240 check: a maker admitted concurrently at a worse price is caught by a
1571
+ per-level backstop in the sweep, which aborts with `MatchAborted` before
1572
+ touching that level. The bound is the worst **reachable** price: a buy
1573
+ walks the asks from the best one until their visible quantity covers
1574
+ its size, so an absurd ask resting far behind the touch cannot make
1575
+ ordinary buys fail. Cost on the common path: one or two cached best-price
1576
+ reads, one level read for a buy that fails the limit fast path, and one
1577
+ or two checked multiplications; no allocation. The sweep's backstop is
1578
+ seeded with the verified price, so levels at or below it cost one
1579
+ comparison. A non-crossing or post-only order is never checked against
1580
+ its notional.
1581
+ - **`FeeSchedule::with_maker_rebate(i32::MIN, _)` no longer panics
1582
+ (#244).** `-maker_rebate_bps.abs()` overflowed; the maker rate is now
1583
+ `-|x|`, which is representable for every `i32`.
1584
+ - **Repricing arithmetic is checked (#244).** A pegged offset of
1585
+ `i64::MIN` no longer overflows its negation (`unsigned_abs`); a pegged
1586
+ price or tick snap above `u128::MAX` and a trailing stop below `0` or
1587
+ above `u128::MAX` now skip the re-price (`None`) instead of saturating.
1588
+ A negative offset deeper than the reference still floors at the minimum
1589
+ valid price, as documented.
1590
+ - **Pre-trade risk uses checked notional arithmetic (#243).** The
1591
+ per-account `resting_notional` counter was updated with a wrapping
1592
+ `fetch_add` and the notional check used `saturating_*`, so two orders
1593
+ whose notional sum exceeded `u128::MAX` could wrap the counter to a
1594
+ small value and bypass `max_notional_per_account`. Every counter update
1595
+ is now a compare-and-swap loop with `checked_add` / `checked_sub`, and
1596
+ admission is all or nothing: the resting remainder's contribution is
1597
+ reserved before the order is placed on its level and released if the
1598
+ placement fails.
1599
+ - **Price band no longer passes at extreme prices (#243).** Both sides of
1600
+ the band comparison saturated to `u128::MAX` at extreme prices and
1601
+ compared equal, so any deviation passed. The comparison is now exact
1602
+ over the whole `u128` domain, with the common path unchanged.
1603
+ - **Release-side underflows are visible (#243).** A fill, cancel or
1604
+ quantity decrease that would take a risk counter below zero (a double
1605
+ release) used to floor silently. It still sets the counter to zero, the
1606
+ only value that keeps the account usable, but now logs a `WARN` with the
1607
+ order, account and counter and increments the anomaly count. A fill
1608
+ larger than the tracked remainder releases only the tracked remainder.
1609
+ The maker-price `debug_assert_eq!` in `on_fill` is now a `WARN`.
1610
+ - **Risk reservations cannot be released by a same-id loser (#243
1611
+ review).** `on_admission` claims the order id and the counters under the
1612
+ order map's shard lock, rejects an id that is already tracked before
1613
+ touching any counter, and returns a generation-tagged reservation; the
1614
+ cleanup after a failed level placement releases only the entry carrying
1615
+ that generation. Before, a concurrent same-id submission could overwrite
1616
+ the winner's entry and its cleanup then released it, leaving the resting
1617
+ winner untracked.
1618
+ - **Discarded reserve remainders are released (#243 review).** A
1619
+ non-auto-replenishing reserve maker removed after its visible tranche is
1620
+ exhausted (#230) kept its discarded hidden quantity booked in the
1621
+ account's risk counters forever (pre-existing on 0.13), counting against
1622
+ `max_open_orders_per_account` and `max_notional_per_account`. The
1623
+ matcher now releases it in the same removal.
1624
+ - **Quantity increases reserve risk before the level changes (#243
1625
+ review).** An in-place quantity increase now pre-books its notional
1626
+ before the price level applies it and settles or rolls it back once the
1627
+ level answers, so a risk overflow is a rejection with the order
1628
+ unchanged instead of a divergence between the book and the risk state.
1629
+ - **Snapshot restore computes risk aggregates in the prepare phase
1630
+ (#243, prepares #250).** When the package carries a risk config, the
1631
+ per-account open-order counts and resting notional are accumulated with
1632
+ checked arithmetic before any live state changes, so an overflowing
1633
+ package fails with a typed error and leaves the book untouched instead
1634
+ of being clamped in the commit phase.
1635
+
1636
+ **Compatibility.** Only books with a `RiskConfig` installed are affected.
1637
+ An admission that previously wrapped the notional counter, or passed the
1638
+ price band because both sides saturated, is now rejected with the
1639
+ existing typed errors (`RiskMaxNotional`, `RiskMaxOpenOrders`,
1640
+ `RiskPriceBand`; same `RejectReason` codes). This applies even when the
1641
+ corresponding limit is `None`: an exposure the counters cannot represent
1642
+ is rejected with `limit = u128::MAX` (or `u64::MAX` for the open-order
1643
+ count), and `attempted = u128::MAX` when `price × quantity` itself
1644
+ overflows. `restore_from_snapshot_package` / `restore_from_snapshot_json`
1645
+ can now return `RiskMaxNotional`, `RiskMaxOpenOrders` or
1646
+ `QuantityOverflow` for a package whose risk aggregates overflow. No
1647
+ snapshot format change; realistic prices and quantities see no behaviour
1648
+ change.
1649
+
1650
+ - **Modifications stop swallowing mutation errors (#247).**
1651
+ - `update_order(OrderUpdate::Cancel)` ignored the level's answer and
1652
+ removed the order's location and user-index entries anyway, leaving a
1653
+ refused order resting but unreachable; it also never recorded the
1654
+ `Cancelled` state, released the risk contribution or unregistered
1655
+ special-order tracking. It now runs the same removal as `cancel_order`:
1656
+ a refusal returns `Err(PriceLevelError)` with the order untouched, a
1657
+ removal the level committed then failed completes and returns
1658
+ `OrderRemovedWithLevelFault` (#248), and a success records
1659
+ `Cancelled { UserRequested }` and releases risk.
1660
+ - A cancel-then-add modify (`UpdatePrice`, `UpdatePriceAndQuantity`,
1661
+ `Replace`) whose re-add failed after the original was cancelled lost the
1662
+ order. The re-add now takes the validate-first verdict as its admission
1663
+ (the kill-switch, risk-limit and shape checks are not re-run after the
1664
+ cancel), and a failure that still happens (a concurrent mutation under
1665
+ the shared gate, a failing level or allocation) is resolved: if nothing
1666
+ traded, the original is restored with the same id, price, quantity and
1667
+ timestamp at the **back** of its level (time priority lost) and the call
1668
+ returns `OrderBookError::ModifyRolledBack`; if the restore fails too, or
1669
+ the re-added order traded before failing, the call returns
1670
+ `OrderBookError::ModifyOrderLost` and the indices hold no trace of the
1671
+ order. A re-add sweep aborted by a failed level after trading still
1672
+ returns `MatchAborted`. A modify whose cancel finds the order already
1673
+ gone (filled concurrently) now returns `Ok(None)` instead of re-adding
1674
+ it.
1675
+ - A submit whose remainder could not be rested after irreversible trades
1676
+ (level admission or risk reservation refused) returned `Err` with no
1677
+ terminal state; the taker now ends
1678
+ `Cancelled { filled_quantity, reason: RestFailed }` (or `Rejected`
1679
+ when it did not trade).
1680
+ - A self-trade-prevention maker cancel (`CancelMaker` / `CancelBoth`)
1681
+ that the level failed was skipped silently and the sweep went on. It is
1682
+ now resolved like a single-order cancel (the maker still rests, or the
1683
+ removal is completed) and stops the sweep with the #240 abort
1684
+ semantics: prefix published, taker `Cancelled { MatchAborted }`,
1685
+ `Err(MatchAborted)`.
1686
+ - The three `debug_assert!`s guarding the modify re-add against
1687
+ fill-or-kill are a typed `InvalidOperation` raised before the cancel;
1688
+ every `saturating_*` and raw arithmetic in `modifications.rs` is
1689
+ checked or an exact case analysis.
1690
+ - Review of #285: a rolled-back modify never restores the original into
1691
+ a crossed or locked book (an opposite order that arrived after the
1692
+ cancel makes the restore fail with `PriceCrossing`: `ModifyOrderLost`,
1693
+ `Cancelled { RestFailed }`). The re-add is built from the order the
1694
+ cancel returned, so a concurrent fill between the modify's read and its
1695
+ cancel no longer creates quantity (pre-existing on main): `UpdatePrice`
1696
+ moves the remainder, `UpdatePriceAndQuantity` / `Replace` roll back
1697
+ with source `OrderChangedDuringModify`. `filled_quantity` in every
1698
+ state a re-add records is cumulative (the original's known fills plus
1699
+ the re-add's), and a re-add failure the modify resolves records no
1700
+ `Rejected` state or reject metric.
1701
+ - **Emptied price levels can no longer unlink a concurrent admission
1702
+ (#247, Copilot on #285).** Under the shared submit gate the single-order
1703
+ cancel, `UpdateQuantity`, the sweep's drain and a failed rest's cleanup
1704
+ removed a level they had seen empty without re-checking, so an order a
1705
+ concurrent submit admitted into it in between was left indexed but
1706
+ unreachable (pre-existing on main). Admissions into a level and
1707
+ removals of emptied levels now run under a striped per-price
1708
+ reader-writer lock (admission shared, removal exclusive) and the removal
1709
+ re-checks emptiness under it (`OrderBook::remove_level_if_empty`).
1710
+ Concurrent admissions at the same price still run in parallel; cost is
1711
+ one uncontended shared acquire per rested order and one exclusive
1712
+ acquire per removed level.
1713
+ - **Concurrent crossing adds no longer leave an order indexed but not
1714
+ resting (#288).** Under the shared submit gate (`STPMode::None`, no
1715
+ strandable maker) an order's location, user-index entry and
1716
+ `Open` / `PartiallyFilled` state were published only **after** its
1717
+ level admitted it. A concurrent sweep could consume the order in that
1718
+ window: its drain found no index to remove, and the resting thread then
1719
+ inserted a location and user-index entry for an order that no longer
1720
+ rested, and overwrote the maker's `Filled` state with `Open`
1721
+ (pre-existing on main; 100/100 runs of the new 8-thread stress test
1722
+ failed). `rest_on_level` now publishes the location (claimed atomically
1723
+ with `DashMap::entry`), the user-index entry and the resting state
1724
+ before the level admits the order, and withdraws them if the level
1725
+ refuses it. The location is the id's ownership token: every remover
1726
+ (sweep drain, cancel, zero-quantity update, rollbacks) releases it
1727
+ last, so a reused id never sees or removes a previous order's user or
1728
+ risk entry, and emptied `user_orders` entries are dropped only if still
1729
+ empty. Special orders are still registered after the admission, so a
1730
+ repricing pass cannot unregister an order that is being admitted. No
1731
+ new lock. The same fix reordered the raw `place_order_in_book`.
1732
+ - **Risk open-order count no longer double-released by two sweeps
1733
+ sharing a maker (#288).** The fill hook of the risk layer marked a fully filled
1734
+ maker's entry exhausted and removed it in two steps; the other sweep's
1735
+ `on_maker_removed` could take the zeroed entry in between and release a
1736
+ second open-order slot for the same order, leaving the account's
1737
+ `open_count` below its resting orders with no anomaly counted. The
1738
+ full-fill removal now happens under the same entry lock.
1739
+
1740
+ Compatibility:
1741
+ - A same-id submit racing a live order is now refused with
1742
+ `DuplicateOrderId` when it would rest, even without a `RiskConfig`
1743
+ (it used to overwrite the other order's location, last writer wins).
1744
+ As before, it may have traded first. `place_order_in_book` returns
1745
+ `DuplicateOrderId` for an id already located on the book instead of
1746
+ overwriting its location.
1747
+ - `SequencerResult::from` classifies `DuplicateOrderId` as
1748
+ `may_have_mutated: true`: the loser of a concurrent same-id race can
1749
+ fail with it after trading (it also counts in the reject metric then,
1750
+ without an order state, which belongs to the winner). Replay was
1751
+ already re-executing these rejections. Replay cannot reproduce such a
1752
+ race (the loser's trades are missing from the replayed book); unique
1753
+ ids per submit are an ingress / sequencing obligation.
1754
+ - A cancel that arrives while an order is being rested now finds it as
1755
+ soon as its level admits it (it used to return `Ok(None)` until the
1756
+ bookkeeping finished).
1757
+ - The order-state listener sees an order's `Open` / `PartiallyFilled`
1758
+ before the level event of its admission. If the level then refuses
1759
+ the order (a resource failure: counter capacity, a poisoned level),
1760
+ that state is followed by the terminal one (`Rejected` or
1761
+ `Cancelled { RestFailed }`), and a rolled-back modify shows the
1762
+ re-add's accepted state ahead of the restore's
1763
+ (`Open, Cancelled, Open, Open` instead of `Open, Cancelled, Open`).
1764
+ - **Post-trade risk rejections replay faithfully (#291).** A taker that
1765
+ traded and then had its residual's risk reservation refused (concurrent
1766
+ admissions on the same account, an unrepresentable counter) returned the
1767
+ plain `RiskMaxNotional` / `RiskMaxOpenOrders` error, which
1768
+ `SequencerResult::from` classified as never mutating and replay skipped
1769
+ (a `RiskConfig` is not part of `ReplayBookConfig`): the replayed book
1770
+ silently kept liquidity the live book had consumed. The failure is now
1771
+ `OrderBookError::RiskRejectedAfterTrades { order_id, executed_quantity,
1772
+ source }` (new reject code `RiskRejectedAfterTrades` = 22,
1773
+ `may_have_mutated: true`), and replay re-executes such an `AddOrder`
1774
+ with its residual refused instead of rested, which reproduces the live
1775
+ trades without the risk configuration. A replay that cannot reproduce
1776
+ it (the sweep fills everything or trades nothing) stops with
1777
+ `ReplayError::OutcomeMismatch`.
1778
+ - **Repricers no longer drop a reused id's special-order tracking
1779
+ (#291).** `reprice_pegged_orders` / `reprice_trailing_stops` released
1780
+ the registration of any id `get_order` could not find; a same-id order
1781
+ admitted in between lost its registration and was never repriced. The
1782
+ release is now conditional, under the tracker's shard lock, on no order
1783
+ owning the id (the #288 location claim).
1784
+
1785
+ Compatibility:
1786
+ - A risk refusal after trades is `Err(RiskRejectedAfterTrades { .. })`
1787
+ wrapping the former error (`source`); the reject metric and
1788
+ `RejectReason::from` report code 22 for it. A risk refusal before any
1789
+ trade is unchanged. Both new variants are additive: `OrderBookError`
1790
+ and `RejectReason` are `#[non_exhaustive]`, so downstream matches
1791
+ already carry a wildcard arm.
1792
+ - A modify re-add refused this way still returns `ModifyOrderLost`, now
1793
+ with `RiskRejectedAfterTrades` as its `source`.
1794
+ - Journals written before this release recorded the post-trade case
1795
+ under a pre-trade risk code with `may_have_mutated: false`; replay
1796
+ still skips those, and only `snapshots_match` detects the gap.
1797
+ - **Bounded journal recovery and NATS shutdown (#295).** Two liveness bugs
1798
+ and several hardening items from the final audit (#260):
1799
+ - `FileJournal::open` on a latest segment whose tail is garbage probed
1800
+ every byte offset and CRC'd each candidate over the rest of the
1801
+ segment (on the order of 10^14 bytes hashed for 256 MB): it
1802
+ effectively never returned. The forward scan that tells a torn tail
1803
+ from mid-segment corruption now filters candidates with
1804
+ allocation-free checks first (framing inside the segment, a sequence
1805
+ strictly above the last good entry, a payload starting with
1806
+ `{"sequence_num":<header sequence>,` and ending with `}`) and
1807
+ CRC-checks at most 64 of them, hashing at most 256 MiB. Random garbage
1808
+ opens in time linear in the segment size (treated as a torn tail,
1809
+ since no valid entry can follow); a tail that exhausts the budget is
1810
+ refused with the damaged entry's `CorruptEntry` / `InvalidEntryHeader`.
1811
+ #252's rule is unchanged: a later valid entry still refuses the open.
1812
+ - A zero-length latest segment (crash between `create_new` and
1813
+ `set_len`) made every append fail with `SegmentExists`; it is now grown
1814
+ to the segment size on open. A failed `msync` of an append re-zeroes
1815
+ the bytes it copied (best effort) before returning the error. A reader
1816
+ whose segment is shorter than its limit gets `InvalidEntryHeader`
1817
+ instead of a silent end. `list_segments` accepts only canonical names
1818
+ (`segment-` + 20 digits + `.journal`, round-tripped), so a stray
1819
+ `segment-5.journal` or `segment-+0…0.journal` can no longer alias a real
1820
+ segment, and it sorts and dedupes.
1821
+ - Replay compares the iteration with `last_sequence()` read before it:
1822
+ a journal whose newest segment vanished returned `Ok` on a truncated
1823
+ prefix and now fails with `ReplayError::JournalTruncated`.
1824
+ - `InMemoryJournal` stores events behind `Arc` and clones `T` outside its
1825
+ read lock; its JSON / CRC parity limits with `FileJournal` are
1826
+ documented.
1827
+ - NATS: `with_max_retries` is clamped to `MAX_PUBLISH_RETRIES` (10). With
1828
+ NATS down, `shutdown()` could take days (unbounded retries, drain with
1829
+ no deadline); once shutdown is requested (in the drain, or in a flush
1830
+ already running when `shutdown()` was called, via shared shutdown
1831
+ state), the first publish that exhausts its retries while the link is
1832
+ down stops publishing and the remaining events are counted in
1833
+ `dropped_events`. `shutdown()` is cancel-safe (a dropped future puts the
1834
+ join handle back instead of detaching the task), and
1835
+ `shutdown_with_deadline(Duration)` aborts the task after the deadline
1836
+ (`NatsPublisherError::ShutdownTimedOut`).
1837
+ - `NatsBookChangePublisher` sends `Content-Type: application/json`
1838
+ (batches are always JSON; the `EventSerializer` trait does not cover
1839
+ batches) and counts `error_count` once per batch, matching the trade
1840
+ publisher's once-per-trade rule.
1841
+ - Wire: `decode_frame` rejects a `len` above `MAX_FRAME_BODY` (4096) with
1842
+ `InvalidPayload` from the header alone (it used to report `Truncated`
1843
+ for up to 4 GiB), and `encode_frame` refuses such a frame.
1844
+ `encode_exec_report` rejects an unknown `status` or non-zero `_pad`, and
1845
+ `encode_book_update` an unknown `side`, with `InvalidPayload` instead of
1846
+ emitting frames their own decoders reject.
1847
+ - `CountingAllocator` (feature `alloc-counters`) documents that its
1848
+ diagnostic counters wrap (no allocation, panic or CAS loop inside the
1849
+ allocator); `doc/panic-boundaries.md` lists it next to `memmap2` as the
1850
+ second documented `unsafe` exception.
1851
+
1852
+ Compatibility:
1853
+ - `ReplayError` gains `JournalTruncated`; the enum is `#[non_exhaustive]`
1854
+ as of 0.14 (#260), so downstream matches need a wildcard arm. A replay
1855
+ that used to succeed on a truncated journal now fails.
1856
+ - `NatsPublisherError` is `#[non_exhaustive]`; `ShutdownTimedOut` is
1857
+ additive. `MAX_PUBLISH_RETRIES` and `wire::MAX_FRAME_BODY` are new
1858
+ public constants.
1859
+ - Callers passing `with_max_retries` above 10 get 10 (and a `WARN`).
1860
+ - `NatsBookChangePublisher::error_count()` is smaller for multi-subject
1861
+ failures (once per batch instead of once per subject). During a
1862
+ shutdown with NATS down, events that used to be retried are now in
1863
+ `dropped_events`.
1864
+ - Book-change messages carry an extra `Content-Type` header; payloads are
1865
+ unchanged.
1866
+ - Wire frames longer than 4096 bytes (none are defined) are refused on
1867
+ both sides; encoder inputs the decoders already rejected now fail at
1868
+ encode time.
1869
+ - Non-canonical segment file names are ignored by `FileJournal` (it never
1870
+ wrote any). No on-disk format change; `ORDERBOOK_SNAPSHOT_FORMAT_VERSION`
1871
+ is unchanged.
1872
+
1873
+ - **Bounded bincode decoding of untrusted payloads (#251).**
1874
+ `BincodeEventSerializer::deserialize_trade` / `deserialize_book_change`
1875
+ decoded with an unlimited `bincode::config::standard()`, so a ~10-byte
1876
+ payload whose `String` length prefix declared `u64::MAX` bytes made
1877
+ bincode 2.0.1 allocate that length before checking the input
1878
+ (capacity-overflow panic or OOM abort in the consumer). Decoding now
1879
+ goes through bincode's borrowed serde path behind a private adapter that
1880
+ routes `deserialize_string` / `deserialize_byte_buf` to the slicing
1881
+ `deserialize_str` / `deserialize_bytes`: a length prefix is checked
1882
+ against the remaining input before anything is allocated, and the copy
1883
+ that follows is the real length, so string / byte allocations over one
1884
+ payload never exceed its length. The same hostile payload now returns
1885
+ `SerializationError::Truncated` after allocating 0 bytes; a 200 MiB
1886
+ prefix inside an 8 MiB payload allocates nothing for the string. No
1887
+ `with_limit` is used: bincode's limit charges the in-memory width of
1888
+ every primitive (16 bytes for a one-byte `u128` varint), so it cannot be
1889
+ set to the input length without rejecting valid payloads. Sequence /
1890
+ map size hints are clamped to the payload length, so a hostile element
1891
+ count (`Vec<Trade>`, `Vec<Id>`) reserves at most
1892
+ `min(payload_len * size_of::<T>(), 1 MiB)` (1 MiB is serde's own cap)
1893
+ before its first element runs out of input.
1894
+ - New typed `SerializationError` variants: `PayloadTooLarge { len, max }`
1895
+ and `Truncated { additional }` (bincode end-of-input or a length prefix
1896
+ longer than the remaining input, previously folded into
1897
+ `Bincode(String)`).
1898
+ - New `DEFAULT_MAX_BINCODE_PAYLOAD_BYTES` (8 MiB, the largest NATS
1899
+ `max_payload` the NATS docs recommend; about 48 000 fills in one
1900
+ `TradeResult`) and `MAX_BINCODE_PAYLOAD_BYTES_CEILING` (64 MiB, the NATS
1901
+ hard maximum). `BincodeEventSerializer::with_max_payload_bytes(n)`
1902
+ configures the limit (clamped to the ceiling);
1903
+ `max_payload_bytes()` reads it back.
1904
+
1905
+ **Compatibility:** bincode payloads larger than the limit (8 MiB by
1906
+ default) are now rejected with `SerializationError::PayloadTooLarge`, on
1907
+ decode before parsing and on encode after producing the bytes, so a
1908
+ producer never emits what its consumer would reject. Raise it on both
1909
+ sides with `with_max_payload_bytes` if you run NATS with a larger
1910
+ `max_payload`. The wire format is unchanged: every payload up to the
1911
+ limit decodes exactly as before. `BincodeEventSerializer` is no longer a
1912
+ unit struct, so construct it with `BincodeEventSerializer::new()` or
1913
+ `Default::default()` instead of the bare `BincodeEventSerializer`
1914
+ expression. Code matching exhaustively on `SerializationError` must
1915
+ handle the two new variants, and bincode end-of-input errors now
1916
+ surface as `Truncated` rather than `Bincode(String)`. JSON is unaffected.
1917
+
1918
+ ### Documentation
1919
+
1920
+ - **Final panic-policy documentation (#260).** `doc/panic-boundaries.md` is
1921
+ complete: enforced contract, concurrent-map write paths, macro-generated
1922
+ `unsafe`, and a per-call-site inventory of caller-supplied code (locks
1923
+ held, committed state, unwind effect). The 0.14.0 notes in `src/lib.rs`
1924
+ / `README.md` are regrouped (breaking behaviour, breaking signatures,
1925
+ hardening, known limitations, tooling) with a completed migration table.
1926
+ `doc/USER_GUIDE.md` samples are updated to the 0.14 API (compile-checked)
1927
+ and recommend `create_snapshot_package` / `restore_from_snapshot_package`;
1928
+ `doc/wire-protocol.md` documents `MAX_FRAME_BODY` (4096) and encoder
1929
+ validation. The trailing-stop limitation (#286: trailing stops rest as
1930
+ limit liquidity and do not trail on an uncrossed book) was stated in the
1931
+ crate docs, the `repricing` module docs and the user guide until #286
1932
+ lifted it (see Changed (breaking)). Broken rustdoc links in the NATS
1933
+ modules are fixed.
1934
+ - **Trailing stops documented (#286).** The #286 warnings are gone from
1935
+ the crate docs, the `repricing` / `orderbook` module docs, the user guide
1936
+ and the README; the user guide gains a trailing-stop section,
1937
+ `doc/panic-boundaries.md` a section on the evaluation's gate mode and
1938
+ cascade bound, and `examples/src/bin/special_orders_demo.rs` shows a
1939
+ stop trailing and triggering on an uncrossed book.
1940
+ - **Level statistics are advisory under concurrent takers (#241).**
1941
+ pricelevel 0.10 supports exactly one concurrent writer of a level's
1942
+ execution statistics (`orders_executed`, `quantity_executed`,
1943
+ `value_executed`, `last_execution_time`, `sum_waiting_time`,
1944
+ `stats_degraded`). Sweeps holding the shared submit gate (non-fill-or-kill
1945
+ takers and matching-capable modifies on an `STPMode::None` book, anonymous
1946
+ `match_order` sweeps) can match one level at the same time, so a level
1947
+ snapshot taken meanwhile (`create_snapshot`, `create_snapshot_package`,
1948
+ `snapshot_to_json`, `enriched_snapshot*`, `Serialize for OrderBook`) can
1949
+ hold a partially recorded execution. Documented on `OrderBook`, the
1950
+ snapshot APIs and types, `match_order`, `snapshots_match` and in
1951
+ `doc/panic-boundaries.md`. Trades, fees, quantities, order vectors and the
1952
+ book-derived analytics are unaffected; the aggregates are exact once the
1953
+ overlapping sweeps return. Replay is single-threaded, so `snapshots_match`
1954
+ keeps comparing the execution counters and stays exact against a live
1955
+ snapshot taken with no sweep in flight. New test
1956
+ `concurrent_level_statistics_tests` pins that contract.
1957
+
1958
+ **Compatibility:** documentation and a test only. No API, behaviour,
1959
+ snapshot-format or performance change; the submit gate is unchanged
1960
+ (decision D6).
1961
+
1962
+ ## [0.13.1] - 2026-09-18
1963
+
1964
+ ### Changed
1965
+
1966
+ - Dependencies updated to latest stable versions (tokio 1.53, uuid 1.26,
1967
+ either 1.18; pricelevel 0.9.2 via the `0.9` requirement). Two rustdoc
1968
+ fixes (#235).
1969
+
1970
+ ## [0.13.0] — 2026-09-13
1971
+
1972
+ ### Added
1973
+
1974
+ - **`OrderBookError::ReserveResidualWouldBeDiscarded` and
1975
+ `OrderBookError::ZeroVisibleTranche` (#230).** Two new typed rejections on
1976
+ the reserve admission and modify paths; see the `Fixed` entries below
1977
+ for when each is raised. `ReserveResidualWouldBeDiscarded` carries both
1978
+ the projected `hidden_quantity` and the `discarded_quantity` that would
1979
+ actually be destroyed. `OrderBookError` is `#[non_exhaustive]`, so
1980
+ downstream matches keep compiling.
1981
+ - **`RejectReason::ReserveResidualWouldBeDiscarded`, wire code 14 (#230).**
1982
+ Additive: `RejectReason` is `#[non_exhaustive]`, serializes as its `u16`
1983
+ code, and `RejectReason::from_u16` maps unknown codes to `Other`, so an
1984
+ older reader decodes the new code as `RejectReason::Other(14)`.
1985
+ `ZeroVisibleTranche` reuses the existing `RejectReason::InvalidQuantity`
1986
+ (code 8) and mints no new code.
1987
+ - **`orderbook_reserve_discards_total` and
1988
+ `orderbook_reserve_hidden_discarded_total` (#230, `metrics` feature).**
1989
+ Counters for reserve residuals discarded because their visible tranche was
1990
+ exhausted without automatic replenishment: the first counts orders, the
1991
+ second sums the hidden quantity dropped. Both are fed from the aggressive
1992
+ taker path and from the maker removal, which also emit a matching `INFO`
1993
+ trace carrying a `path` field (`"taker"` / `"maker"`), the order id, the
1994
+ executed quantity and the discarded hidden quantity.
1995
+
1996
+ - **`SequencerResult::RejectedWithCode { reason, code, may_have_mutated,
1997
+ stp_mode }`** — a rejection carrying its stable wire-side `RejectReason`
1998
+ next to the message, plus the two facts the code cannot express:
1999
+ `may_have_mutated`, set for the errors the engine can return after it has
2000
+ already changed the book, and `stp_mode`, the source book's `STPMode` for
2001
+ a rejection the self-trade-prevention scan produced. `impl
2002
+ From<&OrderBookError> for SequencerResult` fills all four from the typed
2003
+ error in one step and is the intended way to build the variant. Appended
2004
+ variant on the `#[non_exhaustive]` enum: existing journals decode
2005
+ unchanged; journals carrying it fail to decode against older binaries,
2006
+ matching the `MarketOrderByAmount` precedent. The code encodes as its
2007
+ `u16` wire value. The variant governs the sequencer event stream, not
2008
+ the snapshot package, so `ORDERBOOK_SNAPSHOT_FORMAT_VERSION` is
2009
+ unchanged.
2010
+ - **`ReplayError::OutcomeMismatch { sequence_num, recorded, actual }`** —
2011
+ raised when a re-executed rejected submit succeeds or fails under a
2012
+ different code than the journal recorded.
2013
+ - **`ReplayError::StpModeMismatch { sequence_num, recorded, actual }`** —
2014
+ raised when a journaled self-trade-prevention rejection records a
2015
+ different `STPMode` than the replay book is configured with.
2016
+
2017
+ ### Changed (breaking, semver-minor under 0.x)
2018
+
2019
+ - **`OrderBook::get_bids` and `OrderBook::get_asks` are removed (#228).**
2020
+ Both returned `Arc<DashMap<u128, Arc<PriceLevel>>>` holding clones of the
2021
+ book's **live** level handles, and `PriceLevel` exposes `add_order`,
2022
+ `update_order` and `match_order` publicly, so any caller could mutate a
2023
+ price level directly — bypassing the submit gate, the `order_locations`
2024
+ and user-order indices, the risk state, self-trade prevention, the kill
2025
+ switch, the order-state tracker and the trade / book-change listeners.
2026
+ The resulting book was silently inconsistent: orders unreachable by id,
2027
+ depth gauges and caches stale, no events emitted. Deprecating the two
2028
+ accessors would have left the bypass reachable for another release, so
2029
+ they are removed outright. **0.13.0 is the release boundary for breaking
2030
+ changes.**
2031
+
2032
+ Migration — every replacement is read-only and returns values, not
2033
+ handles:
2034
+
2035
+ | Removed usage | Use instead |
2036
+ | --- | --- |
2037
+ | Enumerate levels and their orders | `create_snapshot(depth)` |
2038
+ | Walk levels with running depth | `levels_with_cumulative_depth`, `levels_until_depth` |
2039
+ | Levels within a price band | `levels_in_range` |
2040
+ | One level by price | `find_level` (`LevelInfo`), `order_count_at_price` |
2041
+ | Orders at a price / in the book | `get_orders_at_price`, `get_all_orders` |
2042
+ | Aggregate depth over N levels | `total_depth_at_levels` |
2043
+ | Top of book | `best_bid`, `best_ask` |
2044
+
2045
+ Mutation has no replacement by design: it must go through `add_order`,
2046
+ `update_order`, `cancel_order` or the mass-cancel entry points, which is
2047
+ the point of the removal. No snapshot or journal format change, and
2048
+ `ORDERBOOK_SNAPSHOT_FORMAT_VERSION` is unchanged.
2049
+
2050
+ Following from the same removal, the `new` constructors of the level
2051
+ iterators (`LevelsWithCumulativeDepth`, `LevelsUntilDepth`,
2052
+ `LevelsInRange`) are now crate-private: each takes a reference to the
2053
+ book's live `SkipMap` of price levels, and with `get_bids` / `get_asks`
2054
+ gone no public API yields one. The iterator types themselves stay public
2055
+ — obtain them from `OrderBook::levels_with_cumulative_depth`,
2056
+ `levels_until_depth` and `levels_in_range`, which is how every caller in
2057
+ this repository already did.
2058
+
2059
+ - **`ReplayError` gained the `OutcomeMismatch` and `StpModeMismatch`
2060
+ variants (#224)**, so exhaustive matches need new arms; 0.13.0 is the
2061
+ release boundary for them together with the #228 removal above, as
2062
+ `NamespaceRequiresFullReplay` shipped under 0.11.0. Journals carrying
2063
+ `SequencerResult::RejectedWithCode` fail to decode against older binaries
2064
+ (existing journals decode unchanged); no snapshot format change and no
2065
+ `ORDERBOOK_SNAPSHOT_FORMAT_VERSION` bump.
2066
+
2067
+ ### Fixed
2068
+
2069
+ - **`STPMode::CancelTaker` and `STPMode::CancelBoth` fire only on a
2070
+ same-user maker the taker can reach (#222).** Scope: those two modes.
2071
+ `STPMode::CancelMaker` is deliberately unchanged and still cancels every
2072
+ same-user order at a level the sweep touches, reachable or not — it never
2073
+ destroys the taker, so the gate would only change which resting orders
2074
+ survive. `check_stp_at_level` reports a conflict whenever a
2075
+ same-user maker rests at a crossed level, and the `CancelTaker` /
2076
+ `CancelBoth` arms then cancelled the taker (and, under `CancelBoth`, the
2077
+ maker) unconditionally after their safe-quantity pre-match. A taker the
2078
+ non-self depth ahead of that maker already satisfied therefore returned
2079
+ `SelfTradePrevented` with `Cancelled { filled_quantity: n }` — a client
2080
+ that retried double-filled — and `CancelBoth` destroyed a maker the
2081
+ sweep never touched; market takers reach the same arms through
2082
+ `match_order_with_user`, which drops the taker flag, so the caller saw
2083
+ `Ok` while the maker was gone. The arms now cancel only when the sweep
2084
+ can still execute into the same-user maker, with two guards: a budget
2085
+ the pre-match exhausted (`is_done()`) is an ordinary complete fill, and
2086
+ quote-notional dust — a residual that cannot fund one more lot at the
2087
+ level's price, the usual end of a notional sweep since the budget rarely
2088
+ lands on exactly zero, and the lot-rounded case — leaves the maker
2089
+ untouched and walks on to the next level instead of breaking, because a
2090
+ quote-amount sell can still afford a whole lot at a cheaper bid further
2091
+ down. A base-quantity residual keeps the STP verdict whatever its size:
2092
+ a maker admitted before a lot-size change keeps resting with a
2093
+ misaligned tranche (documented on `set_lot_size`), so a sub-lot
2094
+ residual is reachable, and walked past it would rest crossed against
2095
+ the taker's own maker. The modify precheck
2096
+ `check_modify_stp_self_cross` (#168) rejected a reprice as soon as any
2097
+ same-user order rested at a crossed level, before subtracting the
2098
+ non-self depth queued ahead of it; it now mirrors the sweep's
2099
+ lot-rounded per-level cap and consults the same insertion-sequence
2100
+ `check_stp_at_level` verdict, so a reprice the non-self depth covers is
2101
+ admitted, one it does not cover is still refused before the original is
2102
+ cancelled, and dust the sweep stops on before a deeper same-user level
2103
+ is admitted exactly as a direct submit is. The pre-match is sized by
2104
+ `PriceLevel::matchable_quantity` — the authoritative dry run the
2105
+ no-conflict arm already used — bounded by the non-self prefix, not by
2106
+ `safe_quantity` itself. That sum counts *visible* quantity and can
2107
+ overstate what the sweep executes (a no-progress maker is set aside; a
2108
+ replenish whose checked net delta would overflow the level's visible
2109
+ counter aborts the sweep untouched, #124), and overstating it admitted a
2110
+ reprice the sweep then killed after the original was already cancelled —
2111
+ the destruction #168 exists to prevent. Pinned for base-quantity,
2112
+ fill-or-kill and market takers, quote-amount buys (dust and reachable),
2113
+ a quote-amount sell past an unaffordable self level, a lot-rounded
2114
+ notional residual, a sub-lot reserve tranche resting from before a
2115
+ lot-size change (sweep and reprice),
2116
+ precheck/sweep agreement on dust before a deeper self level, the
2117
+ exact-depth boundary, a maker ahead that is counted in `safe_quantity`
2118
+ yet delivers nothing (the #124 replenish-headroom abort, where the
2119
+ reprice is now refused with the original left resting), and same-level
2120
+ reprices (admitted and refused); a
2121
+ reachable maker still yields `SelfTradePrevented` with the true non-self
2122
+ fill. The notional-sell walk is pinned on a plain STP-off book too, since
2123
+ the walk direction and not the STP mode decides the zero-cap verdict.
2124
+
2125
+ The same walk had a second, older bug the reachability guards exposed:
2126
+ a zero per-level cap ended the whole sweep, which is right for a
2127
+ base-quantity budget (the cap is the lot-rounded residual and ignores
2128
+ the level price) and for a quote-notional buy (asks ascend, so
2129
+ `remaining / price` only shrinks), but wrong for a quote-notional sell,
2130
+ whose walk descends the bids so that a budget too small here can still
2131
+ fund a whole lot lower down. A sell of 150 into bids 100, 75 and 50
2132
+ executed one unit instead of two. The direction-aware decision now
2133
+ lives in `StopCondition::zero_cap_is_terminal`, and the walk skips the
2134
+ level instead of breaking when a notional sell can still reach cheaper
2135
+ bids. Its exact terminal condition is `remaining < lot`: the cheapest a
2136
+ level can be is a price of 1, where the cap is the whole remaining
2137
+ notional, so below one lot no level still ahead can execute. With no lot
2138
+ size configured that reduces to a spent budget, which the loop's own
2139
+ completion check reaches first, so a notional sell then ends only on a
2140
+ spent budget or an exhausted side and visits every level on that side.
2141
+ Each skipped level costs one `u128` division and mutates nothing.
2142
+
2143
+ - **A reserve residual follows `auto_replenish` (#230).**
2144
+ `reduce_reserve_to_total` — the residual-resting helper behind
2145
+ `OrderQuantity::set_total_remaining`, which `add_order` uses to distribute
2146
+ an aggressive taker's unmatched total across its tranches — refreshed an
2147
+ emptied visible tranche with
2148
+ `replenish_amount.map(get).unwrap_or(0).min(hidden)`, ignoring
2149
+ `auto_replenish` entirely. That diverged from `pricelevel`'s contract for
2150
+ a resting maker in two ways. With `auto_replenish = false` upstream
2151
+ removes a maker whose visible tranche is depleted and strands its hidden
2152
+ depth, while the helper refreshed the taker's residual from an explicit
2153
+ amount and rested it. With `replenish_amount = None` and
2154
+ `auto_replenish = true` upstream refreshes with
2155
+ `DEFAULT_RESERVE_REPLENISH_AMOUNT` (80) capped by hidden, while the helper
2156
+ refreshed **zero** and rested an order with no visible tranche at all —
2157
+ `PriceLevel::add_order` does not reject one, so the book displayed nothing
2158
+ for an order that could never refill.
2159
+
2160
+ A third divergence sat in the same branch: the helper only ever looked at
2161
+ an *emptied* visible tranche, ignoring `replenish_threshold` entirely,
2162
+ while upstream also refreshes a **partially** consumed tranche that falls
2163
+ below `safe_threshold = max(replenish_threshold, 1)`. A
2164
+ `{10 visible, 20 hidden, threshold 5, replenish_amount 10}` reserve filled
2165
+ for 8 rested 2 / 20 as a residual while the identical resting maker would
2166
+ have shown 12 / 10.
2167
+
2168
+ `auto_replenish` now governs both paths identically, and the two upstream
2169
+ arms collapse into one rule applied here: with the flag on and hidden
2170
+ left, a post-reduction visible tranche below `safe_threshold` grows by
2171
+ `min(replenish_amount.unwrap_or(DEFAULT_RESERVE_REPLENISH_AMOUNT), hidden)`,
2172
+ drawn out of hidden. An emptied tranche is just that rule at its smallest,
2173
+ since `safe_threshold >= 1`.
2174
+ With the flag off the visible tranche is left empty, nothing is drawn from
2175
+ hidden, and a new scoped guard in `add_order_inner` — matching only a
2176
+ `ReserveOrder { auto_replenish: false, .. }` whose visible tranche the
2177
+ sweep exhausted while hidden remains — ends the order instead of resting
2178
+ it, with the same bookkeeping as the fully-matched branch
2179
+ (`OrderStatus::Filled { filled_quantity }` carrying the executed quantity)
2180
+ plus an `INFO` trace naming the order, the executed quantity and the
2181
+ discarded hidden quantity, and, under the `metrics` feature, the new
2182
+ `orderbook_reserve_discards_total` (orders) and
2183
+ `orderbook_reserve_hidden_discarded_total` (quantity units) counters, both
2184
+ fed from the aggressive taker path and from the maker removal so either
2185
+ side of the trade reports the same loss. Reporting the maker side costs a
2186
+ pre-match pass over a level's resting orders, and `PriceLevel::iter_orders`
2187
+ is a `DashMap` iterator that read-locks **every shard** of the map per
2188
+ level match; the book therefore records whether it has ever rested a
2189
+ `ReserveOrder { auto_replenish: false, .. }` with hidden depth (a
2190
+ monotonic flag, set on admission and re-derived on snapshot restore) and
2191
+ skips the pass entirely otherwise. The flag is read once per sweep, so a
2192
+ book that never rested one pays a single relaxed atomic load and allocates
2193
+ no capture buffer. A book that did pays the full pass on every level
2194
+ holding hidden depth; that pass is **not** free and shows up in the tails
2195
+ of a reserve-maker sweep, while the common-path benchmarks
2196
+ (`aggressive_walk_hdr`, `thin_book_sweep_hdr`) are unaffected. Both arms
2197
+ are covered by the `reserve_sweep_hdr` benchmark — see `BENCH.md` for the
2198
+ figures.
2199
+
2200
+ That once-per-sweep read is only coherent because of a new gate rule: in a
2201
+ book that **holds** strandable makers, **every sweep takes the exclusive
2202
+ side of the submit gate, in every `STPMode`** — matching-capable submits,
2203
+ cancel-then-add re-prices and the match-only entry points (`match_order`,
2204
+ `match_order_with_user`, `match_market_order_by_amount*`) alike —
2205
+ alongside fill-or-kill (#209) and the STP-relevant submits (#225).
2206
+ Admitting a strandable maker is exclusive too, which covers the very first
2207
+ one, when the count is still zero. Post-only submits, `UpdateQuantity`,
2208
+ cancels and mass cancels keep the shared side and never read the count;
2209
+ they are excluded from a sweep's window by that sweep's hold, not by
2210
+ taking the exclusive side themselves. The invariant:
2211
+
2212
+ > Every **sweep** in a book holding a strandable maker runs exclusively,
2213
+ > so no cancel, mass cancel, admission or re-price can land inside its
2214
+ > capture window.
2215
+
2216
+ Two interleavings needed it. A maker admitted at a level a sweep had not
2217
+ reached yet would be consumed with no report, because the sweep had
2218
+ already decided not to capture. And a maker the sweep *had* captured could
2219
+ be cancelled and its id reused by an unrelated `Standard` order at the
2220
+ same level, so the sweep would fill the impostor and report the reserve's
2221
+ hidden quantity as discarded when nothing was stranded.
2222
+
2223
+ The gate mode is decided **before** anything is read, from the count and
2224
+ the STP mode, never from a lookup that could go stale before acquisition;
2225
+ a caller that takes the shared side re-reads the count and, if it grew,
2226
+ drops the guard and restarts the whole operation exclusively (a fresh
2227
+ acquisition, not a lock upgrade, which `std::sync::RwLock` cannot do). The
2228
+ count can only increase under the exclusive side, so a shared holder that
2229
+ saw zero knows it stays zero. Cost: books holding strandable makers
2230
+ serialize their sweeps exactly as STP books have since #225; books holding
2231
+ none pay one relaxed load and are otherwise unchanged. The count is exact
2232
+ rather than conservative: increments sit at the only two places an order
2233
+ is rested, decrements at the only three places such a maker leaves a
2234
+ level and each decides from the removed order's own body, and the fill
2235
+ drain's attribution cannot be stale because of the rule above.
2236
+
2237
+ The
2238
+ returned `Arc<OrderType>` on that branch now carries **both tranches at
2239
+ zero** rather than the stale hidden remainder, so `total_quantity()` is
2240
+ `0` for an order that rests nowhere; `add_order`'s docs state what each
2241
+ of the fully-matched, rested and discarded branches returns. The guard is deliberately narrow: an iceberg
2242
+ residual always keeps `min(display, remaining) > 0` visible, an
2243
+ auto-replenishing reserve was refreshed, and a reserve that did not trade
2244
+ rests as submitted — none of them reach it. The accounting rule is
2245
+ `submitted = executed + resting (visible + hidden) + discarded`, and
2246
+ discarded quantity is **never** counted as executed.
2247
+
2248
+ Because the three cancel-then-add modify variants (`UpdatePrice`,
2249
+ `UpdatePriceAndQuantity`, `Replace`) re-add the order as a taker, that
2250
+ guard would otherwise let a re-price destroy the order it modifies: the
2251
+ original is cancelled, the re-add exhausts the visible tranche, the guard
2252
+ discards the hidden remainder, and `update_order` still returns
2253
+ `Ok(Some(..))`. A new validate-first pre-check beside the #168 STP
2254
+ self-cross check closes it. When the projected order is a `ReserveOrder`
2255
+ with `auto_replenish == false` and a non-empty hidden tranche, the engine
2256
+ dry-runs the crossable depth at the projected price with the same
2257
+ lot-size- and STP-aware feasibility walk fill-or-kill uses; if that depth
2258
+ is at least the projected visible tranche **and** less than the projected
2259
+ total, the modify is rejected with the new
2260
+ `OrderBookError::ReserveResidualWouldBeDiscarded { order_id,
2261
+ visible_quantity, crossable_quantity, hidden_quantity,
2262
+ discarded_quantity }` before anything
2263
+ is cancelled, so the original keeps resting untouched. `hidden_quantity`
2264
+ is the tranche as it would be re-added; `discarded_quantity` is what would
2265
+ actually be destroyed (`visible + hidden - crossable`), so a 10 / 20
2266
+ reserve crossing 15 reports hidden 20 and discarded 15. Crossing into depth
2267
+ smaller than the visible tranche is allowed (the residual rests with a
2268
+ positive visible tranche), and so is a projected **full** fill (it
2269
+ executes everything and discards nothing) and a non-crossing re-price.
2270
+ Auto-replenishing reserves,
2271
+ icebergs, single-tranche kinds and non-crossing re-prices never reach the
2272
+ walk. The dry run is **exact**, not best-effort: whenever the check can
2273
+ fire, the order being modified is itself a strandable maker, so the book's
2274
+ count is at least one and the whole cancel-then-add — lookup, validation,
2275
+ cancel and re-add — already runs on the exclusive side (see the gate note
2276
+ below). The error maps to the new wire code
2277
+ `RejectReason::ReserveResidualWouldBeDiscarded = 14`; older deserializers
2278
+ carry it forward as `RejectReason::Other(14)`.
2279
+
2280
+ Unchanged and documented rather than fixed: an aggressive two-tranche
2281
+ order sweeps with its **total** quantity (`add_order_inner` passes
2282
+ `total_quantity()` to matching), so a 10 visible / 20 hidden reserve
2283
+ submitted into 20 units of contra liquidity executes 20, whereas the
2284
+ identical order resting as a maker without automatic replenishment
2285
+ executes only its 10 visible units before `pricelevel` removes it and
2286
+ discards the 20 hidden. This release only makes the residual's fate follow
2287
+ `auto_replenish` the way the maker's already did.
2288
+
2289
+ Compatibility: `OrderBookError` gains
2290
+ `ReserveResidualWouldBeDiscarded` and `RejectReason` gains the matching
2291
+ variant; both enums are `#[non_exhaustive]`, so downstream matches keep
2292
+ compiling, and `RejectReason::from_u16` already carries unknown codes
2293
+ forward through `Other`. No snapshot or journal format change, and
2294
+ `ORDERBOOK_SNAPSHOT_FORMAT_VERSION` is unchanged. Observable behaviour
2295
+ changes on two counts. A non-auto-replenishing reserve taker whose visible
2296
+ tranche is exhausted now ends instead of resting: a 10 / 20 reserve with
2297
+ `replenish_amount = Some(10)` filled for 10 used to rest 10 / 10 and now
2298
+ ends as `Filled { filled_quantity: 10 }`. And an auto-replenishing
2299
+ residual left below its threshold now refreshes where it previously did
2300
+ not: the threshold-5 example above rests 12 / 10 instead of 2 / 20. A
2301
+ journal recorded before this change that contains either submit replays to
2302
+ the new outcome, so the replayed book legitimately differs from the one
2303
+ the original run produced and `ReplayEngine::verify` on it may return
2304
+ `Ok(false)`. The #226 lot-size transfer check below is narrowed to match
2305
+ this policy: relative to 0.12.x admission is tighter exactly as the #226
2306
+ entry describes and no further, and the narrowing removes rejections
2307
+ #226 would otherwise have raised on non-auto-replenishing reserves.
2308
+
2309
+ - **A non-replenishing reserve must display a positive visible tranche
2310
+ (#230).** A `ReserveOrder` with `auto_replenish == false`,
2311
+ `visible_quantity == 0` and `hidden_quantity > 0` was admitted happily,
2312
+ and rested as a ghost: it showed no visible depth, could not be filled,
2313
+ and `pricelevel` removed it — stranding the whole hidden tranche — the
2314
+ first time a taker reached its level. Since #221 every quantity-carrying
2315
+ modify sets the **visible** tranche, so `UpdatePriceAndQuantity` and
2316
+ `Replace` with a zero quantity could drive a healthy resting reserve into
2317
+ that shape as well. `UpdateQuantity { new_quantity: 0 }` cannot: it is a
2318
+ removal, taken before the validator ever runs (#223, below).
2319
+ `validate_order_shape` now rejects it with the new
2320
+ `OrderBookError::ZeroVisibleTranche { order_id, hidden_quantity }`, which
2321
+ covers `add_order` and every modify projection
2322
+ through the one shared validator; a rejected modify leaves the original
2323
+ resting untouched. The error maps to the existing wire code
2324
+ `RejectReason::InvalidQuantity`, alongside `QuantityOverflow`.
2325
+
2326
+ Scope: that shape **only**. The other zero-visible two-tranche shapes
2327
+ execute rather than vanishing, so they stay admissible — an
2328
+ `IcebergOrder` draws its whole hidden tranche into visible on match, and
2329
+ an auto-replenishing `ReserveOrder` refreshes and re-queues.
2330
+ Single-tranche kinds are unaffected, and a `(0, 0)` reserve is not
2331
+ covered — it carries nothing to strand. The residual paths already
2332
+ produce a positive visible tranche for every admitted order, so this
2333
+ closes the remaining way to create one.
2334
+
2335
+ Compatibility: admission is strictly tighter, and on the modify paths the
2336
+ rule reaches `Replace` and `UpdatePriceAndQuantity` only. The case to
2337
+ check for is a **soft cancel** through one of those two: an integrator
2338
+ that sent `Replace { quantity: 0 }` or
2339
+ `UpdatePriceAndQuantity { .., new_quantity: 0 }` on a reserve carrying
2340
+ hidden depth and no automatic replenishment, expecting the order to go
2341
+ away, now receives `OrderBookError::ZeroVisibleTranche` and the original
2342
+ is left resting. Neither variant ever cancelled anything: the re-add
2343
+ rested a zero-visible ghost, which then lost its hidden tranche to the
2344
+ first taker that reached the level — so the rejection replaces a silent
2345
+ misbehaviour, not a working idiom. Call `cancel_order` instead. On an
2346
+ iceberg or an auto-replenishing reserve the same two variants are **not**
2347
+ rejected: they re-add with a zero visible tranche and live hidden depth,
2348
+ and the order keeps executing.
2349
+
2350
+ `UpdateQuantity { new_quantity: 0 }` is outside this rule. It is a
2351
+ removal taken before the validator runs, so it cancels the whole order —
2352
+ hidden depth included — on every order kind (#223, below). An integrator
2353
+ who reaches for that variant now gets the removal they asked for; it is
2354
+ the supported soft cancel.
2355
+
2356
+ A journal recorded before this change that contains such an `AddOrder`,
2357
+ or a `Replace` / `UpdatePriceAndQuantity` projecting that shape, fails on
2358
+ replay with `ReplayError::OrderBookError`. Snapshot restoration does not
2359
+ run `validate_order_shape`, but its prepare phase rejects the same shape
2360
+ before touching any book state, so a legacy snapshot holding one fails
2361
+ atomically with `ZeroVisibleTranche` and the live book is left as it was;
2362
+ such an order must be cancelled at the source and re-submitted with a
2363
+ positive visible tranche.
2364
+
2365
+ - **Reserve orders are lot-size validated per tranche and on their
2366
+ replenishment transfer (#226).** On a book with a lot size,
2367
+ `validate_order_shape` checked an `IcebergOrder` per tranche (visible and
2368
+ hidden individually) but routed a `ReserveOrder` through a `_` catch-all
2369
+ that only checked its **total**. With `lot_size = 10` a reserve of 15
2370
+ visible / 5 hidden was admitted on its total of 20 while the identical
2371
+ iceberg was rejected, and because the validator also runs on the
2372
+ projected order of every modify arm (`UpdatePrice`, `UpdateQuantity`,
2373
+ `UpdatePriceAndQuantity`, `Replace`) the asymmetry was reachable through
2374
+ updates as well as through `add_order`.
2375
+
2376
+ The lot-size check is now an exhaustive match over every `OrderType`
2377
+ variant. `Standard`, `PostOnly`, `TrailingStop`, `PeggedOrder` and
2378
+ `MarketToLimit` keep the single-quantity rule. `ReserveOrder` takes the
2379
+ iceberg's per-tranche rule — `visible` and `hidden` each a whole multiple
2380
+ of the lot — and, additionally, validates the **capped transfer** that
2381
+ replenishment moves from hidden into the visible tranche, since that
2382
+ transfer is itself a quantity the book displays. The transfer is checked
2383
+ only while `hidden > 0` **and** `auto_replenish` is on, the single flag
2384
+ that decides whether anything is ever transferred on either path (#230):
2385
+ with `replenish_amount = Some(a)` it is `min(a, hidden)`; without an
2386
+ explicit amount it is `min(DEFAULT_RESERVE_REPLENISH_AMOUNT, hidden)`, the
2387
+ amount `pricelevel` transfers on depletion or below-threshold refresh and
2388
+ the one the residual-resting path behind `set_total_remaining` falls back
2389
+ to. With `auto_replenish = false` no transfer check applies whatever
2390
+ `replenish_amount` says: `pricelevel` removes a resting maker whose
2391
+ visible tranche is depleted, and the residual helper leaves the visible
2392
+ tranche empty so `add_order` ends the order — a depleted visible tranche
2393
+ ends the order on both paths and the book can never display a non-aligned
2394
+ quantity for it. `replenish_threshold` is
2395
+ unrestricted — it is only compared against the visible tranche, never
2396
+ transferred. Rejections use the existing
2397
+ `OrderBookError::InvalidLotSize`, carrying the offending quantity — the
2398
+ tranche or the transfer that failed.
2399
+
2400
+ Compatibility: admission is strictly tighter. A reserve order that was
2401
+ previously admitted on its total — and any update projecting such a shape
2402
+ — is now rejected with `InvalidLotSize`. A journal recorded before this
2403
+ change that contains such an `AddOrder` or update therefore fails on
2404
+ replay with `ReplayError::OrderBookError` when the `ReplayBookConfig`
2405
+ carries the lot size; snapshot restoration does not run
2406
+ `validate_order_shape`, so a legacy snapshot may still hold orders that
2407
+ would now fail admission. Such a legacy order — restored from a snapshot,
2408
+ or orphaned by a later `set_lot_size` — can be repaired through
2409
+ `UpdateQuantity`, `UpdatePriceAndQuantity` or `Replace` when only its
2410
+ visible tranche is misaligned (a 15 / 20 reserve on a new lot of 10
2411
+ becomes 20 / 20, since every quantity-carrying update re-validates the
2412
+ projected order); when its hidden tranche or its replenishment
2413
+ configuration is what fails, no update can correct it and it must be
2414
+ cancelled and re-submitted with aligned tranches. No public API, snapshot
2415
+ format or
2416
+ `ORDERBOOK_SNAPSHOT_FORMAT_VERSION` change. This entry changes validation
2417
+ only; the residual-resting behaviour it describes
2418
+ (`reduce_reserve_to_total`, `set_total_remaining`) is changed separately
2419
+ by #230 above, and matching plus the upstream `pricelevel` semantics are
2420
+ untouched by both.
2421
+
2422
+ - **Self-trade prevention holds under concurrent same-user admission
2423
+ (#225).** With STP engaged the matching engine decided the
2424
+ `STPAction` for a price level from a snapshot of that level's queue and
2425
+ then acted on the decision in a second operation on the same level. Both
2426
+ steps ran under the *shared* side of the book's submit gate, so any other
2427
+ thread could admit, cancel or re-price an order in between and the verdict
2428
+ was applied to state it had never been taken on. Observed under
2429
+ `CancelMaker`: a same-user ask scanned a bid level, a same-user post-only
2430
+ landed in that level while the scan's verdict was still in flight, and the
2431
+ ask's sweep filled it — a same-user trade with the post-only as maker. The
2432
+ same window corrupted `safe_quantity` under `CancelTaker` and `CancelBoth`
2433
+ when the foreign maker resting ahead of the same-user maker was cancelled
2434
+ concurrently.
2435
+
2436
+ The gate mode is now decided once, at the public boundary: an
2437
+ STP-relevant submit (STP enabled and a non-zero taker `user_id`) and the
2438
+ cancel-then-add modify variants whose re-add can match (`UpdatePrice`,
2439
+ `UpdatePriceAndQuantity`, `Replace`) take the **exclusive** side of the
2440
+ submit gate, so the scan and the fill it authorises observe the same
2441
+ queue. Books on `STPMode::None`, post-only submits (they never run the
2442
+ STP scan and never take liquidity), anonymous takers on the match-only
2443
+ entry points (`add_order` rejects a zero `user_id` under STP with
2444
+ `MissingUserId`), `UpdateQuantity` and `Cancel` are unchanged and keep
2445
+ the shared, fully concurrent path — with one addition from #230, which
2446
+ takes the exclusive side in every `STPMode` for a submit or re-price of a
2447
+ non-replenishing reserve carrying hidden quantity; on an STP book every other submit
2448
+ and every matching-capable re-price is therefore serialized.
2449
+ Fill-or-kill keeps its existing exclusive gate
2450
+ (#209). Internal helpers (`add_order_inner`, `cancel_order_with_reason`,
2451
+ `match_order_with_user_outcome`, `match_order_by_amount_with_user`)
2452
+ remain ungated and never upgrade, downgrade or re-acquire the lock.
2453
+
2454
+ Scope: the guarantee covers every mutation. The live
2455
+ `restore_from_snapshot(&self)` now takes the exclusive
2456
+ side for its commit phase as well, so a restore can no longer
2457
+ interleave with an in-flight submit (the `&mut self` package and JSON
2458
+ restores were already exclusive by construction). The one remaining way
2459
+ to mutate a level behind the gate — the `Arc<PriceLevel>` handles
2460
+ returned by `get_bids()` / `get_asks()` — is gone: both accessors are
2461
+ removed in this release (#228, above).
2462
+
2463
+ Callback re-entrancy: the documented contract now also covers
2464
+ `OrderStateListener`, which fires while the gate is held like
2465
+ `TradeListener` and `PriceLevelChangedListener`. Any gated `OrderBook`
2466
+ call made from one of these callbacks on the invoking thread may
2467
+ deadlock, and always deadlocks when the gate is held exclusively; the
2468
+ prohibition is absolute.
2469
+
2470
+ No public API, snapshot or journal change;
2471
+ `ORDERBOOK_SNAPSHOT_FORMAT_VERSION` is unchanged. Single-thread and
2472
+ contention measurements are reported in the pull request.
2473
+
2474
+ - **`OrderUpdate::UpdateQuantity` with a zero quantity cancels the order
2475
+ (#223).** A zero `new_quantity` was accepted and applied as a resize:
2476
+ pricelevel keeps a non-growing total in place, so the maker rested at
2477
+ zero depth, holding `best_bid` / `best_ask` on a level with nothing
2478
+ behind it (a post-only at that price was refused against liquidity that
2479
+ did not exist) until a sweep dropped it with no trade and no cancel
2480
+ event, leaking its `order_locations` entry — `cancel_order` then
2481
+ returned `Ok(None)` while re-adding the id reported `DuplicateOrderId`,
2482
+ and the tracked status stayed `Open` forever. The arm now routes to the
2483
+ same `UserRequested` cancel that `OrderBook::cancel_order` performs
2484
+ (`cancel_order_with_reason`), so the level-change event, the
2485
+ `Cancelled { UserRequested }` transition, the per-account risk release,
2486
+ the location / user-index untrack and the empty-level removal happen in
2487
+ lockstep. **Contract:** a zero requested quantity is a removal, not a
2488
+ resize. It cancels the *entire* order, hidden depth of an iceberg or
2489
+ reserve order included (a nonzero `new_quantity` still resizes only the
2490
+ visible tranche), and it bypasses the projected-order validator and the
2491
+ modify-aware risk check, so a configured `min_order_size` no longer
2492
+ rejects it with `OrderSizeOutOfRange`. The kill switch still refuses it,
2493
+ as it refuses every modify. The removal semantic is `UpdateQuantity`'s
2494
+ alone: a zero quantity on `Replace` / `UpdatePriceAndQuantity` re-adds
2495
+ through validate-first, so an iceberg or auto-replenishing reserve rests
2496
+ with a zero visible tranche and its hidden depth live, while a
2497
+ non-replenishing reserve is rejected with `ZeroVisibleTranche` and keeps
2498
+ resting (#230); and on a single-tranche maker a zero quantity on either
2499
+ of those two variants ends the order as a terminal
2500
+ `Filled { filled_quantity: 0 }` — it vanishes with a fill status and no
2501
+ fill, which this release pins but does not change.
2502
+
2503
+ Compatibility: this is a behaviour change on a call that previously
2504
+ succeeded, so a journal recorded before it that contains a zero
2505
+ `UpdateQuantity` replays to the new outcome — the order is removed where
2506
+ it previously replayed to a resting zero-quantity maker. The replayed
2507
+ book therefore legitimately differs from the one the original run
2508
+ produced, and `ReplayEngine::verify` against a snapshot taken before this
2509
+ change may return `Ok(false)`. Nothing fails on replay: the update itself
2510
+ is still accepted. No snapshot or journal format change, and
2511
+ `ORDERBOOK_SNAPSHOT_FORMAT_VERSION` is unchanged.
2512
+
2513
+ Pinned for plain, iceberg and reserve makers, a `min_order_size` book, a
2514
+ risk-limited book, a shared level, an absent id and an engaged kill
2515
+ switch, plus the level-change event, the per-account risk release, the
2516
+ strandable-maker count and the contrast against the two cancel-then-add
2517
+ variants.
2518
+
2519
+ - **Reserve `UpdatePriceAndQuantity` honours the requested visible quantity
2520
+ (#221).** `OrderQuantity::set_quantity` read a `ReserveOrder`'s argument
2521
+ as a **total** target and only ever reduced: a requested increase was
2522
+ silently ignored (the order kept its previous size while the call
2523
+ reported success) and a decrease was drawn total-wise across both
2524
+ tranches, visible first and then hidden with replenish-on-empty. The
2525
+ single production caller is the `OrderUpdate::UpdatePriceAndQuantity`
2526
+ arm of `OrderBook::update_order`, so a reserve re-price plus re-size
2527
+ landed on a size nobody asked for; amplified case: a 30 visible / 70
2528
+ hidden reserve asked to move to 80 ended at 10 / 70 instead of 80 / 70.
2529
+ `set_quantity` now sets the **visible** tranche and leaves hidden
2530
+ untouched for both two-tranche kinds, so the new total is
2531
+ `new_quantity + hidden`. That matches `OrderUpdate::UpdateQuantity`,
2532
+ `OrderUpdate::Replace`, the iceberg arm of the same method and the
2533
+ upstream `pricelevel` contract (`OrderType::with_reduced_quantity`),
2534
+ which all treat the submitted quantity as the display size.
2535
+
2536
+ Compatibility: no signature changes, but `OrderQuantity` is public, so
2537
+ the observable behaviour of `set_quantity` on a `ReserveOrder` changes
2538
+ for direct callers. `OrderQuantity::set_total_remaining` (the #210
2539
+ residual resting path) is unchanged and remains the total-target entry
2540
+ point. The journal format is unchanged and
2541
+ `ORDERBOOK_SNAPSHOT_FORMAT_VERSION` is **not** bumped; however, a
2542
+ journal recorded before this fix that contains a reserve
2543
+ `UpdatePriceAndQuantity` may produce different historical results on
2544
+ replay: the replayed book can differ from the one the original run
2545
+ produced, and the update can surface a validation rejection as
2546
+ `ReplayError::OrderBookError` (`QuantityOverflow`, or
2547
+ `OrderSizeOutOfRange` when the `ReplayBookConfig` carries the original
2548
+ size limits), because the requested size is now actually applied and
2549
+ the projected total is larger than the one the original run evaluated.
2550
+ Account risk limits are not part of `ReplayBookConfig`, so
2551
+ `RiskMaxNotional` cannot arise on replay. `ReplayEngine::verify` on
2552
+ such a journal may return `Ok(false)` when the replay succeeds and the
2553
+ resulting snapshot differs from the one captured by the pre-fix run,
2554
+ or propagate the replay error when the re-executed update is rejected.
2555
+
2556
+ - **Replay re-executes journaled submits that traded before returning an
2557
+ error (#224).** `add_order` emits real fills and *then* returns `Err`
2558
+ for an IOC's unfillable remainder and for a taker STP cancels after
2559
+ non-self fills. A sequencer records those as rejections, and
2560
+ `ReplayEngine` skipped every rejected event, so replay silently rebuilt
2561
+ liquidity the live book had consumed: journal a resting ask of 10 and
2562
+ an IOC buy of 15, and the replayed book still carried the ask. Replay
2563
+ now decides by the *recorded reject code* rather than by the
2564
+ success/failure classification. A submit (`AddOrder`, `MarketOrder`,
2565
+ `MarketOrderByAmount`) journaled as the new
2566
+ `SequencerResult::RejectedWithCode` is re-executed when its code is one
2567
+ replay can reproduce from the book state and `ReplayBookConfig` — the
2568
+ two post-fill codes (`InsufficientLiquidity`, `SelfTradePrevention`)
2569
+ and the pure admission rejections (tick, lot, size band, duplicate id,
2570
+ missing user, post-only crossing), which re-derive the same no-op and
2571
+ double as a check that the config matches the source book — and the
2572
+ re-execution must fail under the same `RejectReason`, or replay aborts
2573
+ with the new `ReplayError::OutcomeMismatch` (sequence, recorded code,
2574
+ and what replay produced instead: a success or a different error). A
2575
+ code whose trigger lives outside the config — the kill switch, the risk
2576
+ limits, `Other` — is **skipped, not re-executed**: those rejections
2577
+ never touch the book, so the skip reproduces the live outcome exactly,
2578
+ where re-executing a kill-switch rejection would rest an order the live
2579
+ book refused or consume liquidity it never touched. Replay therefore
2580
+ does not report a missing kill switch or `RiskConfig` as an
2581
+ `OutcomeMismatch`. A rejected non-submit is skipped as before (the
2582
+ modify paths validate first, cancels are no-ops on a missing order), and
2583
+ a journaled success whose re-execution fails still aborts with
2584
+ `ReplayError::OrderBookError`.
2585
+
2586
+ The reject code is not always enough, so the journal records two more
2587
+ facts. `may_have_mutated` covers the one rejection whose code lies: the
2588
+ residual-admission failure, which the engine returns as a
2589
+ `PriceLevelError` — mapped to `RejectReason::Other(0)` — *after* the
2590
+ sweep's trades are irreversible, and which the code-driven skip would
2591
+ have replayed as a no-op that rebuilds consumed liquidity. A flagged
2592
+ submit is re-executed whatever its code says; since replay cannot
2593
+ reproduce that failure (it takes a concurrent mutation of the level),
2594
+ the disagreement surfaces as `OutcomeMismatch` rather than a silently
2595
+ wrong book. The rest of `Other(0)`, notably the clock-dependent
2596
+ expired-at-admission rejection, is unflagged and still skipped.
2597
+ `stp_mode` records the mode that decided a self-trade-prevention
2598
+ rejection, and replay refuses a `ReplayBookConfig` whose mode differs
2599
+ with the new `ReplayError::StpModeMismatch`.
2600
+
2601
+ `last_applied_seq`, the applied-event count and the progress callback
2602
+ now follow what replay **dispatched** to the book, so a re-executed
2603
+ rejection advances them whether or not it traded; for a journal carrying
2604
+ such rejections they report more than the number of events that changed
2605
+ the book.
2606
+
2607
+ **Stated limitations.** A submit journaled as the string-only `Rejected`
2608
+ keeps the historical skip and therefore the pre-existing gap: replay
2609
+ cannot tell a pure rejection from one that traded first without a code,
2610
+ and producers close it by recording `RejectedWithCode`. Only the reject
2611
+ code is compared — not the error's details (`requested` / `available`
2612
+ and the like), and not the fills behind the rejection — so a discrepancy
2613
+ confined to them can go undetected, because different fills can exhaust
2614
+ the same levels and leave identical books. The same holds for a replay
2615
+ config that differs in a way the code cannot see: under `CancelTaker`
2616
+ and `CancelBoth` alike a taker that fills a foreign maker and then
2617
+ reaches its own is refused under `SelfTradePrevention`, yet only
2618
+ `CancelBoth` cancels that same-user maker. The `stp_mode` guard catches
2619
+ exactly that case, but only for journals that recorded an STP rejection;
2620
+ a mode difference in a run that never prevented a self-trade stays
2621
+ invisible. `replay_from` performs no snapshot comparison —
2622
+ `snapshots_match` is the check that does catch a diverged book, via
2623
+ `ReplayEngine::verify` or run directly against a snapshot of the source
2624
+ book — and matching the source book's configuration remains the caller's
2625
+ contract on every `*_with_config` entry point. Finally, `MarketOrder` /
2626
+ `MarketOrderByAmount` carry no user id, so a market order journaled
2627
+ after STP effects under a user re-executes through the STP-less path and
2628
+ a rejection recorded for it aborts with `OutcomeMismatch` rather than
2629
+ diverging silently.
2630
+
2631
+ Pinned end-to-end from a live book: the IOC remainder and the
2632
+ STP-cancelled taker replay their fills and advance the applied sequence;
2633
+ a kill-switch rejection is skipped with matching books; a tick rejection
2634
+ re-derives the same no-op; the string-only rejection keeps the skip; a
2635
+ rejected submit that succeeds on replay, or fails under a different
2636
+ code, aborts with `OutcomeMismatch`; a success journaled for a failed
2637
+ submit aborts with `OrderBookError`; a rejection flagged
2638
+ `may_have_mutated` under `Other(0)` is re-executed while the expired
2639
+ one is still skipped; a journaled `CancelTaker` rejection replayed under
2640
+ `CancelBoth` aborts with `StpModeMismatch`, and the same journal with
2641
+ the mode unrecorded replays "successfully" into a book `snapshots_match`
2642
+ rejects.
2643
+
2644
+ ## [0.12.1] — 2026-07-23
2645
+
2646
+ ### Changed
2647
+
2648
+ - Dependency bumps: `uuid` 1.23 → 1.24, `tokio` 1.52 → 1.53,
2649
+ `async-nats` 0.49 → 0.50. The `pricelevel` requirement is relaxed from
2650
+ the exact `0.9.1` to `0.9`, so patch releases of the level engine are
2651
+ picked up without a release here.
2652
+
2653
+ ### Fixed
2654
+
2655
+ - Two intra-doc links resolved correctly: the `TradeListener` /
2656
+ `PriceLevelChangedListener` re-entrancy contract on the submit gate,
2657
+ and the `OrderType` reference in the `snapshots_match` replay-oracle
2658
+ docs.
2659
+
2660
+ ## [0.12.0] — 2026-07-14
2661
+
2662
+ ### Changed (breaking, semver-minor under 0.x)
2663
+
2664
+ - **`pricelevel` 0.8.4 → 0.9.1.** Major upstream hardening release
2665
+ (PriceLevel #111–#120): validated admission (duplicate id, counter
2666
+ capacity, price/side topology), atomic PostOnly / fill-or-kill decisions,
2667
+ torn-read-safe execution statistics, and level snapshots materialized in
2668
+ queue-consumption order. 0.9.1 additionally fixes the `MatchResult`
2669
+ bincode round-trip (PriceLevel#135, found by this bump: 0.9.0 serialized
2670
+ a shape its own validated decoder rejected positionally, breaking the
2671
+ `bincode` feature's trade-event round-trip). Ripple on the re-exported
2672
+ surface:
2673
+ `PriceLevel::add_order` returns `Result`, `PriceLevel::matchable_quantity`
2674
+ takes the taker id (the dry run applies the sweep's self-match skip), and
2675
+ `PriceLevelError` gained the `DuplicateOrderId` variant.
2676
+ - **`OrderBook::get_bt_bids` / `get_bt_asks` are now fallible**, returning
2677
+ `Result<BTreeMap<u128, PriceLevel>, OrderBookError>` — rebuilding a
2678
+ `PriceLevel` from a snapshot validates admission upstream (`TryFrom`
2679
+ replaced the infallible `From`).
2680
+
2681
+ ### Fixed
2682
+
2683
+ - **PostOnly and multi-level FOK decisions are atomic at the book boundary
2684
+ (#209).** Both policies were checked before the sweep but every per-level
2685
+ match ran as a standard GTC taker, leaving a check-then-act race: a
2686
+ post-only order could take liquidity admitted between its precheck and
2687
+ its sweep, and a multi-level fill-or-kill could partially execute when a
2688
+ later level was cancelled after feasibility. PostOnly now threads
2689
+ `TakerKind::PostOnly` into every per-level match — pricelevel's
2690
+ structural guard makes trading impossible under any interleaving, with
2691
+ the sweep-time refusal surfacing as the same `PriceCrossing` rejection
2692
+ as the precheck. The crossability verdict is resolved BEFORE the STP
2693
+ block (post-only precedence over STP, documented on the submit APIs):
2694
+ a rejected post-only is a pure no-op that never cancels same-user
2695
+ makers as a CancelMaker/CancelBoth side effect. Multi-level FOK
2696
+ acquires a new book-level submit gate (`std::sync::RwLock`, write
2697
+ side) across its feasibility check and sweep; every other mutating
2698
+ entry point (add / update / cancel / mass cancel / evict / market
2699
+ sweeps) takes the read side. **Stated limitation:** while an FOK holds
2700
+ the gate the whole book serializes for that window, and FOK acquisition
2701
+ latency grows with in-flight readers (platform locks are
2702
+ writer-preferring, so FOK does not starve); trade / level listeners
2703
+ fire under the gate and must never re-enter the book on the invoking
2704
+ thread (contract documented on `TradeListener` /
2705
+ `PriceLevelChangedListener`). The matching core itself stays lock-free;
2706
+ a clean back-to-back HDR bisection shows the gate's uncontended read
2707
+ acquisition is not measurable on any scenario (add-only p50 917 = 917;
2708
+ see `BENCH.md`'s 0.11.0 → 0.12.0 delta section). Pinned by
2709
+ barrier-synchronized race regressions (contra-admission, later-level
2710
+ cancel, same-user CancelMaker) plus deterministic all-or-nothing tests.
2711
+ Three gaps closed on the fallible-mutation integration: (1)
2712
+ `OrderUpdate::UpdateQuantity` silently converted every upstream
2713
+ `PriceLevelError` into `Ok(None)` and bypassed book-level validation — it
2714
+ is now validate-first (projected order checked against tick / lot /
2715
+ min-max / two-tranche representability and the modify-aware risk gate
2716
+ before the level is touched), propagates upstream errors as
2717
+ `OrderBookError::PriceLevelError`, reserves `Ok(None)` for a genuinely
2718
+ absent order, and keeps per-account risk counters in lockstep with the
2719
+ applied update (new `on_quantity_update` hook). Routing through the
2720
+ shared validator also means an expired-but-unevicted GTD/DAY maker and
2721
+ a resting post-only maker whose price now crosses are rejected on
2722
+ quantity update — previously both silently succeeded. (2) A non-immediate
2723
+ taker whose residual could not be admitted into its same-side level
2724
+ (checked aggregate at capacity) used to consume contra liquidity and
2725
+ THEN fail — a headroom pre-check now rejects before the sweep emits any
2726
+ trade (conservative: full submitted total; the concurrent-only remainder
2727
+ is still guarded by pricelevel's validated admission). (3) If that racy
2728
+ post-trade admission ever fails, a level created empty by the attempt is
2729
+ removed — `best_bid` / `best_ask`, the cache, and depth gauges never see
2730
+ a phantom level — and the failure is logged at ERROR.
2731
+ - **Two-tranche quantity conservation (#210).** An aggressive Iceberg /
2732
+ Reserve partial fill assigned the **total** unmatched remainder to the
2733
+ visible tranche while keeping the original hidden tranche — an iceberg
2734
+ `20v/80h` filled by 10 rested `90v/80h`, manufacturing 80 units of
2735
+ liquidity. The residual now rests via the new
2736
+ `OrderQuantity::set_total_remaining` (visible = min(display size,
2737
+ remainder), hidden = remainder − visible; Reserve keeps its
2738
+ visible-first-with-replenish policy), so
2739
+ `executed + resting == submitted` always holds (property-tested).
2740
+ Additionally, a two-tranche total that overflows `u64` (previously
2741
+ silently saturated) is rejected at admission with the new typed
2742
+ `OrderBookError::QuantityOverflow` — on the direct add path before even
2743
+ the risk gate (which would otherwise judge the saturated total), and
2744
+ always before any trade, listener, or book mutation — mapping to the
2745
+ wire code `RejectReason::InvalidQuantity`. `set_quantity` keeps its user-facing
2746
+ visible-tranche semantics for icebergs and is now documented as such.
2747
+ - **`snapshots_match` is a full replay oracle (#208).** The replay equality
2748
+ check compared only per-level aggregates (price, visible/hidden quantity,
2749
+ order count), so two books with the same aggregates but reversed maker
2750
+ FIFO — or different maker ids, users, order variants, or time-in-force —
2751
+ certified as equal while emitting different trades on the next sweep. It
2752
+ now compares every level's complete order vector in queue-consumption
2753
+ order (pricelevel ≥ 0.9 materializes it that way) via full `OrderType`
2754
+ equality, plus the deterministic statistics counters including
2755
+ `stats_degraded`. Intentionally excluded and documented:
2756
+ `first_arrival_time` (pricelevel stamps it from raw `SystemTime::now()`,
2757
+ outside the injectable clock), `last_execution_time` /
2758
+ `sum_waiting_time` (live ingestion and replay consume different
2759
+ clock-tick budgets by design, so these wall-time aggregates diverge even
2760
+ under identically-seeded injected clocks), and the top-level capture
2761
+ timestamp. Order admission timestamps participate — the journal carries
2762
+ the admitted order verbatim and replay never re-stamps it. **Contract
2763
+ note:** this tightens the public `snapshots_match` /
2764
+ `ReplayEngine::verify` pass condition; aggregate-equal books with
2765
+ different maker identity or FIFO no longer certify as equal.
2766
+ - **The upsize queue-priority demotion survives a snapshot round-trip
2767
+ (#205).** Level snapshots now materialize orders in queue-consumption
2768
+ order (pricelevel 0.9, PriceLevel#109), so
2769
+ `restore_from_snapshot_package` rebuilds the exact queue and a
2770
+ quantity-increased order keeps its back-of-queue position after restore.
2771
+ Locked in by a proptest regression
2772
+ (`tests/unit/props_quantity_update_priority.rs`). **Migration note:**
2773
+ snapshots captured with pricelevel < 0.9 restore a demoted order at its
2774
+ old `(timestamp, seq)` position — re-snapshot after upgrading to pin the
2775
+ corrected order.
2776
+ - **Snapshot restoration is failure-atomic (#207).** `restore_from_snapshot`
2777
+ used to clear the live book before converting each level through
2778
+ pricelevel 0.9's fallible `PriceLevel::from_snapshot`, so an invalid later
2779
+ level destroyed the original state and left a valid prefix of the
2780
+ replacement installed; `restore_from_snapshot_package` additionally
2781
+ installed risk configuration before that fallible work. Restore is now
2782
+ two-phase: every fallible step (level validation, plus a new cross-level
2783
+ duplicate-order-id check that reports `OrderBookError::DuplicateOrderId`)
2784
+ runs against off-book structures, and the live book, indices, risk state,
2785
+ and configuration are only touched after all of it succeeds — any error
2786
+ leaves the pre-restore book byte-identical. The package path rebuilds risk
2787
+ entries during the commit walk (same registration as live admission),
2788
+ replacing the snapshot-based `rebuild_from_snapshot`. Two adjacent fixes
2789
+ ride along: a snapshot carrying two same-side levels at one price is now
2790
+ rejected (the install would keep one level while the index rebuild
2791
+ registered both), and restoring a package without a risk config now also
2792
+ purges any pre-restore risk entries — previously they survived `disable()`
2793
+ and could resurrect stale counters on a later `set_risk_config`.
2794
+ - **Snapshot package format bumped to v3 (#206).** The pricelevel 0.9
2795
+ statistics schema can serialize a `stats_degraded` field that a
2796
+ pricelevel 0.8 reader rejects with `unknown field`, so labelling such
2797
+ payloads `version: 2` (as #205 initially shipped) mislabelled them as
2798
+ 0.11-compatible. Newly written packages are stamped `3`; reads accept
2799
+ `2..=3` (`ORDERBOOK_SNAPSHOT_MIN_READ_VERSION`), so legacy v2 packages
2800
+ with the 8-field statistics shape still restore; `1` and future versions
2801
+ are rejected with the existing typed error, and the checksum is
2802
+ validated for both supported versions. Covered by a legacy-v2 restore
2803
+ fixture and a real-engine degraded-statistics (notional > `u64::MAX`)
2804
+ round-trip.
2805
+
2806
+ ### Added
2807
+
2808
+ - **Queue-priority contract documented and property-tested (#203).** The
2809
+ price-time-priority semantics of `OrderBook::update_order` — an in-place
2810
+ quantity decrease keeps the maker's queue position, a quantity increase
2811
+ demotes to the back of the level, and `UpdatePrice` /
2812
+ `UpdatePriceAndQuantity` / `Replace` are cancel-then-add and always lose
2813
+ time priority — were previously documented only inside the embedded
2814
+ `pricelevel` engine. External conformance tooling (Tracebook) now consumes
2815
+ this contract, so it is promoted to the public `update_order` docs and
2816
+ locked in by four proptest invariants
2817
+ (`tests/unit/props_quantity_update_priority.rs`) driven through the public
2818
+ API: quantity decrease keeps the queue position, quantity increase demotes,
2819
+ and same-price `Replace` / `UpdatePriceAndQuantity` always demote. The docs
2820
+ also state a known limitation: the upsize demotion does not yet survive a
2821
+ snapshot restore (#205, upstream fix in `pricelevel`). No behavior change.
2822
+
2823
+ ## [0.11.0] — 2026-07-13
2824
+
2825
+ ### Added
2826
+
2827
+ - **Replay reproduces the trade-ID stream: `trade_id_namespace` on
2828
+ `ReplayBookConfig` (#200).** v0.10.5 (#199) made the trade-ID namespace
2829
+ injectable on `OrderBook`, but every `ReplayEngine::replay_from*` entry
2830
+ point still constructed its book internally with a random
2831
+ `Uuid::new_v4()` namespace, so trade IDs produced through the shipped
2832
+ replay API remained non-reproducible against the live run and across
2833
+ repeated replays of the same journal. `ReplayBookConfig` now carries
2834
+ `trade_id_namespace: Option<Uuid>`, applied via
2835
+ `OrderBook::set_trade_id_namespace` before any journal events are
2836
+ replayed (the book is fresh, honoring the counter-restart contract), so
2837
+ `replay_from_with_clock_and_config` with the live namespace and an
2838
+ injected `Clock` reproduces the live trade-ID stream byte-identically.
2839
+ `ReplayBookConfig::new` keeps its six structural parameters — the new
2840
+ builder-style `with_trade_id_namespace(namespace)` sets the field. The
2841
+ non-config entry points intentionally keep the random namespace
2842
+ (documented) rather than growing more constructor variants.
2843
+ - **Suffix replays with a namespace are rejected.** Applying a namespace
2844
+ restarts the trade-ID counter at 0, so a namespace-carrying config
2845
+ combined with `from_sequence != 0` would mint wrong IDs for the suffix
2846
+ and duplicates of IDs already emitted live under that namespace. The
2847
+ `*_with_config` entry points return the new typed
2848
+ `ReplayError::NamespaceRequiresFullReplay` instead; namespace-free
2849
+ suffix replay keeps working. Residual caveat (documented on the field):
2850
+ the journal must cover the trade-ID stream origin — the engine cannot
2851
+ detect a rotated segment whose earlier segments already produced trades
2852
+ under the same namespace.
2853
+
2854
+ ### Changed
2855
+
2856
+ - **Breaking:** `ReplayBookConfig` gained a public field
2857
+ (`trade_id_namespace`), so exhaustive struct literals no longer compile —
2858
+ add `trade_id_namespace: None` or construct with `..Default::default()`.
2859
+ `ReplayError` gained the `NamespaceRequiresFullReplay` variant, so
2860
+ exhaustive matches need a new arm. Callers using
2861
+ `ReplayBookConfig::new(...)` / `::default()` are unaffected. Hence the
2862
+ 0.11.0 (pre-1.0 breaking) version bump. No journal or snapshot format
2863
+ change, and no `ORDERBOOK_SNAPSHOT_FORMAT_VERSION` bump.
2864
+
2865
+ ## [0.10.5] — 2026-07-13
2866
+
2867
+ ### Added
2868
+
2869
+ - **Injectable trade-ID namespace (#199).** Every `OrderBook` constructor
2870
+ minted its trade/transaction-ID namespace internally with
2871
+ `Uuid::new_v4()`, so trade IDs differed between a live run and its replay
2872
+ even when the command stream, the injected `Clock`, and the matching were
2873
+ identical — the namespace was the only entropy left in the trade-ID
2874
+ stream (`pricelevel::UuidGenerator` derives UUID v5 from namespace +
2875
+ atomic counter). `OrderBook::set_trade_id_namespace(&mut self, namespace)`
2876
+ is a pre-publication setter symmetric with `set_clock`: it replaces the
2877
+ generator (the counter restarts at 0, so call it before any orders are
2878
+ submitted) and composes with every existing constructor.
2879
+ `OrderBook::with_clock_and_namespace(symbol, clock, namespace)` covers the
2880
+ common deterministic-venue setup in one call; a deterministically chosen
2881
+ namespace (e.g. UUID v5 of the symbol under a venue root) then yields
2882
+ byte-identical trade IDs across live/replay. Default constructors are
2883
+ unchanged (fresh random namespace per book). No wire-format or snapshot
2884
+ change, and no `ORDERBOOK_SNAPSHOT_FORMAT_VERSION` bump. The guarantee
2885
+ currently applies to books constructed by the caller; the sequencer's
2886
+ `ReplayEngine` entry points still build their books with a random
2887
+ namespace — wiring the seam into `ReplayBookConfig` is tracked in #200.
2888
+
2889
+ ## [0.10.4] — 2026-07-12
2890
+
2891
+ ### Added
2892
+
2893
+ - **Exact-fee API: `FeeSchedule::try_calculate_fee` + published
2894
+ guaranteed-exact input bound (#197).** `calculate_fee` deliberately
2895
+ saturates when `notional × |bps|` overflows `u128`, and consumers that
2896
+ must guarantee exact integer fees (journaled, replayable venues) could not
2897
+ distinguish a clamped fee from an exact one, nor validate inputs against a
2898
+ documented bound. `try_calculate_fee(notional, is_maker) ->
2899
+ Result<i128, FeeOverflow>` performs the identical computation (same
2900
+ truncation-toward-zero rounding, sign applied after the unsigned-domain
2901
+ magnitude) but returns the new `FeeOverflow` error — carrying the
2902
+ offending `notional`, the signed `bps`, and the
2903
+ `max_guaranteed_exact_notional` for that rate — instead of clamping, so an
2904
+ `Ok` is always mathematically exact and equal to `calculate_fee`'s output.
2905
+ The bound itself is published as
2906
+ `FeeSchedule::max_guaranteed_exact_notional_for_bps(bps)` (`const fn`; the
2907
+ multiplication-safety bound `u128::MAX / |bps|`, `u128::MAX` for a zero
2908
+ rate) and `FeeSchedule::max_guaranteed_exact_notional()` (minimum over the
2909
+ maker and taker legs), so venues can enforce it at admission time and make
2910
+ the saturating branch provably unreachable. The guarantee is sufficient,
2911
+ not tight: above the bound `try_calculate_fee` rejects conservatively even
2912
+ though the clamped `calculate_fee` value can coincide with the exact fee
2913
+ at isolated notionals (documented and pinned by test). `FeeOverflow` is
2914
+ re-exported at the crate root alongside `FeeSchedule`.
2915
+ - `calculate_fee` behavior is unchanged (bit-identical, including the
2916
+ saturated clamp of magnitude `u128::MAX / 10_000`, signed per `bps`); it
2917
+ now delegates to `try_calculate_fee` and its docs state the exactness
2918
+ condition. No wire-format or snapshot change, and no
2919
+ `ORDERBOOK_SNAPSHOT_FORMAT_VERSION` bump.
2920
+
2921
+ ## [0.10.3] — 2026-07-11
2922
+
2923
+ ### Fixed
2924
+
2925
+ - **Special-order tracker now survives snapshot restore (#194).**
2926
+ `OrderBook::restore_from_snapshot` (the shared rebuild path behind
2927
+ `restore_from_snapshot_package` and the JSON entry points) rebuilt the resting
2928
+ bids / asks, `order_locations`, and `user_orders`, but left the
2929
+ `special_order_tracker` (`special_orders` feature) freshly-initialized. A
2930
+ restored resting pegged or trailing-stop order was therefore never
2931
+ re-registered with the tracker, so `reprice_pegged_orders` /
2932
+ `reprice_trailing_stops` never visited it and the order stayed stuck at its
2933
+ snapshotted price. The rebuild now re-registers every restored resting special
2934
+ order in the same fixed price-then-insertion-sequence walk that repopulates
2935
+ `order_locations` / `user_orders` (a single pass, no extra traversal), so
2936
+ re-pricing resumes after restore. The tracker holds only order ids; the
2937
+ trailing-stop watermark (`last_reference_price`) and the pegged / stop price
2938
+ are part of the order data and survive the snapshot round-trip, so no
2939
+ re-pricing state is lost or re-initialized. `restore_from_snapshot` clears the
2940
+ tracker before the rebuild so a restore is a full replacement. Non-special
2941
+ orders and books with no special orders are unaffected.
2942
+ - No wire-format or public-API change: no new fields, no event-shape change, and
2943
+ no `ORDERBOOK_SNAPSHOT_FORMAT_VERSION` bump.
2944
+
2945
+ ## [0.10.2] — 2026-07-11
2946
+
2947
+ ### Fixed
2948
+
2949
+ - **Deterministic `user_orders` rebuild on snapshot restore (#192).**
2950
+ `OrderBook::restore_from_snapshot_package` (and `restore_from_snapshot`)
2951
+ rebuilt the `user_orders` index by walking each level's order-unstable
2952
+ `iter_orders()` view, whose `DashMap` hasher is seeded per instance. As a
2953
+ result the per-user `Vec<Id>` was rebuilt in a different order on each fresh
2954
+ book, and a `cancel_orders_by_user` issued after the restore returned a
2955
+ `MassCancelResult::cancelled_order_ids` sequence that diverged across restores
2956
+ of the same package. The rebuild now walks price levels in the same fixed
2957
+ price-then-insertion-sequence order the mass-cancel and eviction sweeps use
2958
+ (bids ascending price, then asks ascending price; within each level ascending
2959
+ insertion sequence via `PriceLevel::snapshot_by_seq_into`), so the restored
2960
+ `user_orders` index — and therefore any subsequent by-user cancel — is
2961
+ byte-identical across every restore of the same package. This order reflects
2962
+ the resting book at snapshot time, not the original admission history (a
2963
+ snapshot cannot recover that), but it is now fully deterministic. Pure journal
2964
+ replay was unaffected and is unchanged. `order_locations` is a map, so its
2965
+ rebuild order never leaked into emitted output.
2966
+ - No wire-format or public-API change: no new fields, no event-shape change, and
2967
+ no `ORDERBOOK_SNAPSHOT_FORMAT_VERSION` bump.
2968
+
2969
+ ## [0.10.1] — 2026-07-10
2970
+
2971
+ ### Changed
2972
+
2973
+ - **Deterministic, replay-stable mass-cancel result ordering (#190).**
2974
+ `OrderBook::cancel_all_orders`, `cancel_orders_by_side`, and
2975
+ `cancel_orders_by_price_range` now enumerate the cancelled orders through the
2976
+ same fixed traversal the eviction sweep uses — bids first then asks; within a
2977
+ side, price levels in ascending price (the `SkipMap`'s natural key order); and
2978
+ within a level, ascending insertion sequence via
2979
+ `PriceLevel::snapshot_by_seq_into`. Previously these methods collected ids from
2980
+ order-unstable structures (`order_locations` / per-level `iter_orders`), whose
2981
+ `DashMap` hasher is seeded per instance, so two processes replaying the same
2982
+ command stream could produce different `MassCancelResult::cancelled_order_ids`
2983
+ orderings — and therefore divergent journaled `SequencerResult::MassCancelled`
2984
+ payloads. The cancelled **set** and **count** are unchanged; only the order of
2985
+ `cancelled_order_ids` is now deterministic across processes and replay.
2986
+ `cancel_orders_by_user` was already replay-stable (it drains the `user_orders`
2987
+ index in admission-history order) and is unchanged; its determinism contract is
2988
+ now documented.
2989
+ - No wire-format or public-API change: no new fields, no event-shape change, and
2990
+ no `ORDERBOOK_SNAPSHOT_FORMAT_VERSION` bump.
2991
+
2992
+ ## [0.10.0] — 2026-07-10
2993
+
2994
+ ### Breaking
2995
+
2996
+ - **`SequencerCommand` and `SequencerResult` are now `#[non_exhaustive]`.**
2997
+ Downstream code that matches them exhaustively must add a wildcard arm
2998
+ (`_ => …`) and recompile. This is a one-time source break: future
2999
+ command/result variants become source-compatible additions instead of
3000
+ repeating it. Surfaced by adding `EvictExpiredOrders` below — on the
3001
+ previously-exhaustive enum that addition would itself have broken
3002
+ downstream matches silently inside the 0.9.x range (which is why this
3003
+ release is 0.10.0 and not 0.9.3). Wire format is unaffected: bincode
3004
+ variant indices and JSON encodings are unchanged, and existing journals
3005
+ replay as-is.
3006
+
3007
+ ### Added
3008
+
3009
+ - **Host-driven GTD / DAY expiry sweep (#189)** — new
3010
+ `OrderBook::evict_expired_orders(now_ms)` removes every resting order whose
3011
+ time-in-force has expired as of the caller-supplied timestamp. `now_ms` is a
3012
+ `TimestampMs` (Unix milliseconds, the unit `clock().now_millis()` compares
3013
+ against) passed in by the caller — the sweep never reads the book's own clock,
3014
+ so a scheduler drives cadence and the sequencer can journal the exact cutoff.
3015
+ The matching hot path is untouched: there is no lazy per-match expiry check, so
3016
+ expiry is an explicit maintenance pass rather than an implicit per-submit cost.
3017
+ Expiry uses the same boundary predicate as admission (`now >= deadline` for
3018
+ `Gtd`, `now >= market_close` for `Day`), so an order admitted at an instant is
3019
+ never simultaneously evictable at that instant. Returns the evicted orders as
3020
+ `Vec<Arc<OrderType<T>>>`; a second sweep at the same `now_ms` is idempotent and
3021
+ returns empty.
3022
+ - **Manager parity for the sweep (#189).** `BookManagerStd` and
3023
+ `BookManagerTokio` gain `evict_expired_orders(symbol, now_ms)` (per-symbol
3024
+ pass-through, `None` for an unknown symbol) and
3025
+ `evict_expired_across_books(now_ms)` (all books, mirroring the
3026
+ `cancel_*_across_books` idiom).
3027
+ - **`SequencerCommand::EvictExpiredOrders { now_ms }` (#189).** New command
3028
+ variant (appended, so existing journals' bincode variant indices are
3029
+ unchanged). Replay applies the journaled cutoff — never the replay clock — so
3030
+ the sweep reproduces byte-identically and `snapshots_match` holds between a
3031
+ live book and its replay. Old journals replay unchanged; new journals carrying
3032
+ the variant fail on older binaries, consistent with the `MarketOrderByAmount`
3033
+ precedent. No `ORDERBOOK_SNAPSHOT_FORMAT_VERSION` bump required — the version
3034
+ gates the snapshot package, not the journal command enum.
3035
+ - **`TimestampMs` re-exported** at the crate root and via `prelude`, so the new
3036
+ `now_ms` parameter can be constructed without importing from `pricelevel`
3037
+ directly.
3038
+
3039
+ ### Documentation
3040
+
3041
+ - **Deterministic eviction order documented (#189).** The rustdoc on
3042
+ `evict_expired_orders` states the fixed, replay-stable order in which orders
3043
+ are evicted and side-effect events emitted: bids first then asks; within a
3044
+ side, ascending price (the `SkipMap`'s natural key order, no sort); within a
3045
+ level, ascending insertion sequence (the exact order the matching engine
3046
+ consumes resting orders, not the non-deterministic `iter_orders` view). Each
3047
+ order is removed through the same single-order cancel path as `cancel_order`,
3048
+ tagged `CancelReason::TimeInForceExpired`, so the price-level cache, depth
3049
+ statistics, `order_locations` / `user_orders` indices, risk state,
3050
+ special-order tracker, and order-state tracker all stay consistent.
3051
+ - Runnable example `examples/src/bin/gtd_expiry_sweep.rs`
3052
+ (`cargo run -p examples --bin gtd_expiry_sweep`) seeds GTD orders on a
3053
+ `StubClock` book, sweeps at explicit timestamps, and logs the evicted orders
3054
+ via `tracing`.
3055
+
3056
+ ## [0.9.2] — 2026-07-10
3057
+
3058
+ ### Added
3059
+
3060
+ - **Constant-work per-price aggregate accessors (#186)** — an O(log N) point
3061
+ lookup + O(1) counter read, with no per-order materialization. Four read-only
3062
+ methods on `OrderBook<T>`: `visible_quantity_at_price`,
3063
+ `hidden_quantity_at_price`, `total_quantity_at_price`, and
3064
+ `order_count_at_price`. Each performs an O(log N) `SkipMap` point lookup then
3065
+ reads the level's maintained atomic counter (one relaxed load; two for
3066
+ `total_quantity_at_price`, which sums visible + hidden) — no per-order `Arc`
3067
+ is materialized and no `T: Default` conversion runs, so they are the cheap
3068
+ way to poll one level's depth or order count. `order_count_at_price` is the
3069
+ counterpart to `queue_ahead_at_price` that drops the per-order term: O(log N)
3070
+ here vs O(log N + K) for the queue-walking version, which is left unchanged.
3071
+ All four return `None` for an absent level and read advisory,
3072
+ eventually-consistent counters; use `create_snapshot` for a
3073
+ mutually-consistent view. `total_quantity_at_price` saturates a (practically
3074
+ unreachable) `visible + hidden` overflow to `u64::MAX`, never `0`, so an
3075
+ overflow signals "enormous", never "empty".
3076
+ - **`add_limit_order_with_result` / `add_limit_order_with_user_and_result`
3077
+ (#185).** Result-returning counterparts of `add_limit_order` /
3078
+ `add_limit_order_with_user`: they build the same `Standard` order and route
3079
+ through `add_order_with_result`, returning
3080
+ `Ok((Arc<OrderType<T>>, Option<TradeResult>))` so callers get the match's
3081
+ `TradeResult` directly instead of relying on the `TradeListener` callback.
3082
+
3083
+ ### Documentation
3084
+
3085
+ - **Per-call fill attribution guarantee for `add_order_with_result` (#185).**
3086
+ The rustdoc now states explicitly that concurrent submits on the same book
3087
+ each receive exactly their own fills — the `TradeResult` is built from that
3088
+ call's private `MatchResult`, never from shared capture state, because the
3089
+ engine holds no cross-call trade accumulator. On the error-after-fills paths
3090
+ (an unfillable IOC remainder, or a self-trade-prevention cancellation after
3091
+ earlier non-self fills) the caller instead gets the typed `Err` and the
3092
+ executed fills reach only the trade listener. A multi-thread concurrency test
3093
+ (`test_add_order_with_result_concurrent_per_call_attribution`) pins the
3094
+ guarantee.
3095
+ - **GTD / market-close timestamps documented as milliseconds (#187).**
3096
+ `has_expired`, `set_market_close_timestamp`, and the `time_in_force`
3097
+ parameter docs on the limit / iceberg / post-only builders now state that GTD
3098
+ deadlines and the market-close timestamp are **milliseconds since the Unix
3099
+ epoch** — the same unit `clock().now_millis()` compares against. The pinning
3100
+ test `gtd_expiry_unit_is_milliseconds` proves a seconds-form deadline reads
3101
+ as instantly expired.
3102
+
3103
+ ## [0.9.1] — 2026-07-08
3104
+
3105
+ ### Added
3106
+
3107
+ - **`OrderBook::add_order_with_result` (#184).** Submit an order and receive
3108
+ the `TradeResult` produced by the match directly in the return value —
3109
+ `Ok((Arc<OrderType<T>>, Option<TradeResult>))` — instead of relying on the
3110
+ `TradeListener` callback. The trade result is `None` when the order produced
3111
+ no fills; when a listener is installed it still fires with the exact same
3112
+ `TradeResult` (same fills, fees, and `engine_seq`). `add_order` is now a thin
3113
+ wrapper that discards the result, and the `TradeResult` is only constructed
3114
+ when a listener is installed and/or the caller asked for it, so the plain
3115
+ `add_order` path without a listener stays free of the extra `MatchResult`
3116
+ clone. Contributed by @Dev380.
3117
+
3118
+ ## [0.9.0] — 2026-06-24
3119
+
3120
+ ### Performance
3121
+
3122
+ - **Bump `pricelevel` 0.8.2 → 0.8.3 — fixes per-match over-allocation
3123
+ (PriceLevel#106).** `PriceLevel::match_order` previously pre-sized each
3124
+ `MatchResult` to the *whole* level depth (`order_count`), so a small taker
3125
+ against a deep price level allocated (and immediately freed) a multi-MB
3126
+ transient buffer — a qty-1 market order against a 100 k-deep level allocated
3127
+ ~17.6 MB. 0.8.3 bounds the pre-allocation to
3128
+ `min(incoming_quantity, order_count)`. The `alloc_count` bench's
3129
+ `bytes_alloc/op` drops from `~790 KB` back to `~6 KB` (the per-match cost is
3130
+ now flat in level depth instead of linear); `allocs/op` is unchanged. No
3131
+ source change in orderbook-rs — dependency bump only.
3132
+
3133
+ ### Fixed
3134
+
3135
+ - **Surface swallowed re-price failures + clamp telemetry (#174).** The special-order
3136
+ re-price loops used `if self.update_order(update).is_ok()` and discarded the
3137
+ `Err`, and `reprice_special_orders` hardcoded `failed_orders: Vec::new()`, so a
3138
+ re-price rejected by admission (e.g. a risk `RiskMaxNotional`) silently left the
3139
+ order at its stale price with nothing recorded. The loops now capture each
3140
+ rejected `update_order` and `RepricingResult::failed_orders` is populated with a
3141
+ `(order_id, reason)` pair for every failure (a rejected re-price keeps the
3142
+ order's prior price — validate-first modify, #98/#168). The public
3143
+ `RepricingOperations` trait signatures are unchanged: `reprice_pegged_orders` /
3144
+ `reprice_trailing_stops` still return the repriced count; the failure detail is
3145
+ reported through `reprice_special_orders`. Separately, `calculate_pegged_price`
3146
+ now emits a `trace!` when a peg is price-slid off its requested
3147
+ `reference ± offset` to the passive side (or skipped because no valid passive
3148
+ tick exists), so a consumer can distinguish a peg that tracked its reference
3149
+ from one that was clamped.
3150
+ - **Extend modify atomicity to the STP self-cross taker-cancellation edge (#168).**
3151
+ #98 made `UpdatePrice` / `UpdatePriceAndQuantity` / `Replace` validate-first for
3152
+ every *pre-match* admission rejection, but one *post-match* case slipped
3153
+ through: under `STPMode::CancelTaker` / `CancelBoth`, re-pricing an order so it
3154
+ crosses into the **same user's** resting liquidity on the opposite side made
3155
+ `add_order` match post-cancel and cancel the taker (the re-added order) — *after*
3156
+ the original was already removed, destroying it. The modify guard now runs a
3157
+ `check_modify_stp_self_cross` pre-check (after the risk check, before
3158
+ `cancel_order`): it dry-runs the crossable opposite side in the sweep's
3159
+ price-time order, consuming each non-self level's authoritative
3160
+ `matchable_quantity`, and if it reaches a same-user maker while the taker still
3161
+ has unfilled quantity — the exact condition under which the engine sets
3162
+ `stp_taker_cancelled` — returns `OrderBookError::SelfTradePrevented` so the
3163
+ original survives unchanged. No-op for STP `None` / `CancelMaker` (the taker
3164
+ rests, never destroyed) and anonymous takers; lot-aligned by construction
3165
+ (`validate_order_shape` runs first), so the verdict matches the engine exactly.
3166
+
3167
+ ### Changed
3168
+
3169
+ - **Delegate FOK matchable-depth to `PriceLevel::matchable_quantity` (#136).**
3170
+ `fok_fillable_quantity` (#96) computed per-level reachable depth with a
3171
+ hand-rolled `order_matchable_qty` sum (`visible + drawable_hidden`), a
3172
+ re-implementation of pricelevel's authoritative dry-run that could silently
3173
+ drift from `OrderType::match_against` if upstream replenishment/order-kind
3174
+ semantics changed. The non-STP and STP-`NoConflict` paths now delegate to
3175
+ `PriceLevel::matchable_quantity` (made `pub` in pricelevel 0.8.2) — the single
3176
+ upstream source of truth for what `match_order` would consume — so the FOK
3177
+ all-or-nothing verdict can no longer diverge from the real sweep. The
3178
+ hand-rolled helper remains only for the STP `CancelMaker` case, which must sum
3179
+ the *non-self* makers' depth (a per-user filter the upstream primitive cannot
3180
+ express). Behavior is unchanged; the #96 reserve/iceberg FOK regression tests
3181
+ still pass, plus a new iceberg-replenishable-hidden FOK fill test.
3182
+
3183
+ ### Performance — Pool the per-level STP scan buffer (#107)
3184
+
3185
+ - **Zero per-level heap allocation on the STP match path.** Under an active
3186
+ `STPMode`, each crossed price level previously allocated a fresh
3187
+ `Vec<Arc<OrderType<()>>>` for the self-trade scan
3188
+ (`PriceLevel::snapshot_by_insertion_seq`). The matching engine now reuses a
3189
+ single pooled scratch buffer (`MatchingPool::get_order_snapshot_vec` /
3190
+ `return_order_snapshot_vec`), refilled in place via the new
3191
+ `PriceLevel::snapshot_by_seq_into` (pricelevel 0.8.2), so the snapshot is
3192
+ reused across every conflicting level instead of allocated per level.
3193
+ - **Dropped the per-level maker-id `Vec`.** `STPAction::CancelMaker` is now a
3194
+ unit variant — `check_stp_at_level` no longer `collect()`s same-user maker
3195
+ IDs into a `Vec<Id>`. The matching engine re-scans the pooled snapshot in
3196
+ insertion-sequence order and cancels each same-user maker inline. The cancel
3197
+ order (and therefore emitted events / journal) is bit-identical to before, so
3198
+ determinism and snapshot round-trip are unchanged.
3199
+ - **Bumped `pricelevel` 0.8.1 → 0.8.2** for the determinism-preserving
3200
+ `snapshot_by_seq_into` drop-in.
3201
+ - New `stp_sweep_hdr` Criterion HDR bench covers the aggressive self-crossing
3202
+ sweep under `STPMode::CancelMaker`.
3203
+
3204
+ ### Changed — Upgrade to `pricelevel` 0.8.0 (#130)
3205
+
3206
+ - **Bumped `pricelevel` 0.7 → 0.8.0.** Picks up the upstream price-time-priority
3207
+ fix where a partially-filled resting maker keeps its place at the front of the
3208
+ level queue (PriceLevel#39), resolving #88 — a partial fill no longer demotes
3209
+ the maker behind later same-price arrivals. A regression test on the matching
3210
+ path (`test_partial_fill_preserves_price_time_priority_issue_88`) locks it in.
3211
+ - **Deterministic match timestamps.** `PriceLevel::match_order` no longer reads
3212
+ the wall clock; the matching engine passes the book's `Clock` time as the taker
3213
+ timestamp, so trade timestamps follow the installed clock (replay-safe).
3214
+ - **Domain newtypes on the public surface (breaking).** Through the `pricelevel`
3215
+ re-exports and `MatchResult` / `OrderType` accessors, several values now carry
3216
+ `Quantity` / `Price` / `TimestampMs` instead of raw `u64` / `u128`
3217
+ (e.g. `MatchResult::remaining_quantity()` → `Quantity`). OrderBook-rs's own
3218
+ method signatures (snapshot / statistics queries) are unchanged and still
3219
+ return raw integers; downstream code reading `pricelevel` types through the
3220
+ re-exports may need `.as_u64()` / `.as_u128()`. Minor bump under `0.x` semver.
3221
+ - **`ReserveOrder.replenish_amount` is now `Option<NonZeroU64>`** (pricelevel 0.8).
3222
+
3223
+ ### Changed — Dependency refresh
3224
+
3225
+ - `async-nats` 0.47 → 0.49, `dashmap` 6.1 → 6.2, `bitflags` 2.11 → 2.13,
3226
+ `either` 1.15 → 1.16, `crc32fast` 1 → 1.5, `proptest` 1.7 → 1.11.
3227
+
3228
+ ### Removed
3229
+
3230
+ - Dropped the stale `ISSUE_IV.md` implied-volatility design draft from the repo
3231
+ root (the implied-volatility solver now lives in `src/orderbook/implied_volatility/`).
3232
+
3233
+ ### Fixed
3234
+
3235
+ - **Reject zero quantity and zero price at the `NewOrder` wire boundary (#125).**
3236
+ `TryFrom<&NewOrderWire> for OrderType<()>` validated padding, negative price,
3237
+ side, time-in-force, and order type but never checked `qty`, so a wire `qty == 0`
3238
+ became a degenerate `OrderType::Standard { quantity: 0 }` that slipped past the
3239
+ default-config lot check (passes for 0) and `min_order_size` (defaults to `None`)
3240
+ and reached the insert/match path. The boundary now rejects `qty == 0` with
3241
+ `WireError::InvalidPayload("NewOrder: zero quantity")`. **Decision (price 0):**
3242
+ also reject `price == 0` (`"NewOrder: zero price"`) — price 0 is the cache's
3243
+ "no best price" sentinel and a zero-priced limit order is structurally
3244
+ meaningless, so only `price > 0` is admissible. `CancelReplaceWire` carries a
3245
+ `new_qty` field but has no domain conversion yet, so there is nothing to mirror;
3246
+ the same guard should be added when it gains one.
3247
+ - **Resolve declared-but-unemitted wire/event surfaces (#119).** Three public
3248
+ surfaces claimed behavior the engine never implemented; all three are now backed
3249
+ by real engine paths. (a) `RejectReason::DuplicateOrderId` (stable wire code 12)
3250
+ was never emitted and `add_order` performed no duplicate-id check — it silently
3251
+ overwrote the resting order's location, orphaning it. `add_order` now rejects an
3252
+ incoming order whose id already rests on the book with the new
3253
+ `OrderBookError::DuplicateOrderId { order_id }` (mapped to wire code 12); the
3254
+ check lives in `add_order` (not the shared `validate_order_shape`) so the
3255
+ validate-first atomic modify is unaffected, and it does not clobber the live
3256
+ order's tracked state. (b) `TransactionInfo::maker_fee` / `taker_fee` were
3257
+ documented as per-transaction fees but no engine path populated them. The new
3258
+ `TradeInfo::from_trade_result(&TradeResult, Option<&FeeSchedule>)` computes each
3259
+ transaction's maker/taker fee from the schedule; the per-transaction fees sum to
3260
+ the aggregate `TradeResult::total_maker_fees` / `total_taker_fees`, so the
3261
+ detailed and aggregate views agree. (c) `MarketImpact::total_quantity_available`
3262
+ was documented as total available depth but was set to the requested-capped fill
3263
+ quantity, making `can_fill` trivially true and `fill_ratio` capped at `1.0`. It
3264
+ now accumulates the true resting depth across the whole side being hit (the
3265
+ impact metrics still describe only the consumed portion), so `fill_ratio` can
3266
+ exceed `1.0` when the book holds more depth than requested.
3267
+ - **Evict zeroed per-account risk counters; self-balancing fill accounting (#115).**
3268
+ Two hardening fixes in the opt-in pre-trade risk layer (`risk.rs`). (a) `RiskState`
3269
+ kept a per-account `RiskCounters` entry forever — `on_fill`/`on_cancel` decremented
3270
+ the atomics but never removed the entry once `open_count` and `resting_notional`
3271
+ both reached zero, so the map grew monotonically with every distinct account ever
3272
+ seen (a slow leak on a long-running, high-cardinality venue that gradually raised
3273
+ `DashMap` cost on the risk path). A new `evict_if_zeroed` now drops the entry via
3274
+ `DashMap::remove_if` once both counters are zero, called from the `on_fill` full-fill
3275
+ branch and from `on_cancel`. `remove_if` re-checks the predicate under the shard
3276
+ write lock, so it cannot race a concurrent `on_admission` (which holds the same lock
3277
+ for its `entry().or_default()` increment): an admission in flight is observed as a
3278
+ non-zero `open_count` and the entry is kept. (b) `on_fill` decremented
3279
+ `resting_notional` using the passed `maker_price` (`trade.price()`); it now uses the
3280
+ maker's **stored admission price** (`RiskEntry::price`), so admission/fill/cancel are
3281
+ self-balancing by construction rather than relying on the cross-module
3282
+ `maker.price == trade.price` guarantee. `maker_price` is retained only as a debug
3283
+ assertion documenting that the two coincide today (a future price-improvement path
3284
+ that breaks the equality must revisit the accounting).
3285
+ - **Deterministic, non-crossing pegged/trailing-stop repricing (#106).** Two
3286
+ fixes in the `special_orders`-gated repricing path. (a) `pegged_order_ids()` and
3287
+ `trailing_stop_ids()` collected from a `DashSet<Id>` in unspecified order, so the
3288
+ re-pricing sequence — and the events / journal entries it produced — was
3289
+ non-reproducible across runs, breaking replay determinism and price-time
3290
+ tie-breaking on re-insert. `Id` does not implement `Ord`, so both methods now
3291
+ sort by the deterministic `Display`/`to_string` key (`ids.sort_by_key(|id| id.to_string())`)
3292
+ before returning; the `to_string` allocation is acceptable off the matching hot
3293
+ path (operator-triggered maintenance). (b) `calculate_pegged_price` ignored the
3294
+ order `side` and could return a `reference ± offset` price that crossed the
3295
+ spread, so a pegged re-price would aggressively fill during a maintenance
3296
+ operation. It now takes the book `tick_size` and clamps the computed price to
3297
+ the passive side of the market — one tick inside the touch (`best_ask - tick`
3298
+ for a Buy, `best_bid + tick` for a Sell) — then snaps the result onto the tick
3299
+ grid in the passive direction (round down for a Buy, up for a Sell) so the
3300
+ re-priced order is always tick-aligned and restable. This is required because
3301
+ the re-price path swallows `add_order`'s tick-validation error: a `± 1`
3302
+ (off-tick) clamp on a `tick_size > 1` book was silently rejected on re-insert,
3303
+ leaving the peg stuck at its stale price. When no valid passive tick exists
3304
+ (degenerate cases such as `best_ask == tick`), the re-price is skipped (returns
3305
+ `None`) instead of crossing or resting off-book. The order now rests passively,
3306
+ tick-aligned, just inside the spread instead of trading.
3307
+ - **`add_book` refuses to overwrite an existing book (#105, breaking).** Both
3308
+ `BookManagerStd` and `BookManagerTokio` did `self.books.insert(symbol, book)` and
3309
+ ignored the returned `Option`, so a second `add_book` for the same symbol
3310
+ silently replaced the first book — dropping all its resting orders and order
3311
+ locations with no warning. `BookManager::add_book` now returns
3312
+ `Result<(), ManagerError>` and returns the new `ManagerError::BookAlreadyExists { symbol }`
3313
+ instead of overwriting; both managers stay in parity. Breaking: callers must
3314
+ handle the `Result` (the trait method signature changed) — permitted under the
3315
+ 0.8 → 0.9 window.
3316
+ - **Wire `NewOrder` rejects `account_id == 0` (#103).** `TryFrom<&NewOrderWire>`
3317
+ encoded the numeric `account_id` into the low 8 bytes of a `Hash32` to build the
3318
+ `user_id`, with a comment claiming it avoided colliding with `Hash32::zero()`
3319
+ (the documented "no STP" sentinel) — but `account_id == 0` yields an all-zero
3320
+ array, i.e. exactly `Hash32::zero()`, so an order from numeric account 0 silently
3321
+ lost self-trade protection (it could match its own resting orders and was never
3322
+ grouped with other account-0 orders for STP). The conversion now rejects
3323
+ `account_id == 0` at the trust boundary with `WireError::InvalidPayload`, and the
3324
+ inline comment is corrected. `wire`-gated.
3325
+ - **Replay now reconstructs non-default-config books deterministically (#101).**
3326
+ Every public `ReplayEngine` entry point built the target book with all
3327
+ configuration left at its defaults (`tick_size` / `lot_size` / `min_order_size`
3328
+ / `max_order_size` = `None`, `stp_mode` = `None`, `fee_schedule` = `None`), so
3329
+ replaying a journal produced by a book that used those — for example a
3330
+ `MarketOrderByAmount` rounding per level under a `lot_size` — rebuilt a
3331
+ **structurally different** book and could fail `snapshots_match` at verify.
3332
+ Two caller-supplied config variants now inject the original configuration into
3333
+ the fresh book *before* replay: `ReplayEngine::replay_from_with_config` and
3334
+ `ReplayEngine::replay_from_with_clock_and_config`, both taking a new
3335
+ `ReplayBookConfig` carrier (the same six fields persisted in
3336
+ `OrderBookSnapshotPackage`). Two `Option`-taking book setters back this up —
3337
+ `OrderBook::set_tick_size_opt` and `OrderBook::set_lot_size_opt` — alongside
3338
+ the existing `set_min_order_size` / `set_max_order_size` / `set_fee_schedule` /
3339
+ `set_stp_mode`. The configuration is supplied by the **caller** and is not read
3340
+ from the journal, so the on-disk format is unchanged and
3341
+ `ORDERBOOK_SNAPSHOT_FORMAT_VERSION` is **not** bumped. The plain `replay_from`
3342
+ / `replay_from_with_clock` entry points are now documented as valid only for
3343
+ default-config books. `ReplayBookConfig` is re-exported at the crate root and
3344
+ in the prelude.
3345
+
3346
+ - **Atomic modify: a rejected modify no longer destroys the original order (#98).**
3347
+ `UpdatePrice` / `UpdatePriceAndQuantity` / `Replace` previously cancelled the
3348
+ resting order *before* re-adding it, so a **pre-match admission rejection** in
3349
+ `add_order` (risk admission, missing `user_id` under STP, tick / lot size,
3350
+ min/max order size, expiry, post-only-would-cross, or FOK insufficient
3351
+ liquidity) destroyed the live order and returned only an error. These paths are
3352
+ now **validate-first**: a new pure, side-effect-free `validate_order_shape` runs
3353
+ every non-risk admission check (the same checks, in the same order, returning
3354
+ the same typed errors, but without mutating the book, recording state, emitting
3355
+ metrics, or invalidating the cache), and a new modify-aware risk check runs
3356
+ *before* the cancel. The original order is only cancelled once both pass; on
3357
+ any of these pre-match rejections it survives unchanged — no book mutation, no
3358
+ events, no trades. `add_order` now calls the same validator as its single
3359
+ source of truth, preserving its existing reject side-effects on the direct
3360
+ submit path. (Scope: the enumerated pre-match admission rejects. A re-price that
3361
+ would self-cross the same user's resting liquidity under `CancelTaker` /
3362
+ `CancelBoth` STP is a *post-match* cancellation not covered here — tracked as a
3363
+ follow-up; and a concurrent kill-switch flip between the guard and the cancel is
3364
+ a pre-existing, inherent two-step race.)
3365
+ - **Modify-aware risk admission (#98).** Added `RiskState::check_modify_admission`
3366
+ for in-place modifies. A modify keeps the account's `open_count` unchanged
3367
+ (one order out, one in) and the original order is still counted in the
3368
+ account's counters at validation time, so the normal limit-admission check
3369
+ would double-count the original and falsely reject. The modify-aware check
3370
+ therefore (a) skips the open-order-count limit entirely, (b) runs the price
3371
+ band on the new price, and (c) checks notional against the *projected* resting
3372
+ notional `current − old_price·old_qty + new_price·new_qty` (saturating `u128`;
3373
+ the old order's contribution is already inside `current`), so a valid modify
3374
+ by an account sitting exactly at `max_open_orders_per_account` now succeeds.
3375
+ - **Barrier-synchronized risk concurrency tests (#116).** The risk module's core
3376
+ safety claim — bounded over-admission and no wrap-to-MAX lockout under fill /
3377
+ cancel races — was uncovered by any concurrency test (all existing risk tests
3378
+ were single-threaded). Added two `std::thread::Barrier`-synchronized,
3379
+ sleep-free, deterministic tests: an N-thread admission race asserting
3380
+ `open_count` equals the admissions that incremented it and stays within
3381
+ `limit + thread_count` (bounded over-admission), and a full-fill-vs-cancel race
3382
+ over many orders asserting the saturating decrements land both `open_count` and
3383
+ `resting_notional` at `0` and never wrap to a large value. Test-only; no
3384
+ behavior change.
3385
+ - **Manager trade-event channel semantics documented (#129).** `BookManagerStd`
3386
+ (std `mpsc`) and `BookManagerTokio` (tokio `unbounded_channel`) push trade events
3387
+ onto an **unbounded** channel by design — the matching path must never block to
3388
+ deliver an audit event, so the producer applies no backpressure (a bounded
3389
+ channel would force the synchronous matching path to block or drop events). This
3390
+ was previously unstated; the type-level docs and both `start_trade_processor`
3391
+ methods now document the unbounded design and the requirement to **start the
3392
+ processor before submitting orders** (otherwise events buffer without bound).
3393
+ Docs-only; no channel-type or hot-path change.
3394
+ - **`with_channel_capacity` clamps instead of asserting on zero (#128).** The NATS
3395
+ publisher builder used `assert!(channel_capacity > 0, …)` on a caller-supplied
3396
+ argument, so a runtime-derived capacity of `0` aborted the whole process where
3397
+ graceful handling is expected (the error rules reserve `assert!` for truly
3398
+ unrecoverable invariant violations). A `0` capacity is now **clamped up to `1`**
3399
+ with a `tracing::warn!` (the minimum a Tokio mpsc accepts), via a shared
3400
+ `clamp_channel_capacity` helper, and the `# Panics` doc is replaced with the
3401
+ clamp note. Applied to both `NatsTradePublisher` and `NatsBookChangePublisher`.
3402
+ `nats`-gated.
3403
+ - **NATS trade publisher metric counters share one per-trade granularity (#127).**
3404
+ `publish_count` incremented once per trade (only when both subjects succeeded)
3405
+ while `error_count` incremented once per **failed subject** (and once per trade
3406
+ on a serialize failure), so the two counters lived on different scales:
3407
+ `error_count` could exceed the number of trades, and a partial failure (one
3408
+ subject ok, the other exhausted) was invisible to both — making NATS health
3409
+ monitoring unreliable. Counting is now uniformly **per trade**: a trade
3410
+ increments `publish_count` on a clean success or `error_count` otherwise (a
3411
+ shared `account_publish_outcome` helper), so `publish_count + error_count`
3412
+ equals the number of trades processed and a partial failure is attributable to
3413
+ exactly one trade. The field docs are corrected to match. `nats`-gated;
3414
+ observability only, no functional effect.
3415
+ - **`modify` uses a direct deep clone instead of a no-op `Arc::try_unwrap` (#124).**
3416
+ The `UpdatePrice` / `UpdatePriceAndQuantity` paths used
3417
+ `Arc::try_unwrap(order.clone()).unwrap_or_else(|arc| (*arc).clone())`, which
3418
+ cloned the `Arc` (strong count ≥ 2) and so the `try_unwrap` always failed and
3419
+ fell through to the deep clone — the cheap branch was dead and the intermediate
3420
+ `Arc` clone was pure overhead. Both now use `(*order).clone()`. Behavior
3421
+ unchanged.
3422
+ - **Outbound event types surfaced at the crate root; `current_time_millis` gains a
3423
+ determinism caveat (#123).** `TradeEvent`, `TradeInfo`, `TransactionInfo`,
3424
+ `PriceLevelChangedEvent`, and `PriceLevelChangedListener` were re-exported only
3425
+ from the prelude, so `orderbook_rs::TradeEvent` failed to resolve even though the
3426
+ crate docs name `TradeEvent` / `PriceLevelChangedEvent` as first-class outbound
3427
+ types (`orderbook_rs::TradeResult` already resolved). They are now re-exported at
3428
+ the crate root too. Separately, `current_time_millis` documents that it reads the
3429
+ **non-monotonic wall clock**, truncates to `u64` ms, and must **not** be used on
3430
+ deterministic / matching / replay paths — those must take time from the `Clock`
3431
+ trait (`MonotonicClock` / `StubClock`) — and gained `#[must_use]`.
3432
+ - **Doc gaps closed on IV / fee / wire items (#122).** The `Result`-returning IV
3433
+ functions (`solve_iv`, `solve_iv_bisection`, `implied_volatility`,
3434
+ `implied_volatility_with_config`) and the `TryFrom<&NewOrderWire> for OrderType<()>`
3435
+ conversion now carry `# Errors` sections enumerating their failure modes.
3436
+ `FeeSchedule::calculate_fee` documents its rounding rule (integer division
3437
+ truncates **toward zero**, symmetric in magnitude for a taker fee and a maker
3438
+ rebate) with a fractional-bps doctest asserting both signs. The `BookUpdateWire`
3439
+ layout rustdoc is corrected to match the code: **25 bytes of fields + a single
3440
+ 7-byte `_pad`** at offset 25 (it previously claimed 26 fields + 6 pad with
3441
+ phantom `_pad0`/`_pad`). Docs-only, no functional change.
3442
+ - **`#[must_use]` on pure iterator constructors and fallible decoders/IV entry points (#121).**
3443
+ Several public functions lacked the project-mandated `#[must_use]`: the
3444
+ `OrderBook` iterator constructors (`levels_with_cumulative_depth`,
3445
+ `levels_until_depth`, `levels_in_range` — dropping their result is a silent
3446
+ no-op, so these get a bare `#[must_use]`); the wire decoders (`decode_frame`,
3447
+ `decode_new_order`/`_cancel_order`/`_cancel_replace`/`_mass_cancel`/`_exec_report`/
3448
+ `_trade_print`/`_book_update`) and `MessageKind::from_u8`; and the IV entry
3449
+ points (`solve_iv`, `solve_iv_bisection`, `implied_volatility`,
3450
+ `implied_volatility_with_config`). The `Result`-returning functions use the
3451
+ `#[must_use = "…"]` message form (a bare `#[must_use]` on an
3452
+ already-`#[must_use]` `Result` trips `clippy::double_must_use`). No behavior
3453
+ change.
3454
+ - **Analytics paths use ordered skiplist iteration with early exit (#120).**
3455
+ `enriched_snapshot_with_metrics` collected every bid/ask key into `Vec`s, sorted
3456
+ them, truncated to depth, then did a redundant second skiplist lookup per kept
3457
+ level — despite the `SkipMap` already being price-ordered; it now iterates
3458
+ `bids.iter().rev().take(depth)` / `asks.iter().take(depth)` and snapshots the
3459
+ entry directly (O(N log N)+2N-lookups → O(depth)). `LevelsInRange` scanned every
3460
+ remaining entry and never short-circuited at the band edge (its comment falsely
3461
+ claimed it did); it now threads the side and terminates as soon as iteration
3462
+ passes the far edge (Sell/ascending price > max; Buy/descending price < min),
3463
+ turning a narrow-band query on a wide book from O(N) into O(band). Answers are
3464
+ unchanged. `create_snapshot` has the same collect/sort idiom but is left
3465
+ untouched here — it is on the replay-critical path and out of this issue's scope.
3466
+ - **`SerializationError` is a typed `thiserror` enum that bridges into `OrderBookError` (#118).**
3467
+ The `EventSerializer` error was a hand-rolled `struct { message: String }` with
3468
+ manual `Display`/`Error` impls and no `#[from]` bridge, flattening the structured
3469
+ serde/bincode failure to a string and deviating from the documented typed-error
3470
+ convention. It is now a `thiserror` enum — `Json(#[from] serde_json::Error)`
3471
+ (preserves the typed serde error), `Bincode(String)`, `TrailingBytes(String)` —
3472
+ and a `From<SerializationError> for OrderBookError` bridge folds it into
3473
+ `OrderBookError::SerializationError`, so an `EventSerializer` failure can be
3474
+ `?`-propagated on paths that return `OrderBookError`. Breaking for code that
3475
+ constructed/matched the old struct (`SerializationError { message }`); permitted
3476
+ under the 0.8 → 0.9 window.
3477
+ - **`OrderBook` Serialize is deterministic and documented as lossy (#117).** The
3478
+ hand-written `Serialize` for `OrderBook<T>` collected bids/asks/order_locations
3479
+ into `HashMap`s (non-deterministic JSON key order across runs) and serialized
3480
+ the volatile best-bid/ask cache, while omitting the matching configuration
3481
+ (`stp_mode`, tick/lot/min/max order size, engine sequence, kill switch, risk
3482
+ config) that `create_snapshot_package` preserves — with no `Deserialize`, so it
3483
+ is a one-way inspection dump, not a persistence path. The collectors now use
3484
+ `BTreeMap` (deterministic key order; order_locations keyed by the id string),
3485
+ the cache is no longer serialized, and the impl carries rustdoc documenting it
3486
+ as a lossy debug/inspection view, steering callers to `snapshot_to_json` /
3487
+ `create_snapshot_package` for durable, reproducible persistence.
3488
+ - **Best bid/ask cache serves both sides and represents price 0 (#93).**
3489
+ `PriceLevelCache` stored both sides behind a single shared `cache_valid` flag
3490
+ and overloaded price `0` as the absent sentinel, so `best_bid()` zeroed the ask
3491
+ slot (and vice versa) — two consecutive top-of-book reads never benefited from
3492
+ the cache, and a genuine best level at price `0` was permanently uncacheable.
3493
+ The cache now carries an independent `AtomicBool` validity flag per side (with
3494
+ `Acquire`/`Release` so a `valid` reader sees the stored price): `best_bid()`
3495
+ updates only the bid slot and `best_ask()` only the ask slot, so both-sides
3496
+ readers (`mid_price`, `spread`, `micro_price`, `resolve_reference_price(Mid)`)
3497
+ hit the cache in a single call and price `0` is a valid cached value.
3498
+ - **Doc examples use `?` instead of `.unwrap()` (#92).** The remaining `///` doc
3499
+ examples that modelled `.unwrap()` on fallible order-book calls — all nine in
3500
+ `mass_cancel.rs` — now use `?` inside a hidden `Result`-returning harness,
3501
+ matching the idiomatic error handling the rules ask downstream users to follow
3502
+ (the other modules were already swept). Doc-comments only; `#[cfg(test)]` and
3503
+ `tests/` keep their `.unwrap()` per the testing allowance. `cargo test --doc`
3504
+ stays green.
3505
+ - **Restored `#![deny(unsafe_code)]` and `#![warn(missing_docs)]` on `lib.rs` (#90).**
3506
+ Both crate-level attributes — mandated by `rules/global_rules.md` and `CLAUDE.md` —
3507
+ had drifted off `src/lib.rs`, silently allowing `unsafe` to creep in and `pub`
3508
+ items to ship undocumented (the `counting_allocator` module even documented a
3509
+ `deny` that no longer existed). The deny is restored; the only authorized `unsafe`
3510
+ — the four `memmap2` mmap blocks in `sequencer::file_journal` and the
3511
+ `CountingAllocator` `GlobalAlloc` impl — now carry an explicit
3512
+ `#[allow(unsafe_code)]` alongside their existing `// SAFETY:` rationale. The
3513
+ `missing_docs` warn surfaces zero warnings on `--all-features`.
3514
+ - **Protocol counters use `checked_*` instead of `saturating_*` (#91).** Per the
3515
+ no-saturating-on-protocol-counters rule, the remaining protocol-state counters
3516
+ no longer silently cap on overflow. `file_journal`'s `archive_segments_before`
3517
+ tally and the `SegmentIterator` segment index now use `checked_add` and surface
3518
+ overflow as a new typed `JournalError::CounterOverflow`. The two NATS retry
3519
+ bounds (`max_attempts = max_retries + 1`) are computed in `u64` so the `+ 1`
3520
+ cannot overflow even at `max_retries == u32::MAX` — no saturating cap — while the
3521
+ backoff-delay `saturating_mul` clamps stay (they bound a duration, not a
3522
+ counter). The replay sequence counters (#126) and the dead `saturating_sub(0)`
3523
+ in `encode_entry` (#110) were already converted earlier in this cycle. Unreachable
3524
+ at any realistic journal size; the value is rule compliance and correct failure
3525
+ semantics at the boundary.
3526
+ - **Boundary arithmetic in fee/analytics math is overflow-safe (#114).** Several
3527
+ monetary/price sites used unguarded casts or sums that wrap/panic on extreme
3528
+ inputs. `FeeSchedule::calculate_fee` cast `notional: u128` to `i128` with a bare
3529
+ `as` before the multiply, so a `notional > i128::MAX` truncated to a negative
3530
+ value and silently produced a wrong-sign/magnitude fee into a journaled
3531
+ `TradeResult`; it now computes the magnitude in the u128 domain (saturating) and
3532
+ applies the sign afterward, with an accurate doc comment. `resolve_reference_price(Mid)`
3533
+ and `DistributionBin::midpoint` use `u128::midpoint` instead of `(a + b) / 2`;
3534
+ `EnrichedSnapshot::calculate_imbalance` folds volumes with `saturating_add`; and
3535
+ `OrderSimulation::total_cost` folds with `saturating_mul`/`saturating_add`. Behavior
3536
+ is unchanged for all realistic inputs; each site gained a boundary-value test.
3537
+ - **Price-band risk check cross-multiplies to stop sub-bps under-enforcement (#113).**
3538
+ `check_limit_admission` computed the deviation via truncating integer division
3539
+ (`diff * 10_000 / reference`) and rejected only when the floored bps exceeded the
3540
+ limit, so an order whose true deviation was fractionally above the band rounded
3541
+ down to the limit and slipped through (e.g. reference 30000, limit 100 bps, price
3542
+ 30301 = 100.33 bps was admitted). The check now cross-multiplies — rejects when
3543
+ `diff * 10_000 > bps_limit * reference` — so the band never under-enforces, while
3544
+ an order exactly at the limit is still admitted (strict-`>` boundary preserved).
3545
+ The floored bps is recomputed only for the error-payload display.
3546
+ - **IV solver guards NaN/Inf inputs and crossed/locked books (#112).** The
3547
+ Black-Scholes IV solver only checked sign/magnitude — all `false` for NaN — so
3548
+ a NaN/Inf `spot`/`strike`/`time`/`rate`/`market_price` passed validation and
3549
+ propagated NaN through the Newton/bisection loops to a meaningless
3550
+ `ConvergenceFailure { last_iv: NaN }`. `validate_params` now rejects non-finite
3551
+ `spot`/`strike`/`time_to_expiry`/`risk_free_rate`, both solver entry points
3552
+ reject a non-finite `market_price`, and the Newton loop bails with a typed
3553
+ error if a value goes non-finite mid-iteration. Separately, `extract_price_for_iv`
3554
+ computed the spread without checking `bid <= ask`, so a crossed (negative) or
3555
+ locked (zero) spread bypassed the max-spread gate and was classified
3556
+ high-quality; it now rejects such a book with a new `IVError::CrossedBook` before
3557
+ classification (observable via a transient torn read across the independent
3558
+ `best_bid`/`best_ask` calls).
3559
+ - **`file_journal` no longer truncates a mapped segment or swallows poisoned
3560
+ mutexes (#111).** Two robustness defects in the journal subsystem the recovery
3561
+ path depends on. (1) `rotate_segment` called `set_len` to shrink a just-rotated
3562
+ segment that a concurrent reader may already have mmap'd at full capacity —
3563
+ touching pages past the new EOF is UB / SIGBUS on Unix and contradicted the
3564
+ `SegmentWriter` SAFETY invariant. The best-effort truncation is removed; the
3565
+ unused tail is a sparse hole (grown with `set_len`, never written), so there is
3566
+ no physical disk to reclaim and the "never truncated while mapped" invariant now
3567
+ holds. (2) `append` and `rotate_segment` updated `last_seq` / `segment_start_seq`
3568
+ behind `if let Ok(..)`, silently swallowing a poisoned lock — leaving
3569
+ `last_sequence()` under-reporting (breaking replay bounds) and `segment_start_seq`
3570
+ stale (so `archive_segments_before` could archive the active segment). Both now
3571
+ map a poisoned lock to `JournalError::MutexPoisoned` and propagate, so `append`
3572
+ never reports success while `last_seq` is unadvanced. `journal`-gated.
3573
+ - **Journal reopen CRC-validates the tail and truncates a torn entry (#110).**
3574
+ `scan_write_position` determined the write position purely from
3575
+ `entry_length`, so a crash mid-flush that left an intact header but a torn
3576
+ payload/CRC was accepted: the journal resumed on top of the corrupt bytes and
3577
+ `last_sequence()` returned an undecodable sequence (later surfacing as a
3578
+ `CorruptEntry` at replay). The reopen scan now CRC-checks each entry (shared
3579
+ `entry_crc_valid` helper) and treats the first CRC failure as end-of-valid
3580
+ data — `write_pos` points at the torn entry's start so the next append
3581
+ overwrites it, and `last_sequence()` reports the last decodable sequence. A
3582
+ `tracing::warn!` fires on a detected torn tail. `journal`-gated.
3583
+ - **NATS publishers expose a graceful `shutdown`/flush path (#109).** Both
3584
+ `NatsTradePublisher` and `NatsBookChangePublisher` spawned their background
3585
+ batch task and discarded the `JoinHandle` with no cancellation signal, so a
3586
+ pending batch could be silently lost on teardown and the detached task could
3587
+ outlive the publisher. Each now retains the join handle plus a one-shot
3588
+ shutdown signal and exposes an async `shutdown()` that signals the task to
3589
+ drain every event still buffered in the channel, flush it, and exit, then
3590
+ awaits the handle — no fire-and-forget task remains. A shared `drain_buffered`
3591
+ helper (unit-tested) performs the non-blocking, FIFO, chunked drain. `nats`-gated.
3592
+ - **NATS trade publishing is batched/throttled off the matching hot path (#108).**
3593
+ `NatsTradePublisher::into_listener`'s callback used to serialize the payload,
3594
+ build two subjects with `format!`, convert to `Bytes`, and `runtime.spawn` a
3595
+ fresh Tokio task **per trade** on the matching thread — per-operation heap
3596
+ allocation and task-spawn pressure that floods the runtime under a burst. The
3597
+ callback now only clones the `TradeResult` into a bounded channel and returns;
3598
+ a single background task drains, batches (configurable window / size), and
3599
+ optionally throttles before serializing and publishing — mirroring
3600
+ `NatsBookChangePublisher`. The `{prefix}.all` subject is precomputed once at
3601
+ construction. New builders (`with_batch_window_ms`, `with_max_batch_size`,
3602
+ `with_channel_capacity`, `with_min_publish_interval_ms`) and metrics
3603
+ (`events_received`, `batches_published`, `dropped_events`) match the
3604
+ book-change publisher; the per-trade wire format, subjects, and pluggable
3605
+ serializer are unchanged. `nats`-gated.
3606
+ - **Replay protocol sequence counter uses `checked_add` (#126).** `replay_into`
3607
+ advanced `expected_seq` (and the applied-event tally) with `saturating_add`,
3608
+ which violates the no-saturating-on-protocol-counters rule and would silently
3609
+ stop advancing at the `u64` ceiling — masking a real gap instead of surfacing
3610
+ it. Both now use `checked_add` and return the new `ReplayError::SequenceOverflow`
3611
+ on overflow. Unreachable at any realistic journal length; the value is rule
3612
+ compliance and correct failure semantics at the boundary.
3613
+ - **`snapshots_match` compares full per-level structure (#102).** The replay
3614
+ equality oracle now compares each level's `hidden_quantity` and `order_count`
3615
+ in addition to `price` and `visible_quantity`. Previously two books that
3616
+ agreed on visible quantity but differed in reserve/iceberg hidden depth or in
3617
+ the number of resting orders at a level were reported as equal, so a replay
3618
+ that reconstructed the wrong hidden depth or order count could pass
3619
+ verification. The check is now a true structural equality, not a
3620
+ visible-quantity subset.
3621
+ - **STP per-level scan is now deterministic (#94).** The self-trade-prevention
3622
+ pre-scan reads `PriceLevel::snapshot_orders()` (timestamp-ordered) instead of
3623
+ `iter_orders()` (DashMap, non-stable order), so `safe_quantity` and the
3624
+ CancelBoth `maker_order_id` follow price-time priority and are reproducible for a
3625
+ given book state. Non-determinism there previously broke replay (`snapshots_match`
3626
+ could diverge) for `CancelTaker` / `CancelBoth`.
3627
+ - **STP maker cancels now fire the full cancel side-effects (#95).** Under
3628
+ `CancelMaker` / `CancelBoth`, each STP-cancelled resting maker is routed through
3629
+ `cancel_order_with_reason`, so it emits a `PriceLevelChangedEvent`, transitions to
3630
+ `OrderStatus::Cancelled { SelfTradePrevention }`, and releases its per-account risk
3631
+ counter. Previously these three effects were skipped, desynchronizing book-change
3632
+ consumers, leaving the maker in a non-terminal state, and leaking per-account
3633
+ open-order / notional counters.
3634
+ - **Fully-consumed makers record their true filled quantity (#104).** The
3635
+ matching batch-removal path recorded `OrderStatus::Filled { filled_quantity: 0 }`
3636
+ (a placeholder) for every fully-consumed resting maker; it now records the real
3637
+ executed amount (the sum of the maker's trades in the submit), so
3638
+ `OrderStateTracker` / lifecycle consumers and any audit/risk reconciliation that
3639
+ sums filled quantity from terminal events are correct.
3640
+ - **Fill-or-kill feasibility is self-trade-prevention aware (#96).** FOK admission
3641
+ checked feasibility with `peek_match`, which sums raw level depth: under
3642
+ `STPMode::CancelMaker` it counted same-user resting quantity (which the real
3643
+ match *cancels*, not fills), so a FOK could pass the check, cancel the maker,
3644
+ fill nothing, and still return `InsufficientLiquidity` — with the book already
3645
+ mutated. A new faithful `fok_fillable_quantity` mirrors the real walk —
3646
+ `lot_size`-rounded budget, per-level STP via `check_stp_at_level`, and per-order
3647
+ *drawable* depth (a non-auto-replenish reserve's hidden tranche is dropped
3648
+ unfilled by the sweep, so it is excluded) — so a FOK that cannot be fully filled
3649
+ is killed *before* any trade or cancel. (The `lot_size` divergence the report
3650
+ also posited is not reachable through the validated admission path — it rejects
3651
+ non-lot-multiple orders — but the rounding is kept so the check stays faithful to
3652
+ the matching walk.)
3653
+ - **STP-cancelled takers no longer rest a self-cross residual (#97).** When a taker
3654
+ partially filled against another user and then would self-cross under
3655
+ `CancelTaker` / `CancelBoth`, the engine returned `Ok` with a resting remainder
3656
+ (GTC) — defeating STP and never recording the terminal `SelfTradePrevention`
3657
+ state. `match_order_inner` now returns a `MatchOutcome` carrying a
3658
+ `taker_stp_cancelled` flag; `add_order` cancels the residual (records
3659
+ `Cancelled { SelfTradePrevention }` with the true filled quantity and returns
3660
+ `SelfTradePrevented`) instead of resting it. The public `match_order` /
3661
+ `match_order_with_user` signatures are unchanged.
3662
+ - **STP scan follows insertion-sequence (sweep) order (#132).** Bumped `pricelevel`
3663
+ 0.8.0 → 0.8.1 for `PriceLevel::snapshot_by_insertion_seq()`. The STP pre-scan and
3664
+ the FOK feasibility scan now read it instead of `snapshot_orders()`
3665
+ (`(timestamp, sequence)`-ordered), so `safe_quantity` and the cancelled / selected
3666
+ maker match what `match_order` actually consumes even under non-monotonic
3667
+ timestamps — closing the consumption-fidelity gap that #94 left open (and which the
3668
+ #94 determinism fix only addressed for monotonic timestamps).
3669
+ - **`cancel_all_orders` resets per-account risk counters (#99).** The bulk cancel
3670
+ drained the book but never touched `risk_state`, so after a mass unwind every
3671
+ account's `open_orders` / `notional` counters stayed at pre-cancel values and
3672
+ permanently rejected new flow (the exact failure bulk cancel exists to avoid). It
3673
+ now calls a new `RiskState::clear()` (also reused by `rebuild_from_snapshot`),
3674
+ zeroing the per-account counters and the per-order risk map.
3675
+ - **Snapshot packages preserve the scheduled market close (#100).**
3676
+ `create_snapshot_package` did not capture `market_close_timestamp` /
3677
+ `has_market_close`, and `restore_from_snapshot` reset them to `0` / `false`, so a
3678
+ book with a configured market close silently lost it (and its DAY / GTD expiry
3679
+ schedule) after a snapshot round-trip or replay. The two values are now carried on
3680
+ `OrderBookSnapshotPackage` (additive `#[serde(default)]`, format version stays 2)
3681
+ and re-applied on restore, mirroring `kill_switch_engaged`.
3682
+
3683
+ ## [0.8.0] — 2026-05-03
3684
+
3685
+ ### Added — Quote-notional market orders (#85)
3686
+
3687
+ - **New public API** on `OrderBook<T>`: `match_market_order_by_amount`
3688
+ and `match_market_order_by_amount_with_user`, plus the convenience
3689
+ wrappers `submit_market_order_by_amount` and
3690
+ `submit_market_order_by_amount_with_user` (run kill-switch and
3691
+ pre-trade risk gates before matching). Implements Binance
3692
+ `quoteOrderQty` semantics — callers say "buy ~$1,000 of BTC" without
3693
+ converting to base quantity. Fees are exclusive: caller pays
3694
+ `amount + taker_fee`.
3695
+ - **Lot enforcement.** When `OrderBook::with_lot_size` is configured,
3696
+ the per-level base quantity is rounded down to a multiple of
3697
+ `lot_size`. Notional walks never emit `qty = 0` trades when the
3698
+ remaining budget cannot fund one full lot at the current level.
3699
+ - **New error variant `OrderBookError::InsufficientLiquidityNotional
3700
+ { side, requested, spent }`** distinguishes notional from base-qty
3701
+ insufficiencies.
3702
+ - **`TradeResult.quote_notional: u128`** — populated for both
3703
+ base-quantity and quote-notional market-order paths. Carries
3704
+ `Σ price × quantity` so consumers do not recompute per-trade.
3705
+ `#[serde(default)]` keeps pre-0.7.x-tail JSON / Bincode payloads
3706
+ parseable.
3707
+ - **Additive `SequencerCommand::MarketOrderByAmount { id, amount, side }`**
3708
+ variant. Old journals replay byte-identical; the new variant ferries
3709
+ through `submit_market_order_by_amount` on replay. No
3710
+ `ORDERBOOK_SNAPSHOT_FORMAT_VERSION` bump required.
3711
+ - **`StopCondition` refactor of the matching loop** — single inner
3712
+ implementation drives both base-qty and notional walks. The base-qty
3713
+ path retains its previous arithmetic profile when `lot_size` is unset
3714
+ (`lot <= 1` ⇒ no rounding work).
3715
+ - Runnable example: `cargo run -p examples --bin market_order_by_amount`.
3716
+ - HDR latency bench: `notional_walk_hdr` mirrors `aggressive_walk_hdr`
3717
+ on the notional path.
3718
+
3719
+ ## [0.7.0] — 2026-04-25
3720
+
3721
+ > 0.7.0 ships issues #51..#60 and the centralised `engine_seq` minting
3722
+ > refactor (#73). Sub-headings below group changes by feature.
3723
+
3724
+ ### Added — feature-gated allocation counter (#58)
3725
+
3726
+ - **New feature `alloc-counters`** (default off). Exposes
3727
+ `CountingAllocator<Inner: GlobalAlloc>` and `AllocSnapshot` at the
3728
+ crate root, layering four `AtomicU64` counters (`allocs`,
3729
+ `deallocs`, `bytes_allocated`, `bytes_deallocated`) on top of any
3730
+ inner allocator. Bench / test binaries opt in by installing the
3731
+ wrapper as `#[global_allocator]`.
3732
+ - **Bench `alloc_count`** at `benches/order_book/alloc_count.rs`
3733
+ (also feature-gated) runs the mixed 70 / 20 / 10 workload, prints
3734
+ `allocs_per_op` + `bytes_alloc/op` to stdout, and writes a small
3735
+ markdown summary to `target/alloc-counters/<scenario>.md`.
3736
+ - **Integration test `alloc_budget_tests`** at
3737
+ `tests/unit/alloc_budget_tests.rs` runs 10 000 mixed ops and
3738
+ asserts `allocs/op < 10` — conservative ceiling tuned to catch
3739
+ order-of-magnitude regressions in CI, not to certify zero.
3740
+ - **`BENCH.md`** gains an "Allocation profile" section with the
3741
+ workflow + a reference number from a single M4 Max run.
3742
+ - **`mod utils` made `pub mod utils`** so the new types are
3743
+ reachable via `orderbook_rs::utils::CountingAllocator` as well as
3744
+ the crate-root re-export. Existing `pub use utils::current_time_millis`
3745
+ unchanged.
3746
+
3747
+ ### Notes — alloc counter
3748
+
3749
+ - The library `rlib` does **not** install a `#[global_allocator]` —
3750
+ consumers pick their own (`jemalloc`, `mimalloc`, system, …). The
3751
+ wrapper exists to give bench / test binaries a measurement hook
3752
+ without forcing a global choice on the library.
3753
+ - `counting_allocator.rs` carries a documented
3754
+ `#[allow(unsafe_code)]` exception to the crate's
3755
+ `#![deny(unsafe_code)]` policy because Rust's `GlobalAlloc` trait
3756
+ requires `unsafe impl`. The exception is gated on the feature flag
3757
+ and confined to the wrapper module; every `unsafe` block
3758
+ delegates immediately to the inner allocator.
3759
+
3760
+ ### Added — Prometheus metrics feature (#60)
3761
+
3762
+ - **New optional `metrics` feature flag** (default off). When
3763
+ enabled, the matching core emits Prometheus-style counters and
3764
+ gauges through the [`metrics`](https://docs.rs/metrics) crate's
3765
+ global facade. Any compatible recorder (Prometheus exporter,
3766
+ OpenTelemetry bridge, custom collector) can scrape them.
3767
+ - **Surface (stable across `0.7.x`):**
3768
+ - `orderbook_rejects_total{reason="..."}` — counter,
3769
+ incremented exactly once per rejection. Label value is the
3770
+ `RejectReason` `Display` string.
3771
+ - `orderbook_depth_levels_bid` / `orderbook_depth_levels_ask`
3772
+ — gauges, current count of distinct price levels per side,
3773
+ refreshed on every add / cancel / modify / fill.
3774
+ - `orderbook_trades_total` — counter, monotonic count of every
3775
+ emitted trade transaction (one increment per `MatchResult`
3776
+ transaction, summed across all listener-emitted and
3777
+ internal-only matches).
3778
+ - **Out-of-band emission.** Allocation-free on the happy path,
3779
+ no influence on matching outcomes, no recorder dependency on
3780
+ the core engine. `restore_from_snapshot_package` does **not**
3781
+ rehydrate counters — operational only, process-lifetime.
3782
+ - **Compile-time no-op when the feature is disabled.** Every
3783
+ helper in `orderbook::metrics` compiles down to an empty
3784
+ function so call-sites in the matching hot path stay
3785
+ unconditional.
3786
+ - **`metrics = "0.24"`** is the new optional dependency.
3787
+ - Integration test `tests/metrics/` (its own test binary so the
3788
+ global recorder isn't perturbed by the rest of the suite)
3789
+ covers reject counts, trade counts, depth gauges, and a
3790
+ determinism guard that proves metrics emission does not alter
3791
+ byte-identical snapshots.
3792
+ - Example `examples/src/bin/prometheus_export.rs` demonstrates
3793
+ installing `metrics-exporter-prometheus` and dumping the
3794
+ exposition payload.
3795
+
3796
+ ### Added — feature-gated binary wire protocol (#59)
3797
+
3798
+ - **New `wire` feature flag** in `Cargo.toml` plus an optional
3799
+ dependency on `zerocopy = "0.8"` (with `derive`). Disabled by
3800
+ default; the crate's existing JSON and bincode paths are
3801
+ unchanged — the wire protocol is purely additive.
3802
+ - **Length-prefixed framing** — every frame on the wire is
3803
+ `[len:u32 LE | kind:u8 | payload]`. `len` covers `kind + payload`
3804
+ (it does NOT include the 4-byte `len` prefix itself). All
3805
+ multi-byte integers are little-endian. Implementation in
3806
+ `src/wire/framing.rs` with `encode_frame` / `decode_frame`.
3807
+ - **`MessageKind` enum** (`#[repr(u8)]`, `#[non_exhaustive]`) with
3808
+ stable explicit discriminants documented as stable across
3809
+ `0.7.x`:
3810
+
3811
+ | Code | Direction | Message | Payload size |
3812
+ |--------|-----------|-----------------|-------------:|
3813
+ | `0x01` | inbound | `NewOrder` | 48 B |
3814
+ | `0x02` | inbound | `CancelOrder` | 24 B |
3815
+ | `0x03` | inbound | `CancelReplace` | 40 B |
3816
+ | `0x04` | inbound | `MassCancel` | 24 B |
3817
+ | `0x81` | outbound | `ExecReport` | 44 B |
3818
+ | `0x82` | outbound | `TradePrint` | 48 B |
3819
+ | `0x83` | outbound | `BookUpdate` | 32 B |
3820
+
3821
+ - **Inbound messages** are `#[repr(C, packed)]` and derive the
3822
+ `zerocopy` traits (`FromBytes`, `IntoBytes`, `Unaligned`,
3823
+ `Immutable`, `KnownLayout`). Decoding is safe — the crate keeps
3824
+ `#![deny(unsafe_code)]` on the lib root. Each struct ships a
3825
+ compile-time `const _: () = assert!(size_of::<…>() == N)` size
3826
+ guard. Exposed: `NewOrderWire`, `CancelOrderWire`,
3827
+ `CancelReplaceWire`, `MassCancelWire` and the matching
3828
+ `decode_*` helpers.
3829
+ - **Outbound messages** use explicit byte-cursor encoders
3830
+ (`Vec<u8>::extend_from_slice`) rather than packed structs.
3831
+ Outbound is I/O-dominated so the cost of a few dozen bytes of
3832
+ field-by-field copy is dwarfed by socket overhead, and the
3833
+ layout is free to evolve. Exposed: `ExecReport` +
3834
+ `encode_exec_report` + `status_to_wire`,
3835
+ `TradePrintWire` + `encode_trade_print`,
3836
+ `BookUpdateWire` + `encode_book_update`.
3837
+ - **Wire ↔ domain mapping** at the boundary —
3838
+ `impl TryFrom<&NewOrderWire> for OrderType<()>` performs the
3839
+ conversion, copies each packed field into a local first
3840
+ (taking a reference to a packed field is undefined behaviour),
3841
+ and returns `WireError::InvalidPayload` on unknown
3842
+ side / TIF / order_type bytes or a negative price.
3843
+ - **Errors** routed through a manual-`Display`
3844
+ `#[non_exhaustive] WireError` (no `thiserror`, matches the
3845
+ crate's existing manual style for the wire surface): variants
3846
+ `Truncated`, `UnknownKind(u8)`, `InvalidPayload(&'static str)`.
3847
+ - **`doc/wire-protocol.md`** with per-message offset / size /
3848
+ field / type / notes tables, the `MessageKind` discriminant
3849
+ table, the framing rule, and the LE-endianness statement.
3850
+ - **Round-trip `proptest` tests** in every
3851
+ `src/wire/{inbound,outbound}/*.rs` module — encode through the
3852
+ framer, decode back, assert byte-for-byte equality.
3853
+ - **Crate-root re-exports** under `#[cfg(feature = "wire")]` —
3854
+ callers reach types via `orderbook_rs::wire::*`.
3855
+ - **Example** `examples/src/bin/wire_roundtrip.rs` (gated by
3856
+ `required-features = ["wire"]`) — builds a `NewOrderWire`,
3857
+ encodes it through the framer, decodes it back, converts to a
3858
+ domain `OrderType<()>`, and prints every field via
3859
+ `tracing::info!`.
3860
+
3861
+ ### Added — HDR-histogram tail-latency bench suite (#56)
3862
+
3863
+ - **Six new bench binaries** under `benches/order_book/*_hdr.rs` that
3864
+ record per-sample latency into an `hdrhistogram::Histogram` and
3865
+ emit `p50` / `p99` / `p99.9` / `p99.99` + min / max + sample count
3866
+ to stdout. Scenarios: `add_only`, `cancel_only`,
3867
+ `aggressive_walk`, `mixed_70_20_10`, `thin_book_sweep`,
3868
+ `mass_cancel_burst`. Each is a `harness = false` binary that
3869
+ coexists with the existing Criterion benches.
3870
+ - **Shared helpers** in `benches/order_book/hdr_common.rs`
3871
+ (`new_histogram`, `record`, `report`, `persist`) and a
3872
+ self-contained xorshift PRNG so the bench tree pulls no extra
3873
+ runtime dependency beyond `hdrhistogram`.
3874
+ - **`hdrhistogram` ^7** as a dev-dependency.
3875
+ - **`make bench-hdr`** target — runs all six scenarios in series.
3876
+ - **`BENCH.md`** at repo root with methodology (warmup, closed-loop
3877
+ vs open-loop disclosure), reproducibility steps, run conditions
3878
+ block, and an honest table of the headline numbers from a single
3879
+ M4 Max run plus a one-paragraph "where the tail comes from"
3880
+ paragraph per scenario. Format-version stays at `2`.
3881
+ - Raw histograms persist to `target/bench-hdr/<scenario>.hgrm` (V2
3882
+ HDR format, gitignored under `target/`).
3883
+
3884
+ ### Notes — HDR bench
3885
+
3886
+ - **Closed-loop service time only.** The driver waits for each call
3887
+ before issuing the next — tail latencies under saturation will be
3888
+ worse than what these numbers report. Used as a regression signal
3889
+ and a lower-bound on production tail, not as a published SLO.
3890
+ Open-loop measurement is a follow-up.
3891
+ - The Criterion benches under `benches/order_book/` (`add_orders.rs`,
3892
+ `match_orders.rs`, etc.) are unchanged.
3893
+
3894
+ ### Added — closed `RejectReason` enum (#55)
3895
+
3896
+ - **New `RejectReason`** closed `#[non_exhaustive] #[repr(u16)]` enum
3897
+ with stable explicit discriminants (1..13 + `Other(u16)`). It is the
3898
+ canonical wire-side reject taxonomy — consumers can route on the
3899
+ numeric code without parsing strings, and the discriminants are
3900
+ documented as stable across `0.7.x` patch upgrades.
3901
+ - **`OrderStatus::Rejected.reason: String`** → `RejectReason`
3902
+ (breaking change to a public enum's variant shape; allowed under the
3903
+ `0.6.x → 0.7.x` minor delta in `0.x` semver).
3904
+ - **Crate-root + prelude re-export** of `RejectReason`.
3905
+ - **`impl From<&OrderBookError> for RejectReason`** — operational
3906
+ ergonomics. Maps every `OrderBookError` variant to its wire-side
3907
+ reject code (or `Other(0)` for internal-state errors with no public
3908
+ reject mapping). Exhaustive match — adding an `OrderBookError`
3909
+ variant in the future is caught at compile time inside the crate.
3910
+ - **Risk-gate rejection now records the tracker.** When an
3911
+ `OrderStateTracker` is configured and `add_order` is rejected by the
3912
+ risk layer, the engine records
3913
+ `OrderStatus::Rejected { reason: RejectReason::Risk* }` against the
3914
+ rejected order id before propagating the typed error. Mirrors the
3915
+ kill-switch tracker pattern.
3916
+ - **Kill-switch reject now uses the typed code.** The previous string
3917
+ `"kill switch active"` is replaced by
3918
+ `RejectReason::KillSwitchActive`.
3919
+ - **Validation / post-only / missing-user-id rejects also typed.** The
3920
+ internal sites in `modifications.rs` that already transitioned the
3921
+ tracker to `OrderStatus::Rejected` now emit `RejectReason::InvalidPrice`,
3922
+ `RejectReason::PostOnlyWouldCross`, and `RejectReason::MissingUserId`
3923
+ respectively (incidental migration — these paths previously stored a
3924
+ free-form string).
3925
+ - New integration tests `tests/unit/reject_reason_tests.rs` cover the
3926
+ kill-switch and three risk-gate tracker emissions and a Display
3927
+ smoke test.
3928
+
3929
+ ### Notes — `RejectReason`
3930
+
3931
+ - Discriminants are stable wire codes. Do not reorder or reuse a
3932
+ retired discriminant within the `0.7.x` series.
3933
+ - `Other(u16)` is the forward-compat escape hatch for application-side
3934
+ extensions. Values `>= 1000` are reserved for caller use; the
3935
+ library will never emit a value in that range.
3936
+ - The reverse direction `From<RejectReason> for OrderBookError` is
3937
+ **not** provided. The enum is the stable public contract; the error
3938
+ is the internal impl detail.
3939
+ - Snapshot format unchanged. `OrderStateTracker` history is not
3940
+ persisted in `OrderBookSnapshotPackage`; format version stays at `2`.
3941
+ - Out of scope (deferred to a follow-up issue): wiring tracker
3942
+ `Rejected` emission for STP cancel-taker and `InsufficientLiquidity`
3943
+ IOC/FOK paths, both of which currently return errors without
3944
+ transitioning the tracker.
3945
+
3946
+ ### Added — pre-trade risk layer (#54)
3947
+
3948
+ - **Pre-trade risk layer** on `OrderBook<T>`. New `RiskConfig` with
3949
+ three opt-in guard-rails and three new typed reject variants on
3950
+ `OrderBookError`:
3951
+ - `max_open_orders_per_account: Option<u64>` →
3952
+ `OrderBookError::RiskMaxOpenOrders { account, current, limit }`
3953
+ - `max_notional_per_account: Option<u128>` →
3954
+ `OrderBookError::RiskMaxNotional { account, current, attempted, limit }`
3955
+ - `price_band_bps: Option<u32>` (with
3956
+ `ReferencePriceSource::{LastTrade, Mid, FixedPrice(u128)}`) →
3957
+ `OrderBookError::RiskPriceBand { submitted, reference, deviation_bps, limit_bps }`
3958
+ - **Public API on `OrderBook<T>`**:
3959
+ `pub fn set_risk_config(&mut self, RiskConfig)`,
3960
+ `pub fn risk_config(&self) -> Option<&RiskConfig>`,
3961
+ `pub fn disable_risk(&mut self)`. `RiskConfig` is a builder:
3962
+ `RiskConfig::new().with_max_open_orders_per_account(n).with_max_notional_per_account(n).with_price_band_bps(bps, source)`.
3963
+ - **Per-account counters** in `DashMap<Hash32, RiskCounters>` with
3964
+ `open_count: AtomicU64` and `resting_notional: AtomicCell<u128>`.
3965
+ Per-resting-order risk state in `DashMap<Id, RiskEntry>`. All hooks
3966
+ are allocation-free on the happy path.
3967
+ - **Check ordering** on submit/add: `kill_switch → risk → STP →
3968
+ fees → match`. Documented in the rustdoc on
3969
+ `RiskState::check_limit_admission`.
3970
+ - **Market orders bypass the risk layer** (no submitted price, no
3971
+ rest, no contribution to the open-order count). Kill switch still
3972
+ gates them. Documented.
3973
+ - **Reference-price resolution** for `price_band_bps`:
3974
+ - `LastTrade` → `last_trade_price`. Skipped (with one-time
3975
+ `tracing::warn!`) when no trades have occurred.
3976
+ - `Mid` → integer `(best_bid + best_ask) / 2`. One-sided book
3977
+ falls back to `LastTrade`.
3978
+ - `FixedPrice(p)` → caller-supplied `u128` ticks.
3979
+ - **Snapshot persistence**. `OrderBookSnapshotPackage` carries
3980
+ `risk_config: Option<RiskConfig>` (with `#[serde(default)]` for
3981
+ forward-compat). On restore, counters and the per-order map are
3982
+ rebuilt by walking the snapshot's resting orders. Snapshot format
3983
+ version stays at `2` — the field is purely additive.
3984
+ - **Crate-root re-exports**: `RiskConfig`, `RiskState`,
3985
+ `ReferencePriceSource`. Also surfaced via `prelude`.
3986
+ - New example: `examples/src/bin/risk_limits.rs` — operator demo
3987
+ that breaches each gate in sequence.
3988
+ - Integration tests `tests/unit/risk_layer_tests.rs` cover every
3989
+ reject path, every state-update hook, market-order bypass, and
3990
+ snapshot round-trip.
3991
+
3992
+ ### Notes — pre-trade risk layer
3993
+
3994
+ - Counters are estimative. The `open_count` and `resting_notional`
3995
+ pair is two independent atomics; no atomic snapshot of the pair is
3996
+ taken. Under high concurrency the check may admit one order beyond
3997
+ the limit before settling — acceptable for a guard-rail (vs. a
3998
+ hard regulatory cap).
3999
+ - Risk config is operator-driven, not journaled. Replays via
4000
+ `ReplayEngine::replay_from*` start with no risk gating; operators
4001
+ re-attach config post-replay.
4002
+ - `disable_risk()` lifts the gates without dropping per-account
4003
+ counters, so subsequent `set_risk_config(...)` calls re-engage
4004
+ with the existing history intact.
4005
+
4006
+ ### Added — kill switch (#53)
4007
+
4008
+ - **Operational kill switch** on `OrderBook<T>`. New `AtomicBool` on
4009
+ the book and three public methods:
4010
+ `pub fn engage_kill_switch(&self)`,
4011
+ `pub fn release_kill_switch(&self)`,
4012
+ `pub fn is_kill_switch_engaged(&self) -> bool`.
4013
+ While engaged, every public `submit_market_order*`, `add_order`,
4014
+ and non-`Cancel` `update_order` call returns the new
4015
+ `OrderBookError::KillSwitchActive` variant before any matching, fee,
4016
+ or STP work happens — at the cost of a single
4017
+ `AtomicBool::load(Relaxed)` on the gate. Cancel and mass-cancel
4018
+ paths are explicitly **not** gated so operators can drain the
4019
+ resting book in an orderly way. Idempotent.
4020
+ - **`OrderBookError::KillSwitchActive`** — new typed reject variant.
4021
+ Additive on the existing `#[non_exhaustive]` enum.
4022
+ - **Snapshot persistence**. `OrderBookSnapshotPackage` carries
4023
+ `kill_switch_engaged: bool` (with `#[serde(default)]` for JSON
4024
+ forward-compat). `restore_from_snapshot_package` resumes the
4025
+ operational state. Snapshot format version stays at `2` — the
4026
+ field is purely additive.
4027
+ - **`OrderStateTracker` integration**. When a tracker is configured
4028
+ on the book and a kill-switched submit / modify is rejected, the
4029
+ engine records `OrderStatus::Rejected { reason: "kill switch active" }`
4030
+ via the existing `OrderStateTracker::transition`. A future typed
4031
+ `RejectReason` (issue #55) will replace the string code.
4032
+ - New example: `examples/src/bin/kill_switch_drain.rs` — operator
4033
+ halt-and-drain demo. Run with
4034
+ `cargo run --bin kill_switch_drain --manifest-path examples/Cargo.toml`.
4035
+ - Integration tests: `tests/unit/kill_switch_tests.rs` covers every
4036
+ gated and non-gated entry point plus snapshot round-trip and
4037
+ legacy v2 payload (without the new field) defaulting to `false`.
4038
+
4039
+ ### Notes — kill switch
4040
+
4041
+ - The low-level `OrderBook::match_market_order` /
4042
+ `OrderBook::match_limit_order` entry points are **not** gated.
4043
+ Production flow goes through the `submit_*` / `add_order` /
4044
+ `update_order` public surface; this is documented in the rustdoc on
4045
+ `engage_kill_switch`.
4046
+ - The kill switch is operator-driven, not journaled. A book restored
4047
+ via `ReplayEngine::replay_from*` starts with the kill switch
4048
+ disengaged regardless of the original journal author's state.
4049
+ Snapshot/restore preserves it; replay does not.
4050
+
4051
+ ### Added — global `engine_seq` (#52)
4052
+
4053
+ - **Global monotonic `engine_seq`** across every outbound stream.
4054
+ `OrderBook<T>` gains an internal `AtomicU64` counter and two public
4055
+ accessors: `pub fn next_engine_seq(&self) -> u64` (mints the next
4056
+ value via `fetch_add(1, Relaxed)`) and `pub fn engine_seq(&self) -> u64`
4057
+ (current value, used by snapshotting). The counter is incremented
4058
+ exactly once per outbound emission, in emission order. Per-instance
4059
+ contract — replay into a fresh book produces fresh seqs, not the
4060
+ original ones; consumers needing the original outbound stream use
4061
+ the journal's `SequencerEvent.sequence_num`.
4062
+ - **`engine_seq: u64` field** on every outbound event type. JSON
4063
+ payloads are forward-compatible via `#[serde(default)]` where
4064
+ applicable:
4065
+ - `TradeResult.engine_seq`
4066
+ - `TradeEvent.engine_seq`
4067
+ - `PriceLevelChangedEvent.engine_seq`
4068
+ - `BookChangeEntry.engine_seq` (NATS path, `Serialize`-only)
4069
+ - **Snapshot package persistence** — `OrderBookSnapshotPackage` carries
4070
+ `engine_seq: u64` so `restore_from_snapshot_package` resumes
4071
+ monotonicity exactly from the snapshotted point.
4072
+ - Integration proptest `tests/unit/engine_seq_monotonic_tests.rs`
4073
+ (256 cases) asserts the cross-stream monotonicity contract.
4074
+
4075
+ ### Changed — global `engine_seq` (#52)
4076
+
4077
+ - **`ORDERBOOK_SNAPSHOT_FORMAT_VERSION` bumped from `1` to `2`.**
4078
+ Snapshot packages with `version: 1` are now rejected by `validate()`
4079
+ with the existing `Unsupported snapshot version` error. JSON payloads
4080
+ at `version: 2` that omit `engine_seq` deserialize with `engine_seq = 0`.
4081
+ - **`BookChangeBatch.sequence`** retains its existing per-batch
4082
+ publisher-counter semantics. Cross-stream gap detection now uses the
4083
+ new per-event `BookChangeEntry.engine_seq` instead. Both fields ship
4084
+ in the same payload; consumers can adopt the new field incrementally.
4085
+
4086
+ ### Added — `Clock` trait (#51)
4087
+
4088
+ - **`Clock` trait** (`src/orderbook/clock.rs`) — pluggable timestamp source
4089
+ injected at the operations edge so matching stays deterministic under
4090
+ sequencer replay. Two implementations ship: `MonotonicClock` (production,
4091
+ wraps `SystemTime::now`) and `StubClock` (replay / tests, monotonic
4092
+ `AtomicU64` counter with configurable start and step). Exposed at the
4093
+ crate root and via `prelude`.
4094
+ - **`OrderBook::with_clock(symbol, Arc<dyn Clock>)`** constructor and
4095
+ **`OrderBook::set_clock`**, **`OrderBook::clock()`** accessors. The
4096
+ default `OrderBook::new` keeps wrapping `MonotonicClock` internally —
4097
+ existing callers observe no behavioural change.
4098
+ - **`OrderStateTracker::with_clock`** and
4099
+ **`OrderStateTracker::with_capacity_and_clock`** constructors.
4100
+ - **`ReplayEngine::replay_from_with_clock`** and
4101
+ **`ReplayEngine::replay_from_with_clock_and_progress`** — the canonical
4102
+ entry points for byte-identical replay tests and disaster-recovery
4103
+ pipelines that must reproduce engine timestamps deterministically.
4104
+ - Integration proptest `tests/unit/clock_determinism_tests.rs` (128 cases)
4105
+ covering "two replays with identical `StubClock` produce matching
4106
+ snapshots". A strictly byte-identical event-stream oracle (via
4107
+ `EventSerializer`) is widened in issue #57.
4108
+ - New dev-dependency `proptest = "1.7"`.
4109
+
4110
+ ### Changed
4111
+
4112
+ - **`OrderStateTracker` history unit migrated from nanoseconds to
4113
+ milliseconds.** The tracker now stamps via the injected `Clock`, and
4114
+ `Clock::now_millis` is the only unit the trait exposes.
4115
+ `OrderStateTracker::get_history` and `OrderBook::get_order_history`
4116
+ therefore return `Vec<(u64 /* ms */, OrderStatus)>` instead of
4117
+ nanoseconds. `purge_terminal_older_than(Duration)` interprets its
4118
+ argument in milliseconds accordingly.
4119
+ - Wall-clock reads (`SystemTime::now` / `current_time_millis`) removed
4120
+ from `src/orderbook/operations.rs`, `private.rs`, `book.rs`, and
4121
+ `order_state.rs` — every stamp now flows through
4122
+ `self.clock().now_millis()`. `utils::current_time_millis` remains
4123
+ public for non-library callers and is unchanged.
4124
+
4125
+ ### Notes
4126
+
4127
+ - Non-breaking public API surface for the Clock trait. Adding the
4128
+ `engine_seq` fields extends public structs that consumers may
4129
+ construct via struct literals; while `cargo-semver-checks`
4130
+ may flag those, the `0.6.x → 0.7.x` delta in `0.x` semver permits
4131
+ minor breaking changes.
4132
+ - Replay determinism: `ReplayEngine::replay_from` continues to behave
4133
+ as before (production stamping via `MonotonicClock`). Byte-identical
4134
+ replay requires the new `replay_from_with_clock` entry point with a
4135
+ caller-supplied `Arc<StubClock>` and a fixed start value.
4136
+ - Snapshot format version bumped to `2`. Older `version: 1` snapshots
4137
+ do not load. Re-snapshot under 0.7.0 to migrate.
4138
+
4139
+ ## [0.6.2] — 2026-04-20
4140
+
4141
+ ### Changed
4142
+
4143
+ - **Dependencies**: Bump workspace dependencies to latest stable
4144
+ versions — `uuid` → `1.23`, `tokio` → `1.52`, `sha2` → `0.11`,
4145
+ `async-nats` → `0.47`, and `bincode` → `2.0` (the crates.io `3.0.0`
4146
+ release is a `compile_error!` stub, so `2.0` is the current usable
4147
+ major).
4148
+ - **`bincode` migration (feature `bincode`)**: migrated the
4149
+ `BincodeEventSerializer` and the bincode-gated sequencer tests from
4150
+ the legacy `bincode::serialize` / `bincode::deserialize` API to the
4151
+ serde bridge in `bincode 2.x`
4152
+ (`bincode::serde::encode_to_vec` / `bincode::serde::decode_from_slice`
4153
+ with `bincode::config::standard()`). The public
4154
+ `EventSerializer` trait and the `BincodeEventSerializer` type are
4155
+ unchanged.
4156
+ - **`sha2` 0.11 compat**: the finalized `Digest` output type no
4157
+ longer implements `LowerHex` directly, so
4158
+ `OrderBookSnapshotPackage::compute_checksum` now formats the hash
4159
+ bytes explicitly.
4160
+
4161
+ ### Notes
4162
+
4163
+ - **Wire-format change (bincode NATS payloads)**: bincode 1.x and
4164
+ bincode 2.x produce different byte layouts. Consumers that decoded
4165
+ NATS payloads with an older `BincodeEventSerializer` build must
4166
+ upgrade to the new version. The on-disk journal is unaffected — it
4167
+ uses `serde_json`, not bincode. `ORDERBOOK_SNAPSHOT_FORMAT_VERSION`
4168
+ stays at `1`.
4169
+ - No public API changes — `0.6.2` is a compatible minor release.
4170
+
4171
+ ## [0.6.1] — 2026-03-22
4172
+
4173
+ ### Changed
4174
+
4175
+ - **Performance**: Replace `Box<dyn Iterator>` with `either::Either`
4176
+ for bid/ask iterators, eliminating unnecessary heap allocation and
4177
+ dynamic dispatch in the matching hot path.
4178
+
4179
+ ### Fixed
4180
+
4181
+ - Updated dependency management workflows for GitHub Actions
4182
+
4183
+ ## [0.6.0] — 2025-02-28
4184
+
4185
+ ### Added
4186
+
4187
+ - **NATS JetStream Publishers** (`nats` feature): trade event and book change
4188
+ publishers with retry, batching, and throttling.
4189
+ - **Zero-Copy Serialization** (`bincode` feature): pluggable `EventSerializer`
4190
+ trait with JSON and Bincode implementations.
4191
+ - **Sequencer Subsystem**: `SequencerCommand`, `SequencerEvent`,
4192
+ `SequencerResult` types for LMAX Disruptor-style total ordering.
4193
+ - **Append-Only Journal** (`journal` feature): `FileJournal` with
4194
+ memory-mapped segments, CRC32 checksums, and segment rotation.
4195
+ - **In-Memory Journal**: `InMemoryJournal` for testing and benchmarking.
4196
+ - **Deterministic Replay**: `ReplayEngine` for disaster recovery and state
4197
+ verification from journal.
4198
+ - **Order State Machine**: `OrderStatus`, `CancelReason`,
4199
+ `OrderStateTracker` for explicit lifecycle tracking
4200
+ (Open → PartiallyFilled → Filled / Cancelled / Rejected).
4201
+ - **Order Lifecycle Query API**: `get_order_history()`,
4202
+ `active_order_count()`, `terminal_order_count()`,
4203
+ `purge_terminal_states()`.
4204
+ - **Cross-Book Mass Cancel**: `cancel_all_across_books()`,
4205
+ `cancel_by_user_across_books()`, `cancel_by_side_across_books()` on
4206
+ `BookManager`.
4207
+ - **Snapshot Config Preservation**: `restore_from_snapshot_package()`
4208
+ preserves fee schedule, STP mode, tick/lot size, and order size limits.
4209
+ - **Clone for OrderBookError**: manual `Clone` impl to work around
4210
+ `PriceLevelError` not deriving `Clone`.
4211
+
4212
+ ### Changed
4213
+
4214
+ - Upgraded to **pricelevel v0.7** with `Id`, `Price`, `Quantity`,
4215
+ `TimestampMs` newtypes for stronger type safety.
4216
+ - Removed all `.unwrap()` and `.expect()` from production code.
4217
+
4218
+ ## [0.5.0] — 2025-01-15
4219
+
4220
+ ### Added
4221
+
4222
+ - **Order Validation**: tick size, lot size, and min/max order size
4223
+ validation with configurable limits.
4224
+ - **Self-Trade Prevention (STP)**: `CancelTaker`, `CancelMaker`,
4225
+ `CancelBoth` modes with per-order `user_id` enforcement.
4226
+ - **Fee Model**: configurable `FeeSchedule` with maker/taker fees and fee
4227
+ fields in `TradeResult`.
4228
+ - **Mass Cancel Operations**: cancel all, by side, by user, by price
4229
+ range — with `MassCancelResult` tracking.
4230
+
4231
+ ## [0.4.8] — 2024-12-20
4232
+
4233
+ ### Added
4234
+
4235
+ - **PriceLevelCache**: faster best bid/ask lookups.
4236
+ - **MatchingPool**: reduced matching engine allocations.
4237
+
4238
+ ### Changed
4239
+
4240
+ - Refactored modification and matching logic for better separation of
4241
+ concerns.
4242
+ - Improved thread-safe operations under heavy concurrent load.
4243
+
4244
+ ## [0.4.0] — 2024-11-01
4245
+
4246
+ ### Added
4247
+
4248
+ - **Lock-Free Architecture**: `SkipMap` + `DashMap` + `SegQueue` for
4249
+ contention-free concurrent access.
4250
+ - **Multiple Order Types**: Standard, Iceberg, PostOnly, FillOrKill,
4251
+ ImmediateOrCancel, GoodTillDate, TrailingStop, Pegged, MarketToLimit,
4252
+ Reserve.
4253
+ - **Thread-Safe Price Levels**: independent concurrent modification per
4254
+ level.
4255
+ - **Advanced Order Matching**: price-time priority for both market and
4256
+ limit orders with partial fills.
4257
+ - **Multi-Book Management**: `BookManagerStd` and `BookManagerTokio` for
4258
+ managing multiple order books.
4259
+ - **Enriched Snapshots**: single-pass snapshot with VWAP, spread, mid
4260
+ price, imbalance, and depth metrics.
4261
+ - **Implied Volatility**: Black-Scholes implied vol calculation.
4262
+ - **Market Metrics**: VWAP, micro price, queue analysis, depth
4263
+ statistics, and functional iterators.
4264
+
4265
+ [Unreleased]: https://github.com/joaquinbejar/OrderBook-rs/compare/v0.16.0...HEAD
4266
+ [0.16.0]: https://github.com/joaquinbejar/OrderBook-rs/compare/v0.15.4...v0.16.0
4267
+ [0.15.4]: https://github.com/joaquinbejar/OrderBook-rs/compare/v0.15.3...v0.15.4
4268
+ [0.15.3]: https://github.com/joaquinbejar/OrderBook-rs/compare/v0.15.2...v0.15.3
4269
+ [0.15.2]: https://github.com/joaquinbejar/OrderBook-rs/compare/v0.15.1...v0.15.2
4270
+ [0.15.1]: https://github.com/joaquinbejar/OrderBook-rs/compare/v0.15.0...v0.15.1
4271
+ [0.15.0]: https://github.com/joaquinbejar/OrderBook-rs/compare/v0.14.0...v0.15.0
4272
+ [0.14.0]: https://github.com/joaquinbejar/OrderBook-rs/compare/v0.13.1...v0.14.0