chainfold 0.2.0

event-sourced chain fold engine: total order, fork recovery, durable snapshots
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
use crate::{
    batch::{
        Batch,
        SpanView,
    },
    checkpoint::{
        CheckpointRing,
        Slot,
    },
    error::{
        ApplyError,
        ConfigError,
        DivergenceCause,
        EngineStatus,
        FoldError,
        RollbackError,
    },
    fold::Fold,
    position::{
        BlockRef,
        Position,
    },
    ring::{
        BlockRing,
        Observed,
    },
};

/// Smallest allowed observed-block ring capacity.
const MIN_RING_CAPACITY: usize = 2;
/// Largest allowed observed-block ring capacity.
const MAX_RING_CAPACITY: usize = 1 << 20;

/// Fixed engine construction parameters.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EngineConfig {
    /// Observed-block window W; power of two between 2 and 1 << 20.
    pub ring_capacity: usize,
    /// Retained checkpoint slots K; zero disables rollback.
    pub checkpoint_slots: usize,
}

impl EngineConfig {
    /// Accepts a power-of-two ring capacity within the allowed range.
    pub(crate) fn validate(&self) -> Result<(), ConfigError> {
        if !self.ring_capacity.is_power_of_two() {
            return Err(ConfigError::RingCapacityNotPowerOfTwo {
                got: self.ring_capacity,
            });
        }
        if !(MIN_RING_CAPACITY..=MAX_RING_CAPACITY).contains(&self.ring_capacity) {
            return Err(ConfigError::RingCapacityOutOfRange {
                got: self.ring_capacity,
            });
        }
        Ok(())
    }
}

/// Per-batch counts of applied, deduped, and skipped events.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ApplySummary {
    /// Events the fold accepted.
    pub applied: u64,
    /// Events at or below the cursor, dropped as already applied.
    pub deduped: u64,
    /// Events the fold declared not its own.
    pub skipped: u64,
}

/// Single-writer fold engine: ordering, dedup, fork detection, rollback, snapshots.
///
/// When the cursor is set, the ring's newest entry is the cursor block.
#[derive(Debug)]
pub struct Engine<F> {
    fold: F,
    cursor: Option<Position>,
    ring: BlockRing,
    checkpoints: CheckpointRing<F>,
    status: EngineStatus,
    last_verified: Option<BlockRef>,
    skips: u64,
}

impl<F: Fold> Engine<F> {
    /// Builds an engine with an empty ring and no retained checkpoints.
    pub fn new(fold: F, config: EngineConfig) -> Result<Self, ConfigError> {
        config.validate()?;
        Ok(Self {
            ring: BlockRing::with_capacity(config.ring_capacity),
            checkpoints: CheckpointRing::new(config.checkpoint_slots),
            fold,
            cursor: None,
            status: EngineStatus::Active,
            last_verified: None,
            skips: 0,
        })
    }

    /// Returns the coarse engine status.
    pub fn status(&self) -> EngineStatus {
        self.status
    }

    /// Returns the most recently applied position, if any.
    pub fn cursor(&self) -> Option<Position> {
        self.cursor
    }

    /// Most recent block whose hash the source confirmed; None until first confirmation.
    pub fn last_verified(&self) -> Option<BlockRef> {
        self.last_verified
    }

    /// Count of events the fold declared not its own.
    pub fn skip_count(&self) -> u64 {
        self.skips
    }

    /// Count of checkpoints the ring can still serve; expired slots are not counted.
    pub fn checkpoint_count(&self) -> usize {
        self.checkpoints.count(&self.ring)
    }

    /// Cursor of the oldest live checkpoint; the reorg-safe durable point.
    ///
    /// None without checkpoints, when the oldest live slot predates any applied event, or
    /// once every slot's cursor block has left the observed window.
    pub fn durable_point(&self) -> Option<Position> {
        self.checkpoints
            .oldest(&self.ring)
            .and_then(|slot| slot.cursor)
    }

    /// Oldest live checkpoint slot, for the snapshot codec.
    #[cfg(feature = "wincode")]
    pub(crate) fn oldest_checkpoint(&self) -> Option<&Slot<F>> {
        self.checkpoints.oldest(&self.ring)
    }

    /// Borrows the fold state.
    pub fn fold(&self) -> &F {
        &self.fold
    }

    /// Reads the fold's current view.
    pub fn view(&self) -> F::View {
        self.fold.view()
    }

