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
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
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
//! Replication policy: what to copy next, and where the cursor record goes.
//!
//! Pure module — no I/O. Everything here is decidable from records already read
//! and counters already held, which is what lets the blocking and async drivers
//! share it verbatim.

use zerocopy::FromBytes;

use crate::db::{DbStats, LogPosition, ReadCursor, Replicated};
use crate::error::Error;
use crate::sector::LogId;
use crate::spool::cursor::{
    CURSOR_RECORD_SIZE, CURSOR_SECTORS, CursorKind, CursorRegion, SlotAddress, SpoolCursorWire,
};

/// Whether `a` is a later batch than `b`, allowing for the counter wrapping.
///
/// Batch ids are a `u32` that increments forever, so eventually it wraps and the
/// newest record on a medium carries a *smaller* number than the oldest. Plain
/// `>` reads that backwards, picks the wrong cursor sector as active, and —
/// because [`plan_slots`] erases the sector it moves into — erases the one
/// holding the true resume point. Replication would then replay from far behind.
///
/// The fix is serial-number arithmetic (RFC 1982): `a` is newer when the
/// unsigned distance forward from `b` to `a` is less than half the space. That
/// is unambiguous here by construction, because the whole cursor region holds
/// only `2 × slots_per_sector` records — at most a few hundred consecutive
/// batches, nowhere near the 2³¹ needed to make the comparison ambiguous.
fn batch_is_newer(a: u32, b: u32) -> bool {
    a != b && a.wrapping_sub(b) < 1 << 31
}

/// How much one [`Spooler::spool`](crate::spool::Spooler::spool) pass may copy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct SpoolBudget {
    /// Maximum entries copied in one pass.
    ///
    /// **This is the duplicate bound.** A power cut or an unclean removal can
    /// replay at most the batch that was in flight, so this value is the worst
    /// case number of duplicated entries on the replica. Smaller batches mean
    /// fewer possible duplicates and more cursor writes; larger batches mean the
    /// opposite.
    pub max_entries: u32,
}

impl Default for SpoolBudget {
    fn default() -> Self {
        Self { max_entries: 64 }
    }
}

impl SpoolBudget {
    /// A budget of `max_entries` entries per pass.
    pub const fn new(max_entries: u32) -> Self {
        Self { max_entries }
    }
}

/// What a successful [`attach`](crate::spool::Spooler::attach) found.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct Attached {
    /// Source position replication will resume from, before reconciliation.
    ///
    /// When [`recovered_entries`](Self::recovered_entries) is non-zero this is
    /// the *start* of the batch that was interrupted; the first replication pass
    /// skips that many entries before copying anything, so the effective resume
    /// point is further on. [`Spooler::reconcile`](crate::spool::Spooler::reconcile)
    /// applies the skip eagerly and reports the reconciled position.
    pub resume_from: LogPosition,
    /// The most recent batch id on the medium, or 0 if it is fresh.
    pub batch_id: u32,
    /// A batch was in flight when the medium was last detached. This is that
    /// batch's budget — the number of entries it was *allowed* to copy, and so
    /// the worst case duplication if it cannot be reconciled.
    ///
    /// See [`recovered_entries`](Self::recovered_entries) for what actually
    /// happens: when reconciliation succeeds, duplication is zero.
    pub in_flight_entries: u32,
    /// Entries of the interrupted batch found durable **on the replica**.
    ///
    /// This is one side of the reconciliation. Skipping them on the source is
    /// the other, and it can still be abandoned — if the source ring has wrapped
    /// past them, or if the two runs do not fingerprint alike. Read
    /// [`resume_from`](Self::resume_from) to see whether the skip applied:
    /// [`TieredDb::attach`] reconciles before returning, so there it already
    /// accounts for the outcome, while after
    /// [`Spooler::attach`](crate::spool::Spooler::attach) the skip is still
    /// pending.
    ///
    /// Zero when no batch was in flight, and zero when the replica's own ring
    /// had wrapped past where the batch landed — the run would then begin with
    /// entries from earlier batches, so nothing about it can be trusted.
    ///
    /// [`TieredDb::attach`]: crate::spool::TieredDb::attach
    pub recovered_entries: u32,
    /// The medium carried no cursor: it is new to this log.
    pub fresh: bool,
}

/// What one replication pass achieved.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct SpoolProgress {
    /// Entries copied in this pass.
    pub entries_copied: u32,
    /// Source position now durably replicated.
    pub committed_upto: LogPosition,
    /// Nothing further is waiting: the replica is level with the source's
    /// durable tail.
    pub caught_up: bool,
    /// The resume point had fallen off the tail of the source ring, so entries
    /// between it and the oldest retained sector were never copied.
    ///
    /// Not an error: it is what happens when a medium stays away long enough for
    /// the ring to wrap.
    pub gap: bool,
    /// Sectors the pass erased **on the volume**.
    ///
    /// [`SpoolBudget`] bounds how much a pass copies, but not how long it takes,
    /// and an erase is the one operation whose cost is nothing like the rest:
    /// 100 ms or more on many NOR parts, against microseconds for a page write.
    /// A pass that fills the replica's active sector, or that wraps the cursor
    /// region, pays that.
    ///
    /// Use it to back off — spool less often, or with a smaller budget — when a
    /// caller has latency it must meet elsewhere. Zero for most passes.
    ///
    /// This covers erases the *replication* pass caused. Under
    /// [`WritePolicy::CardFirst`](crate::spool::WritePolicy::CardFirst) samples
    /// go straight to the volume, so the same spike can land on `append`
    /// instead; [`SensorDb::sectors_erased`](crate::SensorDb::sectors_erased) on
    /// the volume is the counter that sees those.
    pub volume_erased: u32,
}

impl SpoolProgress {
    /// The outcome of a pass that found nothing waiting.
    ///
    /// Reported before any cursor record is written, so an idle poll costs no
    /// slots — which is why this is not simply `default()` with a position: it
    /// is `caught_up`, and it carries whatever the probe learned about a gap.
    pub(crate) fn idle(at: LogPosition, gap: bool) -> Self {
        Self {
            entries_copied: 0,
            committed_upto: at,
            caught_up: true,
            gap,
            volume_erased: 0,
        }
    }

