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
//! Async store-and-forward drivers: [`SpoolerAsync`] and [`TieredDbAsync`].
//!
//! Mirrors [`blocking`](crate::spool::blocking) operation for operation. Every
//! decision — where the next cursor record goes, what a scan of the region
//! means, which log an append is routed to, when duplicates are possible — lives
//! in the shared pure modules [`cursor`](crate::spool::cursor),
//! [`policy`](crate::spool::policy) and [`tier`](crate::spool::tier); only the
//! code that actually touches flash is written twice, because the sync and async
//! `NorFlash` traits are unrelated types.
//!
//! That split is not tidiness. `tests/tiered_async.rs` asserts the two drivers
//! produce byte-for-byte identical media, so a decision duplicated between them
//! is one the parity suite calls correct however wrong it is — which has already
//! happened once, with the `attach`-before-`reconcile` ordering bug.
//!
//! See the blocking types for the full rationale behind the protocol; the
//! documentation here covers only what differs.

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

use crate::async_db::SensorDbAsync;
use crate::db::{LogPosition, Replicated, SpoolStats};
use crate::entry::{EntryHeader, EntryKind};
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.
enum Slot<C, const PAGE_SIZE: usize, const MAX_SECTORS: usize> {
    Empty,
    Ready(SensorDbAsync<C, PAGE_SIZE, MAX_SECTORS>),
    Faulted(SensorDbAsync<C, PAGE_SIZE, MAX_SECTORS>),
}

/// Copies a log onto a removable volume, and remembers how far it got.
///
/// Async counterpart of [`Spooler`](crate::spool::Spooler), with the same
/// guarantees: no loss, duplication bounded by [`SpoolBudget::max_entries`] and
/// in practice reconciled away on reinsert, and nothing written to a volume
/// belonging to a different log.
pub struct SpoolerAsync<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 blocking 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> SpoolerAsync<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.
    pub fn pending_reconciliation(&self) -> u32 {
        self.state.pending_reconciliation()
    }
}