    /// Iterates observed blocks oldest first.
    pub fn observed(&self) -> Observed<'_> {
        self.ring.iter()
    }

    /// Iterates observed blocks at or below a number, oldest first; a checkpoint's window.
    #[cfg(feature = "wincode")]
    pub(crate) fn observed_at_or_below(&self, number: u64) -> Observed<'_> {
        self.ring.iter_at_or_below(number)
    }

    /// Applies one poll's batch: total order, dedup, boundary recheck, fork detection.
    pub fn apply_batch(
        &mut self,
        batch: &Batch<F::Event>,
    ) -> Result<ApplySummary, ApplyError<F::Error>> {
        if !self.status.is_active() {
            return Err(ApplyError::NotActive {
                status: self.status,
            });
        }
        batch.validate().map_err(ApplyError::Shape)?;

        if let Some(cursor) = self.cursor {
            let boundary = batch.boundary.ok_or(ApplyError::MissingBoundary)?;
            if boundary.number != cursor.block {
                return Err(ApplyError::BoundaryNumberMismatch {
                    expected: cursor.block,
                    got: boundary.number,
                });
            }
            let observed_hash = self.ring.hash_at(cursor.block).ok_or(
                ApplyError::CursorBlockUnobserved {
                    block: cursor.block,
                },
            )?;
            if observed_hash != boundary.hash {
                return Err(fork_suspected(cursor.block, observed_hash, boundary));
            }
            self.last_verified = Some(boundary);
        }

        let mut summary = ApplySummary::default();
        for span in batch.spans() {
            let redelivered = self
                .cursor
                .is_some_and(|cursor| span.number <= cursor.block);
            if redelivered
                && let Some(observed_hash) = self.ring.hash_at(span.number)
                && &observed_hash != span.hash
            {
                return Err(fork_suspected(span.number, observed_hash, span.block()));
            }
            self.apply_span(&span, &mut summary)?;
        }

        Ok(summary)
    }

    /// Stores a checkpoint of the current fold and cursor.
    ///
    /// A slot carries no block history of its own; its window is the engine's ring
    /// truncated to its cursor, so rollback depth is bounded by ring_capacity and a slot
    /// expires once its cursor block leaves the window.
    ///
    /// A no-op with zero slots or a non-Active status, so every stored slot holds
    /// state the engine still trusts.
    pub fn checkpoint(&mut self)
    where
        F: Clone,
    {
        if !self.status.is_active() {
            return;
        }
        self.checkpoints.store(Slot {
            fold: self.fold.clone(),
            cursor: self.cursor,
        });
    }

    /// Restores the newest live checkpoint whose cursor block is at or below the argument,
    /// truncating the ring to that cursor.
    ///
    /// Clears Halted and Poisoned; drops checkpoints above the argument, the fork
    /// boundary, so checkpoints between it and the restored cursor stay valid.
    /// Freshness resets to None, since the restored cursor is unverified until the
    /// next boundary check confirms it. Slots whose cursor block has left the observed
    /// window are expired, so NoCheckpointAtOrBelow also names an exhausted window.
    #[cold]
    pub fn rollback_at_or_below(
        &mut self,
        block: u64,
    ) -> Result<Option<Position>, RollbackError>
    where
        F: Clone,
    {
        if let EngineStatus::Unrecoverable { cause } = self.status {
            return Err(RollbackError::Unrecoverable { cause });
        }
        let slot = self
            .checkpoints
            .best_at_or_below(block, &self.ring)
            .ok_or(RollbackError::NoCheckpointAtOrBelow { block })?;
        self.fold = slot.fold.clone();
        self.cursor = slot.cursor;
        match self.cursor {
            Some(cursor) => self.ring.truncate_above(cursor.block),
            None => self.ring.clear(),
        }
        self.status = EngineStatus::Active;
        self.last_verified = None;
        self.checkpoints.drop_above(block);
        Ok(self.cursor)
    }

    /// Full restart with a fresh fold: clears cursor, ring, checkpoints, counters.
    pub fn reset(&mut self, fold: F) {
        self.ring.clear();
        self.checkpoints.clear();
        self.fold = fold;
        self.cursor = None;
        self.status = EngineStatus::Active;
        self.last_verified = None;
        self.skips = 0;
    }

    /// Terminal for automated paths; only reset leaves this state.
    #[cold]
    pub fn mark_unrecoverable(&mut self, cause: DivergenceCause) {
        self.status = EngineStatus::Unrecoverable { cause };
    }

    /// Overwrites cursor and ring with decoded snapshot data; used by snapshot decode.
    #[cfg(any(feature = "wincode", test))]
    pub(crate) fn restore_cursor_and_ring(
        &mut self,
        cursor: Option<Position>,
        ring: BlockRing,
    ) {
        self.cursor = cursor;
        self.ring = ring;
    }

    /// Applies every event of one span, deduping positions at or below the cursor.
    fn apply_span(
        &mut self,
        span: &SpanView<'_, F::Event>,
        summary: &mut ApplySummary,
    ) -> Result<(), ApplyError<F::Error>> {
        let number = span.number;
        let pos = |log_index: u32| Position::new(number, u64::from(log_index));
        let deduped = match self.cursor {
            Some(cursor) if number > cursor.block => 0,
            Some(cursor) if number < cursor.block => span.log_indices.len(),
            Some(cursor) => span
                .log_indices
                .partition_point(|index| u64::from(*index) <= cursor.log_index),
            None => 0,
        };
        summary.deduped += deduped as u64;
        // lanes are equal length by construction, so the paired walk drops no event
        let indices = &span.log_indices[deduped..];
        let events = &span.events[deduped..];
        let Some(last) = indices.last() else {
            return Ok(());
        };

        for (offset, (log_index, event)) in indices.iter().zip(events).enumerate() {
            let at = pos(*log_index);
            match self.fold.apply(at, event) {
                Ok(()) => summary.applied += 1,
                Err(FoldError::Skip(_)) => {
                    self.skips += 1;
                    summary.skipped += 1;
                }
                Err(FoldError::Halt(error)) => {
                    self.consumed_through(span, indices, offset);
                    return Err(self.halt(at, error));
                }
                Err(FoldError::Poison(error)) => {
                    self.consumed_through(span, indices, offset);
                    return Err(self.poison(at, error));
                }
            }
        }
        self.advance(span.number, span.hash, pos(*last));
        Ok(())
    }

    /// Places the cursor at the predecessor of `indices[offset]`; a no-op at offset 0,
    /// since nothing in this span was consumed yet.
    #[cold]
    fn consumed_through(
        &mut self,
        span: &SpanView<'_, F::Event>,
        indices: &[u32],
        offset: usize,
    ) {
        if let Some(log_index) = offset.checked_sub(1).and_then(|i| indices.get(i)) {
            let pos = Position::new(span.number, u64::from(*log_index));
            self.advance(span.number, span.hash, pos);
        }
    }

    /// Moves the cursor to `pos`, recording the block the first time the cursor enters it.
    ///
    /// Ring and cursor move together, so the ring's newest entry is the cursor block
    /// at every point a batch can return from.
    fn advance(&mut self, number: u64, hash: &[u8; 32], pos: Position) {
        if self
            .ring
            .newest_number()
            .is_none_or(|newest| newest < number)
        {
            let block = BlockRef {
                number,
                hash: *hash,
            };
            self.ring.push(block);
            self.last_verified = Some(block);
        }
        self.cursor = Some(pos);
    }

    #[cold]
    fn halt(&mut self, at: Position, error: F::Error) -> ApplyError<F::Error> {
        self.status = EngineStatus::Halted { at };
        ApplyError::Halted { at, error }
    }

    #[cold]
    fn poison(&mut self, at: Position, error: F::Error) -> ApplyError<F::Error> {
        self.status = EngineStatus::Poisoned { at };
        ApplyError::Poisoned { at, error }
    }
}

