sensor-db 0.1.0

Append-only sensor database for NOR flash on embedded devices
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
//! Model-based testing: random operation sequences against a `Vec` oracle.
//!
//! The two `*_fuzz.rs` suites are exhaustive over *fault position* against one
//! fixed workload. This file covers the other axis — the workload itself. A
//! pseudo-random sequence of appends, syncs, compactions and remounts, with
//! random payload sizes and sensor mixes, is replayed against a `Vec` of
//! everything that was appended, and after **every operation** the database is
//! read back in full and compared with the model.
//!
//! # The invariant that does the work
//!
//! A ring evicts from the front and nothing removes from the middle, so what the
//! database holds must at all times be a **contiguous suffix** of what was
//! appended. Expressed as `actual == model[k..]` for `k = model.len() -
//! actual.len()`, that single equality catches a hole in the middle, a
//! reordering, a fabricated entry, a truncated payload and a lost tail, without
//! the model needing to know anything about sector geometry — which is what
//! keeps it from being a second implementation that would agree with the first
//! about the same mistakes.
//!
//! `k` is *discovered*, never predicted, and only asserted to be monotone: the
//! model deliberately does not know when the ring will evict. A remount is the
//! one operation that can also lose the *tail* (whatever was still in the RAM
//! page buffer), so it is the one place the model learns something and truncates
//! itself — after asserting that nothing a successful `sync` acknowledged went
//! with it.
//!
//! # No `proptest`
//!
//! Deliberate. Deterministic seeds mean CI is reproducible and a green run means
//! the same thing every time, which matches the rest of this crate's testing;
//! and the one feature that would be missed — shrinking — is [`shrink`] below,
//! about forty lines, because the op sequence is a flat `Vec` with an obvious
//! simplification order.

use std::fmt::Write as _;

use sensor_db::db::CompactScope;
use sensor_db::mock::MockFlash;
use sensor_db::zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};
use sensor_db::{Error, RUN_FRAME_SIZE, Run, SensorData, SensorDb};

// =============================================================================
// Randomness
// =============================================================================

/// xorshift64*, so a seed reproduces a run exactly on any machine.
struct Rng(u64);

impl Rng {
    fn new(seed: u64) -> Self {
        // The state must be non-zero; xorshift is stuck at 0 forever.
        Self(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
    }

    fn next_u64(&mut self) -> u64 {
        let mut x = self.0;
        x ^= x >> 12;
        x ^= x << 25;
        x ^= x >> 27;
        self.0 = x;
        x.wrapping_mul(0x2545_F491_4F6C_DD1D)
    }

    fn below(&mut self, n: u64) -> u64 {
        self.next_u64() % n
    }
}

// =============================================================================
// Operations
// =============================================================================

const SENSORS: [u16; 4] = [1, 2, 7, 900];

/// The sample type runs are written with.
///
/// It shares sensor 1 with the raw appends deliberately: a run and an opaque
/// payload landing under one id is exactly the mix where a reader that could
/// tell a run apart would show up.
#[derive(FromBytes, IntoBytes, KnownLayout, Immutable, Clone, Copy)]
#[repr(C)]
struct Burst {
    v: u32,
}

impl SensorData for Burst {
    const SENSOR_ID: u16 = SENSORS[0];
}

/// The payload one sample of a run reads back as — which, because a run is
/// invisible to readers, is byte for byte what `append_sensor` of that sample
/// alone would have stored: the schema tag, then the value.
fn run_sample_payload(ts: u64) -> Vec<u8> {
    let mut payload = vec![Burst::SCHEMA_VERSION];
    payload.extend_from_slice(Burst { v: ts as u32 }.as_bytes());
    payload
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Op {
    /// Append one entry for `sensor` with a `len`-byte payload.
    Append { sensor: u16, len: usize },
    /// Append `count` evenly spaced samples as a single run entry.
    ///
    /// The model expands it into `count` ordinary entries, which is the whole
    /// claim: if any read path could distinguish the two, the oracle diverges.
    Run { count: usize },
    /// Flush the RAM page buffer.
    Sync,
    /// Reclaim up to `0` sealed sectors.
    Compact(u16),
    /// Drop the database and rebuild it from the same flash image — a reboot.
    /// Whatever was still in the page buffer is gone.
    Remount,
}

/// Generate a workload. Appends dominate; the rest are sprinkled in at rates
/// that keep a small ring turning over several times in a few hundred ops.
fn workload(rng: &mut Rng, len: usize, max_payload: usize) -> Vec<Op> {
    (0..len)
        .map(|_| match rng.below(100) {
            0..=59 => Op::Append {
                sensor: SENSORS[rng.below(SENSORS.len() as u64) as usize],
                // Zero-length payloads are legal and worth generating.
                len: rng.below(max_payload as u64 + 1) as usize,
            },
            60..=69 => Op::Run {
                count: rng.below(24) as usize + 1,
            },
            70..=86 => Op::Sync,
            87..=94 => Op::Compact(rng.below(3) as u16 + 1),
            _ => Op::Remount,
        })
        .collect()
}

// =============================================================================
// The oracle
// =============================================================================

#[derive(Clone, PartialEq, Eq)]
struct Entry {
    sensor: u16,
    ts: u64,
    payload: Vec<u8>,
}

impl std::fmt::Debug for Entry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "({}, ts={}, {}B)",
            self.sensor,
            self.ts,
            self.payload.len()
        )
    }
}

