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
//! Blocking store-and-forward drivers: [`Spooler`] and [`TieredDb`].

use embedded_storage::nor_flash::{NorFlash, ReadNorFlash};
use zerocopy::IntoBytes;

use crate::db::{LogPosition, Replicated, SensorDb, SpoolStats};
use crate::entry::EntryHeader;
use crate::error::Error;
use crate::run::{Run, deliver_samples, samples_in};
use crate::sector::LogId;
use crate::spool::cursor::{CURSOR_RECORD_SIZE, CursorRegion, SpoolCursorWire};
use crate::spool::policy::{
    Attached, BatchSector, CursorFold, CursorScan, EraseTally, RunFingerprint, SpoolBudget,
    SpoolFailure, SpoolProgress, SpoolerState, VolumeFill,
};
use crate::spool::port::Removable;
use crate::spool::tier::{
    PROMOTE_MAX_BATCHES, TierMode, WriteMode, WritePolicy, merge, volume_gone,
};

/// State of the removable volume the spooler owns.
///
/// Modelled as a type rather than an `Option` plus a flag so that "attached but
/// broken" cannot be confused with "attached and usable".
enum Slot<C, const PAGE_SIZE: usize, const MAX_SECTORS: usize> {
    /// Nothing attached.
    Empty,
    /// Attached and usable.
    Ready(SensorDb<C, PAGE_SIZE, MAX_SECTORS>),
    /// A flash operation failed. The database is retained so the application can
    /// still detach and inspect it, but no further replication is attempted.
    Faulted(SensorDb<C, PAGE_SIZE, MAX_SECTORS>),
}

/// Copies a log onto a removable volume, and remembers how far it got.
///
/// The spooler owns the volume and borrows the source on each pass, which
/// matches the physical situation: the card comes and goes, the spooler is the
/// long-lived thing.
///
/// # What it guarantees
///
/// - **No loss.** The source's replication watermark advances only after the
///   replica's copy is durable, so an interruption anywhere re-copies rather
///   than skips.
/// - **Bounded duplication.** A power cut or an unclean removal replays at most
///   the batch that was in flight — [`SpoolBudget::max_entries`] entries.
/// - **In practice, none.** [`attach`](Self::attach) reads the replica to find
///   how much of an interrupted batch it kept, and [`reconcile`](Self::reconcile)
///   skips exactly that much on the source. The bound above is what remains when
///   the two sides cannot be made to agree.
/// - **Nothing is written to a foreign volume.** A medium belonging to a
///   different log is rejected at [`attach`](Self::attach).
///
/// # RAM
///
/// One page buffer for cursor records, plus about 64 bytes of state.
pub struct Spooler<C, const PAGE_SIZE: usize, const MAX_SECTORS: usize> {
    slot: Slot<C, PAGE_SIZE, MAX_SECTORS>,
    /// Every decision this spooler makes, shared verbatim with the async one.
    state: SpoolerState,
    scratch: [u8; PAGE_SIZE],
}

/// Inspection that needs no flash access, and therefore no trait bounds.
impl<C, const PAGE_SIZE: usize, const MAX_SECTORS: usize> Spooler<C, PAGE_SIZE, MAX_SECTORS> {
    /// Whether a volume is attached, faulted or not.
    pub fn is_attached(&self) -> bool {
        !matches!(self.slot, Slot::Empty)
    }

    /// Whether the attached volume has faulted and needs detaching.
    pub fn is_faulted(&self) -> bool {
        matches!(self.slot, Slot::Faulted(_))
    }

    /// Source position replication will resume from, if a volume is attached.
    pub fn resume_point(&self) -> Option<LogPosition> {
        self.is_attached().then(|| self.state.resume())
    }

    /// Identity of the log this spooler replicates.
    pub fn source_log(&self) -> Option<LogId> {
        self.state.source_log()
    }

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

    /// Entries of an interrupted batch that the replica already holds and the
    /// next pass will skip rather than copy again.
    ///
    /// Non-zero only between an [`attach`](Self::attach) that found an
    /// unfinished batch and the [`reconcile`](Self::reconcile) or
    /// [`spool`](Self::spool) that applies the skip.
    pub fn pending_reconciliation(&self) -> u32 {
        self.state.pending_reconciliation()
    }
}