impl<C, const PAGE_SIZE: usize, const MAX_SECTORS: usize> SpoolerAsync<C, PAGE_SIZE, MAX_SECTORS>
where
    C: NorFlash + ReadNorFlash,
{
    /// Create a spooler for a log with the given identity.
    ///
    /// See [`Spooler::new`](crate::spool::Spooler::new). `cursor_base` must name
    /// a region **outside** the volume's database region, which
    /// [`attach`](Self::attach) enforces with [`Error::RegionOverlap`].
    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.
    ///
    /// Reconciles an interrupted batch the same way as
    /// [`Spooler::attach`](crate::spool::Spooler::attach); see there for why the
    /// replica is the thing that knows how far the batch got.
    ///
    /// # 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 async fn attach(
        &mut self,
        volume: SensorDbAsync<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: suppress the per-run epoch roll, which would otherwise burn a
        // sector on every insertion to record an epoch that means nothing here.
        volume.mark_as_replica();
        let scan = scan_cursor(&mut volume, &self.state).await?;
        let landed = fingerprint_landed(&mut volume, &scan).await?;

        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.
    ///
    /// See [`Spooler::reconcile`](crate::spool::Spooler::reconcile).
    ///
    /// # Returns
    /// The number of entries skipped.
    pub async fn reconcile<S, const SP: usize, const SS: usize>(
        &mut self,
        source: &mut SensorDbAsync<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)
                },
            )
            .await?;
        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 in its RAM page
    /// buffer, which survives the medium being pulled.
    pub fn fault(&mut self) -> Option<&mut SensorDbAsync<C, PAGE_SIZE, MAX_SECTORS>> {
        // Only move out of the slot when there is something to transition, or an
        // already-faulted volume would be dropped along with its RAM buffer.
        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.
    pub fn detach(&mut self) -> Option<SensorDbAsync<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<&SensorDbAsync<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 SensorDbAsync<C, PAGE_SIZE, MAX_SECTORS>> {
        match &mut self.slot {
            Slot::Ready(v) => Some(v),
            _ => None,
        }
    }

    /// How much room is left on the attached volume.
    ///
    /// See [`Spooler::volume_fill`](crate::spool::Spooler::volume_fill).
    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.
    ///
    /// See [`Spooler::spool`](crate::spool::Spooler::spool).
    pub async fn spool<S, const SP: usize, const SS: usize>(
        &mut self,
        source: &mut SensorDbAsync<S, SP, SS>,
        budget: SpoolBudget,
    ) -> Result<SpoolProgress, Error>
    where
        S: NorFlash + ReadNorFlash,
    {
        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).await {
            Ok(progress) => Ok(progress),
            // A driver cannot distinguish a yanked medium from a genuine fault,
            // so any flash error on the *volume* is treated as removal. One on
            // the source is reported as itself — see `SpoolFailure`.
            Err(f) if !f.from_source && matches!(f.error, Error::Flash(_)) => {
                self.fault();
                Err(Error::VolumeLost)
            }
            Err(f) => Err(f.error),
        }
    }

    async fn spool_inner<S, const SP: usize, const SS: usize>(
        &mut self,
        source: &mut SensorDbAsync<S, SP, SS>,
        budget: SpoolBudget,
    ) -> Result<SpoolProgress, SpoolFailure>
    where
        S: NorFlash + ReadNorFlash,
    {
        // Failures are tagged with the side they came from: 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).await)?;

        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 so an idle poll burns no cursor slots.
        // `Ok(false)` rejects the entry, so this consumes nothing.
        let probe =
            SpoolFailure::from_source(source.read_from(from, 1, |_, _, _| Ok(false)).await)?;
        if probe.exhausted {
            return Ok(SpoolProgress::idle(from, probe.gap));
        }

        let source_epoch =
            SpoolFailure::from_source(source.sector_epoch_at(probe.next).await)?.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, so the resume point is never unrecoverable.
            let region = *state.region();
            volume
                .region(region.base(), region.total_size())?
                .erase(start, end)
                .await
                .map_err(Error::from)?;
            erased.cursor_erase();
        }

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

        let mut copied = Replicated::NONE;
        let mut last_timestamp = 0u64;
        let mut batch_sector = BatchSector::new();

        // The copy cannot run inside `read_from`'s callback here: appending to
        // the volume is `async`, and the callback is a plain `FnMut`. Instead the
        // batch is read into a staging buffer one entry at a time, then written.
        // One source page of stack, the same as the blocking driver's callback.
        let mut staged = [0u8; SP];
        let mut cursor_next = from;
        let mut exhausted = false;
        let mut gap = false;

        loop {
            if copied.entries >= budget.max_entries {
                break;
            }
            let mut pending: Option<(EntryHeader, usize)> = None;
            let read = SpoolFailure::from_source(
                source
                    .read_from(cursor_next, 1, |pos, header, payload| {
                        if !batch_sector.admits(pos.sequence) {
                            return Ok(false);
                        }
                        staged[..payload.len()].copy_from_slice(payload);
                        pending = Some((*header, payload.len()));
                        Ok(true)
                    })
                    .await,
            )?;
            gap |= read.gap;

            let Some((header, len)) = pending else {
                // Either nothing is left, or the batch hit a sector boundary.
                exhausted = read.exhausted;
                break;
            };

            // `append_framed`, not `append`: a run must land on the replica as a
            // run, or its frame becomes one opaque sample no read can interpret.
            volume.append_framed(&header, &staged[..len]).await?;
            copied.push(samples_in(header.is_run(), &staged[..len]));
            last_timestamp = header.timestamp;
            cursor_next = read.next;
        }

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

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

        // 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: exhausted,
            gap,
            volume_erased: erased.total(volume.sectors_erased()),
        })
    }

    /// Copy until the replica is level with the source, or `max_batches` passes
    /// have run.
    pub async fn spool_until_caught_up<S, const SP: usize, const SS: usize>(
        &mut self,
        source: &mut SensorDbAsync<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).await?;
            total.absorb(&progress);
            if progress.caught_up {
                break;
            }
        }
        Ok(total)
    }
}

impl<C, const PAGE_SIZE: usize, const MAX_SECTORS: usize> SpoolerAsync<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.
    pub async fn spool_if_present<S, const SP: usize, const SS: usize>(
        &mut self,
        source: &mut SensorDbAsync<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).await.map(Some)
    }

    /// Whether the driver reports the attached medium as present.
    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.