/// Payload bytes for a given timestamp: derived, so a read-back entry can be
/// checked against the value that was supposed to be there rather than merely
/// against its own length.
fn payload_for(ts: u64, len: usize) -> Vec<u8> {
    let mut rng = Rng::new(ts ^ 0xD1CE_D1CE);
    (0..len).map(|_| rng.next_u64() as u8).collect()
}

struct Model {
    /// Every entry whose `append` returned `Ok`, oldest first. Truncated at the
    /// tail by a remount that finds the page buffer's contents did not survive.
    entries: Vec<Entry>,
    /// How many entries have been evicted from the front. Discovered from the
    /// database, never predicted; only its monotonicity is asserted.
    evicted: usize,
    /// How many entries a `sync` that returned `Ok` has acknowledged. These may
    /// be evicted, but they may never be lost from the tail.
    durable: usize,
    next_ts: u64,
}

impl Model {
    fn new() -> Self {
        Self {
            entries: Vec::new(),
            evicted: 0,
            durable: 0,
            next_ts: 1,
        }
    }

    /// Entries the database is expected to still hold.
    fn live(&self) -> &[Entry] {
        &self.entries[self.evicted.min(self.entries.len())..]
    }
}

// =============================================================================
// Replay
// =============================================================================

/// A failure, as a message. Checks return `Err` rather than panicking so that
/// [`shrink`] can re-run a candidate sequence and ask whether it still fails.
type Failure = String;

macro_rules! ensure {
    ($cond:expr, $($arg:tt)*) => {
        if !($cond) {
            return Err(format!($($arg)*));
        }
    };
}

type Db<const PAGE: usize, const SECTOR: usize, const SECTORS: usize> =
    SensorDb<MockFlash<PAGE, SECTOR>, PAGE, SECTORS>;

/// Read the whole database back, in the order it reports.
fn read_all<const PAGE: usize, const SECTOR: usize, const SECTORS: usize>(
    db: &mut Db<PAGE, SECTOR, SECTORS>,
) -> Result<Vec<Entry>, Error> {
    let mut out = Vec::new();
    db.query_all(None, |hdr, payload| {
        out.push(Entry {
            sensor: hdr.sensor_id,
            ts: hdr.timestamp,
            payload: payload.to_vec(),
        });
        true
    })?;
    Ok(out)
}