    /// Fold a later pass into a running total.
    ///
    /// Counts add, positions and `caught_up` take the later pass's answer, and
    /// `gap` sticks: a gap in any pass of the sequence is a gap in the whole of
    /// it, and a pass that found nothing missing cannot un-report one.
    pub(crate) fn absorb(&mut self, later: &Self) {
        self.entries_copied += later.entries_copied;
        self.committed_upto = later.committed_upto;
        self.caught_up = later.caught_up;
        self.gap |= later.gap;
        self.volume_erased += later.volume_erased;
    }
}

/// Erases one replication pass caused on the volume, from both sides of it.
///
/// The volume's own log counts the rotations its appends cause, but the cursor
/// region is written through a [`Partition`](crate::Partition) — behind the
/// database's back — so those erases reach no counter and have to be added by
/// hand. Getting that wrong under-reports the one cost worth reporting: an erase
/// is 100 ms or more on many NOR parts, against microseconds for a page write.
#[derive(Debug, Clone, Copy)]
pub(crate) struct EraseTally {
    start: u32,
    cursor: u32,
}

impl EraseTally {
    /// Begin counting from the volume's current erase count.
    pub(crate) fn new(volume_erased_so_far: u32) -> Self {
        Self {
            start: volume_erased_so_far,
            cursor: 0,
        }
    }

    /// Record an erase the spooler performed on the cursor region itself.
    pub(crate) fn cursor_erase(&mut self) {
        self.cursor += 1;
    }

    /// Total erases the pass caused, given the volume's count now.
    pub(crate) fn total(&self, volume_erased_now: u32) -> u32 {
        self.cursor + volume_erased_now.saturating_sub(self.start)
    }
}

/// How much room is left on a log, and how close it is to overwriting.
///
/// Built from [`DbStats`] by [`from_stats`](Self::from_stats), and reached
/// through [`TieredDb::volume_fill`](crate::spool::TieredDb::volume_fill).
///
/// # Why this matters more on a removable volume
///
/// Under [`WritePolicy::OnboardFirst`](crate::spool::WritePolicy::OnboardFirst)
/// a full volume wraps and overwrites its own oldest copy of data the onboard
/// log may still hold — bad, but recoverable. Under
/// [`CardFirst`](crate::spool::WritePolicy::CardFirst) the volume holds the
/// *only* copy of everything past the point it took over, so wrapping is real
/// loss. Neither is reported as an error at the time it happens, because the
/// ring overwriting its tail is normal operation for a log. Watching this is how
/// an operator learns the swap window is closing while there is still time to
/// swap.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct VolumeFill {
    /// Sectors holding data — sealed, plus the one being written.
    pub used_sectors: u16,
    /// Sectors still erased. Writes have this much room before the ring starts
    /// reclaiming sectors that hold data.
    pub free_sectors: u16,
    /// Sectors in the volume's database region.
    pub total_sectors: u16,
    /// Entries the volume holds.
    pub entries: u32,
}

impl VolumeFill {
    /// Summarise a volume's statistics.
    pub fn from_stats(stats: &DbStats) -> Self {
        Self {
            used_sectors: stats.used_sectors,
            free_sectors: stats.free_sectors,
            total_sectors: stats.used_sectors.saturating_add(stats.free_sectors),
            entries: stats.total_entries,
        }
    }

    /// Fraction of the region holding data, in tenths of a percent (`0..=1000`).
    ///
    /// Tenths rather than percent because a large card has enough sectors that
    /// whole percent is a coarse warning, and this crate cannot use floats.
    /// Zero when the geometry is empty.
    pub fn used_permille(&self) -> u16 {
        if self.total_sectors == 0 {
            return 0;
        }
        ((self.used_sectors as u32 * 1000) / self.total_sectors as u32) as u16
    }

    /// No erased sectors remain, so the next sector rotation reclaims one that
    /// holds data.
    ///
    /// The last moment at which swapping the medium still costs nothing: the
    /// sector being written is not full yet, so this warns of loss rather than
    /// reporting it. A volume configured with enough reserved sectors refuses
    /// the write with `NoSpace` instead of overwriting, which is louder but
    /// arrives just as late.
    pub fn will_overwrite(&self) -> bool {
        self.free_sectors == 0
    }
}

/// Outcome of reading every slot in the cursor region.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct CursorScan {
    /// Safe source position to resume from.
    pub resume: LogPosition,
    /// Highest batch id found.
    pub last_batch_id: u32,
    /// Entries an unfinished batch may duplicate.
    pub in_flight: u32,
    /// Replica position the unfinished batch's first entry landed at.
    ///
    /// Reading the replica forward from here counts what the batch actually
    /// managed to store, which is what turns the [`in_flight`](Self::in_flight)
    /// bound into an exact answer. Meaningless when `in_flight` is zero.
    pub in_flight_dest: LogPosition,
    /// Cursor sector to append the next record to.
    pub active: u8,
    /// Next free slot in `active`.
    pub next_slot: u32,
    /// Whether any valid record was found at all.
    pub found: bool,
}

impl Default for CursorScan {
    fn default() -> Self {
        Self {
            resume: LogPosition::BEGINNING,
            last_batch_id: 0,
            in_flight: 0,
            in_flight_dest: LogPosition::BEGINNING,
            active: 0,
            next_slot: 0,
            found: false,
        }
    }
}

impl CursorScan {
    /// Where on the replica to read, and how far, to find what an interrupted
    /// batch actually stored.
    ///
    /// `None` when no batch was in flight, which is the ordinary case and the
    /// one that must cost no reads.
    ///
    /// The bound is deliberately **one past** the batch's budget: a run that
    /// comes back longer than the batch was ever allowed to copy proves `dest`
    /// is not describing this batch, and truncating the read at the budget would
    /// hide exactly that.
    pub(crate) fn landed_probe(&self) -> Option<(LogPosition, u32)> {
        (self.in_flight > 0).then_some((self.in_flight_dest, self.in_flight + 1))
    }