async fn scan_cursor<C, const PAGE_SIZE: usize, const MAX_SECTORS: usize>(
    volume: &mut SensorDbAsync<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
            .region(region.base(), region.total_size())?
            .read(at.offset, &mut buf)
            .await?;
        fold.feed(at, &buf, expected)?;
    }

    Ok(fold.finish())
}

/// Fingerprint what an interrupted batch actually managed to store.
///
/// See the blocking `fingerprint_landed` for why everything at or after the
/// intent's `dest` belongs to exactly that batch, and
/// [`CursorScan::accept_landed`] for what makes the run untrustworthy.
async fn fingerprint_landed<C, const PAGE_SIZE: usize, const MAX_SECTORS: usize>(
    volume: &mut SensorDbAsync<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)
        })
        .await?;
    Ok(scan.accept_landed(run, &cursor))
}

/// Serialise a cursor record into a page-sized slot.
async fn write_record<C, const PAGE_SIZE: usize, const MAX_SECTORS: usize>(
    volume: &mut SensorDbAsync<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
        .region(region.base(), region.total_size())?
        .write(offset, &scratch[..])
        .await?;
    Ok(())
}

// =============================================================================
// TieredDbAsync
// =============================================================================

/// An onboard log plus a removable volume, with `append` routed between them.
///
/// Async counterpart of [`TieredDb`](crate::spool::TieredDb).
pub struct TieredDbAsync<S, C, const SP: usize, const SS: usize, const CP: usize, const CS: usize> {
    onboard: SensorDbAsync<S, SP, SS>,
    spooler: SpoolerAsync<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>
    TieredDbAsync<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
    pub fn new(
        onboard: SensorDbAsync<S, SP, SS>,
        spooler: SpoolerAsync<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.
    ///
    /// An interrupted batch is reconciled here, so the restored watermark
    /// accounts for what the replica already holds and
    /// [`Attached::resume_from`] is the reconciled position.
    ///
    /// # Errors
    ///
    /// As for [`TieredDb::attach`](super::TieredDb::attach), a late error from
    /// the watermark's boundary scan leaves the volume attached and draining.
    pub async fn attach(&mut self, volume: SensorDbAsync<C, CP, CS>) -> Result<Attached, Error> {
        let mut attached = self.spooler.attach(volume).await?;

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

        // Restored from the *committed* cursor, before reconciling — see
        // [`TieredDb::attach`](super::TieredDb::attach) for why the order is
        // load-bearing.
        self.onboard
            .restore_spool_watermark(attached.resume_from)
            .await?;

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

    /// Detach the volume, rescuing anything it still held in RAM.
    pub async fn detach(&mut self) -> Option<SensorDbAsync<C, CP, CS>> {
        let _ = self.recover_from_volume_loss().await;
        self.tier.fell_back();
        self.spooler.detach()
    }

    /// Detach the volume without rescuing its RAM buffer.
    pub fn detach_without_recovery(&mut self) -> Option<SensorDbAsync<C, CP, CS>> {
        self.tier.fell_back();
        self.spooler.detach()
    }

    /// Append a sample.
    ///
    /// Never fails because of the volume: a sample that cannot reach it is
    /// written onboard instead, along with everything the volume had buffered.
    pub async 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).await;
        }

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