/// Every assertion that must hold after every single operation.
fn check<const PAGE: usize, const SECTOR: usize, const SECTORS: usize>(
    db: &mut Db<PAGE, SECTOR, SECTORS>,
    model: &mut Model,
    step: usize,
    op: Op,
) -> Result<(), Failure> {
    let at = format!("step {step} after {op:?}");
    let actual = read_all(db).map_err(|e| format!("{at}: query_all failed: {e:?}"))?;

    // -- The contiguous-suffix invariant ------------------------------------
    ensure!(
        actual.len() <= model.entries.len(),
        "{at}: database reports {} entries, only {} were ever appended",
        actual.len(),
        model.entries.len()
    );
    let k = model.entries.len() - actual.len();
    ensure!(
        k >= model.evicted,
        "{at}: {} entries came back from the dead (evicted was {}, now {k})",
        model.evicted - k,
        model.evicted
    );
    ensure!(
        actual == model.entries[k..],
        "{at}: contents are not the model's suffix from {k}\n  expected: {:?}\n  actual:   {:?}",
        &model.entries[k..],
        &actual
    );
    // Nothing a successful `sync` acknowledged may be evicted *and* still be
    // claimed: eviction is legal, so the bound is only that `durable` entries
    // still present must match — which the equality above already gives. What
    // is checked here is that eviction never overshoots into the live sector.
    model.evicted = k;

    // -- Ordering ------------------------------------------------------------
    ensure!(
        actual.windows(2).all(|w| w[0].ts < w[1].ts),
        "{at}: entries are not in ascending timestamp order"
    );

    // -- count(), latest(), oldest() agree with the same suffix --------------
    let live = model.live().to_vec();
    let total = db
        .count(None)
        .map_err(|e| format!("{at}: count(None) failed: {e:?}"))?;
    ensure!(
        total as usize == live.len(),
        "{at}: count(None) = {total}, model has {}",
        live.len()
    );

    for sensor in SENSORS {
        let expected: Vec<&Entry> = live.iter().filter(|e| e.sensor == sensor).collect();

        let counted = db
            .count(Some(sensor))
            .map_err(|e| format!("{at}: count({sensor}) failed: {e:?}"))?;
        ensure!(
            counted as usize == expected.len(),
            "{at}: count({sensor}) = {counted}, model has {}",
            expected.len()
        );

        let mut buf = [0u8; PAGE];
        let latest = db
            .latest(sensor, &mut buf)
            .map_err(|e| format!("{at}: latest({sensor}) failed: {e:?}"))?;
        match (latest, expected.last()) {
            (None, None) => {}
            (Some((hdr, n)), Some(want)) => {
                ensure!(
                    hdr.timestamp == want.ts
                        && hdr.sensor_id == sensor
                        && buf[..n] == want.payload[..],
                    "{at}: latest({sensor}) = ts {} ({n}B), model says {:?}",
                    hdr.timestamp,
                    want
                );
            }
            (a, b) => {
                return Err(format!(
                    "{at}: latest({sensor}) presence disagrees: db {:?}, model {:?}",
                    a.map(|(h, _)| h.timestamp),
                    b.map(|e| e.ts)
                ));
            }
        }

        let oldest = db
            .oldest(sensor, &mut buf)
            .map_err(|e| format!("{at}: oldest({sensor}) failed: {e:?}"))?;
        match (oldest, expected.first()) {
            (None, None) => {}
            (Some((hdr, n)), Some(want)) => {
                ensure!(
                    hdr.timestamp == want.ts && buf[..n] == want.payload[..],
                    "{at}: oldest({sensor}) = ts {}, model says {:?}",
                    hdr.timestamp,
                    want
                );
            }
            (a, b) => {
                return Err(format!(
                    "{at}: oldest({sensor}) presence disagrees: db {:?}, model {:?}",
                    a.map(|(h, _)| h.timestamp),
                    b.map(|e| e.ts)
                ));
            }
        }
    }

    // -- A bounded time range, which exercises the per-sector timestamp index -
    if let (Some(first), Some(last)) = (live.first(), live.last()) {
        let span = last.ts - first.ts;
        let lo = first.ts + span / 4;
        let hi = last.ts - span / 4;
        if lo <= hi {
            let want: Vec<&Entry> = live.iter().filter(|e| e.ts >= lo && e.ts <= hi).collect();
            let mut got = Vec::new();
            let n = db
                .query_range(None, lo, hi, |hdr, _| {
                    got.push(hdr.timestamp);
                    true
                })
                .map_err(|e| format!("{at}: query_range failed: {e:?}"))?;
            ensure!(
                n as usize == want.len() && got == want.iter().map(|e| e.ts).collect::<Vec<_>>(),
                "{at}: query_range({lo}..={hi}) yielded {n}, model says {}",
                want.len()
            );
        }
    }

    Ok(())
}

/// Replay `ops` against a fresh database of the given geometry.
fn replay<const PAGE: usize, const SECTOR: usize, const SECTORS: usize>(
    ops: &[Op],
    reserved: u16,
) -> Result<(), Failure> {
    let max_payload = PAGE - 20;
    let flash = MockFlash::<PAGE, SECTOR>::new(SECTORS * SECTOR);
    let mut db: Db<PAGE, SECTOR, SECTORS> =
        SensorDb::new(flash, 0, SECTORS as u16, reserved).map_err(|e| format!("new: {e:?}"))?;
    db.format().map_err(|e| format!("format: {e:?}"))?;

    let mut model = Model::new();

    for (step, &op) in ops.iter().enumerate() {
        match op {
            Op::Append { sensor, len } => {
                let len = len.min(max_payload);
                let ts = model.next_ts;
                let payload = payload_for(ts, len);
                match db.append(sensor, ts, &payload) {
                    Ok(()) => {
                        model.next_ts += 1;
                        model.entries.push(Entry {
                            sensor,
                            ts,
                            payload,
                        });
                    }
                    // A ring evicts rather than filling up, so the only
                    // tolerable refusal is the reserved-headroom one.
                    Err(Error::NoSpace) => {}
                    Err(e) => return Err(format!("step {step}: append failed: {e:?}")),
                }
            }
            Op::Run { count } => {
                // Clamped to what one entry can hold: splitting a burst is the
                // caller's job, and `append_run` says so rather than guessing.
                let room = max_payload.saturating_sub(RUN_FRAME_SIZE) / size_of::<Burst>();
                let count = count.clamp(1, room.max(1));
                let base = model.next_ts;
                let values: Vec<Burst> = (0..count)
                    .map(|i| Burst {
                        v: (base + i as u64) as u32,
                    })
                    .collect();
                let run = Run::of(base, 1, &values)
                    .map_err(|e| format!("step {step}: Run::of: {e:?}"))?;
                match db.append_run(&run) {
                    Ok(()) => {
                        model.next_ts += count as u64;
                        for i in 0..count as u64 {
                            model.entries.push(Entry {
                                sensor: Burst::SENSOR_ID,
                                ts: base + i,
                                payload: run_sample_payload(base + i),
                            });
                        }
                    }
                    Err(Error::NoSpace) => {}
                    Err(e) => return Err(format!("step {step}: append_run failed: {e:?}")),
                }
            }
            Op::Sync => {
                db.sync().map_err(|e| format!("step {step}: sync: {e:?}"))?;
                model.durable = model.entries.len();
            }
            Op::Compact(n) => {
                db.compact(n, CompactScope::All)
                    .map_err(|e| format!("step {step}: compact: {e:?}"))?;
            }
            Op::Remount => {
                let flash = db.into_inner();
                let mut fresh: Db<PAGE, SECTOR, SECTORS> =
                    SensorDb::new(flash, 0, SECTORS as u16, reserved)
                        .map_err(|e| format!("step {step}: rebuild: {e:?}"))?;
                fresh
                    .mount()
                    .map_err(|e| format!("step {step}: mount: {e:?}"))?;
                db = fresh;
                reconcile_after_remount(&mut db, &mut model, step)?;
            }
        }

        check(&mut db, &mut model, step, op)?;
    }

    Ok(())
}