impl<C, const PAGE_SIZE: usize, const MAX_SECTORS: usize> Spooler<C, PAGE_SIZE, MAX_SECTORS>
where
    C: NorFlash + ReadNorFlash,
{
    /// Create a spooler for a log with the given identity.
    ///
    /// `cursor_base` is a byte offset on the *volume*, and the region it names
    /// must lie **outside** the volume's database region — the cursor is
    /// metadata about the copy, not part of the copied log.
    ///
    /// That is checked, not merely documented: every cursor access goes through
    /// [`SensorDb::with_region`](crate::SensorDb::with_region), so a region that
    /// intersects the volume's sectors fails [`attach`](Self::attach) with
    /// [`Error::RegionOverlap`] instead of overwriting replicated entries. The
    /// check lands at `attach` rather than here because a spooler does not know
    /// the volume's geometry until one is attached.
    ///
    /// # Arguments
    /// - `source_log`: identity of the log being replicated. A volume carrying
    ///   cursor records for a different log is rejected at
    ///   [`attach`](Self::attach).
    /// - `cursor_base`: start of the two-sector cursor region on the volume
    /// - `sector_size`: the volume's erase size
    ///
    /// # Errors
    /// - `InvalidConfig` if the geometry cannot hold cursor records
    /// - `Overflow` if the region runs past the end of the address space
    pub fn new(
        source_log: Option<LogId>,
        cursor_base: u32,
        sector_size: u32,
    ) -> Result<Self, Error> {
        Ok(Self {
            slot: Slot::Empty,
            state: SpoolerState::new(source_log, cursor_base, sector_size, PAGE_SIZE as u32)?,
            scratch: [0xFF; PAGE_SIZE],
        })
    }

    /// Attach a mounted volume and read its cursor.
    ///
    /// The application mounts the volume itself, because only it knows whether
    /// the volume should be indexed for reads
    /// ([`MountMode`](crate::db::MountMode)).
    ///
    /// # Reconciling an interrupted batch
    ///
    /// When the newest cursor record is an intent with no commit, the batch it
    /// describes was cut short somewhere — but the replica itself knows exactly
    /// how far it got. The intent names the replica position its first entry
    /// landed at, so reading the replica forward from there counts what survived.
    /// That count is remembered and skipped on the source side by
    /// [`reconcile`](Self::reconcile), which the next [`spool`](Self::spool)
    /// pass calls if the application has not.
    ///
    /// This is what makes reinsertion exactly-once rather than at-least-once.
    /// It degrades to the old bounded-duplicate behaviour when the count cannot
    /// be trusted — see [`Attached::recovered_entries`].
    ///
    /// # Errors
    /// - `AlreadyAttached` if a volume is already attached
    /// - `NotMounted` if the volume has not been mounted
    /// - `ForeignVolume` if its cursor belongs to a different log
    pub fn attach(
        &mut self,
        volume: SensorDb<C, PAGE_SIZE, MAX_SECTORS>,
    ) -> Result<Attached, Error> {
        if !matches!(self.slot, Slot::Empty) {
            return Err(Error::AlreadyAttached);
        }
        if !volume.is_mounted() {
            return Err(Error::NotMounted);
        }

        let mut volume = volume;
        // Attaching to a spooler *is* the declaration that this volume is a
        // replica. Without this it would roll a fresh sector on the first
        // appended entry after every insertion, to record an epoch that means
        // nothing here — and on a full ring that evicts the oldest sector each
        // time the card goes in.
        volume.mark_as_replica();
        let scan = scan_cursor(&mut volume, &self.state)?;
        let landed = fingerprint_landed(&mut volume, &scan)?;

        let attached = self.state.adopt_scan(scan, landed);
        self.slot = Slot::Ready(volume);
        Ok(attached)
    }

    /// Skip the part of an interrupted batch the replica already holds.
    ///
    /// Reads the source forward over exactly the entries
    /// [`attach`](Self::attach) found durable on the replica and advances the
    /// resume point past them, so the next pass copies only the remainder.
    /// Without this the whole batch replays and the replica ends up holding
    /// duplicates — bounded by [`SpoolBudget::max_entries`], but real.
    ///
    /// Idempotent and cheap: a no-op unless an attach found an unfinished batch,
    /// and the next [`spool`](Self::spool) calls it anyway. Call it directly only
    /// to see the reconciled resume point before spooling — as
    /// [`TieredDb::attach`] does, so the watermark it restores is exact.
    ///
    /// The skip is abandoned, leaving the batch to replay whole, whenever the
    /// two sides do not agree:
    ///
    /// - 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;
    /// - the source run does not [fingerprint](RunFingerprint) the same as the
    ///   replica's copy of it.
    ///
    /// Both fall back to duplicating, never to skipping. Duplication is bounded
    /// and visible; a wrong skip is silent loss.
    ///
    /// # Returns
    /// The number of entries skipped.
    ///
    /// [`TieredDb::attach`]: crate::spool::TieredDb::attach
    pub fn reconcile<S, const SP: usize, const SS: usize>(
        &mut self,
        source: &mut SensorDb<S, SP, SS>,
    ) -> Result<u32, Error>
    where
        S: NorFlash + ReadNorFlash,
    {
        let landed = self.state.take_pending();
        if landed.is_empty() {
            return Ok(0);
        }

        let mut found = RunFingerprint::new();
        let mut moved = Replicated::NONE;
        let cursor = source.read_from(
            self.state.resume(),
            landed.entries(),
            |_, header, payload| {
                found.push(header.sensor_id, header.timestamp);
                moved.push(samples_in(header.is_run(), payload));
                Ok(true)
            },
        )?;
        if !self.state.accept_skip(&landed, &found, &cursor) {
            return Ok(0);
        }

        // These entries are on the replica; the source may reclaim their sectors.
        source.note_spooled(cursor.next, moved);
        Ok(cursor.entries)
    }

    /// Mark the attached volume faulted and borrow it.
    ///
    /// Returns the volume so the caller can still reach data held in its RAM
    /// page buffer — which survives the medium being physically pulled, because
    /// the processor is still running. Returns `None` when nothing is attached.
    pub fn fault(&mut self) -> Option<&mut SensorDb<C, PAGE_SIZE, MAX_SECTORS>> {
        // Only move out of the slot when there is something to transition.
        // Taking unconditionally would drop an already-faulted volume on the
        // floor, along with whatever it still held in RAM.
        if matches!(self.slot, Slot::Ready(_))
            && let Slot::Ready(volume) = core::mem::replace(&mut self.slot, Slot::Empty)
        {
            self.slot = Slot::Faulted(volume);
        }
        match &mut self.slot {
            Slot::Faulted(volume) => Some(volume),
            _ => None,
        }
    }

    /// Detach the volume, returning it to the application.
    ///
    /// Also clears a fault, so a volume that errored can be re-attached after
    /// the application has decided what to do about it.
    pub fn detach(&mut self) -> Option<SensorDb<C, PAGE_SIZE, MAX_SECTORS>> {
        let taken = core::mem::replace(&mut self.slot, Slot::Empty);
        self.state.reset();
        match taken {
            Slot::Empty => None,
            Slot::Ready(volume) | Slot::Faulted(volume) => Some(volume),
        }
    }

    /// The attached volume, if it is usable.
    pub fn volume(&self) -> Option<&SensorDb<C, PAGE_SIZE, MAX_SECTORS>> {
        match &self.slot {
            Slot::Ready(v) => Some(v),
            _ => None,
        }
    }

    /// The attached volume, if it is usable.
    pub fn volume_mut(&mut self) -> Option<&mut SensorDb<C, PAGE_SIZE, MAX_SECTORS>> {
        match &mut self.slot {
            Slot::Ready(v) => Some(v),
            _ => None,
        }
    }

    /// How much room is left on the attached volume.
    ///
    /// `None` when nothing is attached. A **faulted** volume still answers, from
    /// the index it had when it faulted: how full the medium was at the moment
    /// it went is exactly what an operator wants to know afterwards.
    pub fn volume_fill(&self) -> Option<VolumeFill> {
        let volume = match &self.slot {
            Slot::Empty => return None,
            Slot::Ready(v) | Slot::Faulted(v) => v,
        };
        Some(VolumeFill::from_stats(&volume.stats()))
    }

    /// Copy up to `budget.max_entries` durable source entries onto the volume.
    ///
    /// A batch never spans two source sectors, so each cursor record names
    /// exactly one source epoch. That usually costs nothing — a sector holds far
    /// more entries than a typical budget — and it is what lets a reader
    /// attribute copied entries to a particular run of the source device.
    ///
    /// Only entries that are already durable on the source are copied. Call
    /// [`SensorDb::sync`] on the source first to include its buffered tail.
    ///
    /// # Errors
    /// - `NotAttached` if no volume is attached
    /// - `VolumeLost` if the volume errored; detach and re-attach to recover
    /// - `GeometryMismatch` if the volume's pages are smaller than the source's
    pub fn spool<S, const SP: usize, const SS: usize>(
        &mut self,
        source: &mut SensorDb<S, SP, SS>,
        budget: SpoolBudget,
    ) -> Result<SpoolProgress, Error>
    where
        S: NorFlash + ReadNorFlash,
    {
        // Checked before any I/O, and before the intent record: an entry near
        // the source's maximum payload could never be copied onto a volume with
        // smaller pages, so the spooler would livelock retrying it forever.
        if SP > PAGE_SIZE {
            return Err(Error::GeometryMismatch);
        }

        match self.slot {
            Slot::Empty => return Err(Error::NotAttached),
            Slot::Faulted(_) => return Err(Error::VolumeLost),
            Slot::Ready(_) => {}
        }

        match self.spool_inner(source, budget) {
            Ok(progress) => Ok(progress),
            // A flash error on the *volume* is treated as "the volume is gone".
            // A driver cannot distinguish a yanked card from a genuine fault —
            // both surface as `NorFlashErrorKind::Other` — so this is a policy
            // decision, not a hardware report. Drivers that *can* tell the
            // difference should implement `Removable` and use `spool_if_present`.
            //
            // A flash error on the source is reported as itself: the device's
            // own storage failing says nothing about the card, and faulting the
            // card for it would condemn the wrong part.
            Err(f) if !f.from_source && matches!(f.error, Error::Flash(_)) => {
                self.fault();
                Err(Error::VolumeLost)
            }
            Err(f) => Err(f.error),
        }
    }

    fn spool_inner<S, const SP: usize, const SS: usize>(
        &mut self,
        source: &mut SensorDb<S, SP, SS>,
        budget: SpoolBudget,
    ) -> Result<SpoolProgress, SpoolFailure>
    where
        S: NorFlash + ReadNorFlash,
    {
        // Failures are tagged with the side they came from, because faulting the
        // volume is the wrong response to the source's flash failing. A bare `?`
        // attributes to the volume; source operations say so explicitly.
        //
        // Step over whatever an interrupted batch already delivered, so this
        // pass copies the remainder rather than the whole batch again.
        SpoolFailure::from_source(self.reconcile(source))?;

        // Destructure so the closure below can borrow the volume while the
        // spooler's own state stays reachable.
        let Self {
            slot,
            state,
            scratch,
        } = self;
        let Slot::Ready(volume) = slot else {
            return Err(Error::NotAttached.into());
        };

        let from = state.resume();
        let mut erased = EraseTally::new(volume.sectors_erased());

        // Probe before writing an intent: an idle poll must not burn two cursor
        // slots. `Ok(false)` rejects the entry, so this consumes nothing.
        let probe = SpoolFailure::from_source(source.read_from(from, 1, |_, _, _| Ok(false)))?;
        if probe.exhausted {
            return Ok(SpoolProgress::idle(from, probe.gap));
        }

        // The batch is confined to one source sector, so this epoch describes
        // every entry in it.
        let source_epoch =
            SpoolFailure::from_source(source.sector_epoch_at(probe.next))?.unwrap_or(0);

        let batch = state.plan_batch(source_epoch, volume.head_position(), budget);
        if let Some((start, end)) = batch.erase(state.region()) {
            // Erase the sector being moved *into*. The one being left still
            // holds valid records at this moment, so the resume point is never
            // unrecoverable.
            let region = state.region();
            volume
                .with_region(region.base(), region.total_size(), |p| p.erase(start, end))?
                .map_err(Error::from)?;
            erased.cursor_erase();
        }

        write_record(
            volume,
            state.region(),
            batch.sector(),
            batch.intent_slot(),
            &batch.intent(),
            scratch,
        )?;

        let mut copied = Replicated::NONE;
        let mut last_timestamp = 0u64;
        let mut batch_sector = BatchSector::new();
        // The one operation that reads the source and writes the volume in the
        // same call, so the side has to be recorded from inside the callback.
        let mut volume_failed = false;

        let cursor = source
            .read_from(from, budget.max_entries, |pos, header, payload| {
                if !batch_sector.admits(pos.sequence) {
                    return Ok(false);
                }
                // `append_framed`, not `append`: a run must land on the replica
                // as a run. Stored as an ordinary payload its frame would be one
                // opaque sample that no read on the card could interpret, and
                // the amortisation the run exists for would be lost as well.
                volume
                    .append_framed(header, payload)
                    .inspect_err(|_| volume_failed = true)?;
                copied.push(samples_in(header.is_run(), payload));
                last_timestamp = header.timestamp;
                Ok(true)
            })
            .map_err(|error| SpoolFailure {
                error,
                from_source: !volume_failed,
            })?;

        // Make the copy durable *before* the commit record claims it is.
        volume.sync()?;

        write_record(
            volume,
            state.region(),
            batch.sector(),
            batch.commit_slot(),
            &batch.commit(cursor.next, copied, last_timestamp),
            scratch,
        )?;

        // Only now is it safe to let the source consider this replicated.
        state.commit_batch(&batch, cursor.next);
        source.note_spooled(cursor.next, copied);

        Ok(SpoolProgress {
            entries_copied: copied.entries,
            committed_upto: cursor.next,
            caught_up: cursor.exhausted,
            gap: cursor.gap,
            volume_erased: erased.total(volume.sectors_erased()),
        })
    }

    /// Copy until the replica is level with the source, or `max_batches` passes
    /// have run.
    ///
    /// The bound exists so a caller with a large backlog can still service other
    /// work between calls rather than blocking indefinitely.
    pub fn spool_until_caught_up<S, const SP: usize, const SS: usize>(
        &mut self,
        source: &mut SensorDb<S, SP, SS>,
        budget: SpoolBudget,
        max_batches: u32,
    ) -> Result<SpoolProgress, Error>
    where
        S: NorFlash + ReadNorFlash,
    {
        let mut total = SpoolProgress {
            committed_upto: self.state.resume(),
            ..SpoolProgress::default()
        };
        for _ in 0..max_batches {
            let progress = self.spool(source, budget)?;
            total.absorb(&progress);
            if progress.caught_up {
                break;
            }
        }
        Ok(total)
    }
}