        match attempt {
            Ok(()) => Ok(()),
            Err(e) if volume_gone(&e) => {
                self.recover_from_volume_loss().await?;
                self.onboard.append(sensor_id, timestamp, payload).await
            }
            Err(e) => Err(e),
        }
    }

    /// Append a [run](crate::run), routed exactly as [`append`](Self::append) is.
    pub async fn append_run(&mut self, run: &Run<'_>) -> Result<(), Error> {
        if !self.tier.writes_to_volume() {
            return self.onboard.append_run(run).await;
        }

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

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

    /// Flush the buffered tail of whichever log is being written.
    pub async fn sync(&mut self) -> Result<(), Error> {
        if !self.tier.writes_to_volume() {
            return self.onboard.sync().await;
        }

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

        match attempt {
            Ok(()) => Ok(()),
            Err(e) if volume_gone(&e) => {
                self.recover_from_volume_loss().await?;
                self.onboard.sync().await
            }
            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 in
    /// the volume's page buffer are still readable. Draining touches no flash on
    /// the volume, so this works with the medium physically gone.
    ///
    /// The rescued samples are staged in a stack buffer before being appended.
    /// `drain_unflushed` hands them to a synchronous callback, and appending to
    /// the onboard log is `async`, so they cannot be forwarded in one step. The
    /// staging encoding is more compact than the on-flash one, so a page's worth
    /// of entries always fits.
    async fn recover_from_volume_loss(&mut self) -> Result<u32, Error> {
        /// `sensor_id` + `timestamp` + `payload_len` + `kind`.
        ///
        /// The kind is staged too: a run rescued from the card's RAM buffer has
        /// to land onboard as a run, or its frame becomes one opaque sample no
        /// read could interpret.
        const STAGED_HEADER: usize = 2 + 8 + 2 + 1;

        let Self {
            onboard,
            spooler,
            tier,
        } = self;
        tier.fell_back();

        let Some(volume) = spooler.fault() else {
            return Ok(0);
        };

        let mut staging = [0u8; CP];
        let mut used = 0usize;
        let drained = volume.drain_unflushed(|header, payload| {
            let needed = STAGED_HEADER + payload.len();
            if used + needed > staging.len() {
                // Cannot happen: an on-flash entry costs ENTRY_OVERHEAD (20)
                // bytes plus payload, more than the 13 staged here, so a page's
                // worth always fits. Refusing leaves the volume's buffer intact
                // and the operation retryable.
                return Err(Error::NoSpace);
            }
            staging[used..used + 2].copy_from_slice(&header.sensor_id.to_le_bytes());
            staging[used + 2..used + 10].copy_from_slice(&header.timestamp.to_le_bytes());
            staging[used + 10..used + 12].copy_from_slice(&(payload.len() as u16).to_le_bytes());
            staging[used + 12] = u8::from(header.is_run());
            staging[used + STAGED_HEADER..used + needed].copy_from_slice(payload);
            used += needed;
            Ok(())
        })?;

        let mut pos = 0usize;
        while pos + STAGED_HEADER <= used {
            let sensor_id = u16::from_le_bytes([staging[pos], staging[pos + 1]]);
            let mut ts = [0u8; 8];
            ts.copy_from_slice(&staging[pos + 2..pos + 10]);
            let timestamp = u64::from_le_bytes(ts);
            let len = u16::from_le_bytes([staging[pos + 10], staging[pos + 11]]) as usize;
            let kind = match staging[pos + 12] {
                0 => EntryKind::Single,
                _ => EntryKind::Run,
            };
            let start = pos + STAGED_HEADER;
            let header = EntryHeader {
                sensor_id,
                timestamp,
                payload_len: len as u16,
                kind,
            };
            onboard
                .append_framed(&header, &staging[start..start + len])
                .await?;
            pos = start + len;
        }

        Ok(drained)
    }

    /// Run one replication pass, if a volume is attached.
    ///
    /// `Ok(None)` means no volume. A *faulted* volume returns
    /// [`Error::VolumeLost`] until [`detach`](Self::detach) is called.
    pub async 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).await?;
        self.tier.spooled();
        if progress.caught_up {
            self.try_promote(budget).await?;
        }
        Ok(Some(progress))
    }

    /// Replicate until the volume is level with the onboard log.
    pub async 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)
            .await?;
        self.tier.spooled();
        if progress.caught_up {
            self.try_promote(budget).await?;
        }
        Ok(Some(progress))
    }

    /// Promote to [`WriteMode::Direct`] if the backlog is fully replicated.
    async 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().await?;
        let progress = self
            .spooler
            .spool_until_caught_up(&mut self.onboard, budget, PROMOTE_MAX_BATCHES)
            .await?;
        if progress.caught_up {
            self.tier.promoted();
        }
        Ok(())
    }

    /// 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.
    ///
    /// See [`TieredDb::volume_fill`](crate::spool::TieredDb::volume_fill).
    pub fn volume_fill(&self) -> Option<VolumeFill> {
        self.spooler.volume_fill()
    }

    /// The attached volume, if one is attached and usable.
    pub fn volume(&self) -> Option<&SensorDbAsync<C, CP, CS>> {
        self.spooler.volume()
    }

    /// The attached volume, if one is attached and usable.
    pub fn volume_mut(&mut self) -> Option<&mut SensorDbAsync<C, CP, CS>> {
        self.spooler.volume_mut()
    }

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

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

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

    /// 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 async fn latest(
        &mut self,
        sensor_id: u16,
        buf: &mut [u8],
    ) -> Result<Option<(EntryHeader, usize)>, Error> {
        let onboard = self.onboard.latest(sensor_id, buf).await?;

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

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

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

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

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

    /// Entries in a timestamp range, across both logs.
    ///
    /// See [`TieredDb::query_range`](crate::spool::TieredDb::query_range) for
    /// the ordering, the exactness argument, and why the onboard tail is scanned
    /// without the bloom filter.
    pub async 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,
    {
        if self.spooler.volume().is_none() {
            return self
                .onboard
                .query_range(sensor_id, t_start, t_end, callback)
                .await;
        }

        let mut stopped = false;
        let mut delivered = {
            // Records whether the callback asked to stop, which `query_range`
            // itself does not report.
            let mut watched = |header: &EntryHeader, payload: &[u8]| {
                let go = callback(header, payload);
                stopped |= !go;
                go
            };
            self.spooler
                .volume_mut()
                .expect("checked above")
                .query_range(sensor_id, t_start, t_end, &mut watched)
                .await?
        };
        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.
        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,
                )
            };

        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)
            })
            .await?;

        if stopped {
            return Ok(delivered);
        }

        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.
    pub async 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).await
    }

    /// Total entries across both logs, counted without double-counting.
    ///
    /// `sensor_id = None` is O(1). After an unclean removal the answer can
    /// over-count by at most [`SpoolBudget::max_entries`].
    pub async 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 watermark = self.onboard.spool_stats().watermark;

        if self.spooler.volume().is_none() {
            return self.onboard.count(sensor_id).await;
        }

        match sensor_id {
            None => {
                let on_volume = self
                    .spooler
                    .volume_mut()
                    .expect("checked above")
                    .count(None)
                    .await?;
                Ok(on_volume.saturating_add(unspooled))
            }
            Some(id) => {
                let on_volume = self
                    .spooler
                    .volume_mut()
                    .expect("checked above")
                    .count(Some(id))
                    .await?;
                // Count only the un-replicated tail onboard, so nothing is
                // counted twice.
                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)
                    })
                    .await?;
                // `read_from` stops at the durable tail, so this third phase is
                // not optional — `query_range` goes on to `peek_unflushed`, and
                // without it `count` 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>
    TieredDbAsync<S, C, SP, SS, CP, CS>