/// A remount is the one operation that can lose the *tail*: entries still in the
/// RAM page buffer never reached flash. The model cannot predict how much
/// survived — that depends on where page boundaries happened to fall — so it
/// learns it here, having first checked the one thing that is guaranteed:
/// everything a successful `sync` acknowledged is still on the medium.
fn reconcile_after_remount<const PAGE: usize, const SECTOR: usize, const SECTORS: usize>(
    db: &mut Db<PAGE, SECTOR, SECTORS>,
    model: &mut Model,
    step: usize,
) -> Result<(), Failure> {
    let actual = read_all(db).map_err(|e| format!("step {step}: query_all: {e:?}"))?;

    let survived = match actual.last() {
        // Everything is gone. Legal only if everything acknowledged was evicted.
        None => {
            ensure!(
                model.durable <= model.evicted,
                "step {step}: remount lost everything, but {} entries were acknowledged \
                 and only {} had been evicted",
                model.durable,
                model.evicted
            );
            model.entries.len()
        }
        Some(last) => {
            let pos = model
                .entries
                .iter()
                .position(|e| e.ts == last.ts)
                .ok_or_else(|| {
                    format!(
                        "step {step}: remount produced ts {} which was never appended",
                        last.ts
                    )
                })?;
            pos + 1
        }
    };

    ensure!(
        survived >= model.durable,
        "step {step}: remount kept only {survived} entries, but {} were acknowledged by a \
         successful sync",
        model.durable
    );

    // The unacknowledged tail that did not reach flash is gone for good.
    model.entries.truncate(survived);
    Ok(())
}

// =============================================================================
// Shrinking
// =============================================================================

/// Greedily drop operations while the failure survives.
///
/// Two passes: chunks first, so a long run of appends collapses quickly, then
/// single operations for the final polish. The result is printed, not returned
/// to the harness — its only job is to make a failure readable.
fn shrink<const PAGE: usize, const SECTOR: usize, const SECTORS: usize>(
    ops: &[Op],
    reserved: u16,
) -> (Vec<Op>, Failure) {
    let mut best = ops.to_vec();
    let mut failure = match replay::<PAGE, SECTOR, SECTORS>(&best, reserved) {
        Err(f) => f,
        Ok(()) => return (best, "not reproducible".into()),
    };

    let mut chunk = best.len() / 2;
    while chunk > 0 {
        let mut i = 0;
        while i < best.len() {
            let mut candidate = best.clone();
            let end = (i + chunk).min(candidate.len());
            candidate.drain(i..end);
            match replay::<PAGE, SECTOR, SECTORS>(&candidate, reserved) {
                Err(f) => {
                    best = candidate;
                    failure = f;
                    // Do not advance: the next chunk slid into this position.
                }
                Ok(()) => i += chunk,
            }
        }
        chunk /= 2;
    }

    (best, failure)
}

// =============================================================================
// The suites
// =============================================================================