impl<C, const PAGE_SIZE: usize, const MAX_SECTORS: usize> Spooler<C, PAGE_SIZE, MAX_SECTORS>
where
    C: NorFlash + ReadNorFlash + Removable,
{
    /// Like [`spool`](Self::spool), but skip the pass when the driver reports
    /// the medium absent.
    ///
    /// Available only when the volume's driver can answer that question. It lets
    /// a clean removal be noticed *before* a write fails, which keeps a genuine
    /// fault distinguishable from a yank.
    ///
    /// Returns `Ok(None)` when the medium is absent.
    pub fn spool_if_present<S, const SP: usize, const SS: usize>(
        &mut self,
        source: &mut SensorDb<S, SP, SS>,
        budget: SpoolBudget,
    ) -> Result<Option<SpoolProgress>, Error>
    where
        S: NorFlash + ReadNorFlash,
    {
        let present = match &mut self.slot {
            Slot::Empty => return Err(Error::NotAttached),
            Slot::Faulted(_) => return Err(Error::VolumeLost),
            Slot::Ready(volume) => volume.driver_mut().is_present(),
        };
        if !present {
            return Ok(None);
        }
        self.spool(source, budget).map(Some)
    }

    /// Whether the driver reports the attached medium as present.
    ///
    /// `false` when nothing is attached.
    pub fn is_present(&mut self) -> bool {
        match &mut self.slot {
            Slot::Ready(volume) => volume.driver_mut().is_present(),
            _ => false,
        }
    }
}