    /// Decide whether a run read from the replica may be reconciled against.
    ///
    /// Returns an empty fingerprint — meaning "reconcile nothing, replay the
    /// batch whole" — when the replica's own ring has wrapped past where the
    /// batch landed, so the run would begin with entries from earlier batches,
    /// or when it is longer than the batch's budget.
    ///
    /// Both fall back to duplicating rather than skipping, which is the rule the
    /// whole reconciliation is built on: duplication is bounded and visible, a
    /// wrong skip is silent loss.
    pub(crate) fn accept_landed(&self, run: RunFingerprint, cursor: &ReadCursor) -> RunFingerprint {
        if cursor.gap || run.entries() > self.in_flight {
            return RunFingerprint::new();
        }
        run
    }
}

/// A failure during a replication pass, tagged with which side it came from.
///
/// Both sides surface as [`Error::Flash`], and the two mean opposite things. A
/// *volume* flash error is treated as the medium having gone — a driver cannot
/// tell a yanked card from a genuine fault, both arrive as
/// `NorFlashErrorKind::Other`, so the spooler faults the volume and stops. A
/// *source* flash error says the device's own storage is failing and nothing
/// about the card; condemning the card for it would report the wrong part as
/// broken and force a needless detach while the real fault went unnoticed.
///
/// Internal to the drivers: it exists so that distinction survives the `?`
/// operator between an operation and the place that decides what to do.
#[derive(Debug)]
pub(crate) struct SpoolFailure {
    /// The error to report to the caller.
    pub error: Error,
    /// The failure came from reading the source log, not from the volume.
    pub from_source: bool,
}

impl From<Error> for SpoolFailure {
    /// Attribute an untagged failure to the **volume**.
    ///
    /// Most of a replication pass is volume work, so this is what makes a bare
    /// `?` correct there. It is also the safer default of the two: attributing a
    /// volume failure to the source would leave the spooler retrying against a
    /// medium that is no longer present, whereas the reverse merely
    /// over-reports. Source operations must still say so explicitly — see
    /// [`SpoolFailure::from_source`].
    fn from(error: Error) -> Self {
        Self {
            error,
            from_source: false,
        }
    }
}

impl SpoolFailure {
    /// Tag a result from an operation on the **source** log.
    pub fn from_source<T>(result: Result<T, Error>) -> Result<T, Self> {
        result.map_err(|error| Self {
            error,
            from_source: true,
        })
    }
}

/// Identity of a contiguous run of entries: how many, and which ones bound it.
///
/// Reconciling an interrupted batch means skipping, on the source, exactly the
/// entries the replica already holds. Getting that count *too low* costs
/// duplicates; getting it too high skips entries no replica ever received, which
/// is silent data loss. So the count is never trusted on its own: the run is
/// fingerprinted on both sides and the skip is abandoned unless they agree.
///
/// Two entries can legitimately share a sensor and a timestamp, so this is a
/// consistency check rather than a proof. It is enough to catch the failures
/// that matter — a `dest` that does not line up with where the batch began, and
/// a replica whose copy is not a prefix of the source range it claims.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct RunFingerprint {
    entries: u32,
    /// `(sensor_id, timestamp)` of the first entry in the run.
    first: (u16, u64),
    /// `(sensor_id, timestamp)` of the last.
    last: (u16, u64),
}

impl RunFingerprint {
    /// An empty run.
    pub fn new() -> Self {
        Self::default()
    }

    /// Note one more entry. Must be called in log order.
    pub fn push(&mut self, sensor_id: u16, timestamp: u64) {
        if self.entries == 0 {
            self.first = (sensor_id, timestamp);
        }
        self.last = (sensor_id, timestamp);
        self.entries += 1;
    }

    /// How many entries the run holds.
    pub fn entries(&self) -> u32 {
        self.entries
    }

    /// Whether the run is empty, in which case there is nothing to reconcile.
    pub fn is_empty(&self) -> bool {
        self.entries == 0
    }
}

/// The newest batch seen so far, and what its records proved.
#[derive(Debug, Clone, Copy)]
struct NewestBatch {
    batch_id: u32,
    /// Whether a commit record for this batch was read.
    committed: bool,
    /// Commit: entries copied. Intent: the budget.
    entries: u32,
    /// Replica position the batch's first entry landed at.
    dest: LogPosition,
    /// Cursor sector its records live in. A batch's intent and commit are always
    /// in the same sector — [`plan_slots`] moves to the other one rather than
    /// split a pair — so one sector per batch is well defined.
    sector: u8,
}

/// Folds cursor records into a [`CursorScan`] as they are read.
///
/// The driver reads slots in whatever order is convenient and feeds them here;
/// all the ordering logic lives in this type.
#[derive(Debug, Clone, Copy)]
pub struct CursorFold {
    scan: CursorScan,
    /// Slot after the last occupied one, per cursor sector.
    fill: [u32; CURSOR_SECTORS as usize],
    /// The newest batch any record named.
    newest_batch: Option<NewestBatch>,
}

impl Default for CursorFold {
    fn default() -> Self {
        Self::new()
    }
}

impl CursorFold {
    /// Start a fresh scan.
    pub fn new() -> Self {
        Self {
            scan: CursorScan::default(),
            fill: [0; CURSOR_SECTORS as usize],
            newest_batch: None,
        }
    }

    /// Note that a slot has been written to, whatever it now contains.
    ///
    /// This must be called for **every** slot that is not fully erased,
    /// including ones whose contents fail validation. A torn write leaves a slot
    /// with some bits cleared; NOR flash cannot write it again without an erase,
    /// so the next record has to go after it. Tracking only valid records would
    /// aim the next write straight at the damaged slot.
    pub fn occupied(&mut self, sector: u8, slot: u32) {
        let sector_idx = (sector % CURSOR_SECTORS) as usize;
        self.fill[sector_idx] = self.fill[sector_idx].max(slot + 1);
    }

