Skip to main content

chronicle_core/book/
snapshot.rs

1//! Snapshot capture and restore (ARCHITECTURE.md sections 10.2 and
2//! 10.4). Capture reads the arena, the level arrays, and the free list
3//! into the plain [`SnapshotState`] transfer shape. Restore rebuilds a
4//! book from a state that `chronicle-wal` has already validated byte
5//! by byte, reproducing slot assignment, FIFO links, generations, and
6//! the exact free list, so a restored book is indistinguishable from
7//! the captured one, including in the order `cancel_by_participant`
8//! emits its events and in the slots later allocations take.
9
10use crate::arena::{NIL, STATE_FREE, STATE_LIVE, STATE_RETIRED};
11use crate::error::BookError;
12use crate::types::{LevelState, LiveOrderState, OrderId, ParticipantId, Side, SnapshotState};
13
14use super::Book;
15
16impl Book {
17    /// Capture the complete structural state of this book for
18    /// persistence. Live orders are reported in ascending slot order;
19    /// the free list is reported exactly, head and per-slot links, so
20    /// a restore allocates slots in the same order this book would
21    /// have.
22    #[must_use]
23    pub fn capture_snapshot_state(&self) -> SnapshotState {
24        let slots = self.config.max_orders as usize;
25        let mut generations = Vec::with_capacity(slots);
26        let mut free_links = Vec::with_capacity(slots);
27        let mut live_orders = Vec::with_capacity(self.arena.live_count() as usize);
28        for s in 0..slots {
29            generations.push(self.arena.generation[s]);
30            if self.arena.state[s] == STATE_LIVE {
31                free_links.push(NIL);
32                live_orders.push(LiveOrderState {
33                    slot: u32::try_from(s).unwrap_or(NIL),
34                    generation: self.arena.generation[s],
35                    order_id: OrderId(self.arena.order_id[s]),
36                    participant: ParticipantId(self.arena.participant[s]),
37                    price_idx: self.arena.price_idx[s],
38                    qty: self.arena.qty[s],
39                    side: Side::from_u8(self.arena.side[s]),
40                    prev: self.arena.prev[s],
41                    next: self.arena.next[s],
42                });
43            } else {
44                // A free slot's `next` column is its free list link; a
45                // retired slot's is NIL by arena construction. Both
46                // are exactly what the format persists.
47                free_links.push(self.arena.next[s]);
48            }
49        }
50        let levels = (0..self.config.grid_len as usize)
51            .map(|i| LevelState {
52                head: self.levels.head[i],
53                tail: self.levels.tail[i],
54                qty: self.levels.qty[i],
55                count: self.levels.count[i],
56            })
57            .collect();
58        SnapshotState {
59            config: self.config,
60            next_seq: self.next_seq,
61            generations,
62            free_list_head: self.arena.free_head(),
63            free_links,
64            levels,
65            live_orders,
66        }
67    }
68
69    /// Rebuild a book from a captured state. The state must already
70    /// have passed `chronicle-wal`'s checked decode (section 10.4):
71    /// this constructor trusts the state's internal consistency,
72    /// guards it with debug assertions, and runs the full structural
73    /// invariant check on the rebuilt book in debug builds.
74    ///
75    /// # Errors
76    ///
77    /// Returns [`BookError::InvalidConfig`] when the state's own
78    /// configuration fails validation, or when a section length
79    /// disagrees with the configuration it carries. Both are
80    /// unreachable for a state produced by capture or by the checked
81    /// snapshot decode.
82    ///
83    /// # Panics
84    ///
85    /// Panics when the state fails the structural invariant check in
86    /// debug builds, which a state produced by capture or by the
87    /// checked snapshot decode cannot do.
88    pub fn from_snapshot_state(state: SnapshotState) -> Result<Self, BookError> {
89        let SnapshotState {
90            config,
91            next_seq,
92            generations,
93            free_list_head,
94            free_links,
95            levels,
96            live_orders,
97        } = state;
98        let mut book = Self::new(config)?;
99        let max_orders = config.max_orders;
100        let grid_len = config.grid_len;
101        let slots = max_orders as usize;
102        if generations.len() != slots || free_links.len() != slots {
103            return Err(BookError::InvalidConfig {
104                field: "snapshot state",
105                rule: "generation and free link sections must cover every slot",
106            });
107        }
108        if levels.len() != grid_len as usize {
109            return Err(BookError::InvalidConfig {
110                field: "snapshot state",
111                rule: "the level section must cover the whole grid",
112            });
113        }
114        let (on_chain, free_len) = walk_free_chain(&free_links, free_list_head, max_orders)?;
115        let is_live = check_live_records(&live_orders, &generations, max_orders, grid_len)?;
116        // Order ids must be unique; the lookup is the witness, and it
117        // ends up holding exactly the live set.
118        for record in &live_orders {
119            if book.lookup.get(record.order_id.0).is_some() {
120                return Err(BookError::InvalidConfig {
121                    field: "snapshot state",
122                    rule: "live order ids must be unique",
123                });
124            }
125            book.lookup
126                .insert(record.order_id.0, record.slot, record.generation)?;
127        }
128        // Generations for every slot, live and free and retired.
129        book.arena.generation.copy_from_slice(&generations);
130        // Live records into the arena columns, links included.
131        for record in &live_orders {
132            let s = record.slot as usize;
133            book.arena.state[s] = STATE_LIVE;
134            book.arena.order_id[s] = record.order_id.0;
135            book.arena.participant[s] = record.participant.0;
136            book.arena.price_idx[s] = record.price_idx;
137            book.arena.qty[s] = record.qty;
138            book.arena.side[s] = record.side.as_u8();
139            book.arena.prev[s] = record.prev;
140            book.arena.next[s] = record.next;
141        }
142        // Non-live slots: on the persisted chain means free, with the
143        // persisted link; off it means retired (section 10.4's restore
144        // rule, with the state the byte format cannot carry derived
145        // from chain membership).
146        for s in 0..slots {
147            if is_live[s] {
148                continue;
149            }
150            if on_chain[s] {
151                book.arena.state[s] = STATE_FREE;
152                book.arena.next[s] = free_links[s];
153            } else {
154                book.arena.state[s] = STATE_RETIRED;
155                book.arena.next[s] = NIL;
156            }
157            book.arena.prev[s] = NIL;
158        }
159        let live = u32::try_from(live_orders.len()).unwrap_or(0);
160        book.arena
161            .restore_bookkeeping(free_list_head, free_len, live);
162        restore_levels(&mut book, &levels, &is_live);
163        book.next_seq = next_seq;
164        if cfg!(debug_assertions) {
165            book.debug_assert_invariants();
166        }
167        Ok(book)
168    }
169}
170
171/// Walk a persisted free chain once, returning which slots it
172/// visits and how many there are. The chain must stay inside the
173/// slot range and visit no slot twice.
174fn walk_free_chain(
175    free_links: &[u32],
176    head: u32,
177    max_orders: u32,
178) -> Result<(Vec<bool>, u32), BookError> {
179    let mut on_chain = vec![false; max_orders as usize];
180    let mut free_len = 0u32;
181    let mut cursor = head;
182    while cursor != NIL {
183        if cursor >= max_orders || on_chain[cursor as usize] {
184            return Err(BookError::InvalidConfig {
185                field: "snapshot state",
186                rule: "the free list must visit in-range slots at most once",
187            });
188        }
189        on_chain[cursor as usize] = true;
190        free_len += 1;
191        cursor = free_links[cursor as usize];
192    }
193    Ok((on_chain, free_len))
194}
195
196/// Validate the live records of a snapshot state, returning which
197/// slots they occupy. Each record must name an in-range slot and
198/// price, be the only record for its slot, and agree with the
199/// slot's persisted generation.
200fn check_live_records(
201    live_orders: &[LiveOrderState],
202    generations: &[u32],
203    max_orders: u32,
204    grid_len: u32,
205) -> Result<Vec<bool>, BookError> {
206    let mut is_live = vec![false; max_orders as usize];
207    for record in live_orders {
208        if record.slot >= max_orders || record.price_idx >= grid_len {
209            return Err(BookError::InvalidConfig {
210                field: "snapshot state",
211                rule: "live records must name an in-range slot and price",
212            });
213        }
214        if is_live[record.slot as usize] || record.generation != generations[record.slot as usize] {
215            return Err(BookError::InvalidConfig {
216                field: "snapshot state",
217                rule: "live records must be unique per slot and match its generation",
218            });
219        }
220        is_live[record.slot as usize] = true;
221    }
222    Ok(is_live)
223}
224
225/// Copy the level arrays into the book verbatim and rebuild the
226/// side bitmaps from the level counts, reading each non-empty
227/// level's side from its head order.
228fn restore_levels(book: &mut Book, levels: &[LevelState], is_live: &[bool]) {
229    for (i, level) in levels.iter().enumerate() {
230        book.levels.head[i] = level.head;
231        book.levels.tail[i] = level.tail;
232        book.levels.qty[i] = level.qty;
233        book.levels.count[i] = level.count;
234        if level.count > 0 && level.head != NIL && is_live[level.head as usize] {
235            let idx = u32::try_from(i).unwrap_or(0);
236            match Side::from_u8(book.arena.side[level.head as usize]) {
237                Side::Bid => book.bids.set(idx),
238                Side::Ask => book.asks.set(idx),
239            }
240        }
241    }
242}
243
244#[cfg(test)]
245mod tests {
246    use crate::config::BookConfig;
247    use crate::events::{EventBuffer, ExecutionEvent};
248    use crate::types::{OrderType, StpPolicy};
249
250    use super::*;
251
252    fn test_config() -> BookConfig {
253        BookConfig {
254            max_orders: 16,
255            grid_len: 640,
256            tick_size: 1,
257            grid_start_tick: 1,
258            default_stp: StpPolicy::CancelIncoming,
259        }
260    }
261
262    fn add(book: &mut Book, id: u64, participant: u32, side: Side, price: u64, qty: u64) {
263        let mut storage = Vec::with_capacity(64);
264        let mut events = EventBuffer::new(&mut storage);
265        book.add_order(
266            OrderId(id),
267            ParticipantId(participant),
268            side,
269            OrderType::Limit,
270            price,
271            qty,
272            None,
273            &mut events,
274        )
275        .expect("add");
276    }
277
278    fn cancel(book: &mut Book, id: u64) {
279        let mut storage = Vec::with_capacity(4);
280        let mut events = EventBuffer::new(&mut storage);
281        book.cancel_order(OrderId(id), &mut events).expect("cancel");
282    }
283
284    /// A book with churn: fills that free slots, a cancel, and reused
285    /// slots, so generations, the free list, and FIFO links are all
286    /// nontrivial.
287    fn churned_book() -> Book {
288        let mut book = Book::new(test_config()).expect("valid config");
289        add(&mut book, 1, 1, Side::Bid, 100, 10);
290        add(&mut book, 2, 1, Side::Bid, 100, 5);
291        add(&mut book, 3, 2, Side::Ask, 105, 7);
292        add(&mut book, 4, 2, Side::Ask, 100, 4); // fills 4 of order 1
293        cancel(&mut book, 2); // frees slot 1, generation bumps
294        add(&mut book, 5, 3, Side::Bid, 99, 3); // reuses slot 1 (LIFO)
295        add(&mut book, 6, 3, Side::Ask, 106, 2);
296        book
297    }
298
299    #[test]
300    fn capture_of_empty_book_is_exact() {
301        let book = Book::new(test_config()).expect("valid config");
302        let state = book.capture_snapshot_state();
303        assert_eq!(state.next_seq, 1);
304        assert_eq!(state.generations, vec![1; 16]);
305        assert_eq!(state.free_list_head, 0);
306        // The fresh free list is ascending: slot i links to slot i + 1.
307        for (i, link) in state.free_links.iter().enumerate() {
308            let expected = if i + 1 < 16 {
309                u32::try_from(i + 1).unwrap_or(NIL)
310            } else {
311                NIL
312            };
313            assert_eq!(*link, expected, "free link of slot {i}");
314        }
315        assert_eq!(state.levels.len(), 640);
316        assert!(
317            state
318                .levels
319                .iter()
320                .all(|l| l.head == NIL && l.tail == NIL && l.qty == 0 && l.count == 0)
321        );
322        assert_eq!(state.live_orders.len(), 0);
323    }
324
325    #[test]
326    fn capture_reports_live_orders_in_slot_order() {
327        let book = churned_book();
328        let state = book.capture_snapshot_state();
329        let slots: Vec<u32> = state.live_orders.iter().map(|o| o.slot).collect();
330        let mut sorted = slots.clone();
331        sorted.sort_unstable();
332        assert_eq!(slots, sorted, "live records are in ascending slot order");
333        // Order 5 reused the slot order 2 was cancelled from, with the
334        // bumped generation.
335        let reused = state
336            .live_orders
337            .iter()
338            .find(|o| o.order_id == OrderId(5))
339            .expect("order 5 is live");
340        assert_eq!(reused.slot, 1);
341        assert_eq!(reused.generation, 2);
342        assert_eq!(state.generations[1], 2);
343        // Live slots carry NIL free links; the two orders at price 100
344        // on the bid side are linked head to tail in arrival order.
345        for order in &state.live_orders {
346            assert_eq!(state.free_links[order.slot as usize], NIL);
347        }
348        let level = state.levels[99]; // price 100 at tick size 1, start 1
349        assert_eq!(level.count, 1);
350        assert_eq!(level.qty, 6, "order 1 rests with 6 after filling 4");
351    }
352
353    #[test]
354    fn capture_restore_roundtrip() {
355        let book = churned_book();
356        let state = book.capture_snapshot_state();
357        let restored = Book::from_snapshot_state(state.clone()).expect("restore");
358        restored.debug_assert_invariants();
359        assert_eq!(restored.capture_snapshot_state(), state);
360        assert_eq!(restored.next_seq(), book.next_seq());
361        assert_eq!(restored.live_order_count(), book.live_order_count());
362        assert_eq!(restored.best_bid(), book.best_bid());
363        assert_eq!(restored.best_ask(), book.best_ask());
364    }
365
366    #[test]
367    fn restore_preserves_allocation_and_event_order() {
368        // INV-SNAP-3 and INV-SNAP-4 at unit scale: after restore, the
369        // same commands produce the same events and the same slot
370        // assignments as on the original book.
371        let mut original = churned_book();
372        let state = original.capture_snapshot_state();
373        let mut restored = Book::from_snapshot_state(state).expect("restore");
374        let run = |book: &mut Book| -> Vec<ExecutionEvent> {
375            let mut storage = Vec::with_capacity(64);
376            {
377                let mut events = EventBuffer::new(&mut storage);
378                book.cancel_by_participant(ParticipantId(1), &mut events)
379                    .expect("mass cancel");
380            }
381            add(book, 7, 1, Side::Bid, 100, 5);
382            add(book, 8, 2, Side::Ask, 104, 5);
383            storage
384        };
385        let original_events = run(&mut original);
386        let restored_events = run(&mut restored);
387        assert_eq!(restored_events, original_events);
388        assert_eq!(
389            restored.capture_snapshot_state(),
390            original.capture_snapshot_state(),
391            "post-restore behaviour, slots included, matches the original"
392        );
393    }
394
395    #[test]
396    fn book_construction_allocates_levels_and_lookup_once() {
397        // INV-ALLOC-2 at book level: construction allocates each
398        // arena column, level array, and lookup column exactly
399        // once, at the configured capacity. The arena-level half is
400        // the arena unit test of the same invariant, and the
401        // 1,000,000-operation counter proof (INV-ALLOC-1) covers
402        // the no-growth half at full capacity.
403        let cfg = test_config();
404        let book = Book::new(cfg).expect("valid config builds");
405        let max_orders = cfg.max_orders as usize;
406        let grid_len = cfg.grid_len as usize;
407        assert_eq!(book.arena.generation.capacity(), max_orders);
408        assert_eq!(book.arena.state.capacity(), max_orders);
409        assert_eq!(book.arena.order_id.capacity(), max_orders);
410        assert_eq!(book.arena.participant.capacity(), max_orders);
411        assert_eq!(book.arena.price_idx.capacity(), max_orders);
412        assert_eq!(book.arena.qty.capacity(), max_orders);
413        assert_eq!(book.arena.side.capacity(), max_orders);
414        assert_eq!(book.arena.prev.capacity(), max_orders);
415        assert_eq!(book.arena.next.capacity(), max_orders);
416        assert_eq!(book.levels.head.capacity(), grid_len);
417        assert_eq!(book.levels.tail.capacity(), grid_len);
418        assert_eq!(book.levels.qty.capacity(), grid_len);
419        assert_eq!(book.levels.count.capacity(), grid_len);
420        // The lookup table is the smallest power of two holding
421        // twice the order capacity (the 50 percent load cap).
422        assert_eq!(book.lookup.capacity(), (2 * max_orders).next_power_of_two());
423    }
424}