/// Read every cursor slot on the volume and work out where to resume.
fn scan_cursor<C, const PAGE_SIZE: usize, const MAX_SECTORS: usize>(
    volume: &mut SensorDb<C, PAGE_SIZE, MAX_SECTORS>,
    state: &SpoolerState,
) -> Result<CursorScan, Error>
where
    C: NorFlash + ReadNorFlash,
{
    let region = *state.region();
    let expected = state.expected_log();
    let mut fold = CursorFold::new();
    let mut buf = [0u8; CURSOR_RECORD_SIZE];

    for at in region.slots() {
        volume.with_region(region.base(), region.total_size(), |p| {
            p.read(at.offset, &mut buf)
        })??;
        fold.feed(at, &buf, expected)?;
    }

    Ok(fold.finish())
}

/// Fingerprint what an interrupted batch actually managed to store.
///
/// The intent record names where on the replica the batch's first entry landed,
/// and nothing is appended after a batch except the next batch — which never
/// started, or its intent would be the newest record. So everything at or after
/// that position is exactly what this batch delivered.
///
/// What makes a run untrustworthy, and why the read runs one past the budget,
/// is [`CursorScan::accept_landed`] and [`CursorScan::landed_probe`].
fn fingerprint_landed<C, const PAGE_SIZE: usize, const MAX_SECTORS: usize>(
    volume: &mut SensorDb<C, PAGE_SIZE, MAX_SECTORS>,
    scan: &CursorScan,
) -> Result<RunFingerprint, Error>
where
    C: NorFlash + ReadNorFlash,
{
    let Some((dest, limit)) = scan.landed_probe() else {
        return Ok(RunFingerprint::new());
    };
    let mut run = RunFingerprint::new();
    let cursor = volume.read_from(dest, limit, |_, header, _| {
        run.push(header.sensor_id, header.timestamp);
        Ok(true)
    })?;
    Ok(scan.accept_landed(run, &cursor))
}

/// Serialise a cursor record into a page-sized slot.
fn write_record<C, const PAGE_SIZE: usize, const MAX_SECTORS: usize>(
    volume: &mut SensorDb<C, PAGE_SIZE, MAX_SECTORS>,
    region: &CursorRegion,
    sector: u8,
    slot: u32,
    record: &SpoolCursorWire,
    scratch: &mut [u8; PAGE_SIZE],
) -> Result<(), Error>
where
    C: NorFlash + ReadNorFlash,
{
    scratch.fill(0xFF);
    scratch[..CURSOR_RECORD_SIZE].copy_from_slice(record.as_bytes());
    let offset = region.slot_offset(sector, slot);
    volume.with_region(region.base(), region.total_size(), |p| {
        p.write(offset, &scratch[..])
    })??;
    Ok(())
}

// =============================================================================
// TieredDb
// =============================================================================

/// An onboard log plus a removable volume, with `append` routed between them.
///
/// This is the application-facing type for a device that collects data with no
/// network link and offloads it by carrying a card to a computer.
///
/// A device with no card slot does not need this: use [`SensorDb`] directly and
/// pay nothing.
///
/// # Reads
///
/// Queries span both logs. The union is exact and needs no de-duplication: the
/// volume holds everything up to the replication watermark, the onboard log
/// holds the un-replicated tail, and where they overlap the data is identical.
pub struct TieredDb<S, C, const SP: usize, const SS: usize, const CP: usize, const CS: usize> {
    onboard: SensorDb<S, SP, SS>,
    spooler: Spooler<C, CP, CS>,
    /// Where `append` writes, and every rule about when that moves.
    tier: TierMode,
}

impl<S, C, const SP: usize, const SS: usize, const CP: usize, const CS: usize>
    TieredDb<S, C, SP, SS, CP, CS>
