sensor-db 0.1.0

Append-only sensor database for NOR flash on embedded devices
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
//! Async version of SensorDb for use with Embassy and `embedded-storage-async`.
//!
//! This module provides [`SensorDbAsync`], which mirrors the API of [`SensorDb`](crate::SensorDb)
//! but uses `async fn` for all flash-touching operations. This enables DMA-based flash access
//! on targets like RP2350 when used with Embassy.
//!
//! ## Differences from `SensorDb`
//!
//! - **No `RefCell`**: All methods take `&mut self`. Async code cannot safely borrow through
//!   `RefCell` across `.await` points, so interior mutability is not used.
//! - **All flash operations are `async`**: `mount`, `format`, `append`, `sync`, `latest`,
//!   `query_range`, `oldest`, `count`, `compact` are all async.
//!
//! ## What is shared with the sync implementation
//!
//! [`SensorDbAsync`] holds the same `SensorDbState` value as [`SensorDb`](crate::SensorDb),
//! so every field and every helper that does not touch flash — sector ordering, wear
//! levelling (`find_next_sector`), page-buffer scanning, bloom filters — is defined
//! exactly once in `db.rs` and used verbatim here.
//!
//! What remains duplicated is only the code that actually calls flash. The sync and async
//! `NorFlash` traits are unrelated types, so `flush_page`, `seal_and_advance`, the sector
//! scanners and the five `*_in_sector` readers exist in both flavours. That duplication is
//! deliberate: it buys zero-overhead sync and async types with no generic sync/async
//! machinery.
//!
//! ## Example
//!
//! ```ignore
//! use sensor_db::SensorDbAsync;
//!
//! let mut db: SensorDbAsync<_, 256, 512> = SensorDbAsync::new(
//!     flash, 0x0020_0000, 512, 2,
//! )?;
//!
//! db.mount().await?;
//! db.append(0x01, timestamp_us, &temperature_bytes).await?;
//! ```

use crate::db::{
    AppendStep, CompactScope, DbConfig, DbStats, Edge, LogPosition, MountMode, MountStats,
    ReadCursor, Replicated, Scan, ScannedEntry, ScannedSector, SectorScanner, SensorDbState,
    SpoolStats, sort_by_seq,
};
use crate::entry::{ENTRY_HEADER_SIZE, ENTRY_OVERHEAD, EntryHeader, EntryKind};
use crate::error::Error;
use crate::partition::Partition;
use crate::run::{RUN_FRAME_SIZE, Run, RunFrame, deliver_samples, samples_in};
use crate::schema;
use crate::sector::{
    LogId, SECTOR_FOOTER_SIZE, SECTOR_HEADER_SIZE, SectorClass, SectorFooter, SectorHeader,
    SectorState, SectorSummary,
};
use crate::typed::SensorData;
use embedded_storage_async::nor_flash::{NorFlash, ReadNorFlash};
use heapless::Vec as HeaplessVec;
use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};

/// Async twin of [`Geometry`](crate::db::Geometry): compile-time check that the
/// driver's write granularity divides `PAGE_SIZE`.
///
/// Duplicated rather than shared because `embedded-storage` and
/// `embedded-storage-async` are unrelated trait families — `WRITE_SIZE` has to be
/// read from whichever one the driver implements.
struct GeometryAsync<F: ?Sized, const PAGE_SIZE: usize>(core::marker::PhantomData<F>);

impl<F: NorFlash + ?Sized, const PAGE_SIZE: usize> GeometryAsync<F, PAGE_SIZE> {
    /// Fails the build when `PAGE_SIZE` is not a whole number of writes.
    const PAGE_IS_WRITABLE: () = assert!(
        PAGE_SIZE.is_multiple_of(F::WRITE_SIZE),
        "PAGE_SIZE must be a multiple of the flash driver's WRITE_SIZE",
    );
}

/// The blocking [`SectorScanner`] driven with `.await`ing reads.
///
/// There is no async *scanner*: the cursor and every decision it makes live in
/// [`crate::db`], I/O-free, and this is the loop that supplies the reads. The
/// pair of them replaced a hand-written mirror of the whole scanner, whose only
/// difference from the original was the `.await` — and which the byte-for-byte
/// parity suite could never have caught drifting, because a scan performed
/// wrongly by *both* drivers agrees with itself.
async fn next_entry_async<F: ReadNorFlash>(
    scanner: &mut SectorScanner,
    flash: &mut F,
    header_buf: &mut [u8; ENTRY_HEADER_SIZE],
    page_size: usize,
) -> Result<Option<ScannedEntry>, Error> {
    let mut step = scanner.begin();
    loop {
        match step {
            Scan::Done => return Ok(None),
            Scan::Found(entry) => return Ok(Some(entry)),
            Scan::Read(addr) => {
                flash.read(addr, &mut header_buf[..]).await?;
                step = scanner.feed(header_buf, page_size);
            }
        }
    }
}

/// [`ScannedEntry::accept`] with an `.await`ing read in front of it.
async fn accept_entry_async<F: ReadNorFlash>(
    flash: &mut F,
    sector_offset: u32,
    entry: &ScannedEntry,
    buf: &mut [u8],
) -> Result<bool, Error> {
    let (addr, read_len) = entry.payload_read(sector_offset);
    // Defensive: never slice past the caller's buffer on a malformed entry.
    if read_len > buf.len() {
        return Ok(false);
    }
    flash.read(addr, &mut buf[..read_len]).await?;
    Ok(entry.accept(buf))
}

/// Async append-only sensor database for NOR flash.
///
/// This is the async counterpart of [`SensorDb`](crate::SensorDb), using
/// `embedded-storage-async` traits for all flash operations. It is designed
/// for use with Embassy on targets that benefit from DMA-based flash access.
///
/// ## Key differences from `SensorDb`
///
/// - All flash-touching methods are `async fn`
/// - All methods take `&mut self` (no `RefCell` / interior mutability)
/// - Reuses the same wire format, sector layout, and `SensorDbState` value
///
/// Generic parameters:
/// - `F`: Flash storage implementing async `NorFlash` and `ReadNorFlash`
/// - `PAGE_SIZE`: the unit this database writes in. Must be a multiple of
///   `F::WRITE_SIZE`, checked at compile time, and must not exceed the part's
///   physical program page — which the trait does not express, so it cannot be
///   checked. See [`SensorDb`](crate::SensorDb) for the full contract.
/// - `MAX_SECTORS`: Maximum number of sectors this instance can manage
pub struct SensorDbAsync<F, const PAGE_SIZE: usize, const MAX_SECTORS: usize> {
    flash: F,
    state: SensorDbState<PAGE_SIZE, MAX_SECTORS>,
}

impl<F, const PAGE_SIZE: usize, const MAX_SECTORS: usize> core::fmt::Debug
    for SensorDbAsync<F, PAGE_SIZE, MAX_SECTORS>
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("SensorDbAsync")
            .field("base_offset", &self.state.base_offset)
            .field("sector_count", &self.state.sector_count)
            .field("sector_size", &self.state.sector_size)
            .field("mounted", &self.state.mounted)
            .field("active_sector", &self.state.active_sector)
            .field("total_entries", &self.state.total_entries)
            .finish_non_exhaustive()
    }
}