/// Replay `seeds` workloads of the given geometry, shrinking the first failure.
fn sweep<const PAGE: usize, const SECTOR: usize, const SECTORS: usize>(
    seeds: u64,
    ops_per_seed: usize,
    reserved: u16,
) {
    for seed in 0..seeds {
        let mut rng = Rng::new(seed ^ (PAGE as u64) << 32 ^ (SECTORS as u64));
        let ops = workload(&mut rng, ops_per_seed, PAGE - 20);

        if let Err(first) = replay::<PAGE, SECTOR, SECTORS>(&ops, reserved) {
            let (minimal, failure) = shrink::<PAGE, SECTOR, SECTORS>(&ops, reserved);
            let mut trace = String::new();
            for (i, op) in minimal.iter().enumerate() {
                let _ = writeln!(trace, "  {i:3}: {op:?}");
            }
            panic!(
                "model disagreed\n\
                 geometry: PAGE={PAGE} SECTOR={SECTOR} SECTORS={SECTORS} reserved={reserved}\n\
                 seed:     {seed}\n\
                 \n{failure}\n\
                 \nminimal failing sequence ({} ops, shrunk from {}):\n{trace}\
                 \noriginal failure was:\n{first}",
                minimal.len(),
                ops.len()
            );
        }
    }
}

/// The flagship geometry: 256-byte pages, 4 KB sectors.
#[test]
fn model_standard_geometry() {
    sweep::<256, 4096, 8>(24, 160, 1);
}

/// A ring small enough that a few hundred appends wrap it many times, so
/// eviction — and the interaction between eviction and `compact` — is the
/// common case rather than an edge one.
#[test]
fn model_tiny_ring_wraps_constantly() {
    sweep::<64, 512, 4>(24, 200, 1);
}

/// Three sectors with one reserved is the tightest legal ring: two usable
/// sectors, so a compaction can leave almost nothing behind.
#[test]
fn model_minimal_ring() {
    sweep::<64, 256, 3>(24, 160, 1);
}

/// Large pages mean few, long entries per page and a page buffer that holds a
/// lot — so a remount discards much more, which is the case
/// `reconcile_after_remount` exists for.
#[test]
fn model_large_pages() {
    sweep::<1024, 8192, 4>(12, 120, 1);
}

/// No reserved headroom at all.
#[test]
fn model_no_reserved_sectors() {
    sweep::<128, 1024, 6>(16, 160, 0);
}

// =============================================================================
// The tiered model
// =============================================================================

/// The same oracle applied to store-and-forward, where the series is split
/// across two media that come and go.
///
/// The invariants this can assert without duplicating the routing logic:
///
/// 1. **At most two contiguous runs.** Each medium is a ring holding a
///    contiguous slice of the series, and the watermark keeps the two disjoint,
///    so the union must be the card's run followed by the onboard log's — with
///    at most **one** gap between them, and every entry matching the model byte
///    for byte at its own position.
///
///    That gap is real, documented loss and not a defect: the onboard ring
///    overwrites its tail whether or not replication has caught up, so a card
///    left out too long comes back to find the middle gone. What the invariant
///    forbids is a *second* gap, a hole inside either medium, a reorder, or a
///    truncated payload.
/// 2. **Strictly ascending timestamps.** In a fault-free run replication is
///    exactly-once, so a repeated timestamp is a duplicate and a failure. The
///    torn case, where at-least-once is the documented contract, belongs to
///    `spool_fuzz.rs`.
/// 3. **Replication only ever drops the oldest.** A `spool` or `drain` moves
///    entries between media, so the union may shrink only from the front — the
///    card is a ring too, and copying onto a full one evicts its tail, which is
///    what `VolumeFill::will_overwrite` warns about. What replication may never
///    do is lose the *newest*, open a gap at the seam between the two media,
///    duplicate an entry, or reorder one. Checked around every replication op.
/// 4. **Neither does `compact(SpooledOnly)` while the card is attached.** It may
///    only reclaim onboard sectors the card already holds, so with the card
///    present the visible set cannot change.
/// 5. **Detaching never adds and attaching never removes.** Pulling the card can
///    only hide the older run; putting it back can only reveal it.
mod tiered {
    use super::*;
    use sensor_db::db::DbConfig;
    use sensor_db::mock::RemovableFlash;
    use sensor_db::sector::LogId;
    use sensor_db::spool::{SpoolBudget, Spooler, TieredDb, WritePolicy};

    const PAGE: usize = 64;
    const SECTOR: usize = 512;
    const SECTORS: usize = 8;
    /// The card reserves its first two sectors for the replication cursor.
    const CURSOR_SECTORS: u16 = 2;
    /// Sectors on the card's flash, cursor region included.
    ///
    /// Deliberately larger than the onboard log's `SECTORS`, and by more than
    /// the two the cursor takes: the union a `TieredDb` reports reads the card
    /// for everything below the replication watermark, so if the *card's* ring
    /// wraps first it drops entries the onboard log still holds — and detaching
    /// the card then reveals them. That is honest behaviour and not something
    /// this model can call a bug, but it is also not the configuration anyone
    /// deploys: the removable medium is the durable tier and is the larger one.
    /// Sizing it below the onboard log here would trade a real invariant
    /// (`Detach` hides, never reveals) for a check of a misconfiguration.
    const CARD_SECTORS: usize = 12;
    const LOG: u32 = 0x5EED;