where
    S: NorFlash + ReadNorFlash,
    C: NorFlash + ReadNorFlash,
{
    /// Combine a mounted onboard log with a spooler for the removable volume.
    ///
    /// # Errors
    /// - `NotMounted` if the onboard log is not mounted
    /// - `GeometryMismatch` if the volume's pages are smaller than the onboard
    ///   log's, which would make entries near the maximum payload impossible to
    ///   copy
    pub fn new(
        onboard: SensorDb<S, SP, SS>,
        spooler: Spooler<C, CP, CS>,
        policy: WritePolicy,
    ) -> Result<Self, Error> {
        if !onboard.is_mounted() {
            return Err(Error::NotMounted);
        }
        if SP > CP {
            return Err(Error::GeometryMismatch);
        }
        Ok(Self {
            onboard,
            spooler,
            tier: TierMode::new(policy),
        })
    }

    /// Attach a mounted volume and seed the onboard watermark from its cursor.
    ///
    /// The cursor is the only record of what has been replicated — `mount`
    /// cannot recover it — so this is what tells the onboard ring which sectors
    /// are safe to overwrite first.
    ///
    /// An interrupted batch is reconciled here rather than on the first spool
    /// pass, so the watermark restored accounts for what the replica already
    /// holds. [`Attached::resume_from`] is the reconciled position, and
    /// [`Attached::recovered_entries`] says how far past the raw cursor it is.
    ///
    /// # Errors
    ///
    /// A late error — from the boundary scan
    /// [`restore_spool_watermark`](SensorDb::restore_spool_watermark) makes to
    /// count exactly what is already replicated, or from the source read
    /// reconciliation performs — leaves the volume **attached and draining**.
    /// What suffers is the reported `unspooled_entries`, and at worst the
    /// replay of one batch, so a caller that cares more about draining than
    /// about the count may treat it as a warning; the underlying onboard-flash
    /// fault will resurface, attributed, on the next
    /// [`spool_step`](Self::spool_step), which reconciles itself.
    pub fn attach(&mut self, volume: SensorDb<C, CP, CS>) -> Result<Attached, Error> {
        let mut attached = self.spooler.attach(volume)?;

        // Before the fallible part, so an `Err` cannot strand an attached volume
        // behind a mode that will not drain it.
        self.tier.attached();

        // Recompute the accounting from the *committed* cursor before
        // reconciling, not after. `reconcile` advances the watermark itself,
        // through `note_spooled`, which only adds the entries it skipped — and
        // `restore_spool_watermark` does nothing once the watermark has already
        // reached the position it is handed. Reconciling first therefore left
        // everything the committed cursor covered permanently uncounted, so the
        // log reported a backlog it had already replicated for the rest of its
        // life.
        self.onboard.restore_spool_watermark(attached.resume_from)?;

        self.spooler.reconcile(&mut self.onboard)?;
        if let Some(resume) = self.spooler.resume_point() {
            attached.resume_from = resume;
        }
        Ok(attached)
    }

    /// Detach the volume. Samples continue to land in the onboard log.
    ///
    /// Under [`WritePolicy::CardFirst`] this first rescues anything the volume
    /// still held in RAM into the onboard log, so removing a card mid-page
    /// loses nothing. Use [`detach_without_recovery`](Self::detach_without_recovery)
    /// if the volume's buffer should be abandoned instead.
    pub fn detach(&mut self) -> Option<SensorDb<C, CP, CS>> {
        // Ignore the result: a rescue that cannot land onboard is worth
        // reporting, but not at the cost of stranding the volume.
        let _ = self.recover_from_volume_loss();
        self.tier.fell_back();
        self.spooler.detach()
    }

    /// Detach the volume without rescuing its RAM buffer.
    ///
    /// Anything appended to the volume since its last successful
    /// [`sync`](Self::sync) is discarded.
    pub fn detach_without_recovery(&mut self) -> Option<SensorDb<C, CP, CS>> {
        self.tier.fell_back();
        self.spooler.detach()
    }

    /// Append a sample.
    ///
    /// **Never fails because of the volume.** Under
    /// [`WritePolicy::OnboardFirst`] the volume is not on the write path at all.
    /// Under [`WritePolicy::CardFirst`] a sample that cannot reach the volume is
    /// written to the onboard log instead, along with everything the volume had
    /// buffered in RAM — so a card pulled mid-page costs nothing.
    pub fn append(&mut self, sensor_id: u16, timestamp: u64, payload: &[u8]) -> Result<(), Error> {
        if !self.tier.writes_to_volume() {
            return self.onboard.append(sensor_id, timestamp, payload);
        }

        let attempt = match self.spooler.volume_mut() {
            Some(volume) => volume.append(sensor_id, timestamp, payload),
            None => Err(Error::NotAttached),
        };

        match attempt {
            Ok(()) => Ok(()),
            // The medium went away. Rescue whatever it still held in RAM, then
            // write this sample onboard as if the card had never been there.
            Err(e) if volume_gone(&e) => {
                self.recover_from_volume_loss()?;
                self.onboard.append(sensor_id, timestamp, payload)
            }
            Err(e) => Err(e),
        }
    }

    /// Append a [run](crate::run), routed exactly as [`append`](Self::append) is.
    ///
    /// A run written to the card stays a run there, and one written onboard is
    /// replicated as a run, so the amortisation survives the whole journey.
    pub fn append_run(&mut self, run: &Run<'_>) -> Result<(), Error> {
        if !self.tier.writes_to_volume() {
            return self.onboard.append_run(run);
        }

        let attempt = match self.spooler.volume_mut() {
            Some(volume) => volume.append_run(run),
            None => Err(Error::NotAttached),
        };

        match attempt {
            Ok(()) => Ok(()),
            Err(e) if volume_gone(&e) => {
                self.recover_from_volume_loss()?;
                self.onboard.append_run(run)
            }
            Err(e) => Err(e),
        }
    }

    /// Flush the buffered tail of whichever log is being written.
    ///
    /// For the onboard log this is also what makes its tail eligible for
    /// replication: [`spool_step`] only copies entries that are already durable.
    ///
    /// [`spool_step`]: Self::spool_step
    pub fn sync(&mut self) -> Result<(), Error> {
        if !self.tier.writes_to_volume() {
            return self.onboard.sync();
        }

        let attempt = match self.spooler.volume_mut() {
            Some(volume) => volume.sync(),
            None => Err(Error::NotAttached),
        };

        match attempt {
            Ok(()) => Ok(()),
            Err(e) if volume_gone(&e) => {
                // Everything that failed to reach the medium is still in its RAM
                // buffer, and lands onboard instead.
                self.recover_from_volume_loss()?;
                self.onboard.sync()
            }
            Err(e) => Err(e),
        }
    }

    /// Fall back to the onboard log, rescuing whatever the volume held in RAM.
    ///
    /// A yank is not a power loss: the processor is still running, so samples
    /// sitting in the volume's page buffer are still readable and can be
    /// re-appended somewhere that exists. This touches no flash on the volume,
    /// so it works with the medium physically gone.
    ///
    /// Returns the number of samples rescued.
    fn recover_from_volume_loss(&mut self) -> Result<u32, Error> {
        let Self {
            onboard,
            spooler,
            tier,
        } = self;
        tier.fell_back();

        let Some(volume) = spooler.fault() else {
            return Ok(0);
        };
        // `append_framed`: a run rescued from the card's RAM buffer has to land
        // onboard as a run, or its frame becomes an unreadable single sample.
        volume.drain_unflushed(|header, payload| onboard.append_framed(header, payload))
    }

    /// Promote to [`WriteMode::Direct`] if the backlog is fully replicated.
    ///
    /// Only under [`WritePolicy::CardFirst`]. Draining to completion *before*
    /// switching is what keeps the volume's log in timestamp order: if direct
    /// writes resumed while a backlog was still being copied, live samples and
    /// older ones would interleave.
    ///
    /// The `sync` here costs one onboard page write per attach cycle — the
    /// buffered tail has to become durable before it can be replicated, and it
    /// has to be replicated before the onboard log can be left behind.
    fn try_promote(&mut self, budget: SpoolBudget) -> Result<(), Error> {
        if !self
            .tier
            .may_promote(self.spooler.is_attached(), self.spooler.is_faulted())
        {
            return Ok(());
        }

        self.onboard.sync()?;
        let progress =
            self.spooler
                .spool_until_caught_up(&mut self.onboard, budget, PROMOTE_MAX_BATCHES)?;
        if progress.caught_up {
            self.tier.promoted();
        }
        Ok(())
    }

    /// Run one replication pass, if a volume is attached.
    ///
    /// Returns `Ok(None)` when no volume is attached — the normal state while
    /// the card is out, and not an error.
    ///
    /// A volume that has **faulted** is different: it returns
    /// [`Error::VolumeLost`] on every call until
    /// [`detach`](Self::detach) is called. Reporting that as `Ok(None)` would
    /// let a card that fell out mid-write look identical to no card at all, and
    /// the backlog would grow silently until the ring started dropping it.
    pub fn spool_step(&mut self, budget: SpoolBudget) -> Result<Option<SpoolProgress>, Error> {
        if !self
            .tier
            .ready_to_spool(self.spooler.is_attached(), self.spooler.is_faulted())?
        {
            return Ok(None);
        }
        let progress = self.spooler.spool(&mut self.onboard, budget)?;
        self.tier.spooled();
        if progress.caught_up {
            self.try_promote(budget)?;
        }
        Ok(Some(progress))
    }

    /// Replicate until the volume is level with the onboard log, or
    /// `max_batches` passes have run.
    ///
    /// Same contract as [`spool_step`](Self::spool_step): `Ok(None)` means no
    /// volume, while a faulted volume is an error.
    pub fn drain(
        &mut self,
        budget: SpoolBudget,
        max_batches: u32,
    ) -> Result<Option<SpoolProgress>, Error> {
        if !self
            .tier
            .ready_to_spool(self.spooler.is_attached(), self.spooler.is_faulted())?
        {
            return Ok(None);
        }
        let progress =
            self.spooler
                .spool_until_caught_up(&mut self.onboard, budget, max_batches)?;
        self.tier.spooled();
        if progress.caught_up {
            self.try_promote(budget)?;
        }
        Ok(Some(progress))
    }

    /// Which log `append` is currently writing to.
    pub fn mode(&self) -> WriteMode {
        self.tier.mode()
    }

    /// The configured write policy.
    pub fn policy(&self) -> WritePolicy {
        self.tier.policy()
    }

    /// Whether a volume is attached.
    pub fn is_attached(&self) -> bool {
        self.spooler.is_attached()
    }

    /// Replication accounting for the onboard log.
    pub fn spool_stats(&self) -> SpoolStats {
        self.onboard.spool_stats()
    }

    /// How much room is left on the removable volume.
    ///
    /// `None` when no volume is attached. This is the warning an operator needs
    /// before the swap window closes: nothing reports a full medium as an error,
    /// because a ring overwriting its own tail is normal operation for a log.
    ///
    /// It matters most under [`WritePolicy::CardFirst`], where the volume holds
    /// the only copy of everything written since it took over — see
    /// [`VolumeFill`]. Under [`WritePolicy::OnboardFirst`] a full volume
    /// overwrites a copy, and the onboard log's own
    /// [`spool_stats`](Self::spool_stats) is the accounting that matters.
    pub fn volume_fill(&self) -> Option<VolumeFill> {
        self.spooler.volume_fill()
    }

    /// The attached volume, if one is attached and usable.
    ///
    /// Provided for inspection — status displays, diagnostics, and tests.
    /// Appending to the replica behind the spooler's back will make the cursor
    /// disagree with the volume's contents.
    pub fn volume(&self) -> Option<&SensorDb<C, CP, CS>> {
        self.spooler.volume()
    }

    /// The attached volume, if one is attached and usable.
    ///
    /// See [`volume`](Self::volume) for the caveat.
    pub fn volume_mut(&mut self) -> Option<&mut SensorDb<C, CP, CS>> {
        self.spooler.volume_mut()
    }

    /// The onboard log.
    pub fn onboard(&self) -> &SensorDb<S, SP, SS> {
        &self.onboard
    }

    /// The onboard log.
    pub fn onboard_mut(&mut self) -> &mut SensorDb<S, SP, SS> {
        &mut self.onboard
    }

    /// Consume this and return the parts.
    pub fn into_parts(self) -> (SensorDb<S, SP, SS>, Spooler<C, CP, CS>) {
        (self.onboard, self.spooler)
    }

    // -------------------------------------------------------------------------
    // Reads across both logs
    // -------------------------------------------------------------------------

    /// The most recent entry for a sensor, across both logs.
    ///
    /// Exact. Where the two logs overlap they hold identical entries, so taking
    /// the later timestamp cannot be perturbed by the duplication.
    pub fn latest(
        &mut self,
        sensor_id: u16,
        buf: &mut [u8],
    ) -> Result<Option<(EntryHeader, usize)>, Error> {
        let onboard = self.onboard.latest(sensor_id, buf)?;

        // Read the volume into a scratch view; `merge` copies it over only if it
        // wins, so the onboard read already in `buf` is not disturbed.
        let mut alt = [0u8; CP];
        let from_volume = match self.spooler.volume_mut() {
            Some(volume) => volume.latest(sensor_id, &mut alt)?,
            None => return Ok(onboard),
        };

        merge(onboard, from_volume, &alt, buf, |v, o| v > o)
    }

    /// The oldest entry for a sensor, across both logs.
    pub fn oldest(
        &mut self,
        sensor_id: u16,
        buf: &mut [u8],
    ) -> Result<Option<(EntryHeader, usize)>, Error> {
        let onboard = self.onboard.oldest(sensor_id, buf)?;

        let mut alt = [0u8; CP];
        let from_volume = match self.spooler.volume_mut() {
            Some(volume) => volume.oldest(sensor_id, &mut alt)?,
            None => return Ok(onboard),
        };

        merge(onboard, from_volume, &alt, buf, |v, o| v < o)
    }

    /// Entries in a timestamp range, across both logs.
    ///
    /// Delivered card-first and then onboard, which is log order across the
    /// union: the card holds everything up to the replication watermark and the
    /// onboard log holds the un-replicated tail. Within each, entries arrive in
    /// write order — *not* timestamp order, the same caveat as
    /// [`SensorDb::query_range`].
    ///
    /// The union is exact and needs no de-duplication. Un-synced samples still
    /// sitting in a page buffer are included, so this sees everything
    /// [`latest`](Self::latest) would.
    ///
    /// Return `false` from the callback to stop, which — as in
    /// [`SensorDb::query_range`] — stops *after* consuming the entry offered.
    ///
    /// # Cost
    ///
    /// The onboard side is scanned from the watermark forward without the
    /// per-sector bloom filter or timestamp-range skipping that
    /// [`SensorDb::query_range`] uses, because those index by sector and the
    /// watermark cuts across one. That tail is small by construction — it is
    /// exactly what replication has not yet carried off — so the saving would be
    /// on the part that is already cheap.
    ///
    /// # Returns
    /// The number of entries delivered.
    ///
    /// # Errors
    /// - `ReadsUnavailable` if the card was mounted
    ///   [`HeadersOnly`](crate::db::MountMode::HeadersOnly)
    pub fn query_range<F>(
        &mut self,
        sensor_id: Option<u16>,
        t_start: u64,
        t_end: u64,
        mut callback: F,
    ) -> Result<u32, Error>
    where
        F: FnMut(&EntryHeader, &[u8]) -> bool,
    {
        let Some(volume) = self.spooler.volume_mut() else {
            // No card: the onboard log is all there is, and its own query path
            // is strictly better — it can skip sectors by bloom filter.
            return self
                .onboard
                .query_range(sensor_id, t_start, t_end, callback);
        };

        let mut stopped = false;
        let mut delivered = {
            // `SensorDb::query_range` reports how many it delivered but not
            // whether the callback asked to stop, so record that here — the
            // onboard phase must not keep calling a callback that said stop.
            let mut watched = |header: &EntryHeader, payload: &[u8]| {
                let go = callback(header, payload);
                stopped |= !go;
                go
            };
            volume.query_range(sensor_id, t_start, t_end, &mut watched)?
        };
        if stopped {
            return Ok(delivered);
        }

        // The onboard phases stream *entries*, so a run arrives whole and has to
        // be expanded here — the volume's own `query_range` did that internally.
        // `deliver_samples` frames each sample by writing through the payload, so
        // it needs a copy; one buffer serves both phases.
        let mut scratch = [0u8; SP];
        let mut expand =
            |header: &EntryHeader, payload: &[u8], delivered: &mut u32, callback: &mut F| {
                if sensor_id.is_some_and(|id| header.sensor_id != id) {
                    return false;
                }
                let Some(dst) = scratch.get_mut(..payload.len()) else {
                    return false;
                };
                dst.copy_from_slice(payload);
                deliver_samples(
                    header.is_run(),
                    header.sensor_id,
                    header.timestamp,
                    dst,
                    t_start,
                    t_end,
                    delivered,
                    callback,
                )
            };

        // The onboard tail, from the watermark forward. `read_from` reads
        // `Ok(false)` as *rejecting* the entry rather than consuming it, but the
        // cursor it returns is discarded here, so the two conventions cannot
        // collide — and stopping there is what keeps an early exit cheap.
        let watermark = self.onboard.spool_stats().watermark;
        self.onboard
            .read_from(watermark, u32::MAX, |_, header, payload| {
                stopped = expand(header, payload, &mut delivered, &mut callback);
                Ok(!stopped)
            })?;

        if stopped {
            return Ok(delivered);
        }

        // ...and the tail that is still only in RAM. `read_from` stops at the
        // durable end by design; a reader must not.
        self.onboard.peek_unflushed(|header, payload| {
            if !stopped {
                stopped = expand(header, payload, &mut delivered, &mut callback);
            }
            Ok(())
        })?;

        Ok(delivered)
    }

    /// Every entry for a sensor across both logs, in log order.
    ///
    /// [`query_range`](Self::query_range) over the full timestamp range.
    pub fn query_all<F>(&mut self, sensor_id: Option<u16>, callback: F) -> Result<u32, Error>
    where
        F: FnMut(&EntryHeader, &[u8]) -> bool,
    {
        self.query_range(sensor_id, 0, u64::MAX, callback)
    }

    /// Total entries across both logs, counted without double-counting.
    ///
    /// `sensor_id = None` is O(1): the volume's cached total plus the onboard
    /// log's un-replicated count.
    ///
    /// After an unclean removal the answer can over-count by at most
    /// [`SpoolBudget::max_entries`], the same bound that applies to duplicates
    /// on the volume.
    pub fn count(&mut self, sensor_id: Option<u16>) -> Result<u32, Error> {
        // Samples, not entries: `count` has to agree with what `query_range`
        // yields, and that expands runs.
        let unspooled = self.onboard.spool_stats().unspooled_samples;

        let Some(volume) = self.spooler.volume_mut() else {
            // No volume: the onboard log is all there is.
            return self.onboard.count(sensor_id);
        };

        match sensor_id {
            None => Ok(volume.count(None)?.saturating_add(unspooled)),
            Some(id) => {
                // Per-sensor needs a scan either way; the onboard side counts
                // only the un-replicated tail so nothing is counted twice.
                let on_volume = volume.count(Some(id))?;
                let watermark = self.onboard.spool_stats().watermark;
                let mut tail = 0u32;
                let mut tally = |header: &EntryHeader, payload: &[u8]| {
                    if header.sensor_id == id {
                        tail += samples_in(header.is_run(), payload);
                    }
                };
                self.onboard
                    .read_from(watermark, u32::MAX, |_, header, payload| {
                        tally(header, payload);
                        Ok(true)
                    })?;
                // `read_from` stops at the durable tail by design, so the third
                // phase is not optional: [`query_range`](Self::query_range) goes
                // on to `peek_unflushed`, and a `count` that stopped one phase
                // early reported zero for a sensor whose only entry was still in
                // the RAM page buffer.
                self.onboard.peek_unflushed(|header, payload| {
                    tally(header, payload);
                    Ok(())
                })?;
                Ok(on_volume.saturating_add(tail))
            }
        }
    }
}