    /// Offer one structurally valid record, read from `sector`/`slot`.
    ///
    /// Implies [`occupied`](Self::occupied). The caller must have checked
    /// [`SpoolCursorWire::is_valid`] and that the record belongs to the expected
    /// source log.
    pub fn record(&mut self, sector: u8, slot: u32, record: &SpoolCursorWire) {
        self.occupied(sector, slot);

        // The resume point is the highest any record can justify. Commits
        // contribute their end, intents only their start.
        let candidate = record.resume_point();
        if candidate > self.scan.resume {
            self.scan.resume = candidate;
        }

        let batch_id = record.batch_id.get();
        let is_commit = record.kind() == Some(CursorKind::Commit);
        let seen = NewestBatch {
            batch_id,
            committed: is_commit,
            entries: record.entry_count.get(),
            dest: record.dest(),
            sector: sector % CURSOR_SECTORS,
        };

        // Ordering is wrapping-aware, so a region spanning the point where the
        // batch counter rolled over still picks the true newest record.
        self.newest_batch = Some(match self.newest_batch {
            // Same batch: remember whether its commit made it to flash. An
            // intent and its commit carry the same `dest`, so either will do.
            Some(newest) if batch_id == newest.batch_id => NewestBatch {
                committed: newest.committed || is_commit,
                ..seen
            },
            Some(newest) if !batch_is_newer(batch_id, newest.batch_id) => newest,
            _ => seen,
        });

        self.scan.found = true;
    }

    /// Feed one slot's raw bytes, read from `at`.
    ///
    /// This is the whole of what a scan decides, so the drivers contribute only
    /// the read. Three rules, in order:
    ///
    /// - A slot with **any** bit cleared counts as [`occupied`](Self::occupied),
    ///   valid or not. NOR cannot rewrite it without an erase, so the next
    ///   record has to go after it; tracking only readable records would aim the
    ///   next write straight at a slot a torn write had damaged. Only the record
    ///   area can be dirty — the rest of the page is written as `0xFF`, which
    ///   clears nothing.
    /// - A record that fails [`is_valid`](SpoolCursorWire::is_valid) is skipped.
    ///   It still occupied its slot.
    /// - A record naming a **different** source log aborts the scan with
    ///   [`Error::ForeignVolume`]: this medium is not ours, however plausible
    ///   its database region looks. `expected == 0` (an anonymous log) or a
    ///   record's own `0` matches anything.
    ///
    /// # Errors
    /// - `CorruptCursor` if `buf` cannot be interpreted as a record at all
    /// - `ForeignVolume` if the slot belongs to a different log
    pub fn feed(
        &mut self,
        at: SlotAddress,
        buf: &[u8; CURSOR_RECORD_SIZE],
        expected: u32,
    ) -> Result<(), Error> {
        if buf.iter().all(|b| *b == 0xFF) {
            return Ok(());
        }
        self.occupied(at.sector, at.slot);

        let record = SpoolCursorWire::read_from_bytes(buf).map_err(|_| Error::CorruptCursor)?;
        if !record.is_valid() {
            return Ok(());
        }
        let found = record.source_log_id.get();
        if expected != 0 && found != 0 && found != expected {
            return Err(Error::ForeignVolume { expected, found });
        }
        self.record(at.sector, at.slot, &record);
        Ok(())
    }

    /// Finish the scan.
    pub fn finish(mut self) -> CursorScan {
        // Everything about "where writing continues" follows from the newest
        // batch, so it is derived here rather than accumulated per record —
        // the comparison that decides which batch that is has to see them all.
        if let Some(newest) = self.newest_batch {
            self.scan.last_batch_id = newest.batch_id;
            self.scan.active = newest.sector;
            // An intent whose commit never landed: that batch may have been
            // partly copied, so replaying it blind can duplicate up to its
            // budget. `dest` says where on the replica to look to find out how
            // much actually landed, which is what lets a driver replay exactly
            // the remainder.
            if !newest.committed {
                self.scan.in_flight = newest.entries;
                self.scan.in_flight_dest = newest.dest;
            }
        }
        // After `active`, which selects which sector's fill level applies.
        self.scan.next_slot = self.fill[self.scan.active as usize];
        self.scan
    }
}

/// Where the next pair of cursor records should go.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct SlotPlan {
    /// Cursor sector to write into.
    pub sector: u8,
    /// Slot for the intent record. The commit goes in `slot + 1`.
    pub slot: u32,
    /// Whether `sector` must be erased before writing.
    ///
    /// True only when wrapping to the other sector. The sector being left behind
    /// still holds valid records at that moment, so the resume point is never
    /// unrecoverable — which is exactly why the *target* is erased on the way in
    /// rather than the *source* on the way out.
    pub erase_first: bool,
}

/// Decide where the next batch's records go.
///
/// A batch needs two consecutive slots. When fewer than two remain, it moves to
/// the other cursor sector and erases it on arrival.
pub fn plan_slots(region: &CursorRegion, active: u8, next_slot: u32) -> SlotPlan {
    if next_slot + 2 <= region.slots_per_sector() {
        SlotPlan {
            sector: active % CURSOR_SECTORS,
            slot: next_slot,
            erase_first: false,
        }
    } else {
        SlotPlan {
            sector: (active + 1) % CURSOR_SECTORS,
            slot: 0,
            erase_first: true,
        }
    }
}

/// One replication batch, from planned to committed.
///
/// Produced by [`SpoolerState::plan_batch`] and consumed by
/// [`SpoolerState::commit_batch`], with the driver's reads and writes in
/// between. It is what keeps the two-record protocol stated once: which fields
/// an intent carries and which a commit fills in is the reason the cursor needs
/// two records at all, and it was previously written out in both drivers.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Batch {
    slots: SlotPlan,
    batch_id: u32,
    source_log: Option<LogId>,
    source_epoch: u32,
    from: LogPosition,
    dest: LogPosition,
    budget: SpoolBudget,
}

impl Batch {
    /// The cursor sector this batch's two records go in.
    pub(crate) fn sector(&self) -> u8 {
        self.slots.sector
    }

    /// Slot for the intent record.
    pub(crate) fn intent_slot(&self) -> u32 {
        self.slots.slot
    }

    /// Slot for the commit record.
    ///
    /// Always immediately after the intent: [`plan_slots`] moves to the other
    /// cursor sector rather than split a pair across the boundary, which is what
    /// lets [`CursorFold`] treat one sector per batch as well defined.
    pub(crate) fn commit_slot(&self) -> u32 {
        self.slots.slot + 1
    }