    type OnFlash = MockFlash<PAGE, SECTOR>;
    type CardFlash = RemovableFlash<MockFlash<PAGE, SECTOR>>;
    type Card = SensorDb<CardFlash, PAGE, CARD_SECTORS>;
    type Tiered = TieredDb<OnFlash, CardFlash, PAGE, SECTORS, PAGE, CARD_SECTORS>;

    #[derive(Clone, Copy, PartialEq, Eq, Debug)]
    enum TOp {
        Append {
            sensor: u16,
            len: usize,
        },
        /// Append a run, which replication must carry across as a run.
        Run {
            count: usize,
        },
        Sync,
        Spool(u32),
        Drain,
        Detach,
        Attach,
        CompactSpooled(u16),
    }

    fn workload(rng: &mut Rng, len: usize, max_payload: usize) -> Vec<TOp> {
        (0..len)
            .map(|_| match rng.below(100) {
                0..=46 => TOp::Append {
                    sensor: SENSORS[rng.below(SENSORS.len() as u64) as usize],
                    len: rng.below(max_payload as u64 + 1) as usize,
                },
                47..=54 => TOp::Run {
                    count: rng.below(6) as usize + 1,
                },
                55..=67 => TOp::Sync,
                68..=80 => TOp::Spool(rng.below(24) as u32 + 1),
                81..=87 => TOp::Drain,
                88..=92 => TOp::CompactSpooled(rng.below(2) as u16 + 1),
                93..=96 => TOp::Detach,
                _ => TOp::Attach,
            })
            .collect()
    }

    fn log_id() -> Option<LogId> {
        LogId::new(LOG)
    }

    fn card_config() -> DbConfig {
        DbConfig::new(
            CURSOR_SECTORS as u32 * SECTOR as u32,
            CARD_SECTORS as u16 - CURSOR_SECTORS,
            1,
        )
        .unwrap()
        .with_log_id(log_id().unwrap())
    }

    fn new_card() -> Card {
        let flash = RemovableFlash::new(MockFlash::<PAGE, SECTOR>::new(CARD_SECTORS * SECTOR));
        let mut db: Card = SensorDb::with_config(flash, card_config()).unwrap();
        db.format().unwrap();
        db
    }

    fn read_all(db: &mut Tiered) -> Result<Vec<Entry>, Error> {
        let mut out = Vec::new();
        db.query_all(None, |hdr, payload| {
            out.push(Entry {
                sensor: hdr.sensor_id,
                ts: hdr.timestamp,
                payload: payload.to_vec(),
            });
            true
        })?;
        Ok(out)
    }

    /// Suffix equality, ordering, and agreement with the scalar read methods.
    fn check(
        db: &mut Tiered,
        model: &[Entry],
        attached: bool,
        step: usize,
        op: TOp,
    ) -> Result<(), Failure> {
        let card = if attached { "in" } else { "out" };
        let at = format!("step {step} after {op:?} (card {card})");
        let actual = read_all(db).map_err(|e| format!("{at}: query_all: {e:?}"))?;

        ensure!(
            actual.len() <= model.len(),
            "{at}: {} entries visible, only {} appended",
            actual.len(),
            model.len()
        );
        ensure!(
            actual.windows(2).all(|w| w[0].ts < w[1].ts),
            "{at}: timestamps are not strictly ascending — a duplicate or a reorder \
             across the card/onboard seam\n  actual: {actual:?}"
        );

        // Timestamps are handed out as `index + 1`, so an entry names its own
        // position in the model and no searching is needed.
        let mut breaks = Vec::new();
        let mut previous: Option<usize> = None;
        for entry in &actual {
            let i = (entry.ts - 1) as usize;
            ensure!(
                i < model.len() && *entry == model[i],
                "{at}: ts {} does not match the model entry at {i}\n  expected: {:?}\n  \
                 actual:   {entry:?}",
                entry.ts,
                model.get(i)
            );
            if let Some(p) = previous
                && i != p + 1
            {
                breaks.push((p, i));
            }
            previous = Some(i);
        }
        ensure!(
            breaks.len() <= 1,
            "{at}: the union has {} gaps, and two rings can produce at most one: {breaks:?}\n  \
             actual: {actual:?}",
            breaks.len()
        );

        let total = db
            .count(None)
            .map_err(|e| format!("{at}: count(None): {e:?}"))?;
        ensure!(
            total as usize == actual.len(),
            "{at}: count(None) = {total}, {} visible",
            actual.len()
        );

        for sensor in SENSORS {
            let want: Vec<&Entry> = actual.iter().filter(|e| e.sensor == sensor).collect();
            let counted = db
                .count(Some(sensor))
                .map_err(|e| format!("{at}: count({sensor}): {e:?}"))?;
            ensure!(
                counted as usize == want.len(),
                "{at}: count({sensor}) = {counted}, {} visible",
                want.len()
            );

            let mut buf = [0u8; PAGE];
            let latest = db
                .latest(sensor, &mut buf)
                .map_err(|e| format!("{at}: latest({sensor}): {e:?}"))?;
            match (latest, want.last()) {
                (None, None) => {}
                (Some((hdr, n)), Some(w)) => ensure!(
                    hdr.timestamp == w.ts && buf[..n] == w.payload[..],
                    "{at}: latest({sensor}) = ts {}, expected {:?}",
                    hdr.timestamp,
                    w
                ),
                (a, b) => {
                    return Err(format!(
                        "{at}: latest({sensor}) presence disagrees: {:?} vs {:?}",
                        a.map(|(h, _)| h.timestamp),
                        b.map(|e| e.ts)
                    ));
                }
            }
        }

        Ok(())
    }