impl<S, C, const SP: usize, const SS: usize, const CP: usize, const CS: usize>
    TieredDb<S, C, SP, SS, CP, CS>
where
    S: NorFlash + ReadNorFlash,
    C: NorFlash + ReadNorFlash + Removable,
{
    /// Notice a removal before a write has to fail.
    ///
    /// Call this from a card-detect interrupt or a periodic poll. If the driver
    /// reports the medium absent, this rescues whatever it still held in RAM
    /// into the onboard log and falls back to [`WriteMode::Onboard`].
    ///
    /// Without it a removal is only discovered when a write fails, which is
    /// still safe — [`append`](Self::append) recovers the same way — but means
    /// the fault is indistinguishable from a genuine flash error.
    ///
    /// Returns the number of samples rescued; zero when the medium is present.
    pub fn check_presence(&mut self) -> Result<u32, Error> {
        if !self.spooler.is_attached() || self.spooler.is_faulted() {
            return Ok(0);
        }
        if self.spooler.is_present() {
            return Ok(0);
        }
        self.recover_from_volume_loss()
    }

    /// Run one replication pass, skipping it when the medium reports absent.
    ///
    /// Combines [`check_presence`](Self::check_presence) with
    /// [`spool_step`](Self::spool_step): a clean removal is noticed and handled
    /// rather than surfacing as a failed write.
    pub fn spool_step_if_present(
        &mut self,
        budget: SpoolBudget,
    ) -> Result<Option<SpoolProgress>, Error> {
        self.check_presence()?;
        if !self.spooler.is_attached() || self.spooler.is_faulted() {
            return Ok(None);
        }
        self.spool_step(budget)
    }
}