    /// The region-relative range to erase before writing, if any.
    pub(crate) fn erase(&self, region: &CursorRegion) -> Option<(u32, u32)> {
        self.slots
            .erase_first
            .then(|| region.sector_range(self.slots.sector))
    }

    /// The record written **before** anything is copied.
    ///
    /// It can only promise where the batch starts, so `upto` repeats `from` and
    /// the count is the *budget* — the most this batch may copy, which is what
    /// bounds duplication when the commit never lands.
    pub(crate) fn intent(&self) -> SpoolCursorWire {
        SpoolCursorWire::new(
            CursorKind::Intent,
            self.source_log,
            self.source_epoch,
            self.batch_id,
            self.from,
            self.from,
            self.budget.max_entries,
            self.dest,
            0,
        )
    }

    /// The record written **after** the copy is durable.
    ///
    /// `copied` is counted in **entries**, not samples: the cursor describes a
    /// range of the source log, and a run is one entry there however many
    /// samples it holds.
    pub(crate) fn commit(
        &self,
        upto: LogPosition,
        copied: Replicated,
        last_timestamp: u64,
    ) -> SpoolCursorWire {
        SpoolCursorWire::new(
            CursorKind::Commit,
            self.source_log,
            self.source_epoch,
            self.batch_id,
            self.from,
            upto,
            copied.entries,
            self.dest,
            last_timestamp,
        )
    }
}

/// The one source sector a batch is confined to.
///
/// A batch never spans two source sectors, so each cursor record names exactly
/// one source epoch — which is what lets a reader attribute copied entries to a
/// particular run of the source device, whose clock restarts at zero on every
/// boot. It usually costs nothing: a sector holds far more entries than a
/// typical [`SpoolBudget`].
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct BatchSector(Option<u32>);

impl BatchSector {
    /// A batch that has not seen an entry yet.
    pub(crate) fn new() -> Self {
        Self::default()
    }

    /// Whether an entry from source sector `sequence` still belongs to this
    /// batch, adopting that sector if it is the first entry offered.
    pub(crate) fn admits(&mut self, sequence: u32) -> bool {
        match self.0 {
            Some(seq) => seq == sequence,
            None => {
                self.0 = Some(sequence);
                true
            }
        }
    }
}

/// Everything a spooler knows that is not the volume itself.
///
/// The blocking and async spoolers hold one of these and supply only the reads
/// and writes around it: `attach` is a cursor scan fed to [`CursorFold`] and
/// [`adopt_scan`](Self::adopt_scan); `reconcile` is
/// [`take_pending`](Self::take_pending) → a source read →
/// [`accept_skip`](Self::accept_skip); and a `spool` pass is
/// [`plan_batch`](Self::plan_batch) → erase, intent, copy, sync, commit →
/// [`commit_batch`](Self::commit_batch).
///
/// **A spooler method that is more than I/O choreography belongs here instead.**
/// The two drivers are unrelated trait families, so their flash calls cannot be
/// shared — but a decision duplicated between them is invisible to
/// `tests/tiered_async.rs`, which asserts the two produce identical media and
/// therefore calls a bug present in both correct. That has happened: the
/// `attach`-before-`reconcile` ordering bug lived in exactly this code.
#[derive(Debug, Clone, Copy)]
pub(crate) struct SpoolerState {
    source_log: Option<LogId>,
    region: CursorRegion,
    /// Cursor sector currently being appended to.
    active: u8,
    /// Next free slot in `active`.
    next_slot: u32,
    /// Highest batch id written so far.
    last_batch_id: u32,
    /// Source position replication resumes from.
    resume: LogPosition,
    /// The part of an interrupted batch already durable on the replica.
    pending: RunFingerprint,
}

impl SpoolerState {
    /// State for a fresh spooler with no volume attached.
    ///
    /// # Errors
    /// - `InvalidConfig` if the geometry cannot hold cursor records
    /// - `Overflow` if the region runs past the end of the address space
    pub(crate) fn new(
        source_log: Option<LogId>,
        cursor_base: u32,
        sector_size: u32,
        page_size: u32,
    ) -> Result<Self, Error> {
        Ok(Self {
            source_log,
            region: CursorRegion::new(cursor_base, sector_size, page_size)?,
            active: 0,
            next_slot: 0,
            last_batch_id: 0,
            resume: LogPosition::BEGINNING,
            pending: RunFingerprint::new(),
        })
    }

    /// Identity of the log being replicated.
    pub(crate) fn source_log(&self) -> Option<LogId> {
        self.source_log
    }

    /// The log id a cursor record must carry, or 0 for an anonymous log.
    pub(crate) fn expected_log(&self) -> u32 {
        self.source_log.map_or(0, LogId::get)
    }

    /// Layout of the cursor region on the volume.
    pub(crate) fn region(&self) -> &CursorRegion {
        &self.region
    }

    /// Source position replication resumes from.
    pub(crate) fn resume(&self) -> LogPosition {
        self.resume
    }

    /// Entries an attach found on the replica that the next pass will skip.
    pub(crate) fn pending_reconciliation(&self) -> u32 {
        self.pending.entries()
    }

    /// Adopt what a cursor scan and a replica read found, and describe it.
    pub(crate) fn adopt_scan(&mut self, scan: CursorScan, landed: RunFingerprint) -> Attached {
        self.active = scan.active;
        self.next_slot = scan.next_slot;
        self.last_batch_id = scan.last_batch_id;
        self.resume = scan.resume;
        self.pending = landed;

        Attached {
            resume_from: scan.resume,
            batch_id: scan.last_batch_id,
            in_flight_entries: scan.in_flight,
            recovered_entries: landed.entries(),
            fresh: !scan.found,
        }
    }

    /// Forget the volume that is leaving.
    ///
    /// The resume point and the pending reconciliation both describe *that*
    /// medium — the cursor lives on the replica precisely so two cards can be
    /// rotated with no local state — so the next attach recomputes them.
    pub(crate) fn reset(&mut self) {
        self.resume = LogPosition::BEGINNING;
        self.pending = RunFingerprint::new();
    }