    /// Assert an operation left the visible series untouched.
    fn unchanged(
        db: &mut Tiered,
        before: &[Entry],
        step: usize,
        what: &str,
    ) -> Result<(), Failure> {
        let after = read_all(db).map_err(|e| format!("step {step}: post-{what} read: {e:?}"))?;
        ensure!(
            after == before,
            "step {step}: {what} changed the visible series\n  before: {before:?}\n  \
             after:  {after:?}"
        );
        Ok(())
    }

    /// Assert an operation removed only *oldest* entries.
    ///
    /// Replication cannot be required to leave the union untouched: the card is
    /// a ring as well, so copying onto a full one legitimately evicts its
    /// oldest — that is what `VolumeFill::will_overwrite` warns about. What it
    /// may never do is lose the newest, open a gap at the seam between the two
    /// media, duplicate an entry, or reorder one. All of that is exactly
    /// "`after` is a suffix of `before`".
    fn suffix_of_before(
        db: &mut Tiered,
        before: &[Entry],
        step: usize,
        what: &str,
    ) -> Result<(), Failure> {
        let after = read_all(db).map_err(|e| format!("step {step}: post-{what} read: {e:?}"))?;
        ensure!(
            after.len() <= before.len(),
            "step {step}: {what} added {} entries",
            after.len() - before.len()
        );
        let k = before.len() - after.len();
        ensure!(
            after == before[k..],
            "step {step}: {what} did not merely drop the oldest {k}\n  before: {before:?}\n  \
             after:  {after:?}"
        );
        Ok(())
    }