impl<F, const PAGE_SIZE: usize, const MAX_SECTORS: usize> SensorDbAsync<F, PAGE_SIZE, MAX_SECTORS>
where
    F: NorFlash + ReadNorFlash,
{
    /// Create a new async SensorDb instance.
    ///
    /// # Arguments
    /// - `flash`: Async flash storage
    /// - `base_offset`: Starting offset in flash for the database region
    /// - `sector_count`: Number of sectors to use
    /// - `reserved_sectors`: Number of sectors to keep free for compaction headroom
    ///
    /// # Errors
    /// - `TooManySectors` if `sector_count > MAX_SECTORS`
    /// - `InvalidConfig` if `reserved_sectors >= sector_count`
    pub fn new(
        flash: F,
        base_offset: u32,
        sector_count: u16,
        reserved_sectors: u16,
    ) -> Result<Self, Error> {
        Self::with_config(
            flash,
            DbConfig::new(base_offset, sector_count, reserved_sectors)?,
        )
    }

    /// Create a `SensorDbAsync` from a validated [`DbConfig`].
    ///
    /// Use this instead of [`new`](Self::new) when the database needs a
    /// [`LogId`] — for example when its storage is
    /// removable and could be carried to, or confused with, another device.
    ///
    /// # Errors
    /// - `TooManySectors` if `config.sector_count() > MAX_SECTORS`
    /// - `Overflow` if the region does not fit in `u32` address space
    ///
    /// # Panics
    ///
    /// Fails to *compile*, not to run, if `PAGE_SIZE` is not a multiple of
    /// `F::WRITE_SIZE`.
    pub fn with_config(flash: F, config: DbConfig) -> Result<Self, Error> {
        let () = GeometryAsync::<F, PAGE_SIZE>::PAGE_IS_WRITABLE;
        Ok(Self {
            flash,
            state: SensorDbState::new(config, F::ERASE_SIZE as u32)?,
        })
    }

    /// Format the database region, erasing all sectors and initializing the first as active.
    ///
    /// After format, the database is automatically mounted.
    pub async fn format(&mut self) -> Result<(), Error> {
        // Erase all sectors
        for i in 0..self.state.sector_count {
            self.erase_sector(i).await?;
            self.state.sectors[i as usize] = SectorSummary::erased();
            self.state.sectors[i as usize].erase_count = 1;
        }

        // Initialize first sector as active
        self.init_sector(0, 1, 1).await?;
        self.state.sectors[0].state = SectorState::Active;
        self.state.sectors[0].sequence = 1;
        self.state.sectors[0].write_offset = SECTOR_HEADER_SIZE as u32;
        self.state.sectors[0].erase_count = 1;

        self.state.active_sector = Some(0);
        self.state.next_sequence = 2;
        self.state.total_entries = 0;
        self.state.total_samples = 0;
        self.state.mounted = true;
        self.state.mount_mode = MountMode::Full;
        // `init_sector` above stamps epoch 1, so nothing is owed.
        self.state.epoch_pending = false;
        self.state.spool_watermark = LogPosition::BEGINNING;
        self.state.spooled_entries = 0;
        self.state.spooled_samples = 0;
        self.state.dropped_unspooled = 0;

        // Initialize page buffer for the active sector
        self.state.page_flash_offset = self.state.base_offset;
        self.state.page_buf_offset = SECTOR_HEADER_SIZE;
        self.state.page_buf_durable = SECTOR_HEADER_SIZE;
        self.state.page_buf.fill(0xFF);
        let header = self.state.sector_header(1, 1);
        self.state.page_buf[..SECTOR_HEADER_SIZE].copy_from_slice(header.as_bytes());

        Ok(())
    }

    /// Mount an existing database by scanning all sectors and rebuilding the index.
    ///
    /// Equivalent to [`mount_with(MountMode::Full)`](Self::mount_with).
    ///
    /// # Errors
    /// - `AlreadyMounted` if already mounted
    /// - `ForeignVolume` if the medium belongs to a different log
    /// - `UnsupportedVersion` if the medium uses a newer format
    pub async fn mount(&mut self) -> Result<MountStats, Error> {
        self.mount_with(MountMode::Full).await
    }

    /// Mount an existing database, choosing how much of the index to rebuild.
    ///
    /// See [`SensorDb::mount_with`](crate::SensorDb::mount_with) for the
    /// foreign-media and epoch semantics; they are identical here.
    ///
    /// # Errors
    /// - `AlreadyMounted` if already mounted
    /// - `ForeignVolume` if the medium belongs to a different log
    /// - `UnsupportedVersion` if the medium uses a newer format
    pub async fn mount_with(&mut self, mode: MountMode) -> Result<MountStats, Error> {
        if self.state.mounted {
            return Err(Error::AlreadyMounted);
        }

        let mut stats = MountStats::default();
        let mut max_sequence: u32 = 0;
        let mut max_epoch: u32 = 0;

        // Pass 1: headers only. Classification happens before any write, so a
        // foreign or unreadable volume is rejected intact.
        let mut valid: HeaplessVec<u16, MAX_SECTORS> = HeaplessVec::new();
        for i in 0..self.state.sector_count {
            let sector_offset = self.state.sector_offset(i);
            let mut header_buf = [0u8; SECTOR_HEADER_SIZE];
            self.flash.read(sector_offset, &mut header_buf).await?;

            let header =
                SectorHeader::read_from_bytes(&header_buf).map_err(|_| Error::CorruptEntry)?;

            match header.classify(self.state.log_id) {
                SectorClass::Valid => {
                    let seq = header.sequence.get();
                    let epoch = header.epoch.get();
                    self.state.sectors[i as usize].sequence = seq;
                    self.state.sectors[i as usize].erase_count = header.erase_count.get();
                    max_sequence = max_sequence.max(seq);
                    max_epoch = max_epoch.max(epoch);
                    let _ = valid.push(i);
                }
                SectorClass::Free => {
                    self.state.sectors[i as usize] = SectorSummary::erased();
                }
                SectorClass::Foreign { found } => {
                    return Err(Error::ForeignVolume {
                        expected: self.state.log_id_raw(),
                        found,
                    });
                }
                SectorClass::Unsupported { found } => {
                    return Err(Error::UnsupportedVersion { found });
                }
            }
        }

        // The newest sector is the only one an append can land in, so it must be
        // scanned in every mode to find the resume offset.
        let newest = valid
            .iter()
            .copied()
            .max_by_key(|i| self.state.sectors[*i as usize].sequence);

        // Pass 2: rebuild the entry index for the sectors this mode covers.
        // See the blocking driver for why `newest_sealed` is tracked.
        let mut newest_sealed = false;
        for i in valid.iter().copied() {
            let is_newest = Some(i) == newest;

            // Read a footer when it can index the sector — and always for the
            // newest one, where it is not an optimisation at all but the signal
            // that the sector is already closed.
            let footer = if self.state.wants_footer(mode, is_newest) {
                self.read_sector_footer(i).await?
            } else {
                None
            };
            if is_newest {
                newest_sealed = footer.is_some();
            }

            // `Verify` exists to re-read the medium, so it indexes from entries
            // even where a footer would have answered.
            if let Some(footer) = footer.filter(|_| mode != MountMode::Verify) {
                self.state.adopt_footer(i, &footer, &mut stats);
            } else if mode != MountMode::HeadersOnly || is_newest {
                let (scanned, corrupt) = self.scan_sector_entries(i).await?;
                self.state.adopt_scan(i, &scanned, corrupt, &mut stats);
            } else {
                self.state.adopt_unindexed(i);
            }
            self.state.sectors[i as usize].state = SectorState::Sealed;
            stats.sealed_sectors += 1;
        }

        self.state
            .finish_mount(mode, max_sequence, max_epoch, &stats);

        if let Some(idx) = newest {
            self.state.sectors[idx as usize].state = SectorState::Active;
            self.state.active_sector = Some(idx);
            stats.sealed_sectors = stats.sealed_sectors.saturating_sub(1);

            // This sector was created by an earlier run, so it carries that run's
            // epoch. Owe a sector roll, paid on the first append.
            self.state.epoch_pending = true;

            let sector_offset = self.state.sector_offset(idx);

            // Where writing resumes inside this sector — the footer page when
            // the sector was already sealed, so `append`'s boundary check seals
            // and moves on rather than appending into a frozen summary. See the
            // blocking driver.
            let resume = if newest_sealed {
                self.state.footer_offset()
            } else {
                self.state.sectors[idx as usize].write_offset
            };

            let page_start = (resume / PAGE_SIZE as u32) * PAGE_SIZE as u32;
            self.state.page_flash_offset = sector_offset + page_start;
            self.state.page_buf_offset = (resume % PAGE_SIZE as u32) as usize;
            self.state.page_buf_durable = self.state.page_buf_offset;
            self.state.page_buf.fill(0xFF);

            // A power loss can leave written bytes *past* the last valid entry,
            // and not only in this page: the scanner steps over uncommitted
            // entries without adopting them, so whole pages of half-committed
            // data can sit ahead of the resume point. Appending before them
            // would eventually flush into a dirty page, and NOR cannot set bits
            // back — the write fails and the log wedges.
            //
            // Find the last page in this sector that still holds data, and
            // resume after it. Bounded by the footer offset: the final page is
            // not data.
            let mut last_dirty: Option<u32> = None;
            let mut probe = page_start;
            while probe < self.state.footer_offset() {
                self.flash
                    .read(sector_offset + probe, &mut self.state.page_buf)
                    .await?;
                let from = if probe == page_start {
                    self.state.page_buf_offset
                } else {
                    0
                };
                if self.state.page_buf[from..].iter().any(|b| *b != 0xFF) {
                    last_dirty = Some(probe);
                }
                probe += PAGE_SIZE as u32;
            }

            match last_dirty {
                None if resume < self.state.footer_offset() => {
                    self.flash
                        .read(self.state.page_flash_offset, &mut self.state.page_buf)
                        .await?;
                }
                None => {}
                Some(dirty) => {
                    self.state.page_flash_offset = sector_offset + dirty + PAGE_SIZE as u32;
                    self.state.page_buf_offset = 0;
                    self.state.page_buf_durable = 0;
                    self.state.page_buf.fill(0xFF);
                    self.state.sectors[idx as usize].write_offset = dirty + PAGE_SIZE as u32;
                }
            }
        } else {
            // No valid sectors found. The chosen sector may hold stale data from a
            // previous format (NOR writes only clear bits, so writing a fresh
            // header over it would corrupt the magic), so erase before init.
            //
            // Reaching here means every sector classified as Free, so nothing
            // another log owns is being destroyed.
            self.erase_sector(0).await?;
            self.init_sector(0, self.state.next_sequence, 1).await?;
            // That header carries this run's epoch, so nothing is owed.
            self.state.epoch_pending = false;
            self.state.sectors[0].state = SectorState::Active;
            self.state.sectors[0].sequence = self.state.next_sequence;
            self.state.sectors[0].write_offset = SECTOR_HEADER_SIZE as u32;
            self.state.sectors[0].erase_count = 1;
            self.state.active_sector = Some(0);
            self.state.next_sequence += 1;

            self.state.page_flash_offset = self.state.base_offset;
            self.state.page_buf_offset = SECTOR_HEADER_SIZE;
            self.state.page_buf_durable = SECTOR_HEADER_SIZE;
            self.state.page_buf.fill(0xFF);
            let header = self.state.sector_header(self.state.sectors[0].sequence, 1);
            self.state.page_buf[..SECTOR_HEADER_SIZE].copy_from_slice(header.as_bytes());
        }

        self.state.mounted = true;
        Ok(stats)
    }

    /// Append a sensor reading to the database.
    ///
    /// # Errors
    /// - `NotMounted` if not mounted
    /// - `PayloadTooLarge` if payload exceeds max size
    /// - `NoSpace` if no sectors available
    pub async fn append(
        &mut self,
        sensor_id: u16,
        timestamp: u64,
        payload: &[u8],
    ) -> Result<(), Error> {
        self.append_entry(
            EntryKind::Single,
            sensor_id,
            timestamp,
            timestamp,
            1,
            &[],
            payload,
        )
        .await
    }

    /// Append a [run](crate::run): many evenly spaced samples under one header.
    ///
    /// Async mirror of [`SensorDb::append_run`](crate::SensorDb::append_run),
    /// including its invisibility to every read.
    pub async fn append_run(&mut self, run: &Run<'_>) -> Result<(), Error> {
        let mut frame = [0u8; RUN_FRAME_SIZE];
        run.write_frame(&mut frame);
        self.append_entry(
            EntryKind::Run,
            run.sensor_id(),
            run.base_timestamp(),
            run.span_end(),
            run.count(),
            &frame,
            run.samples(),
        )
        .await
    }

    /// Append an entry exactly as another log stored it.
    ///
    /// Async mirror of
    /// [`SensorDb::append_framed`](crate::SensorDb::append_framed).
    pub async fn append_framed(
        &mut self,
        header: &EntryHeader,
        payload: &[u8],
    ) -> Result<(), Error> {
        match header.kind {
            EntryKind::Single => {
                self.append(header.sensor_id, header.timestamp, payload)
                    .await
            }
            EntryKind::Run => {
                let frame = RunFrame::parse(payload).ok_or(Error::CorruptEntry)?;
                self.append_entry(
                    EntryKind::Run,
                    header.sensor_id,
                    header.timestamp,
                    frame.span_end(header.timestamp),
                    frame.count(),
                    &[],
                    payload,
                )
                .await
            }
        }
    }

    /// The one write path; see
    /// [`SensorDb::append_entry`](crate::SensorDb) for the reasoning.
    #[allow(clippy::too_many_arguments)]
    async fn append_entry(
        &mut self,
        kind: EntryKind,
        sensor_id: u16,
        timestamp: u64,
        span_end: u64,
        samples: u32,
        head: &[u8],
        tail: &[u8],
    ) -> Result<(), Error> {
        if !self.state.mounted {
            return Err(Error::NotMounted);
        }

        let payload_len = head.len() + tail.len();
        let entry_size = ENTRY_OVERHEAD + payload_len;
        if payload_len > self.max_payload_size() {
            return Err(Error::PayloadTooLarge);
        }

        // Roll to a fresh sector so this run's epoch reaches the medium; see the
        // blocking driver. `NoSpace` is tolerated — provenance never costs a
        // write.
        if self.state.epoch_pending {
            match self.seal_and_advance().await {
                Ok(()) => {}
                Err(Error::NoSpace) => self.state.epoch_pending = false,
                Err(e) => return Err(e),
            }
        }

        let mut sealed_once = false;
        loop {
            match self.state.plan_append(entry_size)? {
                AppendStep::Stage => break,
                AppendStep::FlushPage => self.flush_page().await?,
                AppendStep::Seal => {
                    if sealed_once {
                        return Err(Error::PayloadTooLarge);
                    }
                    sealed_once = true;
                    self.seal_and_advance().await?;
                }
            }
        }

        self.state
            .stage_entry(kind, sensor_id, timestamp, span_end, samples, head, tail)
    }

    /// Flush the page buffer to flash, committing buffered entries.
    pub async fn sync(&mut self) -> Result<(), Error> {
        if !self.state.mounted {
            return Err(Error::NotMounted);
        }
        self.flush_page().await?;
        Ok(())
    }

    /// Find the most recent entry for a given sensor.
    ///
    /// # Arguments
    /// - `sensor_id`: Sensor to query
    /// - `buf`: Buffer to receive payload
    ///
    /// # Returns
    /// `Some((header, payload_len))` if found, `None` if no entries for this sensor.
    pub async fn latest(
        &mut self,
        sensor_id: u16,
        buf: &mut [u8],
    ) -> Result<Option<(EntryHeader, usize)>, Error> {
        self.state.require_reads()?;

        let mut sector_order: HeaplessVec<(u16, u32), MAX_SECTORS> = HeaplessVec::new();
        for i in 0..self.state.sector_count {
            let summary = &self.state.sectors[i as usize];
            if summary.state != SectorState::Erased && summary.might_contain_sensor(sensor_id) {
                let _ = sector_order.push((i, summary.sequence));
            }
        }
        sort_by_seq(&mut sector_order, |a, b| b.cmp(a));

        let mut best: Option<(EntryHeader, usize)> = None;
        for (sector_idx, _) in sector_order {
            if let Some(result) = self
                .find_latest_in_sector(sector_idx, sensor_id, buf)
                .await?
            {
                best = Some(result);
                break;
            }
        }

        let min_ts = best.as_ref().map_or(0, |(h, _)| h.timestamp);
        if let Some((hdr, len)) = self
            .state
            .scan_page_buf_for_latest(sensor_id, min_ts, buf)?
        {
            best = Some((hdr, len));
        }

        Ok(best)
    }

    /// Query entries within a time range.
    ///
    /// # Arguments
    /// - `sensor_id`: Optional sensor filter (None for all sensors)
    /// - `t_start`: Start timestamp (inclusive)
    /// - `t_end`: End timestamp (inclusive)
    /// - `callback`: Called for each matching entry. Return `false` to stop early.
    ///
    /// # Returns
    /// Number of entries that matched.
    pub async fn query_range<C>(
        &mut self,
        sensor_id: Option<u16>,
        t_start: u64,
        t_end: u64,
        mut callback: C,
    ) -> Result<u32, Error>
    where
        C: FnMut(&EntryHeader, &[u8]) -> bool,
    {
        self.state.require_reads()?;

        let mut count = 0u32;

        let mut sector_order: HeaplessVec<(u16, u32), MAX_SECTORS> = HeaplessVec::new();
        for i in 0..self.state.sector_count {
            let summary = &self.state.sectors[i as usize];
            if summary.state != SectorState::Erased
                && summary.entry_count > 0
                && summary.overlaps_time_range(t_start, t_end)
                && sensor_id.is_none_or(|id| summary.might_contain_sensor(id))
            {
                let _ = sector_order.push((i, summary.sequence));
            }
        }
        sort_by_seq(&mut sector_order, u32::cmp);

        let mut entry_buf = [0u8; PAGE_SIZE];
        let mut stopped = false;

        for (sector_idx, _) in sector_order {
            stopped = self
                .scan_sector_for_query(
                    sector_idx,
                    sensor_id,
                    t_start,
                    t_end,
                    &mut entry_buf,
                    &mut count,
                    &mut callback,
                )
                .await?;
            if stopped {
                break;
            }
        }

        if !stopped {
            self.state.scan_page_buf_for_query(
                sensor_id,
                t_start,
                t_end,
                &mut entry_buf,
                &mut count,
                &mut callback,
            );
        }

        Ok(count)
    }

    /// Query all entries for a sensor (or all sensors) without time constraints.
    pub async fn query_all<C>(&mut self, sensor_id: Option<u16>, callback: C) -> Result<u32, Error>
    where
        C: FnMut(&EntryHeader, &[u8]) -> bool,
    {
        self.query_range(sensor_id, 0, u64::MAX, callback).await
    }

    /// Find the oldest (earliest) entry for a given sensor.
    pub async fn oldest(
        &mut self,
        sensor_id: u16,
        buf: &mut [u8],
    ) -> Result<Option<(EntryHeader, usize)>, Error> {
        self.state.require_reads()?;

        let mut sector_order: HeaplessVec<(u16, u32), MAX_SECTORS> = HeaplessVec::new();
        for i in 0..self.state.sector_count {
            let summary = &self.state.sectors[i as usize];
            if summary.state != SectorState::Erased && summary.might_contain_sensor(sensor_id) {
                let _ = sector_order.push((i, summary.sequence));
            }
        }
        sort_by_seq(&mut sector_order, u32::cmp);

        for (sector_idx, _) in sector_order {
            if let Some((header, payload_len)) = self
                .find_oldest_in_sector(sector_idx, sensor_id, buf)
                .await?
            {
                return Ok(Some((header, payload_len)));
            }
        }

        if let Some(result) = self.state.scan_page_buf_for_oldest(sensor_id, buf) {
            return Ok(Some(result));
        }

        Ok(None)
    }

    /// Count entries for a specific sensor (or all sensors).
    ///
    /// Exact, and priced, exactly as [`SensorDb::count`](crate::SensorDb::count)
    /// — the count matches what [`query_range`](Self::query_range) would yield,
    /// at the cost of a payload read per entry in each sector the bloom filter
    /// does not reject.
    pub async fn count(&mut self, sensor_id: Option<u16>) -> Result<u32, Error> {
        self.state.require_reads()?;

        let Some(target) = sensor_id else {
            return Ok(self.state.total_samples);
        };

        let mut count = 0u32;

        for i in 0..self.state.sector_count {
            let summary = &self.state.sectors[i as usize];
            if summary.state != SectorState::Erased && summary.might_contain_sensor(target) {
                count += self.count_sensor_in_sector(i, target).await?;
            }
        }

        count += self.state.count_sensor_in_page_buf(target);

        Ok(count)
    }

    /// Compact the database by erasing the oldest sealed sectors.
    ///
    /// See [`SensorDb::compact`](crate::SensorDb::compact) for the meaning of
    /// `scope`.
    pub async fn compact(&mut self, count: u16, scope: CompactScope) -> Result<u16, Error> {
        if !self.state.mounted {
            return Err(Error::NotMounted);
        }

        let mut sealed: HeaplessVec<(u16, u32), MAX_SECTORS> = HeaplessVec::new();
        for i in 0..self.state.sector_count {
            let summary = &self.state.sectors[i as usize];
            if summary.state != SectorState::Sealed {
                continue;
            }
            if scope == CompactScope::SpooledOnly && !self.state.is_fully_spooled(summary) {
                continue;
            }
            let _ = sealed.push((i, summary.sequence));
        }

        sort_by_seq(&mut sealed, u32::cmp);

        let mut erased = 0u16;
        for (sector_idx, _) in sealed.iter().take(count as usize) {
            let victim = self.state.sectors[*sector_idx as usize];
            self.erase_sector(*sector_idx).await?;
            // Only after the erase actually succeeded.
            self.state.account_eviction(&victim);
            self.state.sectors[*sector_idx as usize] = SectorSummary::erased();
            self.state.sectors[*sector_idx as usize].erase_count = victim.erase_count;
            erased += 1;
        }

        Ok(erased)
    }

    /// Sectors this instance has erased, since it was created.
    ///
    /// See [`SensorDb::sectors_erased`](crate::SensorDb::sectors_erased).
    pub fn sectors_erased(&self) -> u32 {
        self.state.sectors_erased
    }

    /// Get database statistics.
    pub fn stats(&self) -> DbStats {
        self.state.stats()
    }

    /// Check if the database is mounted.
    pub fn is_mounted(&self) -> bool {
        self.state.mounted
    }

    /// Maximum payload size that can fit in a single entry.
    pub fn max_payload_size(&self) -> usize {
        PAGE_SIZE - ENTRY_OVERHEAD
    }

    // -------------------------------------------------------------------------
    // Typed API - Layer 1: Explicit sensor ID with zerocopy types
    // -------------------------------------------------------------------------

    /// Append a typed value with an explicit sensor ID, untagged.
    ///
    /// Entries written this way carry no schema version and are not readable
    /// through the `*_sensor` methods.
    pub async fn append_value<T: IntoBytes + Immutable>(
        &mut self,
        sensor_id: u16,
        timestamp: u64,
        data: &T,
    ) -> Result<(), Error> {
        self.append(sensor_id, timestamp, data.as_bytes()).await
    }

    /// Find the most recent entry for a sensor and interpret as a typed value.
    pub async fn latest_value<T: FromBytes + KnownLayout>(
        &mut self,
        sensor_id: u16,
    ) -> Result<Option<(EntryHeader, T)>, Error> {
        let expected_size = core::mem::size_of::<T>();
        let mut buf = [0u8; PAGE_SIZE];

        match self.latest(sensor_id, &mut buf).await? {
            Some((header, payload_len)) => {
                if payload_len != expected_size {
                    return Err(Error::SizeMismatch {
                        expected: expected_size,
                        actual: payload_len,
                    });
                }
                let value =
                    T::read_from_bytes(&buf[..payload_len]).map_err(|_| Error::InvalidData)?;
                Ok(Some((header, value)))
            }
            None => Ok(None),
        }
    }

    // -------------------------------------------------------------------------
    // Typed API - Layer 2: Type-driven sensor ID via SensorData trait
    // -------------------------------------------------------------------------

    /// Append a sensor reading using the type-driven API.
    ///
    /// The payload is the type's `SCHEMA_VERSION` followed by the value's
    /// bytes; see [`SensorData::SCHEMA_VERSION`].
    pub async fn append_sensor<T: SensorData>(
        &mut self,
        timestamp: u64,
        data: &T,
    ) -> Result<(), Error> {
        // Bound before the await: a temporary in the call would not outlive it.
        let framed = schema::tag(data);
        self.append(T::SENSOR_ID, timestamp, framed.bytes()).await
    }

    /// Find the most recent entry for a sensor type.
    ///
    /// # Errors
    /// - `SizeMismatch` if the stored payload is not `size_of::<T>() + 1` bytes
    /// - `SchemaMismatch` if it was written under another `SCHEMA_VERSION`
    pub async fn latest_sensor<T: SensorData>(
        &mut self,
    ) -> Result<Option<(EntryHeader, T)>, Error> {
        let mut framed = schema::Tagged::<T>::empty();
        let found = self.latest(T::SENSOR_ID, framed.bytes_mut()).await?;
        schema::untag(found, framed)
    }

    /// Query sensor entries within a time range using the type-driven API.
    pub async fn query_sensor<T: SensorData, C>(
        &mut self,
        t_start: u64,
        t_end: u64,
        mut callback: C,
    ) -> Result<u32, Error>
    where
        C: FnMut(&EntryHeader, &T) -> bool,
    {
        let mut count = 0u32;

        self.query_range(Some(T::SENSOR_ID), t_start, t_end, |header, payload| {
            // Skipped, not raised — see the blocking driver.
            let Some(value) = schema::untag_payload::<T>(payload) else {
                return true;
            };
            count += 1;
            callback(header, &value)
        })
        .await?;

        Ok(count)
    }

    /// Query all entries for a sensor type without time constraints.
    pub async fn query_all_sensor<T: SensorData, C>(&mut self, callback: C) -> Result<u32, Error>
    where
        C: FnMut(&EntryHeader, &T) -> bool,
    {
        self.query_sensor(0, u64::MAX, callback).await
    }

    /// Find the oldest (earliest) entry for a sensor type.
    pub async fn oldest_sensor<T: SensorData>(
        &mut self,
    ) -> Result<Option<(EntryHeader, T)>, Error> {
        let mut framed = schema::Tagged::<T>::empty();
        let found = self.oldest(T::SENSOR_ID, framed.bytes_mut()).await?;
        schema::untag(found, framed)
    }

    /// Count entries for a sensor type.
    pub async fn count_sensor<T: SensorData>(&mut self) -> Result<u32, Error> {
        self.count(Some(T::SENSOR_ID)).await
    }

    // -------------------------------------------------------------------------
    // Replication primitives
    // -------------------------------------------------------------------------

    /// Deliver committed entries in log order, starting at `from` (inclusive).
    ///
    /// Async mirror of [`SensorDb::read_from`](crate::SensorDb::read_from); see
    /// there for the durability boundary, ordering, and gap semantics.
    ///
    /// # Errors
    /// - `NotMounted` if the database is not mounted
    /// - whatever the callback returns
    pub async fn read_from<C>(
        &mut self,
        from: LogPosition,
        max_entries: u32,
        mut callback: C,
    ) -> Result<ReadCursor, Error>
    where
        C: FnMut(LogPosition, &EntryHeader, &[u8]) -> Result<bool, Error>,
    {
        if !self.state.mounted {
            return Err(Error::NotMounted);
        }

        let mut order: HeaplessVec<(u16, u32), MAX_SECTORS> = HeaplessVec::new();
        let mut oldest_seq = u32::MAX;
        for i in 0..self.state.sector_count {
            let summary = &self.state.sectors[i as usize];
            if summary.state == SectorState::Erased {
                continue;
            }
            if summary.sequence < oldest_seq {
                oldest_seq = summary.sequence;
            }
            if summary.sequence >= from.sequence {
                let _ = order.push((i, summary.sequence));
            }
        }
        sort_by_seq(&mut order, u32::cmp);

        let gap =
            from != LogPosition::BEGINNING && oldest_seq != u32::MAX && from.sequence < oldest_seq;

        let mut cursor = ReadCursor {
            next: from,
            entries: 0,
            exhausted: false,
            gap,
        };

        if max_entries == 0 {
            return Ok(cursor);
        }

        let mut header_buf = [0u8; ENTRY_HEADER_SIZE];
        let mut buf = [0u8; PAGE_SIZE];
        let mut stopped = false;

        for (sector_idx, seq) in order {
            let sector_offset = self.state.sector_offset(sector_idx);
            // `write_offset` is the right limit even for the active sector: the
            // bytes past the last flush read back as 0xFF, so the scanner runs
            // out of page before it runs out of limit and stops on its own.
            let limit = self.state.sectors[sector_idx as usize].write_offset;
            let start = if seq == from.sequence {
                from.offset.max(SECTOR_HEADER_SIZE as u32)
            } else {
                SECTOR_HEADER_SIZE as u32
            };
            if start >= limit {
                continue;
            }

            let mut scanner = SectorScanner::new(sector_offset, start, limit);
            while let Some(entry) =
                next_entry_async(&mut scanner, &mut self.flash, &mut header_buf, PAGE_SIZE).await?
            {
                if !accept_entry_async(&mut self.flash, sector_offset, &entry, &mut buf).await? {
                    scanner.skip(1);
                    continue;
                }

                let position = LogPosition {
                    sequence: seq,
                    offset: entry.offset_in_sector,
                };
                let header = entry.header.to_header();
                // A rejected entry must not advance the cursor past it, or the
                // caller would resume after something it never accepted.
                if !callback(position, &header, &buf[..entry.payload_len])? {
                    stopped = true;
                    break;
                }

                scanner.skip(entry.entry_size);
                cursor.entries += 1;
                cursor.next = LogPosition {
                    sequence: seq,
                    offset: scanner.offset(),
                };

                if cursor.entries >= max_entries {
                    stopped = true;
                    break;
                }
            }

            if stopped {
                break;
            }
        }

        cursor.exhausted = !stopped;
        Ok(cursor)
    }

    /// Hand out entries buffered in RAM but not yet durable, then discard them.
    ///
    /// Async mirror of
    /// [`SensorDb::drain_unflushed`](crate::SensorDb::drain_unflushed). Touches
    /// no flash, so it works when the device has physically gone away.
    pub fn drain_unflushed<C>(&mut self, callback: C) -> Result<u32, Error>
    where
        C: FnMut(&EntryHeader, &[u8]) -> Result<(), Error>,
    {
        self.state.drain_unflushed(callback)
    }

    /// Show the RAM-buffered entries without removing them.
    ///
    /// Async mirror of
    /// [`SensorDb::peek_unflushed`](crate::SensorDb::peek_unflushed). Not
    /// `async`: it touches no flash.
    pub fn peek_unflushed<C>(&self, callback: C) -> Result<u32, Error>
    where
        C: FnMut(&EntryHeader, &[u8]) -> Result<(), Error>,
    {
        self.state.peek_unflushed(callback)
    }

    /// The epoch of the sector containing `position`.
    ///
    /// Async mirror of
    /// [`SensorDb::sector_epoch_at`](crate::SensorDb::sector_epoch_at).
    pub async fn sector_epoch_at(&mut self, position: LogPosition) -> Result<Option<u32>, Error> {
        if !self.state.mounted {
            return Err(Error::NotMounted);
        }
        let Some(idx) = self.state.sector_at_sequence(position.sequence) else {
            return Ok(None);
        };

        let offset = self.state.sector_offset(idx);
        let mut buf = [0u8; SECTOR_HEADER_SIZE];
        self.flash.read(offset, &mut buf).await?;
        let header = SectorHeader::read_from_bytes(&buf).map_err(|_| Error::CorruptEntry)?;
        Ok(header.is_valid().then(|| header.epoch.get()))
    }

    /// Declare this log a replica of another, suppressing the per-run epoch roll.
    ///
    /// See [`SensorDb::mark_as_replica`](crate::SensorDb::mark_as_replica).
    pub fn mark_as_replica(&mut self) {
        self.state.epoch_pending = false;
    }

    /// Position immediately after the newest entry, buffered entries included.
    pub fn head_position(&self) -> LogPosition {
        self.state.head_position()
    }

    /// Position of the oldest entry the log still retains.
    pub fn tail_position(&self) -> LogPosition {
        self.state.tail_position()
    }

    /// Advance the replication watermark. See
    /// [`SensorDb::note_spooled`](crate::SensorDb::note_spooled).
    pub fn note_spooled(&mut self, upto: LogPosition, moved: Replicated) {
        self.state.note_spooled(upto, moved);
    }

    /// Restore the replication watermark from an external source of truth. See
    /// [`SensorDb::restore_spool_watermark`](crate::SensorDb::restore_spool_watermark),
    /// including why an `Err` leaves the log fully usable.
    ///
    /// `async` because exact accounting costs one scan of the sector the
    /// watermark falls inside.
    pub async fn restore_spool_watermark(&mut self, upto: LogPosition) -> Result<(), Error> {
        let Some(boundary) = self.state.restore_spool_watermark(upto) else {
            return Ok(());
        };
        let counted = self.count_entries_before(boundary, upto.offset).await?;
        self.state.add_spooled(counted);
        Ok(())
    }

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

    /// This log's declared identity, if any.
    pub fn log_id(&self) -> Option<LogId> {
        self.state.log_id
    }

    /// The current epoch — one higher than any epoch seen on the medium at mount.
    pub fn epoch(&self) -> u32 {
        self.state.epoch
    }

    /// How much of the index the current mount rebuilt.
    pub fn mount_mode(&self) -> MountMode {
        self.state.mount_mode
    }

    /// Flash access bounded to `[base, base + len)`.
    ///
    /// The async counterpart of
    /// [`SensorDb::with_region`](crate::SensorDb::with_region), and it returns
    /// the [`Partition`] rather than taking a closure: a closure cannot express
    /// an awaited operation, because the future it returned would borrow from
    /// its own argument and the signature has nowhere to tie that lifetime to.
    ///
    /// The same check applies — a region intersecting the database's sectors is
    /// rejected with [`Error::RegionOverlap`] — and it applies at the point the
    /// partition is handed out, which is the only place it can be applied.
    ///
    /// # Errors
    /// - `RegionOverlap` if the region intersects the database's sectors
    /// - `InvalidConfig` if `base` or `len` is misaligned, `len` is zero, or the
    ///   region runs past the device's capacity
    /// - `Overflow` if `base + len` does not fit in `u32`
    pub fn region(&mut self, base: u32, len: u32) -> Result<Partition<&mut F>, Error> {
        self.state.check_disjoint(base, len)?;
        Partition::new_async(&mut self.flash, base, len)
    }

    /// Borrow the underlying flash driver.
    ///
    /// See [`SensorDb::driver_mut`](crate::SensorDb::driver_mut): driver
    /// capabilities only — presence detection, wear counters, chip
    /// identification, power modes. To address flash, use
    /// [`region`](Self::region), which is checked.
    pub fn driver_mut(&mut self) -> &mut F {
        &mut self.flash
    }

    /// Consume the database and return the underlying flash storage.
    pub fn into_inner(self) -> F {
        self.flash
    }

    // =========================================================================
    // Async flash-accessing helpers
    // =========================================================================

    async fn erase_sector(&mut self, sector_idx: u16) -> Result<(), Error> {
        let offset = self.state.sector_offset(sector_idx);
        self.flash
            .erase(offset, offset + self.state.sector_size)
            .await?;
        // After the erase, so the count is of sectors actually erased. A failure
        // reaches the caller as an error, which is a louder signal than this.
        self.state.sectors_erased = self.state.sectors_erased.saturating_add(1);
        Ok(())
    }

    async fn init_sector(
        &mut self,
        sector_idx: u16,
        sequence: u32,
        erase_count: u32,
    ) -> Result<(), Error> {
        let header = self.state.sector_header(sequence, erase_count);
        let offset = self.state.sector_offset(sector_idx);

        let mut page = [0xFFu8; PAGE_SIZE];
        page[..SECTOR_HEADER_SIZE].copy_from_slice(header.as_bytes());
        self.flash.write(offset, &page).await?;

        Ok(())
    }

    /// Read and validate the footer of `sector_idx`; `None` for anything that
    /// does not describe this sector's current incarnation. See the blocking
    /// driver's `read_sector_footer`.
    async fn read_sector_footer(&mut self, sector_idx: u16) -> Result<Option<SectorFooter>, Error> {
        let offset = self.state.sector_offset(sector_idx) + self.state.footer_offset();
        let mut buf = [0u8; SECTOR_FOOTER_SIZE];
        self.flash.read(offset, &mut buf).await?;

        let footer = SectorFooter::read_from_bytes(&buf).map_err(|_| Error::CorruptEntry)?;
        let sequence = self.state.sectors[sector_idx as usize].sequence;
        Ok(footer.describes(sequence).then_some(footer))
    }

    /// Write `sector_idx`'s summary into its reserved final page. See the
    /// blocking driver's `write_sector_footer`.
    async fn write_sector_footer(&mut self, sector_idx: u16) -> Result<(), Error> {
        debug_assert_eq!(
            self.state.page_buf_offset, self.state.page_buf_durable,
            "a sector is sealed only with a page buffer that flash already has"
        );

        let footer = SectorFooter::new(&self.state.sectors[sector_idx as usize]);
        let mut page = [0xFFu8; PAGE_SIZE];
        page[..SECTOR_FOOTER_SIZE].copy_from_slice(footer.as_bytes());
        let offset = self.state.sector_offset(sector_idx) + self.state.footer_offset();
        self.flash.write(offset, &page).await?;
        Ok(())
    }

    async fn flush_page(&mut self) -> Result<(), Error> {
        let Some(addr) = self.state.commit_target() else {
            return Ok(());
        };
        // Phase 1: the entries still carry flags=0xFF (uncommitted).
        self.flash.write(addr, &self.state.page_buf).await?;
        // Phase 2: mark, then re-write the same page.
        self.state.mark_page_committed();
        self.flash.write(addr, &self.state.page_buf).await?;
        self.state.advance_page();
        Ok(())
    }

    async fn seal_and_advance(&mut self) -> Result<(), Error> {
        let old_active = self.state.sealing()?;

        // Deliberately not propagated: the footer is an optimisation and must
        // never make the log less usable than it would be without one. See the
        // blocking driver for the full argument.
        let _ = self.write_sector_footer(old_active).await;

        let plan = self.state.begin_seal(old_active)?;
        self.erase_sector(plan.new_active).await?;
        self.state.account_seal(&plan);
        self.init_sector(plan.new_active, self.state.next_sequence, plan.erase_count)
            .await?;
        self.state.finish_seal(&plan);

        Ok(())
    }

    async fn scan_sector_entries(
        &mut self,
        sector_idx: u16,
    ) -> Result<(ScannedSector, u32), Error> {
        let sector_offset = self.state.sector_offset(sector_idx);
        let entry_start = SECTOR_HEADER_SIZE as u32;
        // Bounded by the footer offset, not the sector size: the final page
        // holds a summary, not entries.
        let mut scanner =
            SectorScanner::new(sector_offset, entry_start, self.state.footer_offset());
        let mut header_buf = [0u8; ENTRY_HEADER_SIZE];
        let mut buf = [0u8; PAGE_SIZE];

        let mut found = ScannedSector {
            write_offset: entry_start,
            ..ScannedSector::EMPTY
        };

        while let Some(entry) =
            next_entry_async(&mut scanner, &mut self.flash, &mut header_buf, PAGE_SIZE).await?
        {
            if !accept_entry_async(&mut self.flash, sector_offset, &entry, &mut buf).await? {
                scanner.corrupt_count += 1;
                scanner.skip(1);
                continue;
            }

            found.record(&entry, &buf[..entry.payload_len]);

            scanner.skip(entry.entry_size);
            found.write_offset = scanner.offset();
        }

        Ok((found, scanner.corrupt_count()))
    }

    async fn find_latest_in_sector(
        &mut self,
        sector_idx: u16,
        target_sensor: u16,
        buf: &mut [u8],
    ) -> Result<Option<(EntryHeader, usize)>, Error> {
        let sector_offset = self.state.sector_offset(sector_idx);
        let write_offset = self.state.sectors[sector_idx as usize].write_offset;
        let entry_start = SECTOR_HEADER_SIZE as u32;
        let mut scanner = SectorScanner::new(sector_offset, entry_start, write_offset);
        let mut header_buf = [0u8; ENTRY_HEADER_SIZE];
        let mut payload_buf = [0u8; PAGE_SIZE];

        let mut latest: Option<(EntryHeader, usize)> = None;
        let mut latest_ts = 0u64;

        while let Some(entry) =
            next_entry_async(&mut scanner, &mut self.flash, &mut header_buf, PAGE_SIZE).await?
        {
            if !accept_entry_async(&mut self.flash, sector_offset, &entry, &mut payload_buf).await?
            {
                scanner.skip(1);
                continue;
            }

            if entry.sensor_id() == target_sensor {
                let (header, payload) =
                    entry.edge(&mut payload_buf[..entry.payload_len], Edge::Last);

                if header.timestamp >= latest_ts {
                    let len = payload.len();
                    if len > buf.len() {
                        return Err(Error::BufferTooSmall);
                    }
                    buf[..len].copy_from_slice(payload);
                    latest_ts = header.timestamp;
                    latest = Some((header, len));
                }
            }

            scanner.skip(entry.entry_size);
        }

        Ok(latest)
    }

    #[allow(clippy::too_many_arguments)]
    async fn scan_sector_for_query<C>(
        &mut self,
        sector_idx: u16,
        sensor_filter: Option<u16>,
        t_start: u64,
        t_end: u64,
        buf: &mut [u8],
        count: &mut u32,
        callback: &mut C,
    ) -> Result<bool, Error>
    where
        C: FnMut(&EntryHeader, &[u8]) -> bool,
    {
        let sector_offset = self.state.sector_offset(sector_idx);
        let write_offset = self.state.sectors[sector_idx as usize].write_offset;
        let entry_start = SECTOR_HEADER_SIZE as u32;
        let mut scanner = SectorScanner::new(sector_offset, entry_start, write_offset);
        let mut header_buf = [0u8; ENTRY_HEADER_SIZE];

        while let Some(entry) =
            next_entry_async(&mut scanner, &mut self.flash, &mut header_buf, PAGE_SIZE).await?
        {
            if !accept_entry_async(&mut self.flash, sector_offset, &entry, buf).await? {
                scanner.skip(1);
                continue;
            }

            let sensor = entry.sensor_id();

            if sensor_filter.is_none_or(|f| f == sensor)
                && deliver_samples(
                    entry.is_run(),
                    sensor,
                    entry.timestamp(),
                    &mut buf[..entry.payload_len],
                    t_start,
                    t_end,
                    count,
                    callback,
                )
            {
                return Ok(true);
            }

            scanner.skip(entry.entry_size);
        }

        Ok(false)
    }

    async fn find_oldest_in_sector(
        &mut self,
        sector_idx: u16,
        target_sensor: u16,
        buf: &mut [u8],
    ) -> Result<Option<(EntryHeader, usize)>, Error> {
        let sector_offset = self.state.sector_offset(sector_idx);
        let write_offset = self.state.sectors[sector_idx as usize].write_offset;
        let entry_start = SECTOR_HEADER_SIZE as u32;
        let mut scanner = SectorScanner::new(sector_offset, entry_start, write_offset);
        let mut header_buf = [0u8; ENTRY_HEADER_SIZE];
        let mut payload_buf = [0u8; PAGE_SIZE];

        while let Some(entry) =
            next_entry_async(&mut scanner, &mut self.flash, &mut header_buf, PAGE_SIZE).await?
        {
            if !accept_entry_async(&mut self.flash, sector_offset, &entry, &mut payload_buf).await?
            {
                scanner.skip(1);
                continue;
            }

            if entry.sensor_id() == target_sensor {
                let (header, payload) =
                    entry.edge(&mut payload_buf[..entry.payload_len], Edge::First);

                if payload.len() > buf.len() {
                    return Err(Error::BufferTooSmall);
                }
                buf[..payload.len()].copy_from_slice(payload);
                return Ok(Some((header, payload.len())));
            }

            scanner.skip(entry.entry_size);
        }

        Ok(None)
    }

    /// Count the entries in `sector_idx` that start below `offset_limit`.
    ///
    /// Async mirror of `SensorDbState::count_entries_before`.
    async fn count_entries_before(
        &mut self,
        sector_idx: u16,
        offset_limit: u32,
    ) -> Result<Replicated, Error> {
        let sector_offset = self.state.sector_offset(sector_idx);
        let entry_count = self.state.sectors[sector_idx as usize].entry_count;
        let sample_count = self.state.sectors[sector_idx as usize].sample_count;
        let write_offset = self.state.sectors[sector_idx as usize].write_offset;
        let entry_start = SECTOR_HEADER_SIZE as u32;
        let limit = offset_limit.min(write_offset);
        if limit <= entry_start {
            return Ok(Replicated::NONE);
        }

        let mut scanner = SectorScanner::new(sector_offset, entry_start, limit);
        let mut header_buf = [0u8; ENTRY_HEADER_SIZE];
        let mut buf = [0u8; PAGE_SIZE];
        let mut found = Replicated::NONE;

        while let Some(entry) =
            next_entry_async(&mut scanner, &mut self.flash, &mut header_buf, PAGE_SIZE).await?
        {
            if !accept_entry_async(&mut self.flash, sector_offset, &entry, &mut buf).await? {
                scanner.skip(1);
                continue;
            }
            found.push(samples_in(entry.is_run(), &buf[..entry.payload_len]));
            scanner.skip(entry.entry_size);
        }

        Ok(Replicated {
            entries: found.entries.min(entry_count),
            samples: found.samples.min(sample_count),
        })
    }

    /// Count the entries in `sector_idx` belonging to `target_sensor`.
    ///
    /// CRC-validated, matching the blocking driver's
    /// [`count_sensor_in_sector`](crate::SensorDb) and this driver's own query
    /// path: `count` and `query_range` must not disagree about how many entries
    /// exist.
    async fn count_sensor_in_sector(
        &mut self,
        sector_idx: u16,
        target_sensor: u16,
    ) -> Result<u32, Error> {
        let sector_offset = self.state.sector_offset(sector_idx);
        let write_offset = self.state.sectors[sector_idx as usize].write_offset;
        let entry_start = SECTOR_HEADER_SIZE as u32;
        let mut scanner = SectorScanner::new(sector_offset, entry_start, write_offset);
        let mut header_buf = [0u8; ENTRY_HEADER_SIZE];
        let mut payload_buf = [0u8; PAGE_SIZE];
        let mut count = 0u32;

        while let Some(entry) =
            next_entry_async(&mut scanner, &mut self.flash, &mut header_buf, PAGE_SIZE).await?
        {
            // Every entry is verified, not only the matching ones — see the
            // blocking driver for why a selective check walks the sector
            // differently from the read path.
            if !accept_entry_async(&mut self.flash, sector_offset, &entry, &mut payload_buf).await?
            {
                scanner.skip(1);
                continue;
            }
            if entry.sensor_id() == target_sensor {
                // Samples, not entries: a run answers for all of its own, which
                // is what `query_range` would yield for it.
                count += samples_in(entry.is_run(), &payload_buf[..entry.payload_len]);
            }
            scanner.skip(entry.entry_size);
        }

        Ok(count)
    }
}