    /// Take the interrupted batch's fingerprint, leaving nothing behind.
    ///
    /// Taking rather than reading is what makes reconciliation idempotent: an
    /// attempt that is abandoned must not be retried on the next pass, because
    /// the resume point it would be judged against has since moved.
    pub(crate) fn take_pending(&mut self) -> RunFingerprint {
        core::mem::take(&mut self.pending)
    }

    /// Decide whether the source run just read may be skipped as already
    /// replicated, advancing the resume point if so.
    ///
    /// The skip is abandoned — leaving the batch to replay whole — when the
    /// source ring has wrapped past the resume point, so the entries the replica
    /// holds are gone and skipping the same *count* from the new tail would step
    /// over entries that were never copied; or when the two runs do not
    /// [fingerprint](RunFingerprint) alike.
    ///
    /// Both fall back to duplicating, never to skipping.
    pub(crate) fn accept_skip(
        &mut self,
        landed: &RunFingerprint,
        found: &RunFingerprint,
        cursor: &ReadCursor,
    ) -> bool {
        if cursor.gap || found != landed {
            return false;
        }
        self.resume = cursor.next;
        true
    }

    /// Plan the next batch: where its records go, and what they will say.
    pub(crate) fn plan_batch(
        &self,
        source_epoch: u32,
        dest: LogPosition,
        budget: SpoolBudget,
    ) -> Batch {
        Batch {
            slots: plan_slots(&self.region, self.active, self.next_slot),
            batch_id: self.last_batch_id.wrapping_add(1),
            source_log: self.source_log,
            source_epoch,
            from: self.resume,
            dest,
            budget,
        }
    }