    fn replay(ops: &[TOp]) -> Result<(), Failure> {
        let max_payload = PAGE - 20;
        let mut onboard: SensorDb<OnFlash, PAGE, SECTORS> = SensorDb::with_config(
            MockFlash::new(SECTORS * SECTOR),
            DbConfig::new(0, SECTORS as u16, 1)
                .unwrap()
                .with_log_id(log_id().unwrap()),
        )
        .map_err(|e| format!("onboard: {e:?}"))?;
        onboard.format().map_err(|e| format!("format: {e:?}"))?;

        let spooler: Spooler<CardFlash, PAGE, CARD_SECTORS> =
            Spooler::new(log_id(), 0, SECTOR as u32).map_err(|e| format!("spooler: {e:?}"))?;
        let mut db = TieredDb::new(onboard, spooler, WritePolicy::OnboardFirst)
            .map_err(|e| format!("tiered: {e:?}"))?;

        // The card starts inserted. `Detach` parks it and `Attach` puts the same
        // medium back, so the sequence rotates one card rather than conjuring
        // fresh ones — which is what makes the cursor protocol do any work.
        db.attach(new_card())
            .map_err(|e| format!("attach: {e:?}"))?;
        let mut parked: Option<Card> = None;

        let mut model: Vec<Entry> = Vec::new();
        let mut next_ts = 1u64;

        for (step, &op) in ops.iter().enumerate() {
            let before = read_all(&mut db).map_err(|e| format!("step {step}: pre-read: {e:?}"))?;
            let attached_before = parked.is_none();

            match op {
                TOp::Append { sensor, len } => {
                    let len = len.min(max_payload);
                    let payload = payload_for(next_ts, len);
                    match db.append(sensor, next_ts, &payload) {
                        Ok(()) => {
                            model.push(Entry {
                                sensor,
                                ts: next_ts,
                                payload,
                            });
                            next_ts += 1;
                        }
                        Err(Error::NoSpace) => {}
                        Err(e) => return Err(format!("step {step}: append: {e:?}")),
                    }
                }
                TOp::Run { count } => {
                    let room = max_payload.saturating_sub(RUN_FRAME_SIZE) / size_of::<Burst>();
                    let count = count.clamp(1, room.max(1));
                    let base = next_ts;
                    let values: Vec<Burst> = (0..count)
                        .map(|i| Burst {
                            v: (base + i as u64) as u32,
                        })
                        .collect();
                    let run = Run::of(base, 1, &values)
                        .map_err(|e| format!("step {step}: Run::of: {e:?}"))?;
                    match db.append_run(&run) {
                        Ok(()) => {
                            for i in 0..count as u64 {
                                model.push(Entry {
                                    sensor: Burst::SENSOR_ID,
                                    ts: base + i,
                                    payload: run_sample_payload(base + i),
                                });
                            }
                            next_ts += count as u64;
                        }
                        Err(Error::NoSpace) => {}
                        Err(e) => return Err(format!("step {step}: append_run: {e:?}")),
                    }
                }
                TOp::Sync => db.sync().map_err(|e| format!("step {step}: sync: {e:?}"))?,
                TOp::Spool(n) => {
                    db.spool_step(SpoolBudget::new(n))
                        .map_err(|e| format!("step {step}: spool_step: {e:?}"))?;
                    suffix_of_before(&mut db, &before, step, "spool_step")?;
                }
                TOp::Drain => {
                    db.drain(SpoolBudget::new(16), 64)
                        .map_err(|e| format!("step {step}: drain: {e:?}"))?;
                    suffix_of_before(&mut db, &before, step, "drain")?;
                }
                TOp::CompactSpooled(n) => {
                    db.onboard_mut()
                        .compact(n, CompactScope::SpooledOnly)
                        .map_err(|e| format!("step {step}: compact: {e:?}"))?;
                    // With the card present, `SpooledOnly` may only reclaim what
                    // the card already holds — so nothing can disappear.
                    if attached_before {
                        unchanged(&mut db, &before, step, "compact(SpooledOnly)")?;
                    }
                }
                TOp::Detach => {
                    if let Some(card) = db.detach() {
                        parked = Some(card);
                        let after = read_all(&mut db)
                            .map_err(|e| format!("step {step}: post-detach read: {e:?}"))?;
                        ensure!(
                            after.len() <= before.len(),
                            "step {step}: detaching the card revealed {} entries",
                            after.len() - before.len()
                        );
                    }
                }
                TOp::Attach => {
                    if let Some(card) = parked.take() {
                        // Reinsert the medium the way a real one comes back:
                        // rebuilt and remounted from its own flash image.
                        let mut flash = card.into_inner();
                        flash.insert();
                        let mut card: Card = SensorDb::with_config(flash, card_config())
                            .map_err(|e| format!("step {step}: rebuild card: {e:?}"))?;
                        card.mount()
                            .map_err(|e| format!("step {step}: card mount: {e:?}"))?;
                        db.attach(card)
                            .map_err(|e| format!("step {step}: attach: {e:?}"))?;
                        let after = read_all(&mut db)
                            .map_err(|e| format!("step {step}: post-attach read: {e:?}"))?;
                        ensure!(
                            after.len() >= before.len(),
                            "step {step}: attaching the card hid {} entries",
                            before.len() - after.len()
                        );
                    }
                }
            }

            check(&mut db, &model, parked.is_none(), step, op)?;
        }

        Ok(())
    }

    /// Greedy shrinker, the same shape as the single-log one.
    fn shrink(ops: &[TOp]) -> (Vec<TOp>, Failure) {
        let mut best = ops.to_vec();
        let mut failure = match replay(&best) {
            Err(f) => f,
            Ok(()) => return (best, "not reproducible".into()),
        };
        let mut chunk = best.len() / 2;
        while chunk > 0 {
            let mut i = 0;
            while i < best.len() {
                let mut candidate = best.clone();
                let end = (i + chunk).min(candidate.len());
                candidate.drain(i..end);
                match replay(&candidate) {
                    Err(f) => {
                        best = candidate;
                        failure = f;
                    }
                    Ok(()) => i += chunk,
                }
            }
            chunk /= 2;
        }
        (best, failure)
    }

    #[test]
    fn model_store_and_forward() {
        for seed in 0..16u64 {
            let mut rng = Rng::new(seed ^ 0x7EA5_1E55);
            let ops = workload(&mut rng, 140, PAGE - 20);
            if let Err(first) = replay(&ops) {
                let (minimal, failure) = shrink(&ops);
                let mut trace = String::new();
                for (i, op) in minimal.iter().enumerate() {
                    let _ = writeln!(trace, "  {i:3}: {op:?}");
                }
                panic!(
                    "tiered model disagreed\nseed: {seed}\n\n{failure}\n\n\
                     minimal failing sequence ({} ops, shrunk from {}):\n{trace}\n\
                     original failure was:\n{first}",
                    minimal.len(),
                    ops.len()
                );
            }
        }
    }
}