// =============================================================================
// Capability ports
// =============================================================================
//
// Delegation only, spelled with UFCS — see the note on the blocking driver's
// impls for why the inherent method is never reached through `self.`.

impl<F, const PAGE_SIZE: usize, const MAX_SECTORS: usize> crate::port::LogSinkAsync
    for SensorDbAsync<F, PAGE_SIZE, MAX_SECTORS>
where
    F: NorFlash + ReadNorFlash,
{
    fn append(
        &mut self,
        sensor_id: u16,
        timestamp: u64,
        payload: &[u8],
    ) -> impl core::future::Future<Output = Result<(), Error>> {
        SensorDbAsync::append(self, sensor_id, timestamp, payload)
    }

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

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

impl<F, const PAGE_SIZE: usize, const MAX_SECTORS: usize> crate::port::LogSourceAsync
    for SensorDbAsync<F, PAGE_SIZE, MAX_SECTORS>
where
    F: NorFlash + ReadNorFlash,
{
    fn latest(
        &mut self,
        sensor_id: u16,
        buf: &mut [u8],
    ) -> impl core::future::Future<Output = Result<Option<(EntryHeader, usize)>, Error>> {
        SensorDbAsync::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>> {
        SensorDbAsync::oldest(self, sensor_id, buf)
    }

    fn count(
        &mut self,
        sensor_id: Option<u16>,
    ) -> impl core::future::Future<Output = Result<u32, Error>> {
        SensorDbAsync::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>> {
        SensorDbAsync::query_range(self, sensor_id, t_start, t_end, callback)
    }
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(all(test, feature = "std", feature = "async"))]
mod tests {
    extern crate alloc;
    use alloc::vec;
    use alloc::vec::Vec;

    use super::*;
    use crate::entry::{ENTRY_CRC_SIZE, EntryHeaderWire, FLAGS_COMMITTED, compute_entry_crc};
    use crate::mock::{MockFlash, MockFlashAsync, block_on};

    const PAGE: usize = 256;
    const SECTOR: usize = 4096;
    const SECTORS: usize = 8;

    // -------------------------------------------------------------------------
    // Helper
    // -------------------------------------------------------------------------

    fn make_db() -> SensorDbAsync<MockFlashAsync<PAGE, SECTOR>, PAGE, SECTORS> {
        let flash = MockFlashAsync::<PAGE, SECTOR>::new(SECTORS * SECTOR);
        let mut db = SensorDbAsync::new(flash, 0, SECTORS as u16, 1).unwrap();
        block_on(db.format()).unwrap();
        db
    }

    // -------------------------------------------------------------------------
    // Tests
    // -------------------------------------------------------------------------

    #[test]
    fn async_format_and_mount() {
        let flash = MockFlashAsync::<PAGE, SECTOR>::new(SECTORS * SECTOR);
        let mut db: SensorDbAsync<_, PAGE, SECTORS> =
            SensorDbAsync::new(flash, 0, SECTORS as u16, 1).unwrap();
        block_on(db.format()).unwrap();
        assert!(db.is_mounted());
        assert_eq!(db.stats().total_entries, 0);
    }

    #[test]
    fn async_append_and_latest() {
        let mut db = make_db();
        let payload = [0xDE, 0xAD, 0xBE, 0xEF];
        block_on(db.append(1, 1000, &payload)).unwrap();
        block_on(db.append(2, 1001, &[0x42])).unwrap();
        block_on(db.append(1, 1002, &[0x01, 0x02])).unwrap();

        let mut buf = [0u8; 16];
        let (hdr, n) = block_on(db.latest(1, &mut buf)).unwrap().unwrap();
        assert_eq!(hdr.sensor_id, 1);
        assert_eq!(hdr.timestamp, 1002);
        assert_eq!(&buf[..n], &[0x01, 0x02]);

        let (hdr2, n2) = block_on(db.latest(2, &mut buf)).unwrap().unwrap();
        assert_eq!(hdr2.sensor_id, 2);
        assert_eq!(&buf[..n2], &[0x42]);
    }

    #[test]
    fn async_query_range_filters() {
        let mut db = make_db();
        block_on(db.append(1, 100, &[0x01])).unwrap();
        block_on(db.append(1, 200, &[0x02])).unwrap();
        block_on(db.append(2, 150, &[0x0A])).unwrap();
        block_on(db.append(1, 300, &[0x03])).unwrap();
        block_on(db.sync()).unwrap();

        let mut results = Vec::new();
        let count = block_on(db.query_range(Some(1), 100, 250, |hdr, payload| {
            results.push((hdr.timestamp, payload[0]));
            true
        }))
        .unwrap();

        assert_eq!(count, 2);
        assert_eq!(results, vec![(100, 0x01), (200, 0x02)]);
    }

    #[test]
    fn async_survives_remount() {
        let flash = MockFlashAsync::<PAGE, SECTOR>::new(SECTORS * SECTOR);
        let mut db: SensorDbAsync<_, PAGE, SECTORS> =
            SensorDbAsync::new(flash, 0, SECTORS as u16, 1).unwrap();
        block_on(db.format()).unwrap();

        block_on(db.append(5, 42, &[0xAA, 0xBB])).unwrap();
        block_on(db.append(5, 43, &[0xCC])).unwrap();
        block_on(db.sync()).unwrap();

        let flash = db.into_inner();
        let mut db2: SensorDbAsync<_, PAGE, SECTORS> =
            SensorDbAsync::new(flash, 0, SECTORS as u16, 1).unwrap();
        let mount_stats = block_on(db2.mount()).unwrap();

        assert_eq!(mount_stats.total_entries, 2);

        let mut buf = [0u8; 16];
        let (hdr, n) = block_on(db2.latest(5, &mut buf)).unwrap().unwrap();
        assert_eq!(hdr.timestamp, 43);
        assert_eq!(&buf[..n], &[0xCC]);
    }

    #[test]
    fn async_circular_wrap() {
        const SMALL: usize = 4;
        let flash = MockFlashAsync::<PAGE, SECTOR>::new(SMALL * SECTOR);
        let mut db: SensorDbAsync<_, PAGE, SMALL> =
            SensorDbAsync::new(flash, 0, SMALL as u16, 1).unwrap();
        block_on(db.format()).unwrap();

        for i in 0..800u64 {
            let payload = (i as u32).to_le_bytes();
            block_on(db.append(1, i * 100, &payload)).unwrap();
        }

        let stats = db.stats();
        assert!(stats.total_entries > 0);
        assert!(stats.used_sectors <= SMALL as u16);

        let mut buf = [0u8; 4];
        let (hdr, _) = block_on(db.latest(1, &mut buf)).unwrap().unwrap();
        assert_eq!(hdr.timestamp, 799 * 100);
    }

    #[test]
    fn async_compact() {
        let mut db = make_db();
        for i in 0..50u64 {
            block_on(db.append(1, i, &[i as u8])).unwrap();
        }
        block_on(db.sync()).unwrap();

        let before = db.stats();
        let freed = block_on(db.compact(1, CompactScope::All)).unwrap();
        let after = db.stats();

        if before.used_sectors > 1 {
            assert!(freed > 0);
            assert!(after.free_sectors > before.free_sectors);
        }
    }

    #[test]
    fn async_oldest() {
        let mut db = make_db();
        block_on(db.append(1, 100, &[0x01])).unwrap();
        block_on(db.append(1, 200, &[0x02])).unwrap();
        block_on(db.append(1, 300, &[0x03])).unwrap();
        block_on(db.sync()).unwrap();

        let mut buf = [0u8; 16];
        let (hdr, n) = block_on(db.oldest(1, &mut buf)).unwrap().unwrap();
        assert_eq!(hdr.timestamp, 100);
        assert_eq!(&buf[..n], &[0x01]);
    }

    #[test]
    fn async_count() {
        let mut db = make_db();
        block_on(db.append(1, 100, &[0x01])).unwrap();
        block_on(db.append(2, 200, &[0x02])).unwrap();
        block_on(db.append(1, 300, &[0x03])).unwrap();
        block_on(db.sync()).unwrap();

        assert_eq!(block_on(db.count(None)).unwrap(), 3);
        assert_eq!(block_on(db.count(Some(1))).unwrap(), 2);
        assert_eq!(block_on(db.count(Some(2))).unwrap(), 1);
        assert_eq!(block_on(db.count(Some(99))).unwrap(), 0);
    }

    #[test]
    fn async_typed_api() {
        use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};

        #[derive(Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable)]
        #[repr(C)]
        struct Temp {
            celsius: f32,
        }

        impl SensorData for Temp {
            const SENSOR_ID: u16 = 0x01;
        }

        let mut db = make_db();
        block_on(db.append_sensor(1000, &Temp { celsius: 25.5 })).unwrap();
        block_on(db.append_sensor(2000, &Temp { celsius: 26.0 })).unwrap();
        block_on(db.sync()).unwrap();

        let (hdr, val) = block_on(db.latest_sensor::<Temp>()).unwrap().unwrap();
        assert_eq!(hdr.timestamp, 2000);
        assert_eq!(val.celsius, 26.0);

        let (hdr, val) = block_on(db.oldest_sensor::<Temp>()).unwrap().unwrap();
        assert_eq!(hdr.timestamp, 1000);
        assert_eq!(val.celsius, 25.5);

        assert_eq!(block_on(db.count_sensor::<Temp>()).unwrap(), 2);
    }

    #[test]
    fn async_max_payload() {
        let mut db = make_db();
        let max = db.max_payload_size();
        let payload = vec![0x42u8; max];
        block_on(db.append(1, 999, &payload)).unwrap();
        block_on(db.sync()).unwrap();

        let mut buf = vec![0u8; max];
        let (hdr, n) = block_on(db.latest(1, &mut buf)).unwrap().unwrap();
        assert_eq!(n, max);
        assert_eq!(hdr.payload_len as usize, max);
    }

    #[test]
    fn async_rejects_oversized() {
        let mut db = make_db();
        let too_big = vec![0u8; db.max_payload_size() + 1];
        let result = block_on(db.append(1, 100, &too_big));
        assert!(result.is_err());
    }

    /// Async mirror of `scanner_resyncs_past_oversized_false_marker`
    /// (`tests/comprehensive.rs`): the field crash that motivated this fix was in
    /// `verify_entry_crc_async`. A forged false marker encodes an oversized
    /// `payload_len` (3840) that fits the sector (4096) but dwarfs the 256-byte
    /// verify buffer. The async scanner must reject it on the `payload_len` bound,
    /// resync, and still find the valid entry that follows — no panic.
    #[test]
    fn async_scanner_resyncs_past_oversized_false_marker() {
        use embedded_storage::nor_flash::NorFlash as SyncNorFlash;
        use zerocopy::IntoBytes;

        let mut raw = MockFlash::<PAGE, SECTOR>::new(SECTORS * SECTOR);
        let mut page = [0xFFu8; PAGE];

        let sh = SectorHeader::new(None, 1, 1, 1);
        page[..SECTOR_HEADER_SIZE].copy_from_slice(sh.as_bytes());

        // E1: real committed entry just after the sector header.
        let e1_off = SECTOR_HEADER_SIZE;
        let e1_payload = [0x01u8, 0x02, 0x03, 0x04];
        let mut e1 = EntryHeaderWire::new(1, 100, e1_payload.len() as u16);
        let e1_crc = compute_entry_crc(&e1, &e1_payload, e1_off as u32);
        e1.flags = FLAGS_COMMITTED;
        page[e1_off..e1_off + ENTRY_HEADER_SIZE].copy_from_slice(e1.as_bytes());
        page[e1_off + ENTRY_HEADER_SIZE..e1_off + ENTRY_HEADER_SIZE + e1_payload.len()]
            .copy_from_slice(&e1_payload);
        let e1_crc_off = e1_off + ENTRY_HEADER_SIZE + e1_payload.len();
        page[e1_crc_off..e1_crc_off + ENTRY_CRC_SIZE].copy_from_slice(&e1_crc.to_le_bytes());

        // Forged false marker: "committed" header with payload_len = 3840.
        let forged_off = e1_crc_off + ENTRY_CRC_SIZE;
        let mut forged = EntryHeaderWire::new(1, 0, 3840);
        forged.flags = FLAGS_COMMITTED;
        page[forged_off..forged_off + ENTRY_HEADER_SIZE].copy_from_slice(forged.as_bytes());

        // E2: real committed entry after the forged header.
        let e2_off = forged_off + ENTRY_HEADER_SIZE;
        let e2_payload = [0x11u8, 0x22, 0x33, 0x44];
        let mut e2 = EntryHeaderWire::new(1, 200, e2_payload.len() as u16);
        let e2_crc = compute_entry_crc(&e2, &e2_payload, e2_off as u32);
        e2.flags = FLAGS_COMMITTED;
        page[e2_off..e2_off + ENTRY_HEADER_SIZE].copy_from_slice(e2.as_bytes());
        page[e2_off + ENTRY_HEADER_SIZE..e2_off + ENTRY_HEADER_SIZE + e2_payload.len()]
            .copy_from_slice(&e2_payload);
        let e2_crc_off = e2_off + ENTRY_HEADER_SIZE + e2_payload.len();
        page[e2_crc_off..e2_crc_off + ENTRY_CRC_SIZE].copy_from_slice(&e2_crc.to_le_bytes());

        raw.write(0, &page).unwrap();

        let flash = MockFlashAsync::<PAGE, SECTOR>::wrap(raw);
        let mut db: SensorDbAsync<_, PAGE, SECTORS> =
            SensorDbAsync::new(flash, 0, SECTORS as u16, 1).unwrap();
        let stats = block_on(db.mount()).unwrap();
        assert_eq!(
            stats.total_entries, 2,
            "both real entries found, forged skipped"
        );
        assert!(
            stats.corrupt_entries > 0,
            "forged marker counted as corrupt"
        );

        let mut buf = [0u8; 16];
        let (hdr, n) = block_on(db.latest(1, &mut buf)).unwrap().unwrap();
        assert_eq!(hdr.timestamp, 200);
        assert_eq!(&buf[..n], &e2_payload);
    }

    /// Restoring a mid-sector watermark must give the same answer as the
    /// blocking driver — the two boundary scanners are hand-written mirrors, and
    /// a difference in either the scan limit or the entry-acceptance test would
    /// show up as a different count.
    #[test]
    fn async_restore_spool_watermark_matches_the_blocking_driver() {
        use crate::SensorDb;

        let mut a = make_db();
        let mut b: SensorDb<MockFlash<PAGE, SECTOR>, PAGE, SECTORS> =
            SensorDb::new(MockFlash::new(SECTORS * SECTOR), 0, SECTORS as u16, 1).unwrap();
        b.format().unwrap();
        for i in 0..500u64 {
            block_on(a.append(1, i, &[i as u8])).unwrap();
            b.append(1, i, &[i as u8]).unwrap();
        }
        block_on(a.sync()).unwrap();
        b.sync().unwrap();

        // A run of 137 ends part-way into a sector, which is the case the
        // in-RAM index alone cannot answer.
        let tail = a.tail_position();
        let cut = block_on(a.read_from(tail, 137, |_, _, _| Ok(true)))
            .unwrap()
            .next;
        assert!(
            cut.offset > SECTOR_HEADER_SIZE as u32,
            "the watermark must fall inside a sector for this test to mean anything"
        );

        block_on(a.restore_spool_watermark(cut)).unwrap();
        b.restore_spool_watermark(cut).unwrap();

        assert_eq!(a.spool_stats(), b.spool_stats());
        let total = block_on(a.count(None)).unwrap();
        assert_eq!(total - a.spool_stats().unspooled_entries, 137);
    }
}