/// Builds the fork report comparing the hash the ring observed for a block against
/// the refetched header for that same block.
#[cold]
fn fork_suspected<E>(
    number: u64,
    observed_hash: [u8; 32],
    refetched: BlockRef,
) -> ApplyError<E> {
    ApplyError::ForkSuspected {
        observed: BlockRef {
            number,
            hash: observed_hash,
        },
        refetched,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        batch::BatchShapeError,
        test_util::{
            FailKind,
            RecordingFold,
        },
    };
    #[cfg(not(feature = "std"))]
    use alloc::{
        vec,
        vec::Vec,
    };
    #[cfg(feature = "std")]
    use std::{
        vec,
        vec::Vec,
    };

    fn block(number: u64, salt: u8) -> BlockRef {
        let mut hash = [0u8; 32];
        hash[..8].copy_from_slice(&number.to_le_bytes());
        hash[8] = salt;
        BlockRef { number, hash }
    }

    fn batch_of(
        boundary: Option<BlockRef>,
        spans: Vec<(BlockRef, Vec<u32>)>,
    ) -> Batch<u64> {
        let mut batch = Batch::new();
        batch.boundary = boundary;
        for (block, log_indices) in spans {
            batch.push_block(
                block,
                log_indices
                    .into_iter()
                    .map(|index| (index, u64::from(index))),
            );
        }
        batch
    }

    fn new_engine() -> Engine<RecordingFold> {
        Engine::new(
            RecordingFold::default(),
            EngineConfig {
                ring_capacity: 8,
                checkpoint_slots: 0,
            },
        )
        .unwrap()
    }

    fn engine_with_checkpoints(slots: usize) -> Engine<RecordingFold> {
        Engine::new(
            RecordingFold::default(),
            EngineConfig {
                ring_capacity: 8,
                checkpoint_slots: slots,
            },
        )
        .unwrap()
    }

    fn scripted_engine(fail_at: Position, kind: FailKind) -> Engine<RecordingFold> {
        Engine::new(
            RecordingFold {
                applied: Vec::new(),
                fail_at: Some((fail_at, kind)),
            },
            EngineConfig {
                ring_capacity: 8,
                checkpoint_slots: 0,
            },
        )
        .unwrap()
    }

    #[test]
    fn first_batch_applies_without_boundary() {
        // given a fresh engine and a two-span batch with no boundary
        let mut engine = new_engine();
        let batch = batch_of(
            None,
            vec![(block(1, 0), vec![0, 1]), (block(2, 0), vec![0])],
        );
        // when applied
        let summary = engine.apply_batch(&batch).unwrap();
        // then all events applied and cursor is the last position
        assert_eq!(
            summary,
            ApplySummary {
                applied: 3,
                deduped: 0,
                skipped: 0,
            }
        );
        assert_eq!(engine.cursor(), Some(Position::new(2, 0)));
    }

    #[test]
    fn matching_boundary_updates_freshness() {
        // given an engine at block 5
        let mut engine = new_engine();
        let first = batch_of(None, vec![(block(5, 0), vec![0])]);
        engine.apply_batch(&first).unwrap();
        // when a batch with the correct boundary hash applies
        let next = batch_of(Some(block(5, 0)), vec![]);
        engine.apply_batch(&next).unwrap();
        // then last_verified is the boundary
        assert_eq!(engine.last_verified(), Some(block(5, 0)));
    }

    #[test]
    fn mismatched_boundary_reports_fork() {
        // given an engine at block 5
        let mut engine = new_engine();
        let first = batch_of(None, vec![(block(5, 0), vec![0])]);
        engine.apply_batch(&first).unwrap();
        let view_before = engine.view();
        // when the boundary carries a different hash
        let next = batch_of(Some(block(5, 1)), vec![]);
        let result = engine.apply_batch(&next);
        // then ForkSuspected and the fold state is untouched
        assert_eq!(
            result,
            Err(ApplyError::ForkSuspected {
                observed: block(5, 0),
                refetched: block(5, 1),
            })
        );
        assert_eq!(engine.view(), view_before);
    }

    #[test]
    fn wrong_boundary_number_is_rejected() {
        // given cursor block 5 and boundary number 4
        let mut engine = new_engine();
        let first = batch_of(None, vec![(block(5, 0), vec![0])]);
        engine.apply_batch(&first).unwrap();
        // when applied
        let next = batch_of(Some(block(4, 0)), vec![]);
        let result = engine.apply_batch(&next);
        // then BoundaryNumberMismatch
        assert_eq!(
            result,
            Err(ApplyError::BoundaryNumberMismatch {
                expected: 5,
                got: 4,
            })
        );
    }

    #[test]
    fn missing_boundary_with_cursor_is_rejected() {
        // given a cursor
        let mut engine = new_engine();
        let first = batch_of(None, vec![(block(5, 0), vec![0])]);
        engine.apply_batch(&first).unwrap();
        // when the batch has no boundary
        let next = batch_of(None, vec![]);
        let result = engine.apply_batch(&next);
        // then MissingBoundary
        assert_eq!(result, Err(ApplyError::MissingBoundary));
    }

    #[test]
    fn redelivered_span_with_same_hash_dedupes() {
        // given an applied block
        let mut engine = new_engine();
        let first = batch_of(None, vec![(block(5, 0), vec![0, 1])]);
        engine.apply_batch(&first).unwrap();
        // when the same span is redelivered with its boundary
        let next = batch_of(Some(block(5, 0)), vec![(block(5, 0), vec![0, 1])]);
        let summary = engine.apply_batch(&next).unwrap();
        // then summary counts deduped and applies nothing
        assert_eq!(
            summary,
            ApplySummary {
                applied: 0,
                deduped: 2,
                skipped: 0,
            }
        );
    }

    #[test]
    fn redelivered_span_with_different_hash_reports_fork() {
        // given an applied block
        let mut engine = new_engine();
        let first = batch_of(None, vec![(block(5, 0), vec![0])]);
        engine.apply_batch(&first).unwrap();
        // when a span at that number returns a different hash
        let next = batch_of(Some(block(5, 0)), vec![(block(5, 1), vec![0])]);
        let result = engine.apply_batch(&next);
        // then ForkSuspected
        assert_eq!(
            result,
            Err(ApplyError::ForkSuspected {
                observed: block(5, 0),
                refetched: block(5, 1),
            })
        );
    }

    #[test]
    fn skip_advances_cursor_and_counter() {
        // given fail_at Skip at block 1 log index 0
        let mut engine = scripted_engine(Position::new(1, 0), FailKind::Skip);
        let batch = batch_of(None, vec![(block(1, 0), vec![0, 1])]);
        // when applied
        let summary = engine.apply_batch(&batch).unwrap();
        // then Ok summary with one skipped, cursor past the position, skip_count 1
        assert_eq!(
            summary,
            ApplySummary {
                applied: 1,
                deduped: 0,
                skipped: 1,
            }
        );
        assert_eq!(engine.cursor(), Some(Position::new(1, 1)));
        assert_eq!(engine.skip_count(), 1);
    }

    #[test]
    fn a_lone_skip_consumes_its_position_and_observes_the_block() {
        // given a fold skipping the only event of block 1, so no later apply masks it
        let mut engine = scripted_engine(Position::new(1, 0), FailKind::Skip);
        let batch = batch_of(None, vec![(block(1, 0), vec![0])]);
        // when applied
        let summary = engine.apply_batch(&batch).unwrap();
        // then the position is consumed and the block still entered the ring
        assert_eq!(
            summary,
            ApplySummary {
                applied: 0,
                deduped: 0,
                skipped: 1,
            }
        );
        assert_eq!(engine.cursor(), Some(Position::new(1, 0)));
        assert_eq!(engine.observed().collect::<Vec<_>>(), vec![block(1, 0)]);
        assert_eq!(engine.last_verified(), Some(block(1, 0)));
    }

    #[test]
    fn halt_stops_at_declared_position() {
        // given fail_at Halt at the third event
        let halt_pos = Position::new(1, 2);
        let mut engine = scripted_engine(halt_pos, FailKind::Halt);
        let batch = batch_of(None, vec![(block(1, 0), vec![0, 1, 2])]);
        // when applied
        let result = engine.apply_batch(&batch);
        // then Halted at that position, cursor at the second event, status Halted
        assert_eq!(
            result,
            Err(ApplyError::Halted {
                at: halt_pos,
                error: FailKind::Halt,
            })
        );
        assert_eq!(engine.cursor(), Some(Position::new(1, 1)));
        assert_eq!(engine.status(), EngineStatus::Halted { at: halt_pos });
        let next = batch_of(None, vec![(block(2, 0), vec![0])]);
        let next_result = engine.apply_batch(&next);
        assert_eq!(
            next_result,
            Err(ApplyError::NotActive {
                status: EngineStatus::Halted { at: halt_pos },
            })
        );
    }

    #[test]
    fn halt_mid_span_leaves_the_ring_on_the_cursor_block() {
        // given a fold halting at the second event of a three-event first block
        let halt_pos = Position::new(1, 1);
        let mut engine = Engine::new(
            RecordingFold {
                applied: Vec::new(),
                fail_at: Some((halt_pos, FailKind::Halt)),
            },
            EngineConfig {
                ring_capacity: 8,
                checkpoint_slots: 2,
            },
        )
        .unwrap();
        // when the batch halts mid span
        let halted =
            engine.apply_batch(&batch_of(None, vec![(block(1, 0), vec![0, 1, 2])]));
        // then the cursor rests on block 1 and the ring's newest entry is that block
        assert!(matches!(halted, Err(ApplyError::Halted { .. })));
        assert_eq!(engine.cursor(), Some(Position::new(1, 0)));
        assert_eq!(engine.observed().collect::<Vec<_>>(), vec![block(1, 0)]);
    }

    #[test]
    fn halt_before_a_block_leaves_it_out_of_the_ring() {
        // given a fold halting at the first event of block 2
        let halt_pos = Position::new(2, 0);
        let mut engine = Engine::new(
            RecordingFold {
                applied: Vec::new(),
                fail_at: Some((halt_pos, FailKind::Halt)),
            },
            EngineConfig {
                ring_capacity: 8,
                checkpoint_slots: 2,
            },
        )
        .unwrap();
        engine
            .apply_batch(&batch_of(None, vec![(block(1, 0), vec![0])]))
            .unwrap();
        // when the next batch halts on the first event of block 2
        let halted = engine
            .apply_batch(&batch_of(Some(block(1, 0)), vec![(block(2, 0), vec![0])]));
        // then block 2 never entered the ring and the cursor still rests on block 1
        assert!(matches!(halted, Err(ApplyError::Halted { .. })));
        assert_eq!(engine.cursor(), Some(Position::new(1, 0)));
        assert_eq!(engine.observed().collect::<Vec<_>>(), vec![block(1, 0)]);
    }

    #[test]
    fn checkpoint_after_a_halt_is_refused() {
        // given a Halted engine that had one checkpoint before the halt
        let halt_pos = Position::new(1, 1);
        let mut engine = Engine::new(
            RecordingFold {
                applied: Vec::new(),
                fail_at: Some((halt_pos, FailKind::Halt)),
            },
            EngineConfig {
                ring_capacity: 8,
                checkpoint_slots: 4,
            },
        )
        .unwrap();
        engine
            .apply_batch(&batch_of(None, vec![(block(1, 0), vec![0])]))
            .unwrap();
        engine.checkpoint();
        let halted = engine
            .apply_batch(&batch_of(Some(block(1, 0)), vec![(block(1, 0), vec![1])]));
        assert!(matches!(halted, Err(ApplyError::Halted { .. })));
        // when checkpointing while halted, then rolling back
        engine.checkpoint();
        let restored = engine.rollback_at_or_below(1).unwrap();
        // then only the pre-halt slot exists and the rollback restores Active state
        assert_eq!(engine.checkpoint_count(), 1);
        assert_eq!(restored, Some(Position::new(1, 0)));
        assert_eq!(engine.status(), EngineStatus::Active);
        let resumed = engine
            .apply_batch(&batch_of(Some(block(1, 0)), vec![(block(2, 0), vec![0])]));
        assert!(resumed.is_ok());
    }

    #[test]
    fn rollback_clears_freshness() {
        // given a checkpointed engine whose boundary was verified at block 2
        let mut engine = engine_with_checkpoints(4);
        engine
            .apply_batch(&batch_of(None, vec![(block(1, 0), vec![0])]))
            .unwrap();
        engine.checkpoint();
        engine
            .apply_batch(&batch_of(Some(block(1, 0)), vec![(block(2, 0), vec![0])]))
            .unwrap();
        assert_eq!(engine.last_verified(), Some(block(2, 0)));
        // when rolling back to block 1
        engine.rollback_at_or_below(1).unwrap();
        // then freshness resets, never naming a block above the restored cursor
        assert_eq!(engine.last_verified(), None);
    }

    #[test]
    fn unobserved_cursor_block_is_typed() {
        // given a cursor restored without its ring entry
        let mut engine = new_engine();
        engine.restore_cursor_and_ring(
            Some(Position::new(5, 0)),
            BlockRing::with_capacity(8),
        );
        // when a batch arrives with the boundary for that cursor block
        let result = engine.apply_batch(&batch_of(Some(block(5, 0)), vec![]));
        // then CursorBlockUnobserved, never a panic
        assert_eq!(result, Err(ApplyError::CursorBlockUnobserved { block: 5 }));
    }

    #[test]
    fn poison_marks_state_untrusted() {
        // given fail_at Poison
        let poison_pos = Position::new(1, 0);
        let mut engine = scripted_engine(poison_pos, FailKind::Poison);
        let batch = batch_of(None, vec![(block(1, 0), vec![0])]);
        // when applied
        let result = engine.apply_batch(&batch);
        // then Poisoned status and the partial mutation is visible in the view
        assert_eq!(
            result,
            Err(ApplyError::Poisoned {
                at: poison_pos,
                error: FailKind::Poison,
            })
        );
        assert_eq!(engine.status(), EngineStatus::Poisoned { at: poison_pos });
        assert_eq!(engine.view(), vec![(poison_pos, 0)]);
    }

    #[test]
    fn ring_records_each_observed_block_once() {
        // given two batches over four blocks
        let mut engine = new_engine();
        let first = batch_of(None, vec![(block(1, 0), vec![0]), (block(2, 0), vec![0])]);
        engine.apply_batch(&first).unwrap();
        let second = batch_of(
            Some(block(2, 0)),
            vec![(block(3, 0), vec![0]), (block(4, 0), vec![0])],
        );
        // when applied
        engine.apply_batch(&second).unwrap();
        // then observed yields the four blocks ascending
        let observed: Vec<BlockRef> = engine.observed().collect();
        assert_eq!(
            observed,
            vec![block(1, 0), block(2, 0), block(3, 0), block(4, 0)]
        );
    }

    #[test]
    fn invalid_shape_is_rejected_before_fold_runs() {
        // given a batch whose second span moves the block number backwards
        let mut engine = new_engine();
        let batch = batch_of(None, vec![(block(2, 0), vec![0]), (block(1, 0), vec![0])]);
        // when applied
        let result = engine.apply_batch(&batch);
        // then Shape and the fold recorded nothing
        assert_eq!(
            result,
            Err(ApplyError::Shape(BatchShapeError::BlocksNotAscending {
                span: 1
            }))
        );
        assert_eq!(engine.view(), Vec::<(Position, u64)>::new());
    }

    #[test]
    fn config_rejects_non_power_of_two_ring() {
        // given capacity 12
        let config = EngineConfig {
            ring_capacity: 12,
            checkpoint_slots: 0,
        };
        // when constructing
        let result = Engine::new(RecordingFold::default(), config);
        // then RingCapacityNotPowerOfTwo
        assert_eq!(
            result.err(),
            Some(ConfigError::RingCapacityNotPowerOfTwo { got: 12 })
        );
    }

    #[test]
    fn checkpoint_then_rollback_restores_view() {
        // given a checkpoint at block 3 and applies through block 6
        let mut engine = engine_with_checkpoints(4);
        engine
            .apply_batch(&batch_of(None, vec![(block(3, 0), vec![0])]))
            .unwrap();
        engine.checkpoint();
        let checkpoint_view = engine.view();
        let checkpoint_cursor = engine.cursor();
        let rest = batch_of(
            Some(block(3, 0)),
            vec![
                (block(4, 0), vec![0]),
                (block(5, 0), vec![0]),
                (block(6, 0), vec![0]),
            ],
        );
        engine.apply_batch(&rest).unwrap();
        // when rolling back at or below 4
        let restored = engine.rollback_at_or_below(4).unwrap();
        // then the view equals the checkpoint view and cursor is the checkpoint cursor
        assert_eq!(engine.view(), checkpoint_view);
        assert_eq!(restored, checkpoint_cursor);
        assert_eq!(engine.cursor(), checkpoint_cursor);
    }

    #[test]
    fn rollback_prefers_newest_eligible_checkpoint() {
        // given checkpoints at blocks 2 and 4
        let mut engine = engine_with_checkpoints(4);
        engine
            .apply_batch(&batch_of(None, vec![(block(2, 0), vec![0])]))
            .unwrap();
        engine.checkpoint();
        engine
            .apply_batch(&batch_of(Some(block(2, 0)), vec![(block(4, 0), vec![0])]))
            .unwrap();
        engine.checkpoint();
        engine
            .apply_batch(&batch_of(Some(block(4, 0)), vec![(block(6, 0), vec![0])]))
            .unwrap();
        // when rolling back at or below 5
        let restored = engine.rollback_at_or_below(5).unwrap();
        // then block 4 restores
        assert_eq!(restored, Some(Position::new(4, 0)));
    }

    #[test]
    fn rollback_without_eligible_checkpoint_is_typed() {
        // given only a checkpoint at block 6
        let mut engine = engine_with_checkpoints(4);
        engine
            .apply_batch(&batch_of(None, vec![(block(6, 0), vec![0])]))
            .unwrap();
        engine.checkpoint();
        // when rolling back at or below 4
        let result = engine.rollback_at_or_below(4);
        // then NoCheckpointAtOrBelow { block: 4 }
        assert_eq!(
            result,
            Err(RollbackError::NoCheckpointAtOrBelow { block: 4 })
        );
    }

    #[test]
    fn zero_slots_never_checkpoints() {
        // given checkpoint_slots 0
        let mut engine = new_engine();
        engine
            .apply_batch(&batch_of(None, vec![(block(1, 0), vec![0])]))
            .unwrap();
        // when checkpointing and rolling back
        engine.checkpoint();
        let result = engine.rollback_at_or_below(1);
        // then count stays 0 and rollback errors
        assert_eq!(engine.checkpoint_count(), 0);
        assert_eq!(
            result,
            Err(RollbackError::NoCheckpointAtOrBelow { block: 1 })
        );
    }

    #[test]
    fn slot_ring_overwrites_oldest() {
        // given 2 slots and 3 checkpoints
        let mut engine = engine_with_checkpoints(2);
        engine
            .apply_batch(&batch_of(None, vec![(block(1, 0), vec![0])]))
            .unwrap();
        engine.checkpoint();
        engine
            .apply_batch(&batch_of(Some(block(1, 0)), vec![(block(2, 0), vec![0])]))
            .unwrap();
        engine.checkpoint();
        engine
            .apply_batch(&batch_of(Some(block(2, 0)), vec![(block(3, 0), vec![0])]))
            .unwrap();
        engine.checkpoint();
        // when rolling back to the earliest
        let result = engine.rollback_at_or_below(1);
        // then it is gone and the call errors
        assert_eq!(
            result,
            Err(RollbackError::NoCheckpointAtOrBelow { block: 1 })
        );
    }

    #[test]
    fn rollback_clears_halted_state() {
        // given a Halted engine with an earlier checkpoint
        let halt_pos = Position::new(2, 0);
        let mut engine = Engine::new(
            RecordingFold {
                applied: Vec::new(),
                fail_at: Some((halt_pos, FailKind::Halt)),
            },
            EngineConfig {
                ring_capacity: 8,
                checkpoint_slots: 2,
            },
        )
        .unwrap();
        engine
            .apply_batch(&batch_of(None, vec![(block(1, 0), vec![0])]))
            .unwrap();
        engine.checkpoint();
        let checkpoint_cursor = engine.cursor();
        let halted = engine
            .apply_batch(&batch_of(Some(block(1, 0)), vec![(block(2, 0), vec![0])]));
        assert_eq!(
            halted,
            Err(ApplyError::Halted {
                at: halt_pos,
                error: FailKind::Halt,
            })
        );
        // when rolled back
        let restored = engine.rollback_at_or_below(1).unwrap();
        // then status Active and applying resumes
        assert_eq!(engine.status(), EngineStatus::Active);
        assert_eq!(restored, checkpoint_cursor);
        let resumed = engine
            .apply_batch(&batch_of(Some(block(1, 0)), vec![(block(3, 0), vec![0])]));
        assert!(resumed.is_ok());
        assert_eq!(engine.cursor(), Some(Position::new(3, 0)));
    }

    #[test]
    fn rollback_restores_poisoned_state() {
        // given a Poisoned engine
        let poison_pos = Position::new(2, 0);
        let mut engine = Engine::new(
            RecordingFold {
                applied: Vec::new(),
                fail_at: Some((poison_pos, FailKind::Poison)),
            },
            EngineConfig {
                ring_capacity: 8,
                checkpoint_slots: 2,
            },
        )
        .unwrap();
        engine
            .apply_batch(&batch_of(None, vec![(block(1, 0), vec![0])]))
            .unwrap();
        engine.checkpoint();
        let checkpoint_view = engine.view();
        let poisoned = engine
            .apply_batch(&batch_of(Some(block(1, 0)), vec![(block(2, 0), vec![0])]));
        assert!(matches!(poisoned, Err(ApplyError::Poisoned { .. })));
        assert_ne!(engine.view(), checkpoint_view);
        // when rolled back
        engine.rollback_at_or_below(1).unwrap();
        // then the view has no trace of the partial mutation
        assert_eq!(engine.view(), checkpoint_view);
        assert_eq!(engine.status(), EngineStatus::Active);
    }

    #[test]
    fn rollback_drops_checkpoints_above_restore_point() {
        // given checkpoints at 2 and 5
        let mut engine = engine_with_checkpoints(4);
        engine
            .apply_batch(&batch_of(None, vec![(block(2, 0), vec![0])]))
            .unwrap();
        engine.checkpoint();
        engine
            .apply_batch(&batch_of(Some(block(2, 0)), vec![(block(5, 0), vec![0])]))
            .unwrap();
        engine.checkpoint();
        // when rolling back at or below 3
        engine.rollback_at_or_below(3).unwrap();
        // then only the block 2 checkpoint remains
        assert_eq!(engine.checkpoint_count(), 1);
    }

    #[test]
    fn rollback_truncates_observed_ring() {
        // given a checkpoint at block 2 and applies through block 4
        let mut engine = engine_with_checkpoints(4);
        engine
            .apply_batch(&batch_of(
                None,
                vec![(block(1, 0), vec![0]), (block(2, 0), vec![0])],
            ))
            .unwrap();
        engine.checkpoint();
        engine
            .apply_batch(&batch_of(
                Some(block(2, 0)),
                vec![(block(3, 0), vec![0]), (block(4, 0), vec![0])],
            ))
            .unwrap();
        // when rolling back at or below block 2
        engine.rollback_at_or_below(2).unwrap();
        // then observed ends at block 2 and a fresh batch from block 3 applies cleanly
        let observed: Vec<BlockRef> = engine.observed().collect();
        assert_eq!(observed, vec![block(1, 0), block(2, 0)]);
        let result = engine
            .apply_batch(&batch_of(Some(block(2, 0)), vec![(block(3, 0), vec![0])]));
        assert!(result.is_ok());
    }

    #[test]
    fn reset_returns_engine_to_genesis() {
        // given an advanced engine
        let mut engine = new_engine();
        engine
            .apply_batch(&batch_of(None, vec![(block(1, 0), vec![0])]))
            .unwrap();
        // when reset with a fresh fold
        engine.reset(RecordingFold::default());
        // then cursor None, empty ring, zero checkpoints, Active
        assert_eq!(engine.cursor(), None);
        assert_eq!(engine.observed().len(), 0);
        assert_eq!(engine.checkpoint_count(), 0);
        assert_eq!(engine.status(), EngineStatus::Active);
    }

    #[test]
    fn unrecoverable_refuses_apply_and_rollback() {
        // given mark_unrecoverable
        let mut engine = new_engine();
        engine.mark_unrecoverable(DivergenceCause::ForkBeyondWindow);
        // when applying or rolling back
        let apply_result =
            engine.apply_batch(&batch_of(None, vec![(block(1, 0), vec![0])]));
        let rollback_result = engine.rollback_at_or_below(0);
        // then NotActive and Unrecoverable errors carry the cause
        assert_eq!(
            apply_result,
            Err(ApplyError::NotActive {
                status: EngineStatus::Unrecoverable {
                    cause: DivergenceCause::ForkBeyondWindow
                },
            })
        );
        assert_eq!(
            rollback_result,
            Err(RollbackError::Unrecoverable {
                cause: DivergenceCause::ForkBeyondWindow,
            })
        );
    }

    #[test]
    fn durable_point_is_the_oldest_retained_checkpoint_cursor() {
        // given 3 slots checkpointed at blocks 1, 3, 5, 7, 9, and 11
        let mut engine = engine_with_checkpoints(3);
        let mut boundary = None;
        for number in [1u64, 3, 5, 7, 9, 11] {
            engine
                .apply_batch(&batch_of(boundary, vec![(block(number, 0), vec![0])]))
                .unwrap();
            engine.checkpoint();
            boundary = Some(block(number, 0));
        }
        // when reading durable_point
        let point = engine.durable_point();
        // then it is block 7, the oldest slot the wraparound left behind
        assert_eq!(point, Some(Position::new(7, 0)));
    }

    #[test]
    fn rollback_refuses_a_checkpoint_whose_block_left_the_ring() {
        // given a checkpoint at block 1, then twelve blocks through a ring holding 8
        let mut engine = engine_with_checkpoints(2);
        engine
            .apply_batch(&batch_of(None, vec![(block(1, 0), vec![0])]))
            .unwrap();
        engine.checkpoint();
        for number in 2..=12u64 {
            engine
                .apply_batch(&batch_of(
                    Some(block(number - 1, 0)),
                    vec![(block(number, 0), vec![0])],
                ))
                .unwrap();
        }
        // when rolling back to the expired checkpoint's block
        let result = engine.rollback_at_or_below(1);
        // then it is refused rather than restored against a window that cannot serve it
        assert_eq!(
            result,
            Err(RollbackError::NoCheckpointAtOrBelow { block: 1 })
        );
        assert_eq!(engine.checkpoint_count(), 0);
    }

    #[test]
    fn durable_point_is_none_without_checkpoints() {
        // given a fresh engine with no retained slots
        let engine = new_engine();
        // when reading durable_point
        let point = engine.durable_point();
        // then None
        assert_eq!(point, None);
    }

    #[test]
    fn durable_point_follows_rollback_dropping_newer_slots() {
        // given checkpoints at blocks 2 and 5
        let mut engine = engine_with_checkpoints(4);
        engine
            .apply_batch(&batch_of(None, vec![(block(2, 0), vec![0])]))
            .unwrap();
        engine.checkpoint();
        engine
            .apply_batch(&batch_of(Some(block(2, 0)), vec![(block(5, 0), vec![0])]))
            .unwrap();
        engine.checkpoint();
        // when rolling back at or below block 3
        engine.rollback_at_or_below(3).unwrap();
        // then durable_point is the block 2 cursor
        assert_eq!(engine.durable_point(), Some(Position::new(2, 0)));
    }

    #[test]
    fn cursorless_oldest_slot_yields_no_durable_point() {
        // given a checkpoint taken before any apply and a later one at block 1
        let mut engine = engine_with_checkpoints(3);
        engine.checkpoint();
        engine
            .apply_batch(&batch_of(None, vec![(block(1, 0), vec![0])]))
            .unwrap();
        engine.checkpoint();
        // when reading durable_point
        let point = engine.durable_point();
        // then None while the cursor-less slot is the oldest
        assert_eq!(point, None);
    }

    #[test]
    fn repeated_rollback_to_same_checkpoint_succeeds() {
        // given one checkpoint
        let mut engine = engine_with_checkpoints(4);
        engine
            .apply_batch(&batch_of(None, vec![(block(1, 0), vec![0])]))
            .unwrap();
        engine.checkpoint();
        let checkpoint_view = engine.view();
        let checkpoint_cursor = engine.cursor();
        engine
            .apply_batch(&batch_of(Some(block(1, 0)), vec![(block(2, 0), vec![0])]))
            .unwrap();
        // when rolled back twice with applies between
        let first_restore = engine.rollback_at_or_below(1).unwrap();
        engine
            .apply_batch(&batch_of(Some(block(1, 0)), vec![(block(3, 0), vec![9])]))
            .unwrap();
        let second_restore = engine.rollback_at_or_below(1).unwrap();
        // then both restores match
        assert_eq!(first_restore, checkpoint_cursor);
        assert_eq!(second_restore, checkpoint_cursor);
        assert_eq!(engine.view(), checkpoint_view);
    }

    #[test]
    fn cursor_does_not_regress_when_the_stop_span_is_partially_deduped() {
        // given cursor at block 5 log index 3 and a fold halting at log index 5
        let halt_pos = Position::new(5, 5);
        let mut engine = scripted_engine(halt_pos, FailKind::Halt);
        let first = batch_of(None, vec![(block(5, 0), vec![0, 1, 2, 3])]);
        engine.apply_batch(&first).unwrap();
        // when block 5 is redelivered as [0, 1, 5], dropping 2 and 3 as deduped
        let next = batch_of(Some(block(5, 0)), vec![(block(5, 0), vec![0, 1, 5])]);
        let result = engine.apply_batch(&next);
        // then Halted at (5, 5) and the cursor is still (5, 3), not lower
        assert_eq!(
            result,
            Err(ApplyError::Halted {
                at: halt_pos,
                error: FailKind::Halt,
            })
        );
        assert_eq!(engine.cursor(), Some(Position::new(5, 3)));
    }
}