// ---------------------------------------------------------------------------
// Capability ports
// ---------------------------------------------------------------------------
//
// This is what the ports are for: a caller that only wants to record samples
// and read them back does not have to know whether a card is in the slot, and
// so `SensorLogger` and the typed API work over a tier just as they do over one
// log. Delegation only, spelled with UFCS so the inherent method is never
// reached through `self.`.

impl<S, C, const SP: usize, const SS: usize, const CP: usize, const CS: usize> crate::port::LogSink
    for TieredDb<S, C, SP, SS, CP, CS>
where
    S: NorFlash + ReadNorFlash,
    C: NorFlash + ReadNorFlash,
{
    fn append(&mut self, sensor_id: u16, timestamp: u64, payload: &[u8]) -> Result<(), Error> {
        TieredDb::append(self, sensor_id, timestamp, payload)
    }

    fn append_run(&mut self, run: &Run<'_>) -> Result<(), Error> {
        TieredDb::append_run(self, run)
    }

    fn sync(&mut self) -> Result<(), Error> {
        TieredDb::sync(self)
    }
}

impl<S, C, const SP: usize, const SS: usize, const CP: usize, const CS: usize>
    crate::port::LogSource for TieredDb<S, C, SP, SS, CP, CS>
where
    S: NorFlash + ReadNorFlash,
    C: NorFlash + ReadNorFlash,
{
    fn latest(
        &mut self,
        sensor_id: u16,
        buf: &mut [u8],
    ) -> Result<Option<(EntryHeader, usize)>, Error> {
        TieredDb::latest(self, sensor_id, buf)
    }

    fn oldest(
        &mut self,
        sensor_id: u16,
        buf: &mut [u8],
    ) -> Result<Option<(EntryHeader, usize)>, Error> {
        TieredDb::oldest(self, sensor_id, buf)
    }

    fn count(&mut self, sensor_id: Option<u16>) -> Result<u32, Error> {
        TieredDb::count(self, sensor_id)
    }

    fn query_range(
        &mut self,
        sensor_id: Option<u16>,
        t_start: u64,
        t_end: u64,
        callback: &mut dyn FnMut(&EntryHeader, &[u8]) -> bool,
    ) -> Result<u32, Error> {
        TieredDb::query_range(self, sensor_id, t_start, t_end, callback)
    }
}

impl<S, C, const SP: usize, const SS: usize, const CP: usize, const CS: usize> core::fmt::Debug
    for TieredDb<S, C, SP, SS, CP, CS>
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("TieredDb")
            .field("policy", &self.tier.policy())
            .field("mode", &self.tier.mode())
            .field("attached", &self.spooler.is_attached())
            .finish_non_exhaustive()
    }
}