    /// Adopt a batch whose commit record is durable.
    ///
    /// **Only after the commit write succeeds.** Advancing `resume` is what
    /// lets the source reclaim those sectors, so doing it any earlier trades the
    /// crate's one hard guarantee — no loss — for nothing.
    pub(crate) fn commit_batch(&mut self, batch: &Batch, upto: LogPosition) {
        self.active = batch.slots.sector;
        self.next_slot = batch.commit_slot() + 1;
        self.last_batch_id = batch.batch_id;
        self.resume = upto;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn region() -> CursorRegion {
        CursorRegion::new(0, 4096, 256).unwrap()
    }

    fn pos(sequence: u32, offset: u32) -> LogPosition {
        LogPosition { sequence, offset }
    }

    /// Replica position a batch's records name. Derived from the batch id so
    /// each batch has a distinguishable one. Wrapping so the batch ids near
    /// `u32::MAX` used by the wrap tests do not overflow it.
    fn dest_of(batch_id: u32) -> LogPosition {
        pos(100u32.wrapping_add(batch_id), 28)
    }

    fn intent(batch_id: u32, from: LogPosition, budget: u32) -> SpoolCursorWire {
        SpoolCursorWire::new(
            CursorKind::Intent,
            LogId::new(1),
            1,
            batch_id,
            from,
            from,
            budget,
            dest_of(batch_id),
            0,
        )
    }

    fn commit(batch_id: u32, from: LogPosition, upto: LogPosition, n: u32) -> SpoolCursorWire {
        SpoolCursorWire::new(
            CursorKind::Commit,
            LogId::new(1),
            1,
            batch_id,
            from,
            upto,
            n,
            dest_of(batch_id),
            0,
        )
    }

    #[test]
    fn an_empty_region_resumes_from_the_beginning() {
        let scan = CursorFold::new().finish();
        assert!(!scan.found);
        assert_eq!(scan.resume, LogPosition::BEGINNING);
        assert_eq!(scan.next_slot, 0);
        assert_eq!(scan.in_flight, 0);
    }

    #[test]
    fn a_completed_batch_resumes_after_it() {
        let mut fold = CursorFold::new();
        fold.record(0, 0, &intent(1, pos(1, 28), 64));
        fold.record(0, 1, &commit(1, pos(1, 28), pos(1, 900), 40));
        let scan = fold.finish();

        assert_eq!(scan.resume, pos(1, 900), "the commit is authoritative");
        assert_eq!(scan.last_batch_id, 1);
        assert_eq!(scan.next_slot, 2);
        assert_eq!(scan.in_flight, 0, "the batch finished");
    }

    #[test]
    fn an_unfinished_batch_reports_where_on_the_replica_it_landed() {
        let mut fold = CursorFold::new();
        fold.record(0, 0, &intent(1, pos(1, 28), 64));
        fold.record(0, 1, &commit(1, pos(1, 28), pos(1, 900), 40));
        fold.record(0, 2, &intent(2, pos(1, 900), 64));
        let scan = fold.finish();

        assert_eq!(
            scan.in_flight_dest,
            dest_of(2),
            "reconciling batch 2 means reading the replica from where it began"
        );
    }

    #[test]
    fn a_finished_batch_reports_no_replica_position() {
        let mut fold = CursorFold::new();
        fold.record(0, 0, &intent(1, pos(1, 28), 64));
        fold.record(0, 1, &commit(1, pos(1, 28), pos(1, 900), 40));
        let scan = fold.finish();

        assert_eq!(scan.in_flight, 0);
        assert_eq!(
            scan.in_flight_dest,
            LogPosition::BEGINNING,
            "nothing to reconcile, so nothing to read"
        );
    }

    #[test]
    fn an_intent_and_its_commit_agree_on_the_replica_position() {
        // The commit copies `dest` from the intent, so a fold that sees only one
        // of them must reach the same answer as one that sees both.
        let mut intent_only = CursorFold::new();
        intent_only.record(0, 0, &intent(3, pos(2, 28), 64));

        let mut both = CursorFold::new();
        both.record(0, 0, &intent(3, pos(2, 28), 64));
        both.record(0, 1, &commit(3, pos(2, 28), pos(2, 500), 20));

        assert_eq!(intent_only.finish().in_flight_dest, dest_of(3));
        assert_eq!(both.finish().in_flight, 0);
    }

    #[test]
    fn a_run_fingerprint_distinguishes_length_and_bounds() {
        let mut a = RunFingerprint::new();
        assert!(a.is_empty());
        for (sensor, ts) in [(1u16, 10u64), (1, 11), (2, 12)] {
            a.push(sensor, ts);
        }
        assert_eq!(a.entries(), 3);
        assert!(!a.is_empty());

        // Same entries: identical.
        let mut same = RunFingerprint::new();
        for (sensor, ts) in [(1u16, 10u64), (1, 11), (2, 12)] {
            same.push(sensor, ts);
        }
        assert_eq!(a, same);

        // A shorter run, a different start, and a different end all differ.
        let mut shorter = RunFingerprint::new();
        for (sensor, ts) in [(1u16, 10u64), (1, 11)] {
            shorter.push(sensor, ts);
        }
        assert_ne!(a, shorter);

        let mut shifted = RunFingerprint::new();
        for (sensor, ts) in [(1u16, 11u64), (2, 12), (2, 13)] {
            shifted.push(sensor, ts);
        }
        assert_ne!(a, shifted, "a run starting one entry late must not match");

        let mut other_end = RunFingerprint::new();
        for (sensor, ts) in [(1u16, 10u64), (1, 11), (2, 99)] {
            other_end.push(sensor, ts);
        }
        assert_ne!(a, other_end);
    }

    #[test]
    fn a_torn_commit_falls_back_to_the_intent_start() {
        // The crash case: the intent is durable, the data may be partly copied,
        // and the commit never landed.
        let mut fold = CursorFold::new();
        fold.record(0, 0, &intent(1, pos(1, 28), 64));
        fold.record(0, 1, &commit(1, pos(1, 28), pos(1, 900), 40));
        fold.record(0, 2, &intent(2, pos(1, 900), 64));
        let scan = fold.finish();

        assert_eq!(
            scan.resume,
            pos(1, 900),
            "resume where the unfinished batch began, so nothing is skipped"
        );
        assert_eq!(scan.last_batch_id, 2);
        assert_eq!(
            scan.in_flight, 64,
            "the unfinished batch may have copied up to its budget"
        );
    }

    #[test]
    fn a_lost_commit_is_recovered_from_the_next_intent() {
        // batch 1's commit is missing entirely, but batch 2's intent records the
        // same position by construction, so no data is re-copied unnecessarily.
        let mut fold = CursorFold::new();
        fold.record(0, 0, &intent(1, pos(1, 28), 64));
        fold.record(0, 2, &intent(2, pos(1, 900), 64));
        fold.record(0, 3, &commit(2, pos(1, 900), pos(2, 300), 30));
        let scan = fold.finish();

        assert_eq!(scan.resume, pos(2, 300));
        assert_eq!(scan.in_flight, 0);
    }

    #[test]
    fn record_order_does_not_matter() {
        let records = [
            (0u8, 0u32, intent(1, pos(1, 28), 64)),
            (0, 1, commit(1, pos(1, 28), pos(1, 900), 40)),
            (0, 2, intent(2, pos(1, 900), 64)),
            (0, 3, commit(2, pos(1, 900), pos(2, 300), 30)),
        ];

        let mut forward = CursorFold::new();
        for (s, i, r) in records.iter() {
            forward.record(*s, *i, r);
        }
        let mut backward = CursorFold::new();
        for (s, i, r) in records.iter().rev() {
            backward.record(*s, *i, r);
        }
        assert_eq!(forward.finish(), backward.finish());
    }

    #[test]
    fn the_newest_batch_wins_across_cursor_sectors() {
        // After a wrap, the old sector still holds lower-numbered batches.
        let mut fold = CursorFold::new();
        fold.record(0, 14, &commit(9, pos(4, 28), pos(4, 900), 10));
        fold.record(1, 0, &intent(10, pos(4, 900), 64));
        fold.record(1, 1, &commit(10, pos(4, 900), pos(5, 100), 20));
        let scan = fold.finish();

        assert_eq!(scan.active, 1, "writing continues in the newer sector");
        assert_eq!(scan.next_slot, 2);
        assert_eq!(scan.resume, pos(5, 100));
        assert_eq!(scan.last_batch_id, 10);
    }

    #[test]
    fn a_torn_slot_still_consumes_its_place() {
        // A slot damaged by an interrupted write cannot be written again without
        // an erase, so the next record must go after it — even though nothing
        // valid was ever read from it.
        let mut fold = CursorFold::new();
        fold.record(0, 0, &intent(1, pos(1, 28), 64));
        fold.record(0, 1, &commit(1, pos(1, 28), pos(1, 900), 40));
        fold.record(0, 2, &intent(2, pos(1, 900), 64));
        fold.occupied(0, 3); // torn commit for batch 2
        let scan = fold.finish();

        assert_eq!(scan.next_slot, 4, "the damaged slot is not reusable");
        assert_eq!(scan.resume, pos(1, 900), "and its batch replays");
        assert_eq!(scan.in_flight, 64);
    }

    #[test]
    fn a_region_holding_only_a_torn_slot_skips_past_it() {
        let mut fold = CursorFold::new();
        fold.occupied(0, 0);
        let scan = fold.finish();

        assert!(!scan.found, "no valid record was read");
        assert_eq!(scan.resume, LogPosition::BEGINNING);
        assert_eq!(scan.next_slot, 1, "but slot 0 is spent");
    }

    #[test]
    fn batch_ordering_is_serial_not_numeric() {
        assert!(batch_is_newer(2, 1));
        assert!(!batch_is_newer(1, 2));
        assert!(!batch_is_newer(7, 7), "a batch is not newer than itself");

        // The point of the exercise: across the wrap, the smaller number is the
        // newer batch.
        assert!(batch_is_newer(0, u32::MAX));
        assert!(batch_is_newer(3, u32::MAX - 3));
        assert!(!batch_is_newer(u32::MAX, 0));
    }

    #[test]
    fn the_newest_batch_survives_the_counter_wrapping() {
        // Sector 0 holds the last batches before the counter wrapped; sector 1
        // holds the first ones after. Comparing ids with `<` reads this exactly
        // backwards — it calls u32::MAX the newest — and so would name sector 0
        // as active. The next batch would then be planned into sector 0 and,
        // once it filled, `plan_slots` would erase sector 1: the one holding the
        // true resume point.
        let mut fold = CursorFold::new();
        fold.record(0, 0, &intent(u32::MAX - 1, pos(1, 28), 64));
        fold.record(0, 1, &commit(u32::MAX - 1, pos(1, 28), pos(1, 500), 20));
        fold.record(0, 2, &intent(u32::MAX, pos(1, 500), 64));
        fold.record(0, 3, &commit(u32::MAX, pos(1, 500), pos(1, 900), 20));
        fold.record(1, 0, &intent(0, pos(1, 900), 64));
        fold.record(1, 1, &commit(0, pos(1, 900), pos(2, 300), 20));
        fold.record(1, 2, &intent(1, pos(2, 300), 64));
        fold.record(1, 3, &commit(1, pos(2, 300), pos(2, 700), 20));
        let scan = fold.finish();

        assert_eq!(
            scan.active, 1,
            "writing continues where the newest batch is"
        );
        assert_eq!(scan.next_slot, 4);
        assert_eq!(scan.last_batch_id, 1);
        assert_eq!(scan.resume, pos(2, 700));
    }

    #[test]
    fn an_unfinished_batch_is_still_detected_across_the_wrap() {
        // The dangerous half of the same bug: a torn commit on the batch *after*
        // the wrap. Numeric ordering would call u32::MAX the newest batch, see
        // its commit, and report nothing in flight — so reconciliation would not
        // run and the interrupted batch would replay whole, duplicating.
        let mut fold = CursorFold::new();
        fold.record(0, 0, &intent(u32::MAX, pos(1, 28), 64));
        fold.record(0, 1, &commit(u32::MAX, pos(1, 28), pos(1, 900), 20));
        fold.record(1, 0, &intent(0, pos(1, 900), 64));
        let scan = fold.finish();

        assert_eq!(scan.in_flight, 64, "batch 0 is the newest, and unfinished");
        assert_eq!(scan.in_flight_dest, dest_of(0));
        assert_eq!(scan.resume, pos(1, 900), "the interrupted batch replays");
        assert_eq!(scan.active, 1);
    }

    #[test]
    fn a_wrapped_region_folds_the_same_in_any_order() {
        let records = [
            (0u8, 2u32, intent(u32::MAX, pos(1, 500), 64)),
            (0, 3, commit(u32::MAX, pos(1, 500), pos(1, 900), 20)),
            (1, 0, intent(0, pos(1, 900), 64)),
            (1, 1, commit(0, pos(1, 900), pos(2, 300), 20)),
        ];

        let mut forward = CursorFold::new();
        for (s, i, r) in records.iter() {
            forward.record(*s, *i, r);
        }
        let mut backward = CursorFold::new();
        for (s, i, r) in records.iter().rev() {
            backward.record(*s, *i, r);
        }
        assert_eq!(forward.finish(), backward.finish());
    }

    #[test]
    fn volume_fill_reports_headroom_and_the_last_moment_to_swap() {
        let fill = VolumeFill::from_stats(&DbStats {
            total_entries: 4200,
            total_samples: 4200,
            used_sectors: 6,
            free_sectors: 2,
            reserved_sectors: 1,
            min_erase_count: 1,
            max_erase_count: 1,
            total_erase_count: 8,
        });

        assert_eq!(fill.total_sectors, 8);
        assert_eq!(fill.entries, 4200);
        assert_eq!(fill.used_permille(), 750);
        assert!(!fill.will_overwrite(), "two sectors of headroom remain");

        let full = VolumeFill::from_stats(&DbStats {
            used_sectors: 8,
            free_sectors: 0,
            ..DbStats {
                total_entries: 0,
                total_samples: 0,
                used_sectors: 0,
                free_sectors: 0,
                reserved_sectors: 0,
                min_erase_count: 0,
                max_erase_count: 0,
                total_erase_count: 0,
            }
        });
        assert_eq!(full.used_permille(), 1000);
        assert!(
            full.will_overwrite(),
            "the next rotation reclaims a sector holding data"
        );

        // An empty geometry must not divide by zero.
        assert_eq!(VolumeFill::default().used_permille(), 0);
    }

    #[test]
    fn a_batch_is_confined_to_the_first_source_sector_it_sees() {
        let mut batch = BatchSector::new();
        // The first entry chooses the sector; it can never be refused.
        assert!(batch.admits(7));
        assert!(batch.admits(7));

        // The next sector ends the batch — and keeps ending it, so a caller that
        // asks twice does not accidentally adopt the new sector.
        assert!(!batch.admits(8));
        assert!(!batch.admits(8));
        assert!(batch.admits(7), "the batch still belongs to sector 7");

        // A batch that has seen nothing adopts whatever it is offered, including
        // sector 0 — which an `Option`-free `u32` sentinel would get wrong.
        let mut from_zero = BatchSector::new();
        assert!(from_zero.admits(0));
        assert!(!from_zero.admits(1));
    }

    #[test]
    fn slots_are_allocated_in_pairs_then_wrap_to_the_other_sector() {
        let region = region();
        assert_eq!(region.slots_per_sector(), 16);

        let plan = plan_slots(&region, 0, 0);
        assert_eq!(
            plan,
            SlotPlan {
                sector: 0,
                slot: 0,
                erase_first: false
            }
        );

        // 14 leaves room for exactly one more pair.
        let plan = plan_slots(&region, 0, 14);
        assert_eq!(
            plan,
            SlotPlan {
                sector: 0,
                slot: 14,
                erase_first: false
            }
        );

        // 15 does not: a pair would not fit, so wrap and erase on arrival.
        let plan = plan_slots(&region, 0, 15);
        assert_eq!(
            plan,
            SlotPlan {
                sector: 1,
                slot: 0,
                erase_first: true
            }
        );

        // ...and back again.
        let plan = plan_slots(&region, 1, 16);
        assert_eq!(
            plan,
            SlotPlan {
                sector: 0,
                slot: 0,
                erase_first: true
            }
        );
    }
}