where
    S: NorFlash + ReadNorFlash,
    C: NorFlash + ReadNorFlash + Removable,
{
    /// Notice a removal before a write has to fail.
    ///
    /// Returns the number of samples rescued; zero when the medium is present.
    pub async 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().await
    }

    /// Run one replication pass, skipping it when the medium reports absent.
    pub async fn spool_step_if_present(
        &mut self,
        budget: SpoolBudget,
    ) -> Result<Option<SpoolProgress>, Error> {
        self.check_presence().await?;
        if !self.spooler.is_attached() || self.spooler.is_faulted() {
            return Ok(None);
        }
        self.spool_step(budget).await
    }
}

// ---------------------------------------------------------------------------
// Capability ports
// ---------------------------------------------------------------------------
//
// Async mirror of the blocking impls; see those for why delegation is spelled
// with UFCS.

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

    fn append_run(
        &mut self,
        run: &Run<'_>,
    ) -> impl core::future::Future<Output = Result<(), Error>> {
        TieredDbAsync::append_run(self, run)
    }

    fn sync(&mut self) -> impl core::future::Future<Output = Result<(), Error>> {
        TieredDbAsync::sync(self)
    }
}

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

    fn oldest(
        &mut self,
        sensor_id: u16,
        buf: &mut [u8],
    ) -> impl core::future::Future<Output = Result<Option<(EntryHeader, usize)>, Error>> {
        TieredDbAsync::oldest(self, sensor_id, buf)
    }

    fn count(
        &mut self,
        sensor_id: Option<u16>,
    ) -> impl core::future::Future<Output = Result<u32, Error>> {
        TieredDbAsync::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,
    ) -> impl core::future::Future<Output = Result<u32, Error>> {
        TieredDbAsync::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 TieredDbAsync<S, C, SP, SS, CP, CS>
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("TieredDbAsync")
            .field("policy", &self.tier.policy())
            .field("mode", &self.tier.mode())
            .field("attached", &self.spooler.is_attached())
            .finish_non_exhaustive()
    }
}