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
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
//! SensorDb implementation.
//!
//! Append-only sensor database for NOR flash with circular sector management.
//!
//! ## Usage
//!
//! ```ignore
//! use sensor_db::{MockFlash, SensorDb};
//!
//! const PAGE: usize = 256;
//! const SECTOR: usize = 4096;
//! const SECTORS: usize = 32;
//!
//! let flash = MockFlash::<PAGE, SECTOR>::new(SECTORS * SECTOR);
//! let mut db: SensorDb<_, PAGE, SECTORS> = SensorDb::new(flash, 0, 32, 2).unwrap();
//! db.format().unwrap();
//!
//! db.append(1, 1000, &[0xAB, 0xCD]).unwrap();
//! let mut buf = [0u8; 16];
//! let (hdr, n) = db.latest(1, &mut buf).unwrap().unwrap();
//! assert_eq!(&buf[..n], &[0xAB, 0xCD]);
//! ```

use crate::entry::{
    ENTRY_CRC_SIZE, ENTRY_HEADER_SIZE, ENTRY_OVERHEAD, EntryHeader, EntryHeaderWire, EntryKind,
    FLAGS_COMMITTED, FLAGS_UNCOMMITTED, compute_entry_crc, is_entry_marker,
};
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, sensor_id_to_bit,
};
use crate::typed::SensorData;
use embedded_storage::nor_flash::{NorFlash, ReadNorFlash};
use heapless::Vec as HeaplessVec;
use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};

/// Simple insertion sort for small heapless vectors (no alloc required).
/// Sorts by the second element of the tuple using the given comparator.
pub(crate) fn sort_by_seq<const N: usize>(
    vec: &mut HeaplessVec<(u16, u32), N>,
    cmp: fn(&u32, &u32) -> core::cmp::Ordering,
) {
    for i in 1..vec.len() {
        let mut j = i;
        while j > 0 && cmp(&vec[j - 1].1, &vec[j].1) == core::cmp::Ordering::Greater {
            vec.swap(j - 1, j);
            j -= 1;
        }
    }
}

/// Statistics about the database state.
#[derive(Debug, Clone, Copy, Default)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct DbStats {
    /// Total number of valid entries across all sectors.
    ///
    /// *Entries*, so a [run](crate::run) counts once however many samples it
    /// holds. This is what the log wrote and what replication moves;
    /// [`total_samples`](Self::total_samples) is what a reader sees, and their
    /// ratio is what run encoding bought.
    pub total_entries: u32,
    /// Total number of readable samples across all sectors.
    ///
    /// What [`count(None)`](crate::SensorDb::count) reports, and what a query
    /// over the whole time range yields.
    pub total_samples: u32,
    /// Number of sectors currently in use (active or sealed).
    pub used_sectors: u16,
    /// Number of erased sectors available.
    pub free_sectors: u16,
    /// Number of reserved sectors for headroom.
    pub reserved_sectors: u16,
    /// Minimum erase count across all sectors.
    pub min_erase_count: u32,
    /// Maximum erase count across all sectors.
    pub max_erase_count: u32,
    /// Total erase count summed across all sectors.
    pub total_erase_count: u64,
}

/// Geometry and identity of a database region.
///
/// Validated once, here, so everything downstream receives a configuration that
/// is already known-good.
///
/// ```
/// use sensor_db::db::DbConfig;
/// use sensor_db::sector::LogId;
///
/// let config = DbConfig::new(0, 8, 1)?
///     .with_log_id(LogId::new(0xC0FFEE).unwrap());
/// # Ok::<(), sensor_db::Error>(())
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct DbConfig {
    base_offset: u32,
    sector_count: u16,
    reserved_sectors: u16,
    log_id: Option<LogId>,
}

impl DbConfig {
    /// Describe a database region.
    ///
    /// # Arguments
    /// - `base_offset`: starting byte offset of the region in flash
    /// - `sector_count`: number of erase sectors the region spans
    /// - `reserved_sectors`: sectors kept free as compaction headroom
    ///
    /// # Errors
    /// - `InvalidConfig` if `reserved_sectors >= sector_count`
    pub fn new(base_offset: u32, sector_count: u16, reserved_sectors: u16) -> Result<Self, Error> {
        if reserved_sectors >= sector_count {
            return Err(Error::InvalidConfig);
        }
        Ok(Self {
            base_offset,
            sector_count,
            reserved_sectors,
            log_id: None,
        })
    }

    /// Declare this database's logical identity.
    ///
    /// The id is written into every sector header, and mounting a medium whose
    /// sectors carry a *different* id fails with
    /// [`Error::ForeignVolume`] instead of treating them as free space. Set this
    /// on any database whose storage can be swapped between devices.
    pub fn with_log_id(mut self, log_id: LogId) -> Self {
        self.log_id = Some(log_id);
        self
    }

    /// Starting byte offset of the region.
    pub fn base_offset(&self) -> u32 {
        self.base_offset
    }

    /// Number of erase sectors in the region.
    pub fn sector_count(&self) -> u16 {
        self.sector_count
    }

    /// Sectors kept free as compaction headroom.
    pub fn reserved_sectors(&self) -> u16 {
        self.reserved_sectors
    }

    /// Declared logical identity, if any.
    pub fn log_id(&self) -> Option<LogId> {
        self.log_id
    }
}

/// Which sealed sectors [`SensorDb::compact`] may erase.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum CompactScope {
    /// Every sealed sector is eligible, oldest first, replicated or not.
    #[default]
    All,
    /// Only sealed sectors whose contents are fully replicated elsewhere.
    ///
    /// Reclaims space without ever destroying data that has not been copied off
    /// the device. Erases nothing until a replica has acknowledged something —
    /// on a log with no replica this is always a no-op.
    SpooledOnly,
}

/// How much of the log to index when mounting.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum MountMode {
    /// Rebuild the full index — entry counts, timestamp ranges and bloom
    /// filters — reading each sealed sector's
    /// [`SectorFooter`] where one is present and
    /// valid, and scanning the sector body only where it is not.
    ///
    /// Required for reads, and the default. Cost is one page read per sealed
    /// sector, so it is proportional to the *sector count* on a log this build
    /// wrote. It falls back to a body scan — proportional to the data stored —
    /// for the sector a crashed run left active, and for any sector whose footer
    /// is missing or fails to validate.
    ///
    /// Because a footer records what was written rather than what is still
    /// readable, this mode does not re-verify sealed entries and therefore
    /// reports no [`corrupt_entries`](MountStats::corrupt_entries) for the
    /// sectors it took from a footer. Reads are unaffected: every entry a query
    /// returns is CRC-checked when it is read. Use [`Verify`](Self::Verify) to
    /// check the whole medium at mount instead.
    #[default]
    Full,
    /// Scan every entry of every valid sector, ignoring footers.
    ///
    /// Identical to [`Full`](Self::Full) in what it produces, and the only mode
    /// that re-verifies stored data at mount: the index is built from entries
    /// whose CRCs pass *now*, and
    /// [`corrupt_entries`](MountStats::corrupt_entries) counts the rest. Cost is
    /// proportional to the data stored, so a large nearly-full medium can take
    /// seconds on a slow bus.
    ///
    /// This is what `Full` did before sectors carried footers.
    Verify,
    /// Read sector headers only, plus a full scan of the single highest-sequence
    /// sector so appends can resume at the right offset.
    ///
    /// Bloom filters, per-sector entry counts and timestamp ranges are not
    /// rebuilt, so [`latest`](SensorDb::latest), [`oldest`](SensorDb::oldest),
    /// [`count`](SensorDb::count) and [`query_range`](SensorDb::query_range)
    /// return [`Error::ReadsUnavailable`]. Streaming via
    /// [`read_from`](SensorDb::read_from) still works.
    ///
    /// Now that sealed sectors carry footers, [`Full`](Self::Full) costs one
    /// page read per sector where this costs one header read, so the gap is
    /// small on a log this build wrote. What `HeadersOnly` still guarantees is
    /// that the cost is `O(sector_count)` *unconditionally* — it never falls
    /// back to a body scan, whatever state the medium is in. That is the reason
    /// to keep reaching for it on a write-only replica read elsewhere.
    HeadersOnly,
}

/// Replication accounting for a log.
///
/// Returned by [`SensorDb::spool_stats`]. Kept separate from [`DbStats`], which
/// describes the sector index and means the same thing whether or not anything
/// is replicating this log.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct SpoolStats {
    /// Durable entries not yet known to be replicated elsewhere.
    ///
    /// Entries, which is the unit a spool pass moves and its
    /// [budget](crate::SpoolBudget) is denominated in. For "how many readings
    /// are still only here", see
    /// [`unspooled_samples`](Self::unspooled_samples).
    pub unspooled_entries: u32,
    /// Durable *samples* not yet known to be replicated elsewhere.
    ///
    /// Larger than [`unspooled_entries`](Self::unspooled_entries) when the
    /// un-replicated tail holds [runs](crate::run).
    pub unspooled_samples: u32,
    /// Everything strictly before this position is durably replicated.
    pub watermark: LogPosition,
    /// Position after the newest entry.
    pub head: LogPosition,
    /// Entries the ring overwrote before they could be replicated.
    ///
    /// Counted against the watermark *as it stood at the time of the eviction*.
    /// Because [`mount`](SensorDb::mount) starts every run with the watermark at
    /// [`LogPosition::BEGINNING`], data overwritten before a replica reappears
    /// and calls [`restore_spool_watermark`](SensorDb::restore_spool_watermark)
    /// is counted here even if a replica already had it. Attach early in boot,
    /// or seed the watermark from wherever the application stashed it.
    pub dropped_unspooled: u32,
    /// Sticky: set once any un-replicated data has been overwritten, never
    /// cleared. Surface this to the operator — it means data may have been lost.
    ///
    /// On a log that never replicates, *everything* is un-replicated, so this
    /// becomes true the first time the ring wraps. That is accurate but rarely
    /// interesting: `SpoolStats` is only meaningful for a log with a replica.
    pub data_lost: bool,
}

/// How much one replication step carried, in both units the accounting needs.
///
/// A pair rather than two arguments because they are trivially transposable and
/// a swap would be silent: entries drive the eviction and budget arithmetic,
/// samples drive `count`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct Replicated {
    /// Entries copied.
    pub entries: u32,
    /// Samples those entries hold; equal to `entries` unless runs were copied.
    pub samples: u32,
}

impl Replicated {
    /// Nothing carried.
    pub const NONE: Self = Self {
        entries: 0,
        samples: 0,
    };

    /// `n` entries holding one sample each — what a log with no runs in it
    /// carries, and the shape a caller driving replication by hand usually has.
    pub const fn singles(n: u32) -> Self {
        Self {
            entries: n,
            samples: n,
        }
    }

    /// Record one more entry holding `samples` samples.
    pub fn push(&mut self, samples: u32) {
        self.entries = self.entries.saturating_add(1);
        self.samples = self.samples.saturating_add(samples);
    }
}

/// A position in the log: sector sequence plus byte offset within that sector.
///
/// Sequence numbers are monotonic for the lifetime of a database, so ordering
/// `LogPosition` lexicographically — which is what the derived `Ord` does — is
/// exactly log order. This is the coordinate system used to resume a replication
/// stream across reboots and across removals of the destination medium.
///
/// A position is *not* portable between databases: sequence numbers are
/// allocated per database, so a position from one log means nothing in another.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct LogPosition {
    /// Sequence number of the sector this position falls in.
    pub sequence: u32,
    /// Byte offset within that sector.
    pub offset: u32,
}

impl LogPosition {
    /// A position before every entry the log has ever held.
    ///
    /// Real sector sequences start at 1, so sequence 0 is an unambiguous
    /// sentinel. Reading from `BEGINNING` yields whatever the log still
    /// retains, and never reports a gap.
    pub const BEGINNING: Self = Self {
        sequence: 0,
        offset: 0,
    };
}

/// Outcome of a [`SensorDb::read_from`] pass.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct ReadCursor {
    /// Position immediately after the last entry delivered — pass this back as
    /// `from` to continue where this pass stopped.
    pub next: LogPosition,
    /// Number of entries delivered to the callback in this pass.
    pub entries: u32,
    /// No further durable entries exist after [`next`](Self::next).
    ///
    /// False when the pass stopped because it hit `max_entries` or because the
    /// callback asked to stop.
    pub exhausted: bool,
    /// The requested `from` had already fallen off the tail of the ring, so
    /// entries between it and the oldest retained sector were skipped.
    ///
    /// This is not an error: it is the expected consequence of the log wrapping
    /// while a replication target was unavailable.
    pub gap: bool,
}

/// Statistics returned after mounting.
#[derive(Debug, Clone, Copy, Default)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct MountStats {
    /// Total entries found during scan.
    pub total_entries: u32,
    /// Total readable samples found during scan, which exceeds
    /// [`total_entries`](Self::total_entries) by what the log's
    /// [runs](crate::run) hold.
    pub total_samples: u32,
    /// Number of sealed sectors found.
    pub sealed_sectors: u16,
    /// Number of corrupt entries skipped.
    ///
    /// Only sectors this mount actually read end to end can contribute: a
    /// sector indexed from its [`SectorFooter`] is
    /// not re-verified. See [`MountMode::Full`] and [`MountMode::Verify`].
    pub corrupt_entries: u32,
    /// Sector bodies this mount read end to end, rather than indexing from a
    /// footer or skipping.
    ///
    /// This is the number that says what the footers bought: it is the mount
    /// cost that scales with *data stored* instead of with sector count. On a
    /// medium written entirely by this build it is 1 — the sector the last run
    /// left active.
    pub scanned_sectors: u16,
}

/// A parsed entry returned by [`SectorScanner`] (and its async twin).
pub(crate) struct ScannedEntry {
    /// The wire-format header.
    pub(crate) header: EntryHeaderWire,
    /// Byte offset of this entry within the sector.
    pub(crate) offset_in_sector: u32,
    /// Payload length in bytes.
    pub(crate) payload_len: usize,
    /// Total entry size (header + payload + CRC).
    pub(crate) entry_size: u32,
}

impl ScannedEntry {
    /// Whether this entry holds a [run](crate::run).
    pub(crate) fn is_run(&self) -> bool {
        self.header.is_run()
    }

    /// The sensor id, which every sample of a run shares.
    pub(crate) fn sensor_id(&self) -> u16 {
        self.header.sensor_id.get()
    }

    /// The header timestamp, which for a run is its *first* sample's.
    pub(crate) fn timestamp(&self) -> u64 {
        self.header.timestamp.get()
    }
}

/// One whole entry found in the RAM page buffer.
struct BufferedEntry {
    header: EntryHeaderWire,
    payload_start: usize,
    payload_len: usize,
}

/// Which end of an entry a single-entry read wants: for a run, its first or its
/// last sample, which are its oldest and newest.
#[derive(Clone, Copy)]
pub(crate) enum Edge {
    First,
    Last,
}

/// One chosen sample, located in the page buffer and not yet framed.
///
/// `latest` picks a winner across the whole buffer and copies once, so the
/// choice and the copy have to be separable.
#[derive(Clone, Copy)]
struct BufferedSample {
    payload_start: usize,
    payload_len: usize,
    /// The run this sample came from, and which sample it is. `None` for a
    /// single-sample entry, whose payload is already exactly what to hand back.
    run: Option<(RunFrame, u32)>,
}

impl BufferedEntry {
    fn is_committed(&self) -> bool {
        self.header.flags == FLAGS_COMMITTED
    }

    fn is_run(&self) -> bool {
        self.header.is_run()
    }

    fn sensor_id(&self) -> u16 {
        self.header.sensor_id.get()
    }

    fn timestamp(&self) -> u64 {
        self.header.timestamp.get()
    }
}

/// What a body scan learned about one sector.
///
/// Exactly the fields a [`SectorFooter`] carries, which is the point: mount
/// takes whichever is available and nothing downstream can tell which.
#[derive(Debug, Clone, Copy)]
pub(crate) struct ScannedSector {
    pub(crate) entries: u32,
    pub(crate) samples: u32,
    pub(crate) write_offset: u32,
    pub(crate) min_timestamp: u64,
    pub(crate) max_timestamp: u64,
    pub(crate) sensor_bloom: u64,
}

impl ScannedSector {
    /// A sector with nothing in it, with the bounds inverted so the first entry
    /// scanned sets both.
    pub(crate) const EMPTY: Self = Self {
        entries: 0,
        samples: 0,
        write_offset: 0,
        min_timestamp: u64::MAX,
        max_timestamp: 0,
        sensor_bloom: 0,
    };

    /// Fold one accepted entry into the running scan.
    ///
    /// Pure, and shared by both drivers: a run reaches past its header
    /// timestamp, and the index has to know it — otherwise a query for the run's
    /// tail prunes away the very sector the run lives in.
    pub(crate) fn record(&mut self, entry: &ScannedEntry, payload: &[u8]) {
        let base = entry.timestamp();
        let span_end = match RunFrame::parse(payload).filter(|_| entry.is_run()) {
            Some(frame) => {
                self.samples += frame.count();
                frame.span_end(base)
            }
            None => {
                self.samples += 1;
                base
            }
        };

        self.entries += 1;
        self.min_timestamp = self.min_timestamp.min(base);
        self.max_timestamp = self.max_timestamp.max(span_end);
        self.sensor_bloom |= sensor_id_to_bit(entry.sensor_id());
    }

    /// Copy the scan's findings into `summary`, leaving `state`, `sequence` and
    /// `erase_count` — which come from the sector *header* — alone.
    pub(crate) fn apply_to(&self, summary: &mut SectorSummary) {
        summary.entry_count = self.entries;
        summary.sample_count = self.samples;
        summary.write_offset = self.write_offset;
        summary.min_timestamp = self.min_timestamp;
        summary.max_timestamp = self.max_timestamp;
        summary.sensor_bloom = self.sensor_bloom;
    }
}

/// What a [`SectorScanner`] needs next, or what it found.
///
/// This is the whole reason the scanner is I/O-free: the decisions it makes —
/// where to resume after a bad byte, when an erased region ends the scan, which
/// headers to reject before their `payload_len` is trusted — are identical for
/// the blocking and async drivers, and a sector walked differently by two of
/// them is exactly how `count` and `query_range` came to disagree once before.
/// Stating the decisions once and letting each driver supply only the read is
/// what makes that class of drift impossible rather than merely tested for.
pub(crate) enum Scan {
    /// Read [`ENTRY_HEADER_SIZE`] bytes at this **absolute** flash address, then
    /// hand them to [`SectorScanner::feed`].
    Read(u32),
    /// A committed entry, at the scanner's current offset.
    Found(ScannedEntry),
    /// The sector is exhausted.
    Done,
}

/// Stateful, I/O-free cursor that walks committed entry headers within a single
/// sector.
///
/// Drive it with [`begin`](Self::begin) and [`feed`](Self::feed); each driver
/// wraps those in a small loop that performs the reads
/// ([`SectorScanner::next_entry`] here, its `.await`ing twin in
/// [`async_db`](crate::async_db)).
pub(crate) struct SectorScanner {
    /// Absolute flash address of the sector start.
    sector_offset: u32,
    /// Current read position (relative to sector start).
    offset: u32,
    /// Upper bound for scanning (typically `write_offset` or `sector_size`).
    limit: u32,
    /// Number of corrupt/invalid bytes skipped.
    pub(crate) corrupt_count: u32,
}

impl SectorScanner {
    pub(crate) fn new(sector_offset: u32, entry_start: u32, limit: u32) -> Self {
        Self {
            sector_offset,
            offset: entry_start,
            limit,
            corrupt_count: 0,
        }
    }

    /// Current byte offset within the sector.
    pub(crate) fn offset(&self) -> u32 {
        self.offset
    }

    /// Number of corrupt/invalid bytes encountered so far.
    pub(crate) fn corrupt_count(&self) -> u32 {
        self.corrupt_count
    }

    /// Advance past an entry of the given size.
    pub(crate) fn skip(&mut self, entry_size: u32) {
        self.offset += entry_size;
    }

    /// What to read next from the current position, or `Done` if no entry can
    /// still fit before the limit.
    pub(crate) fn begin(&self) -> Scan {
        if self.offset + ENTRY_OVERHEAD as u32 > self.limit {
            return Scan::Done;
        }
        Scan::Read(self.sector_offset + self.offset)
    }

    /// Interpret the header bytes just read, and say what comes next.
    ///
    /// Skips erased regions (jumping to the next page boundary) and uncommitted
    /// entries, and resyncs one byte forward past anything that does not parse.
    pub(crate) fn feed(&mut self, header_buf: &[u8; ENTRY_HEADER_SIZE], page_size: usize) -> Scan {
        // Erased area — skip to next page boundary
        if header_buf[0] == 0xFF {
            let next_page = ((self.offset as usize / page_size) + 1) * page_size;
            if next_page as u32 + ENTRY_OVERHEAD as u32 > self.limit {
                return Scan::Done;
            }
            self.offset = next_page as u32;
            return self.begin();
        }

        // Not a valid marker — skip one byte
        if !is_entry_marker(header_buf[0]) {
            return self.resync();
        }

        let Ok(header) = EntryHeaderWire::read_from_bytes(&header_buf[..]) else {
            return self.resync();
        };

        let payload_len = header.payload_len.get() as usize;

        // Validate the header before trusting its length. The marker byte
        // (0xAA) occurs naturally inside payload data, so matching it alone is
        // not enough: without validation a false marker yields a garbage
        // `payload_len` that desyncs the scan and — via `accept_entry` —
        // slices a fixed buffer out of bounds. We reject on three grounds, in
        // increasing cost: `flags` must be exactly COMMITTED or UNCOMMITTED
        // (the header CRC masks flags, so it cannot vouch for them); the
        // payload must fit within a page (defends against a CRC collision that
        // still yields an impossible length); and the header CRC must match,
        // which rejects false markers structurally rather than heuristically.
        // On any failure, treat it as a stray byte and resync one byte forward.
        let max_payload = page_size.saturating_sub(ENTRY_OVERHEAD);
        if (header.flags != FLAGS_COMMITTED && header.flags != FLAGS_UNCOMMITTED)
            || payload_len > max_payload
            || !header.header_crc_valid()
        {
            return self.resync();
        }

        let entry_size = (ENTRY_OVERHEAD + payload_len) as u32;

        if self.offset + entry_size > self.limit {
            return Scan::Done;
        }

        // Skip uncommitted entries (power loss before commit)
        if header.flags != FLAGS_COMMITTED {
            self.offset += entry_size;
            return self.begin();
        }

        Scan::Found(ScannedEntry {
            header,
            offset_in_sector: self.offset,
            payload_len,
            entry_size,
        })
    }

    /// Count a bad byte and step over it.
    fn resync(&mut self) -> Scan {
        self.corrupt_count += 1;
        self.offset += 1;
        self.begin()
    }

    /// Read the next committed entry header from flash.
    ///
    /// The blocking driver's loop over [`begin`](Self::begin) and
    /// [`feed`](Self::feed) — everything it decides lives there, so this is only
    /// the read.
    fn next_entry<F: ReadNorFlash>(
        &mut self,
        flash: &mut F,
        header_buf: &mut [u8; ENTRY_HEADER_SIZE],
        page_size: usize,
    ) -> Result<Option<ScannedEntry>, Error> {
        let mut step = self.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[..])?;
                    step = self.feed(header_buf, page_size);
                }
            }
        }
    }
}

/// Whether an entry's stored bytes are the ones that were written.
///
/// Two tests, and every scan applies both so that they all walk a sector
/// identically — `count` and `query_range` disagreeing about how many entries
/// exist is a defect, not an optimisation:
///
/// - the entry CRC must match, which is what says these bytes are the ones that
///   were written;
/// - a *run* must additionally carry a well-formed [`RunFrame`], because the
///   scans downstream index by its sample count and span. Only a writer this
///   crate does not have could produce a run that fails this, so it is a
///   structural backstop rather than a case that arises — and rejecting it here
///   means every caller handles it by the resync it already performs for a bad
///   CRC.
impl ScannedEntry {
    /// The header and payload of this entry's first or last sample.
    ///
    /// For an ordinary entry both edges are the entry itself. For a run they are
    /// its first and last samples — which are its oldest and newest, because the
    /// interval is unsigned and a run's timestamps therefore never decrease.
    ///
    /// Shared by `latest` and `oldest` in both drivers, so the run/single
    /// distinction is drawn once rather than in four places.
    pub(crate) fn edge<'a>(&self, payload: &'a mut [u8], edge: Edge) -> (EntryHeader, &'a [u8]) {
        // `RunFrame` borrows nothing, so the immutable parse ends before
        // `tagged_sample` takes the buffer mutably.
        match RunFrame::parse(payload).filter(|_| self.is_run()) {
            Some(frame) => {
                let index = match edge {
                    Edge::First => 0,
                    Edge::Last => frame.count() - 1,
                };
                (
                    frame.header_at(self.sensor_id(), self.timestamp(), index),
                    frame.tagged_sample(payload, index),
                )
            }
            None => (self.header.to_header(), payload),
        }
    }

    /// Where this entry's payload and CRC live, and how many bytes that is.
    ///
    /// Absolute address, so a driver can read it without knowing the layout.
    pub(crate) fn payload_read(&self, sector_offset: u32) -> (u32, usize) {
        (
            sector_offset + self.offset_in_sector + ENTRY_HEADER_SIZE as u32,
            self.payload_len + ENTRY_CRC_SIZE,
        )
    }

    /// Verify the bytes [`payload_read`](Self::payload_read) asked for.
    ///
    /// `buf` holds `payload_len` payload bytes followed by the stored CRC.
    pub(crate) fn accept(&self, buf: &[u8]) -> bool {
        let stored_crc = u32::from_le_bytes([
            buf[self.payload_len],
            buf[self.payload_len + 1],
            buf[self.payload_len + 2],
            buf[self.payload_len + 3],
        ]);
        let computed_crc = compute_entry_crc(
            &self.header,
            &buf[..self.payload_len],
            self.offset_in_sector,
        );

        if stored_crc != computed_crc {
            return false;
        }

        !self.is_run() || RunFrame::parse(&buf[..self.payload_len]).is_some()
    }
}

/// Read an entry's payload into `buf` and decide whether to accept it.
///
/// The blocking driver's read around [`ScannedEntry::accept`]; the async driver
/// has the same four lines with an `.await`.
///
/// On success returns `true` and `buf[..entry.payload_len]` holds the payload.
fn accept_entry<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.
    // The scanner already bounds `payload_len` to a page, but treat an
    // oversized length as a CRC failure rather than panicking.
    if read_len > buf.len() {
        return Ok(false);
    }
    flash.read(addr, &mut buf[..read_len])?;
    Ok(entry.accept(buf))
}

/// What a seal has decided, between the parts of it that touch flash.
///
/// [`begin_seal`](SensorDbState::begin_seal) produces it, the driver performs
/// the erase and the header write, and
/// [`finish_seal`](SensorDbState::finish_seal) consumes it — so the sequencing
/// is the only thing each driver states for itself.
pub(crate) struct SealPlan {
    /// The sector being erased and made active.
    pub(crate) new_active: u16,
    /// Its erase count after this erase, carried over from the victim.
    pub(crate) erase_count: u32,
    /// The victim as it stood before the erase, for eviction accounting.
    victim: SectorSummary,
}

/// What has to happen on flash before an entry can be staged.
///
/// [`plan_append`](SensorDbState::plan_append) decides; each driver's loop only
/// performs. The decision is subtle enough to be worth stating once: an entry
/// never spans a page, sealing does *not* hand back an empty page (page 0
/// carries the 28-byte sector header), and a maximum-size entry therefore has to
/// start on page 1 — which is why the driver loops rather than checking once.
/// Checking once wrote such an entry at offset `SECTOR_HEADER_SIZE` of a
/// `PAGE_SIZE` buffer and panicked on the slice index, reachable from a plain
/// `append` of exactly the documented maximum payload.
pub(crate) enum AppendStep {
    /// There is room — call [`stage_entry`](SensorDbState::stage_entry).
    Stage,
    /// Close the current page, then ask again.
    FlushPage,
    /// Seal the active sector and advance, then ask again.
    Seal,
}

/// Internal state of the sensor database (everything except the flash device).
///
/// Separated from [`SensorDb`] so a method can borrow `flash` and `state`
/// disjointly — the flash-touching helpers take `&mut F` alongside `&mut self`,
/// which the borrow checker only permits across two fields.
///
/// Shared verbatim with [`SensorDbAsync`](crate::SensorDbAsync), and it holds
/// the **logic**, not merely the fields.
///
/// `embedded-storage` and `embedded-storage-async` are unrelated trait families,
/// so the async driver cannot call a helper that takes a sync `&mut F`. It used
/// to answer that by reimplementing the algorithm — 80% of `async_db.rs` was a
/// line-for-line copy — which is worse than it sounds: the async test suite is
/// largely byte-for-byte *parity* assertions against the blocking driver, so a
/// defect present in both is invisible to it by construction.
///
/// So each flash-touching operation is split: the decisions live here, pure, and
/// each driver contributes only the reads and writes between them. `flush_page`
/// is [`commit_target`](Self::commit_target) →
/// [`mark_page_committed`](Self::mark_page_committed) →
/// [`advance_page`](Self::advance_page) with two writes interleaved;
/// `seal_and_advance` is [`sealing`](Self::sealing) →
/// [`begin_seal`](Self::begin_seal) → [`account_seal`](Self::account_seal) →
/// [`finish_seal`](Self::finish_seal); `append_entry` is a loop over
/// [`plan_append`](Self::plan_append) ending in
/// [`stage_entry`](Self::stage_entry); and the scan itself is
/// [`SectorScanner::feed`].
///
/// **A driver method that is more than I/O choreography belongs here instead.**
pub(crate) struct SensorDbState<const PAGE_SIZE: usize, const MAX_SECTORS: usize> {
    pub(crate) base_offset: u32,
    pub(crate) sector_count: u16,
    pub(crate) reserved_sectors: u16,
    pub(crate) sector_size: u32,
    pub(crate) sectors: [SectorSummary; MAX_SECTORS],
    pub(crate) active_sector: Option<u16>,
    pub(crate) page_buf: [u8; PAGE_SIZE],
    pub(crate) page_buf_offset: usize,
    /// Bytes of `page_buf` below this offset are already durable on flash.
    ///
    /// Non-zero only after a `mount` that adopted a partially filled page: every
    /// successful flush empties the buffer. This — not the flags byte — is what
    /// says whether a buffered entry is safe on flash. `flush_page` flips flags
    /// to committed *in RAM* before writing them, so a failed commit pass leaves
    /// the buffer claiming a durability that flash does not have.
    pub(crate) page_buf_durable: usize,
    pub(crate) page_flash_offset: u32,
    pub(crate) mounted: bool,
    pub(crate) next_sequence: u32,
    /// Valid entries the ring holds — the unit replication and eviction work in.
    pub(crate) total_entries: u32,
    /// Readable samples the ring holds, which exceeds `total_entries` by what
    /// its [runs](crate::run) hold.
    ///
    /// Kept alongside rather than replacing it because the two answer different
    /// questions: a spool pass moves *entries* and its budget is in entries,
    /// while `count` and `query_range` speak in samples. Collapsing them would
    /// make one of the two silently wrong the moment a run is written.
    pub(crate) total_samples: u32,
    /// Declared identity of this log, written into every sector header.
    pub(crate) log_id: Option<LogId>,
    /// Incremented once per mount; disambiguates boot-relative timestamps.
    pub(crate) epoch: u32,
    /// This run adopted a sector an earlier run created, so its epoch is not yet
    /// recorded anywhere on the medium.
    ///
    /// Cleared by rolling to a fresh sector, which stamps it. Deferred to the
    /// first append so that a run which only reads costs nothing.
    pub(crate) epoch_pending: bool,
    /// How much of the index this mount rebuilt.
    pub(crate) mount_mode: MountMode,
    /// Everything strictly before this position is durably replicated elsewhere.
    ///
    /// Not persisted here: the replica is the source of truth, and it restores
    /// this via [`SensorDb::restore_spool_watermark`] when it reappears. That is
    /// what lets two media be rotated against one log with no local state.
    pub(crate) spool_watermark: LogPosition,
    /// Entries counted as replicated, mirroring `total_entries` accounting.
    pub(crate) spooled_entries: u32,
    /// Samples counted as replicated, mirroring `total_samples` accounting.
    ///
    /// The pair moves together everywhere `spooled_entries` does, because a
    /// tiered `count` needs "how many samples are *not* yet on the card" and
    /// the entry figure cannot answer it once runs exist.
    pub(crate) spooled_samples: u32,
    /// Entries the ring overwrote before they could be replicated.
    pub(crate) dropped_unspooled: u32,
    /// Sector erases this instance has performed, saturating.
    ///
    /// An erase costs 100 ms or more on many NOR parts, against microseconds for
    /// a page write, so it is the one operation whose latency a caller may need
    /// to see. Counted here rather than derived from the per-sector erase counts
    /// in [`DbStats`] because those are a *wear* history that survives remounts
    /// and says nothing about when the erases happened.
    pub(crate) sectors_erased: u32,
}

/// Compile-time check that a driver's write granularity divides `PAGE_SIZE`.
///
/// The database writes a page at a time, so a `PAGE_SIZE` the driver cannot
/// express as a whole number of writes fails at the first flush with
/// `NotAligned` — a geometry mistake reported as a runtime I/O error, on a
/// device, long after the type that caused it was chosen.
///
/// The check is a *multiple*, not equality, because `embedded-storage`'s
/// `WRITE_SIZE` is the minimum write **granularity** and not the program-page
/// size: several HALs report 1, which divides every `PAGE_SIZE`. The other half
/// of the contract — that `PAGE_SIZE` not exceed the part's physical program
/// page — cannot be checked here, because the trait does not carry it.
///
/// An associated const rather than a bare `const` block, which cannot name the
/// generic parameters it would need. Instantiating it in a constructor is what
/// forces evaluation.
pub(crate) struct Geometry<F: ?Sized, const PAGE_SIZE: usize>(core::marker::PhantomData<F>);

impl<F: NorFlash + ?Sized, const PAGE_SIZE: usize> Geometry<F, PAGE_SIZE> {
    /// Fails the build when `PAGE_SIZE` is not a whole number of writes.
    pub(crate) 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",
    );
}

impl<const PAGE_SIZE: usize, const MAX_SECTORS: usize> SensorDbState<PAGE_SIZE, MAX_SECTORS> {
    /// Validate the geometry and build the initial (unmounted) state.
    ///
    /// Shared by both `SensorDb::new` and `SensorDbAsync::new` so the geometry
    /// rules are stated exactly once.
    ///
    /// # Errors
    /// - `TooManySectors` if `sector_count > MAX_SECTORS`
    /// - `InvalidConfig` if a sector is smaller than three pages
    /// - `Overflow` if the region does not fit in a `u32` address space
    pub(crate) fn new(config: DbConfig, sector_size: u32) -> Result<Self, Error> {
        if config.sector_count as usize > MAX_SECTORS {
            return Err(Error::TooManySectors);
        }

        // Page 0 carries the sector header, the last page carries the footer,
        // and an entry of the documented maximum payload needs a whole page to
        // itself. Below three pages a sector could be initialised and then have
        // nowhere to put a legal entry, which `append` could only report as
        // `PayloadTooLarge` — a geometry mistake dressed up as a call mistake.
        if sector_size < 3 * PAGE_SIZE as u32 {
            return Err(Error::InvalidConfig);
        }

        let total_size = (config.sector_count as u32)
            .checked_mul(sector_size)
            .ok_or(Error::Overflow)?;
        config
            .base_offset
            .checked_add(total_size)
            .ok_or(Error::Overflow)?;

        Ok(Self {
            base_offset: config.base_offset,
            sector_count: config.sector_count,
            reserved_sectors: config.reserved_sectors,
            sector_size,
            sectors: [SectorSummary::default(); MAX_SECTORS],
            active_sector: None,
            page_buf: [0xFF; PAGE_SIZE],
            page_buf_offset: 0,
            page_buf_durable: 0,
            page_flash_offset: 0,
            mounted: false,
            next_sequence: 1,
            total_entries: 0,
            total_samples: 0,
            log_id: config.log_id,
            epoch: 1,
            epoch_pending: false,
            mount_mode: MountMode::Full,
            spool_watermark: LogPosition::BEGINNING,
            spooled_entries: 0,
            spooled_samples: 0,
            dropped_unspooled: 0,
            sectors_erased: 0,
        })
    }

    /// The raw `log_id` this database expects, 0 when anonymous.
    pub(crate) fn log_id_raw(&self) -> u32 {
        self.log_id.map_or(0, LogId::get)
    }

    /// Gate for query methods: mounted, and with an index good enough to answer.
    ///
    /// A [`MountMode::HeadersOnly`] mount deliberately skips the per-sector
    /// entry counts, timestamp ranges and bloom filters that every query relies
    /// on, so those queries must refuse rather than quietly return a subset.
    /// Streaming via `read_from` still works, because it reads flash directly.
    pub(crate) fn require_reads(&self) -> Result<(), Error> {
        if !self.mounted {
            return Err(Error::NotMounted);
        }
        if self.mount_mode == MountMode::HeadersOnly {
            return Err(Error::ReadsUnavailable);
        }
        Ok(())
    }

    /// Build a sector header carrying this database's identity and epoch.
    pub(crate) fn sector_header(&self, sequence: u32, erase_count: u32) -> SectorHeader {
        SectorHeader::new(self.log_id, self.epoch, sequence, erase_count)
    }

    /// Whether a sealed sector's contents are entirely replicated.
    ///
    /// Derived rather than stored, so there is no second copy of the truth to
    /// keep in sync. The comparison is strict: if the watermark falls *inside*
    /// sector `S`, every sector below `S` is fully replicated and `S` is not.
    pub(crate) fn is_fully_spooled(&self, summary: &SectorSummary) -> bool {
        summary.sequence < self.spool_watermark.sequence
    }

    /// Apply the accounting for a sector whose contents have just been erased.
    ///
    /// Called *after* the erase succeeds, never before: an erase that fails must
    /// not leave the index claiming data is gone, and must not report a loss
    /// that did not happen.
    pub(crate) fn account_eviction(&mut self, victim: &SectorSummary) {
        let entries = victim.entry_count;
        let samples = victim.sample_count;
        self.total_entries = self.total_entries.saturating_sub(entries);
        self.total_samples = self.total_samples.saturating_sub(samples);
        if self.is_fully_spooled(victim) {
            self.spooled_entries = self.spooled_entries.saturating_sub(entries);
            self.spooled_samples = self.spooled_samples.saturating_sub(samples);
            return;
        }

        // The victim is the sector the watermark falls inside, or one above it.
        // In the first case part of it *was* replicated and is counted in
        // `spooled_entries`; only the rest is a loss. The split is recoverable
        // without a scan: whatever stays replicated is exactly what the other
        // fully-spooled sectors hold, so the remainder is the victim's share.
        // Charging the whole sector to `dropped_unspooled` would report a loss
        // of data a replica demonstrably has.
        let spooled_elsewhere = self.spooled_in_whole_sectors();
        let victim_share = self.spooled_entries.saturating_sub(spooled_elsewhere);
        self.spooled_entries = spooled_elsewhere;
        self.dropped_unspooled = self
            .dropped_unspooled
            .saturating_add(entries.saturating_sub(victim_share));

        // The same split, in samples. `dropped_unspooled` stays in entries: it
        // reports loss against the replication budget, which is entry-shaped.
        let samples_elsewhere = self.spooled_samples_in_whole_sectors();
        self.spooled_samples = samples_elsewhere;
    }

    /// Entries held by retained sectors that lie entirely below the watermark.
    ///
    /// Excludes the sector the watermark falls inside, whose replicated prefix
    /// the in-RAM index cannot measure.
    fn spooled_in_whole_sectors(&self) -> u32 {
        self.fold_whole_spooled_sectors(|s| s.entry_count)
    }

    /// The same, in samples.
    fn spooled_samples_in_whole_sectors(&self) -> u32 {
        self.fold_whole_spooled_sectors(|s| s.sample_count)
    }

    fn fold_whole_spooled_sectors(&self, of: impl Fn(&SectorSummary) -> u32) -> u32 {
        (0..self.sector_count)
            .map(|i| &self.sectors[i as usize])
            .filter(|s| s.state != SectorState::Erased && self.is_fully_spooled(s))
            .fold(0u32, |acc, s| acc.saturating_add(of(s)))
    }
}

/// Append-only sensor database for NOR flash.
///
/// Generic parameters:
/// - `F`: Flash storage implementing `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 `embedded-storage` does not express and so
///   cannot be checked. Note `WRITE_SIZE` is the minimum write *granularity*,
///   not the program-page size; a driver reporting 1 constrains nothing.
/// - `MAX_SECTORS`: Maximum number of sectors this instance can manage
///
/// # Memory Usage
///
/// The struct's RAM footprint is approximately:
/// - `MAX_SECTORS × 48` bytes for the in-RAM sector index ([`SectorSummary`] array)
/// - `PAGE_SIZE` bytes for the write page buffer
/// - ~30 bytes for bookkeeping fields
///
/// Example: with `PAGE_SIZE = 256` and `MAX_SECTORS = 32`, total ≈ 1,822 bytes.
///
/// # NOR Flash Constraints
///
/// Entries cannot span page boundaries because NOR flash requires page-aligned
/// writes. Each entry (header + payload + CRC) must fit within a single
/// `PAGE_SIZE` page. The maximum payload size is `PAGE_SIZE - 20` bytes.
///
/// The database does not perform active wear leveling beyond the implicit
/// distribution of the circular sector ring. Sectors are used round-robin
/// starting from the sector after the current active one. For applications
/// needing precise wear balancing, consider tracking erase counts externally.
///
/// # Read Model
///
/// Reads do **not** write to flash: `latest`, `oldest`, `count`, `query_range`
/// and their typed variants scan committed entries and transparently include
/// any buffered (unflushed) entries from the page buffer, so a read never
/// triggers a flash write and `sync()` is needed for **durability** alone, not
/// for read visibility.
///
/// They do take `&mut self`, because `ReadNorFlash::read` does. An earlier
/// revision wrapped the driver in a `RefCell` so they could take `&self`, and
/// it bought nothing: `RefCell<F>` is `!Sync`, so the only way to share a
/// `SensorDb` was a `Mutex`, which hands back `&mut` anyway. What it cost was
/// real — reads split into two shapes (`&self` here, `&mut self` on
/// [`LogSource`](crate::LogSource), which
/// [`TieredDb`](crate::TieredDb) forces), a re-entrancy panic to fence off
/// (a callback capturing `&db` and calling `latest()` double-borrowed), and a
/// panic path in a `no_std` crate. Without it `SensorDb` is `Sync` whenever
/// `F` is, and the port and the inherent methods agree.
///
/// Methods that touch no flash — [`stats`](Self::stats),
/// [`is_mounted`](Self::is_mounted), [`head_position`](Self::head_position),
/// [`peek_unflushed`](Self::peek_unflushed) and the rest — still take `&self`.
///
/// # Stack Usage
///
/// Most public methods allocate a single `[u8; PAGE_SIZE]` temporary buffer
/// on the stack. The deepest call chains (e.g., `latest_value` → `latest` →
/// `find_latest_in_sector`) pass buffers through rather than allocating new
/// ones, so the worst-case stack overhead per call is approximately
/// `1 × PAGE_SIZE` bytes on top of the `SensorDb` struct itself.
///
/// With `PAGE_SIZE = 256`, this is negligible. With `PAGE_SIZE = 4096`, each
/// read/query call uses ~4 KB of stack — plan accordingly on Cortex-M targets
/// with limited stack space.
pub struct SensorDb<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 SensorDb<F, PAGE_SIZE, MAX_SECTORS>
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("SensorDb")
            .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> SensorDb<F, PAGE_SIZE, MAX_SECTORS>
where
    F: NorFlash + ReadNorFlash,
{
    /// Create a new SensorDb instance.
    ///
    /// # Arguments
    /// - `flash`: 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
    ///
    /// # Limits
    ///
    /// - The entire database region (`sector_count × ERASE_SIZE + base_offset`)
    ///   must fit within `u32` address space (4 GB).
    /// - `SectorSummary.write_offset` is `u32`, supporting individual sectors
    ///   up to 4 GB.
    /// - `sector_count` must not exceed `MAX_SECTORS`.
    ///
    /// # 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 `SensorDb` 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` — the compile-time `Geometry` assert.
    pub fn with_config(flash: F, config: DbConfig) -> Result<Self, Error> {
        let () = Geometry::<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. All sectors carry
    /// this database's [`LogId`] and `erase_count = 1`, and the epoch restarts
    /// at 1.
    ///
    /// This destroys everything in the region unconditionally — including a
    /// foreign volume. Use [`mount`](Self::mount), which refuses to touch
    /// another log's data, when the medium's provenance is not certain.
    pub fn format(&mut self) -> Result<(), Error> {
        let flash = &mut self.flash;
        // Erase all sectors
        for i in 0..self.state.sector_count {
            self.state.erase_sector(flash, i)?;
            self.state.sectors[i as usize] = SectorSummary::erased();
            self.state.sectors[i as usize].erase_count = 1;
        }

        self.state.epoch = 1;
        // `init_sector` below stamps epoch 1, so nothing is owed.
        self.state.epoch_pending = false;

        // Initialize first sector as active
        self.state.init_sector(flash, 0, 1, 1)?;
        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;
        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);
        // Read the sector header into the page buffer
        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 fn mount(&mut self) -> Result<MountStats, Error> {
        self.mount_with(MountMode::Full)
    }

    /// Mount an existing database, choosing how much of the index to rebuild.
    ///
    /// # Foreign media
    ///
    /// A sector whose header parses as this format but carries a different
    /// [`LogId`] aborts the mount with [`Error::ForeignVolume`], **before**
    /// anything is written. This matters for removable storage: the fallback
    /// path for "no valid sectors found" erases a sector to bootstrap the log,
    /// so without this check, inserting another device's card and mounting it
    /// would destroy its data.
    ///
    /// An anonymous database (no `log_id` in its [`DbConfig`]) accepts any
    /// medium, preserving the behaviour of databases that never declare an
    /// identity.
    ///
    /// # Epoch
    ///
    /// Each successful mount takes an epoch one higher than any found on the
    /// medium, and stamps it into every sector header written from then on.
    /// Timestamps from a device with no real-time clock restart at zero on every
    /// boot; the epoch is what lets a reader tell those runs apart.
    ///
    /// # Errors
    /// - `AlreadyMounted` if already mounted
    /// - `ForeignVolume` if the medium belongs to a different log
    /// - `UnsupportedVersion` if the medium uses a newer format
    pub fn mount_with(&mut self, mode: MountMode) -> Result<MountStats, Error> {
        if self.state.mounted {
            return Err(Error::AlreadyMounted);
        }

        let flash = &mut self.flash;
        let mut stats = MountStats::default();
        let mut max_sequence: u32 = 0;
        let mut max_epoch: u32 = 0;

        // Pass 1: read every sector header. 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];
            flash.read(sector_offset, &mut header_buf)?;

            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 => {
                    // Erased, never written, or data this format cannot parse.
                    // The body is not a valid entry stream, so treat the sector
                    // as free rather than scanning it.
                    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.
        //
        // The newest sector is where an append resumes, so it is always indexed
        // exactly — but even it can carry a footer: a run that sealed a sector
        // and then died before the successor's header reached flash leaves the
        // sealed sector holding the highest valid sequence. `newest_sealed`
        // records that, because the cursor must then be parked at the footer
        // page rather than inside data the footer already describes.
        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. `HeadersOnly` keeps its
            // one-read-per-sector promise everywhere else.
            let footer = if self.state.wants_footer(mode, is_newest) {
                self.state.read_sector_footer(flash, i)?
            } 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.state.scan_sector_entries(flash, i)?;
                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. Anything appended into it would be attributed to that run.
            // 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. Normally the end of its
            // data — but a sector that already carries a footer was *sealed*,
            // and its frozen summary would become a lie if anything were
            // appended into it. Resume such a sector at its footer page, which
            // is where `append`'s boundary check seals and moves on. That
            // happens when a run sealed a sector and then lost power before the
            // successor's header landed, leaving the sealed sector holding the
            // highest valid sequence.
            let resume = if newest_sealed {
                self.state.footer_offset()
            } else {
                self.state.sectors[idx as usize].write_offset
            };

            // Load the partial page into the buffer
            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. This costs one read per page of the active
            // sector, on a path that has already read every entry.
            //
            // Usually nothing depends on it: `epoch_pending` was just set, so
            // the first append rolls to a fresh sector and abandons this one
            // before any of it matters. But that roll is skipped when the ring
            // has no sector to give (`append` swallows `NoSpace` rather than
            // fail a write for the sake of provenance metadata), and *then* this
            // is the only thing standing between a torn page and a log that
            // cannot be written to again. A full ring is exactly when losing the
            // log would hurt most.
            //
            // Bounded by the footer offset: the final page is not data, and on a
            // sector parked there by `newest_sealed` the probe does not run at
            // all — there is nothing ahead of the cursor to be in the way of.
            let mut last_dirty: Option<u32> = None;
            let mut probe = page_start;
            while probe < self.state.footer_offset() {
                flash.read(sector_offset + probe, &mut self.state.page_buf)?;
                // In the resume page, only what lies *after* the write position
                // counts as in the way.
                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 {
                // Everything from the write position on is erased: resume there,
                // continuing to fill the partial page. Nothing to re-read when
                // the cursor is parked on the footer page.
                None if resume < self.state.footer_offset() => {
                    flash.read(self.state.page_flash_offset, &mut self.state.page_buf)?;
                }
                None => {}
                // Something is in the way. Start after it, giving up the rest of
                // the skipped pages — cheaper than an unusable log.
                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.state.erase_sector(flash, 0)?;
            self.state
                .init_sector(flash, 0, self.state.next_sequence, 1)?;
            // 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.
    ///
    /// # Arguments
    /// - `sensor_id`: Sensor identifier
    /// - `timestamp`: Timestamp (typically microseconds since epoch)
    /// - `payload`: Raw sensor data
    ///
    /// # Errors
    /// - `NotMounted` if not mounted
    /// - `PayloadTooLarge` if payload exceeds max size
    /// - `NoSpace` if no sectors available
    pub fn append(&mut self, sensor_id: u16, timestamp: u64, payload: &[u8]) -> Result<(), Error> {
        self.append_entry(
            EntryKind::Single,
            sensor_id,
            timestamp,
            timestamp,
            1,
            &[],
            payload,
        )
    }

    /// Append a [run](crate::run): many evenly spaced samples under one header.
    ///
    /// One entry header and one CRC for the whole burst, which is what makes it
    /// worth doing — thirty-two `f32` samples cost 148 bytes here against 800
    /// appended one at a time.
    ///
    /// The run is **invisible to every read**: [`query_range`](Self::query_range),
    /// [`latest`](Self::latest), [`oldest`](Self::oldest) and
    /// [`count`](Self::count) expand it back into the samples it holds, so they
    /// deliver byte for byte what [`append_sensor`](Self::append_sensor) of the
    /// same samples would have delivered. Only
    /// [`read_from`](Self::read_from) sees it as one entry, because replication
    /// copies entries and a replica should keep the amortisation.
    ///
    /// ```ignore
    /// use sensor_db::Run;
    ///
    /// let burst: [Temperature; 32] = collect_burst();
    /// db.append_run(&Run::of(t0, 10_000, &burst)?)?;
    /// ```
    ///
    /// # Errors
    /// - `NotMounted` if not mounted
    /// - `PayloadTooLarge` if the framed run exceeds
    ///   [`max_payload_size`](Self::max_payload_size); split the burst
    /// - `NoSpace` if no sectors available
    pub 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(),
        )
    }

    /// Append an entry exactly as another log stored it.
    ///
    /// The write side of replication, and the mirror of
    /// [`read_from`](Self::read_from): hand back the `(header, payload)` pair a
    /// stream delivered and the entry is reproduced here — a
    /// [run](crate::run) as a run, so the copy keeps the amortisation instead of
    /// storing the frame as one opaque sample no read could interpret.
    ///
    /// # Errors
    /// - `CorruptEntry` if the header claims a run and the payload is not one
    /// - otherwise as [`append`](Self::append)
    pub fn append_framed(&mut self, header: &EntryHeader, payload: &[u8]) -> Result<(), Error> {
        match header.kind {
            EntryKind::Single => self.append(header.sensor_id, header.timestamp, payload),
            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,
                )
            }
        }
    }

    /// The one write path: buffer an entry of either kind, sealing as needed.
    ///
    /// The payload arrives in two pieces so a run costs no staging buffer — the
    /// frame header and the sample bytes go straight into the page buffer, which
    /// is also where the entry CRC is then computed from.
    ///
    /// `span_end` and `samples` describe what the entry contributes to the
    /// sector index: a single sample spans its own timestamp and counts once, a
    /// run spans to its last sample and counts all of them.
    #[allow(clippy::too_many_arguments)]
    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);
        }

        let flash = &mut self.flash;

        // This run inherited a sector an earlier run created, so appending into
        // it would stamp these entries with the earlier run's epoch. Roll to a
        // fresh sector, which records this run's epoch on the medium.
        //
        // Deferred to here rather than done at mount so a run that only reads
        // costs no erase at all.
        if self.state.epoch_pending {
            match self.state.seal_and_advance(flash) {
                Ok(()) => {}
                // Provenance metadata must never cost a write. If the ring has
                // no sector to give, append into the inherited one; the only
                // casualty is epoch precision.
                Err(Error::NoSpace) => self.state.epoch_pending = false,
                Err(e) => return Err(e),
            }
        }

        // Make room. One seal always suffices: a fresh sector gives a whole page
        // after its header page. A second would mean the geometry cannot hold
        // this entry anywhere, so refuse rather than seal forever — burning the
        // entire ring one sector per iteration.
        let mut sealed_once = false;
        loop {
            match self.state.plan_append(entry_size)? {
                AppendStep::Stage => break,
                AppendStep::FlushPage => self.state.flush_page(flash)?,
                AppendStep::Seal => {
                    if sealed_once {
                        return Err(Error::PayloadTooLarge);
                    }
                    sealed_once = true;
                    self.state.seal_and_advance(flash)?;
                }
            }
        }

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

    /// Flush the page buffer to flash, committing buffered entries.
    ///
    /// Call this after writing entries to ensure they survive a power loss.
    /// Read methods (`latest`, `query_range`, `oldest`, `count`) do **not**
    /// require a prior `sync()` — they transparently scan the page buffer for
    /// unflushed entries. `sync()` is only needed for **durability**, not for
    /// read visibility.
    ///
    /// # Sync Policy
    ///
    /// There is a trade-off between data safety and flash wear:
    /// - **Sync after every append**: Maximum durability — no data loss on power
    ///   failure, but each sync writes a full flash page (two writes for the
    ///   two-phase commit), increasing wear.
    /// - **Sync periodically** (e.g., every N entries or every T seconds):
    ///   Reduces wear but risks losing buffered entries on power failure.
    ///   Entries written since the last sync are not yet committed to flash.
    ///
    /// On embedded systems with limited flash endurance (~100K erase cycles),
    /// prefer batching writes and syncing periodically.
    pub fn sync(&mut self) -> Result<(), Error> {
        if !self.state.mounted {
            return Err(Error::NotMounted);
        }
        self.state.flush_page(&mut self.flash)?;
        Ok(())
    }

    /// Find the most recent entry for a given sensor.
    ///
    /// This method does **not** write to flash. It scans committed entries on
    /// flash and any buffered (unflushed) entries in the page buffer, returning
    /// the one with the highest timestamp.
    ///
    /// # 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 fn latest(
        &mut self,
        sensor_id: u16,
        buf: &mut [u8],
    ) -> Result<Option<(EntryHeader, usize)>, Error> {
        self.state.require_reads()?;

        let flash = &mut self.flash;

        // Sort sectors by sequence (newest first), skipping sectors that
        // definitely don't contain this sensor (bloom filter)
        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) {
                // Cannot fail: vec capacity is MAX_SECTORS >= sector_count
                let _ = sector_order.push((i, summary.sequence));
            }
        }
        // Sort descending by sequence
        sort_by_seq(&mut sector_order, |a, b| b.cmp(a));

        // Scan committed sectors from flash (newest first, writes payload to buf)
        let mut best: Option<(EntryHeader, usize)> = None;
        for (sector_idx, _) in sector_order {
            if let Some(result) =
                self.state
                    .find_latest_in_sector(&mut *flash, sector_idx, sensor_id, buf)?
            {
                best = Some(result);
                break;
            }
        }

        // Scan page buffer for unflushed entries. Only accepts entries with
        // timestamp >= the committed best, so buf is only overwritten if the
        // page buffer entry actually wins.
        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.
    ///
    /// This method does **not** write to flash. It scans committed entries on
    /// flash and any buffered (unflushed) entries in the page buffer.
    ///
    /// # 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.
    ///
    /// **Note:** Entries are returned in write order (sector sequence, then offset
    /// within sector), not sorted by timestamp. If timestamps are non-monotonic,
    /// the callback will see them out of chronological order.
    pub 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 flash = &mut self.flash;
        let mut count = 0u32;

        // Sort sectors by sequence (oldest first for chronological order)
        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))
            {
                // Cannot fail: vec capacity is MAX_SECTORS >= sector_count
                let _ = sector_order.push((i, summary.sequence));
            }
        }
        // Sort ascending by sequence for chronological order
        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.state.scan_sector_for_query(
                flash,
                sector_idx,
                sensor_id,
                t_start,
                t_end,
                &mut entry_buf,
                &mut count,
                &mut callback,
            )?;
            if stopped {
                break;
            }
        }

        // Scan page buffer for unflushed entries (newest, after all committed)
        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.
    ///
    /// This is a convenience wrapper around `query_range` that uses the full timestamp range.
    ///
    /// # Arguments
    /// - `sensor_id`: Optional sensor filter (None for all sensors)
    /// - `callback`: Called for each matching entry. Return `false` to stop early.
    ///
    /// # Returns
    /// Number of entries that matched.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let count = db.query_all(Some(SENSOR_TEMP), |hdr, payload| {
    ///     println!("Entry at {}: {:?}", hdr.timestamp, payload);
    ///     true
    /// })?;
    /// ```
    pub 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)
    }

    /// Find the oldest (earliest) entry for a given sensor.
    ///
    /// This method does **not** write to flash. It scans committed entries on
    /// flash and falls back to the page buffer if no committed entries exist
    /// for this 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.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let mut buf = [0u8; 64];
    /// if let Some((hdr, n)) = db.oldest(SENSOR_TEMP, &mut buf)? {
    ///     let first_reading = &buf[..n];
    ///     println!("First reading at {}", hdr.timestamp);
    /// }
    /// ```
    pub fn oldest(
        &mut self,
        sensor_id: u16,
        buf: &mut [u8],
    ) -> Result<Option<(EntryHeader, usize)>, Error> {
        self.state.require_reads()?;

        let flash = &mut self.flash;

        // Sort sectors by sequence (oldest first), skipping sectors that
        // definitely don't contain this sensor (bloom filter)
        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) {
                // Cannot fail: vec capacity is MAX_SECTORS >= sector_count
                let _ = sector_order.push((i, summary.sequence));
            }
        }
        // Sort ascending by sequence (oldest first)
        sort_by_seq(&mut sector_order, u32::cmp);

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

        // Fallback: check page buffer. The active sector is the newest, so
        // buffered entries can only be "oldest" if no committed entries exist.
        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: the count is the number of entries
    /// [`query_range`](Self::query_range) would yield over the whole time range,
    /// because both apply the same acceptance test — a matching entry CRC — and
    /// resync the same way when one fails. Buffered entries not yet on flash are
    /// included, as they are for [`latest`](Self::latest).
    ///
    /// This method does **not** write to flash.
    ///
    /// # Cost
    ///
    /// `None` is free: it returns the total the mount scan established.
    ///
    /// A sensor filter scans every sector the per-sector bloom filter does not
    /// reject, reading each entry's payload to verify its CRC. That payload read
    /// is the price of agreeing with the read path; it was once skipped, which
    /// made `count` cheaper and wrong — it included entries `latest` and
    /// `query_range` refused to return. It is still cheaper than
    /// [`query_all`](Self::query_all), which has no bloom filter to skip
    /// sectors by.
    ///
    /// # Arguments
    /// - `sensor_id`: Optional sensor filter (None to count all entries)
    ///
    /// # Returns
    /// Number of entries matching the filter.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let temp_count = db.count(Some(SENSOR_TEMP))?;
    /// let total = db.count(None)?;
    /// ```
    pub fn count(&mut self, sensor_id: Option<u16>) -> Result<u32, Error> {
        self.state.require_reads()?;

        // For counting all entries, we can use the cached total
        let Some(target) = sensor_id else {
            return Ok(self.state.total_samples);
        };

        let flash = &mut self.flash;
        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.state.count_sensor_in_sector(&mut *flash, i, target)?;
            }
        }

        // Include unflushed entries in the page buffer
        count += self.state.count_sensor_in_page_buf(target);

        Ok(count)
    }

    /// Compact the database by erasing the oldest sealed sectors.
    ///
    /// # Arguments
    /// - `count`: Maximum number of sectors to erase
    /// - `scope`: Which sealed sectors are eligible. Use
    ///   [`CompactScope::SpooledOnly`] to reclaim space without destroying
    ///   anything that has not been replicated yet.
    ///
    /// # Returns
    /// Number of sectors actually erased.
    pub fn compact(&mut self, count: u16, scope: CompactScope) -> Result<u16, Error> {
        if !self.state.mounted {
            return Err(Error::NotMounted);
        }

        // Find eligible sealed sectors
        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;
            }
            // Cannot fail: vec capacity is MAX_SECTORS >= sector_count
            let _ = sealed.push((i, summary.sequence));
        }

        // Sort by sequence (oldest first)
        sort_by_seq(&mut sealed, u32::cmp);

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

        Ok(erased)
    }

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

    /// Sectors this instance has erased, since it was created.
    ///
    /// An erase takes 100 ms or more on many NOR parts, against microseconds for
    /// a page write, so it is the one operation that can make a single `append`
    /// or [`compact`](Self::compact) call visibly slow. Sampling this around a
    /// call says whether one happened — useful for a caller with a real-time
    /// deadline, and for
    /// [`WritePolicy::CardFirst`](crate::spool::WritePolicy::CardFirst), where
    /// appends go straight to a removable volume.
    ///
    /// Not the same as [`DbStats::total_erase_count`], which is a *wear* history
    /// read back from the sector headers and therefore counts erases from every
    /// previous run too. This counter starts at zero for each `SensorDb` value,
    /// including across a remount, and saturates rather than wrapping.
    pub fn sectors_erased(&self) -> u32 {
        self.state.sectors_erased
    }

    /// 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.
    ///
    /// Returns `PAGE_SIZE - 20` bytes (`PAGE_SIZE` minus the 16-byte entry
    /// header and 4-byte CRC-32C). Each entry must fit entirely within a
    /// single flash page.
    ///
    /// A *typed* payload carries a one-byte schema tag, so the largest storable
    /// `T` is one byte smaller again — see
    /// [`SCHEMA_TAG_SIZE`](crate::SCHEMA_TAG_SIZE).
    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 to the database with an explicit sensor ID.
    ///
    /// This is the Layer 1 API where you provide the sensor ID explicitly.
    /// The value type must implement [`IntoBytes`] and [`Immutable`] from zerocopy.
    ///
    /// # Arguments
    /// - `sensor_id`: Sensor identifier
    /// - `timestamp`: Timestamp (typically microseconds since epoch)
    /// - `data`: Reference to the typed value to store
    ///
    /// # Example
    ///
    /// ```ignore
    /// #[derive(IntoBytes, Immutable)]
    /// #[repr(C)]
    /// struct Temperature { celsius: f32 }
    ///
    /// db.append_value(0x01, timestamp, &Temperature { celsius: 25.5 })?;
    /// ```
    pub 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())
    }

    /// Find the most recent entry for a given sensor and interpret as a typed value.
    ///
    /// This is the Layer 1 API where you provide the sensor ID explicitly.
    /// The value type must implement [`FromBytes`] and [`KnownLayout`] from zerocopy.
    ///
    /// # Arguments
    /// - `sensor_id`: Sensor to query
    ///
    /// # Returns
    /// `Some((header, value))` if found, `None` if no entries for this sensor.
    ///
    /// # Errors
    /// - `SizeMismatch` if the stored payload size doesn't match `size_of::<T>()`
    /// - `InvalidData` if the bytes cannot be interpreted as type `T`
    ///
    /// # Example
    ///
    /// ```ignore
    /// #[derive(FromBytes, KnownLayout)]
    /// #[repr(C)]
    /// struct Temperature { celsius: f32 }
    ///
    /// if let Some((hdr, temp)) = db.latest_value::<Temperature>(0x01)? {
    ///     println!("Temperature: {} °C", temp.celsius);
    /// }
    /// ```
    pub 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)? {
            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.
    ///
    /// This is the Layer 2 API where the sensor ID is derived from the type.
    /// The data type must implement [`SensorData`].
    ///
    /// # Arguments
    /// - `timestamp`: Timestamp (typically microseconds since epoch)
    /// - `data`: Reference to the sensor data to store
    ///
    /// # Example
    ///
    /// ```ignore
    /// #[derive(FromBytes, IntoBytes, KnownLayout, Immutable)]
    /// #[repr(C)]
    /// struct Temperature { celsius: f32 }
    ///
    /// impl SensorData for Temperature {
    ///     const SENSOR_ID: u16 = 0x01;
    /// }
    ///
    /// db.append_sensor(timestamp, &Temperature { celsius: 25.5 })?;
    /// ```
    ///
    /// # Schema tag
    ///
    /// The payload is the type's
    /// [`SCHEMA_VERSION`](SensorData::SCHEMA_VERSION) followed by the value's
    /// bytes, so the entry's `payload_len` is `size_of::<T>() + 1`. Entries
    /// written with the untagged [`append_value`](Self::append_value) are not
    /// readable through the `*_sensor` methods, and vice versa.
    pub fn append_sensor<T: SensorData>(&mut self, timestamp: u64, data: &T) -> Result<(), Error> {
        let framed = schema::tag(data);
        self.append(T::SENSOR_ID, timestamp, framed.bytes())
    }

    /// Find the most recent entry for a sensor type.
    ///
    /// This is the Layer 2 API where the sensor ID is derived from the type.
    /// The data type must implement [`SensorData`].
    ///
    /// # Returns
    /// `Some((header, value))` if found, `None` if no entries for this sensor.
    ///
    /// # Errors
    /// - `SizeMismatch` if the stored payload is not `size_of::<T>() + 1` bytes
    /// - `SchemaMismatch` if it was written under another
    ///   [`SCHEMA_VERSION`](SensorData::SCHEMA_VERSION) of this type
    ///
    /// # Example
    ///
    /// ```ignore
    /// if let Some((hdr, temp)) = db.latest_sensor::<Temperature>()? {
    ///     println!("Temperature: {} °C at {}", temp.celsius, hdr.timestamp);
    /// }
    /// ```
    pub fn latest_sensor<T: SensorData>(&mut self) -> Result<Option<(EntryHeader, T)>, Error> {
        schema::read_tagged(|buf| self.latest(T::SENSOR_ID, buf))
    }

    /// Query sensor entries within a time range using the type-driven API.
    ///
    /// This is the Layer 2 API where the sensor ID is derived from the type.
    /// The data type must implement [`SensorData`].
    ///
    /// # Arguments
    /// - `t_start`: Start timestamp (inclusive)
    /// - `t_end`: End timestamp (inclusive)
    /// - `callback`: Called for each matching entry with the header and typed value.
    ///   Return `false` to stop early.
    ///
    /// # Returns
    /// Number of entries that matched and were successfully deserialized.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let count = db.query_sensor::<Temperature, _>(t_start, t_end, |hdr, temp| {
    ///     println!("{}: {} °C", hdr.timestamp, temp.celsius);
    ///     true // continue iterating
    /// })?;
    /// ```
    pub 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| {
            // Entries of another schema version, or of another shape entirely,
            // are skipped rather than raised: aborting on the first stale one
            // would hide every good entry behind it. Two types sharing a sensor
            // ID at different versions therefore each read their own era.
            let Some(value) = schema::untag_payload::<T>(payload) else {
                return true;
            };
            count += 1;
            callback(header, &value)
        })?;

        Ok(count)
    }

    /// Query all entries for a sensor type without time constraints.
    ///
    /// This is a convenience wrapper that queries all entries for the sensor type.
    ///
    /// # Arguments
    /// - `callback`: Called for each matching entry with the header and typed value.
    ///   Return `false` to stop early.
    ///
    /// # Returns
    /// Number of entries that matched and were successfully deserialized.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let count = db.query_all_sensor::<Temperature, _>(|hdr, temp| {
    ///     println!("{}: {} °C", hdr.timestamp, temp.celsius);
    ///     true
    /// })?;
    /// ```
    pub 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)
    }

    /// Find the oldest (earliest) entry for a sensor type.
    ///
    /// # Returns
    /// `Some((header, value))` if found, `None` if no entries for this sensor.
    ///
    /// # Errors
    /// - `SizeMismatch` if the stored payload size doesn't match `size_of::<T>()`
    /// - `InvalidData` if the bytes cannot be interpreted as type `T`
    ///
    /// # Example
    ///
    /// ```ignore
    /// if let Some((hdr, temp)) = db.oldest_sensor::<Temperature>()? {
    ///     println!("First reading: {} °C at {}", temp.celsius, hdr.timestamp);
    /// }
    /// ```
    pub fn oldest_sensor<T: SensorData>(&mut self) -> Result<Option<(EntryHeader, T)>, Error> {
        schema::read_tagged(|buf| self.oldest(T::SENSOR_ID, buf))
    }

    /// Count entries for a sensor type.
    ///
    /// # Returns
    /// Number of entries for this sensor type.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let temp_count = db.count_sensor::<Temperature>()?;
    /// ```
    pub fn count_sensor<T: SensorData>(&mut self) -> Result<u32, Error> {
        self.count(Some(T::SENSOR_ID))
    }

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

    /// Deliver committed entries in log order, starting at `from` (inclusive).
    ///
    /// This is the read side of replication: it walks the log as a *stream*
    /// rather than a query, so a copy can be resumed from a durable position
    /// after a reboot or after the destination went away.
    ///
    /// # Durability boundary
    ///
    /// Only entries that are **durable on flash** are delivered. Entries still
    /// sitting in the page buffer are excluded, so a caller replicating this log
    /// never copies something the source itself could still lose to a power cut.
    /// Call [`sync`](Self::sync) first to make the tail eligible.
    ///
    /// # Arguments
    /// - `from`: where to resume. Use [`LogPosition::BEGINNING`] to start at
    ///   whatever the log still retains.
    /// - `max_entries`: upper bound on entries delivered in this pass. Bounds
    ///   both the work done and, for a replicating caller, the amount that has
    ///   to be redone after a crash.
    /// - `callback`: receives each entry's position, header, and payload.
    ///   Return `Ok(false)` to stop, **rejecting** the entry just offered; return
    ///   `Err` to abort the pass.
    ///
    /// # Rejection semantics
    ///
    /// `Ok(false)` means *"I did not take this one, and I want to stop"*. The
    /// entry is not counted in [`ReadCursor::entries`] and
    /// [`ReadCursor::next`] stops **before** it, so resuming from `next`
    /// re-offers it. Likewise, an `Err` from the callback leaves `next` at the
    /// last entry the callback actually accepted.
    ///
    /// This is the opposite of [`query_range`](Self::query_range), where
    /// returning `false` stops *after* consuming the entry — and deliberately
    /// so. A caller forwarding this stream to somewhere else must be able to
    /// decline an entry (because the destination is full, or the batch has
    /// reached a boundary) without the log recording it as delivered.
    ///
    /// The callback returns `Result<bool, Error>` rather than a bare `bool`
    /// because its dominant use is writing each entry somewhere that can fail;
    /// a bare `bool` would force every such caller to smuggle the error out
    /// through captured state.
    ///
    /// # Ordering
    ///
    /// Entries are delivered in write order (ascending sector sequence, then
    /// ascending offset), which is not necessarily timestamp order — the same
    /// caveat as [`query_range`](Self::query_range).
    ///
    /// # Errors
    /// - `NotMounted` if the database is not mounted
    /// - whatever the callback returns
    pub 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);
        }

        // Collect retained sectors at or after `from`, and find the oldest
        // retained sequence so we can tell whether `from` fell off the tail.
        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 flash = &mut self.flash;
        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) = scanner.next_entry(flash, &mut header_buf, PAGE_SIZE)? {
                if !accept_entry(flash, sector_offset, &entry, &mut buf)? {
                    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 that are buffered in RAM but not yet durable, then
    /// discard them from this database.
    ///
    /// **Touches no flash.** This is what makes it usable when the underlying
    /// device has physically gone away: a removable medium can be pulled
    /// mid-page, and the entries still sitting in the page buffer are recovered
    /// into RAM and can be re-appended somewhere that still exists. A yank is
    /// not a power loss — the processor is still running, so nothing needs to be
    /// lost.
    ///
    /// Entries already durable on flash are left alone; only the RAM-only tail
    /// is drained. On return the page buffer is truncated to its durable prefix
    /// and the entry accounting is adjusted to match.
    ///
    /// "Durable" here means *written to flash*, which is not the same as the
    /// entry's committed flag: a commit pass that failed part-way leaves entries
    /// flagged committed in RAM that flash never received. Those are drained,
    /// because a later `mount` would not see them.
    ///
    /// The per-sector bloom filter and timestamp range are *not* rolled back —
    /// they may stay wider than the data warrants, which costs a redundant
    /// sector scan on some queries but never returns a wrong answer.
    ///
    /// # Returns
    /// The number of entries handed to the callback.
    ///
    /// # Errors
    /// - `NotMounted` if the database is not mounted
    /// - whatever the callback returns; the drain stops there and the buffer is
    ///   left untouched, so the operation can be retried
    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 entries that are buffered in RAM but not yet durable, without
    /// removing them.
    ///
    /// The non-destructive twin of [`drain_unflushed`](Self::drain_unflushed),
    /// and the piece [`read_from`](Self::read_from) deliberately leaves out:
    /// `read_from` streams only what flash has, because a replica must never be
    /// told about data the source could still lose, whereas a *reader* of this
    /// log should see everything the log holds. Composing the two covers the
    /// whole log from a position.
    ///
    /// Touches no flash, so it costs nothing, works on a device that has gone
    /// away, and is one of the few reads that still takes `&self`.
    ///
    /// # Errors
    /// - `NotMounted` if the database is not mounted
    /// - whatever the callback returns, which stops the walk
    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`.
    ///
    /// Reads the sector header from flash on demand rather than caching an
    /// epoch per sector in RAM — with `MAX_SECTORS = 512` that cache would cost
    /// 2 KB for a field consulted once per replication batch.
    ///
    /// Returns `None` when no retained sector holds that position, which is the
    /// normal answer for a position that has fallen off the tail of the ring.
    pub 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)?;
        let header = SectorHeader::read_from_bytes(&buf).map_err(|_| Error::CorruptEntry)?;
        Ok(header.is_valid().then(|| header.epoch.get()))
    }

    /// Position immediately after the newest entry, buffered entries included.
    ///
    /// Note this can be ahead of what [`read_from`](Self::read_from) will
    /// deliver, which stops at the durable tail. Returns
    /// [`LogPosition::BEGINNING`] when there is no active sector.
    pub fn head_position(&self) -> LogPosition {
        self.state.head_position()
    }

    /// Position of the oldest entry the log still retains.
    ///
    /// A [`read_from`](Self::read_from) starting before this reports a gap.
    /// Returns [`LogPosition::BEGINNING`] when the log is empty.
    pub fn tail_position(&self) -> LogPosition {
        self.state.tail_position()
    }

    /// Run `f` with flash access bounded to `[base, base + len)`.
    ///
    /// This is how something else on the same chip — a config store, a
    /// replication cursor, a firmware slot — reaches the device the database
    /// owns by value. The closure gets a [`Partition`], so its offsets are
    /// relative to `base` and an access past `len` is
    /// [`PartitionError::OutOfBounds`](crate::PartitionError::OutOfBounds)
    /// rather than a write into a neighbour.
    ///
    /// A region intersecting `[base_offset, base_offset + sector_count *
    /// sector_size)` is rejected with [`Error::RegionOverlap`]. That check is
    /// the point of this method: writing inside the database region behind the
    /// database's back corrupts the log, the in-RAM index silently disagrees
    /// with flash, and nothing surfaces until a later mount.
    ///
    /// For a *driver* capability rather than a region — presence detection, a
    /// wear counter, a chip id, deep power-down — use
    /// [`driver_mut`](Self::driver_mut).
    ///
    /// # 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`
    ///
    /// ```ignore
    /// // Read the config block that lives just below the log.
    /// let mut buf = [0u8; 64];
    /// db.with_region(CONFIG_BASE, CONFIG_LEN, |p| p.read(0, &mut buf))??;
    /// ```
    pub fn with_region<R>(
        &mut self,
        base: u32,
        len: u32,
        f: impl FnOnce(&mut Partition<&mut F>) -> R,
    ) -> Result<R, Error> {
        self.state.check_disjoint(base, len)?;
        let mut partition = Partition::new(&mut self.flash, base, len)?;
        Ok(f(&mut partition))
    }

    /// Borrow the underlying flash driver.
    ///
    /// For capabilities that belong to the *driver* rather than to any region of
    /// the chip: presence detection, wear counters, chip identification, power
    /// modes, and test introspection. The database owns `F` by value, so without
    /// this nothing else can reach those.
    ///
    /// # Correctness
    ///
    /// This is the unbounded escape hatch, and nothing here can enforce
    /// anything: `F` is a `NorFlash`, so a caller *can* write anywhere on the
    /// chip. **Do not address flash through it.** Use
    /// [`with_region`](Self::with_region), which is checked.
    pub fn driver_mut(&mut self) -> &mut F {
        &mut self.flash
    }

    /// Advance the replication watermark.
    ///
    /// Call this only after `moved`, ending at `upto`, is **durably** stored
    /// somewhere else. Advancing it early is the one way to turn this design's
    /// at-least-once guarantee into data loss: the watermark is what tells the
    /// ring which sectors are safe to overwrite first.
    ///
    /// Monotonic — an `upto` at or behind the current watermark is ignored, so
    /// replaying an old acknowledgement cannot move it backwards.
    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.
    ///
    /// [`mount`](Self::mount) deliberately cannot recover this: the watermark
    /// lives on the replica, which is what lets two removable media be rotated
    /// against one log with no local state. Until a replica reappears and calls
    /// this, [`spool_stats`](Self::spool_stats) reports everything as
    /// un-replicated — the safe direction, because it can only cause redundant
    /// copying, never loss.
    ///
    /// Accounting is recomputed from the in-RAM index for whole sectors, plus one
    /// scan of the sector the watermark falls *inside* — the index knows how many
    /// entries a sector holds but not where each one starts, so the entries below
    /// the watermark within that sector have to be counted off flash. The result
    /// matches what [`note_spooled`](Self::note_spooled) would have accumulated
    /// had the replica never gone away.
    ///
    /// # Errors
    ///
    /// Only from that one scan, and only ever `Flash`. The watermark itself is
    /// restored *before* the scan and stays restored, because it is the part that
    /// matters: it is what tells the ring which sectors are safe to overwrite.
    /// An `Err` therefore means the log is fully usable and only
    /// [`spool_stats`](Self::spool_stats) is degraded — it over-reports
    /// `unspooled_entries` by at most one sector's worth, the same conservative
    /// answer this method used to give unconditionally.
    pub 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
            .state
            .count_entries_before(&mut self.flash, boundary, upto.offset)?;
        self.state.add_spooled(counted);
        Ok(())
    }

    /// Replication accounting for this log.
    ///
    /// `unspooled_entries` is O(1). See [`SpoolStats`] for the meaning of each
    /// field, and note that `data_lost` is sticky.
    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 found on the medium at mount.
    ///
    /// Stamped into every sector header this run creates, which is what lets a
    /// reader attribute data to a particular run of a device whose clock
    /// restarts at zero on every boot.
    ///
    /// # How a run's epoch reaches the medium
    ///
    /// Epochs live in sector headers, so a run only records one by creating a
    /// sector. To keep the attribution exact, the **first append after a mount
    /// rolls to a fresh sector** rather than continuing in the one the previous
    /// run left open. Every entry a run writes therefore sits in a sector
    /// stamped with that run's epoch.
    ///
    /// The roll is deferred to the first append, so a run that only reads costs
    /// nothing. A run that writes costs one extra sector transition — one erase,
    /// plus whatever space was left unused in the inherited sector. That is
    /// cheap when reboots are rare, which is the case this is built for.
    ///
    /// If the ring is completely full and cannot yield a sector, the roll is
    /// skipped rather than failing the append: losing epoch precision is always
    /// preferable to losing a sample. Replication correctness never depends on
    /// the epoch — it rests on [`LogPosition`].
    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
    }

    /// Declare this log a replica of another, suppressing the per-run epoch roll.
    ///
    /// A primary log rolls to a fresh sector on its first append after a mount
    /// so that the run's [`epoch`](Self::epoch) is recorded on the medium. For a
    /// replica that is pure waste: its entries are copies, and their provenance
    /// lives in the replication cursor, not in this log's sector headers. Left
    /// enabled it would burn a sector — and on a full ring, evict the oldest one
    /// — every single time the medium is inserted.
    ///
    /// [`Spooler::attach`](crate::spool::Spooler::attach) calls this, so a
    /// volume managed by a spooler needs no action. Call it directly only when
    /// maintaining a replica by hand.
    ///
    /// Takes effect for the current mount; call it again after each `mount`.
    pub fn mark_as_replica(&mut self) {
        self.state.epoch_pending = false;
    }

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

// =============================================================================
// SensorDbState — all non-flash state and helpers
// =============================================================================

impl<const PAGE_SIZE: usize, const MAX_SECTORS: usize> SensorDbState<PAGE_SIZE, MAX_SECTORS> {
    // -------------------------------------------------------------------------
    // Pure state helpers (no flash parameter)
    // -------------------------------------------------------------------------

    pub(crate) fn sector_offset(&self, sector_idx: u16) -> u32 {
        // Safety: `new()` validates that base_offset + sector_count * sector_size
        // fits in u32, so this cannot overflow for any valid sector_idx.
        self.base_offset + sector_idx as u32 * self.sector_size
    }

    /// Offset within a sector of the reserved footer page.
    ///
    /// Doubles as the limit for entry data: everything from here to the end of
    /// the sector belongs to the [`SectorFooter`]
    /// written when the sector is sealed, so `append` must stop before it and
    /// every scan must be bounded by it.
    ///
    /// Cannot underflow: `new` rejects a sector smaller than three pages.
    pub(crate) fn footer_offset(&self) -> u32 {
        self.sector_size - PAGE_SIZE as u32
    }

    /// Byte after the last byte of the database region.
    pub(crate) fn region_end(&self) -> u32 {
        self.base_offset + self.sector_count as u32 * self.sector_size
    }

    /// Reject a region that intersects the database's own sectors.
    ///
    /// This is the check that turns the old "only touch addresses outside the
    /// database region" doc comment into something enforced. Shared by both
    /// drivers so the rule is stated once.
    pub(crate) fn check_disjoint(&self, base: u32, len: u32) -> Result<(), Error> {
        let end = (base as u64)
            .checked_add(len as u64)
            .ok_or(Error::Overflow)?;
        let (db_base, db_end) = (self.base_offset, self.region_end());
        if (base as u64) < db_end as u64 && (db_base as u64) < end {
            return Err(Error::RegionOverlap { db_base, db_end });
        }
        Ok(())
    }

    /// Choose the sector to write into next.
    ///
    /// Pure selection — this mutates no counters. The caller applies
    /// [`account_eviction`](Self::account_eviction) *after* the erase succeeds,
    /// so a failed erase cannot leave the index claiming data is gone.
    pub(crate) fn find_next_sector(&mut self) -> Result<u16, Error> {
        // Tier 1: an already-erased sector, lowest erase count (wear levelling).
        // Tie-break: round-robin starting from active_sector + 1.
        let start = self
            .active_sector
            .map_or(0, |a| (a + 1) % self.sector_count);
        let mut best_idx: Option<u16> = None;
        let mut best_erase = u32::MAX;
        for offset in 0..self.sector_count {
            let i = (start + offset) % self.sector_count;
            let summary = &self.sectors[i as usize];
            if summary.state == SectorState::Erased && summary.erase_count < best_erase {
                best_erase = summary.erase_count;
                best_idx = Some(i);
            }
        }
        if let Some(idx) = best_idx {
            return Ok(idx);
        }

        // No erased sectors — reclaim a sealed one, respecting reserved_sectors.
        let sealed_count: u16 = self.sectors[..self.sector_count as usize]
            .iter()
            .filter(|s| s.state == SectorState::Sealed)
            .count() as u16;

        if sealed_count <= self.reserved_sectors {
            return Err(Error::NoSpace);
        }

        // Tier 2: the oldest sealed sector whose contents are fully replicated.
        // Tier 3: the oldest sealed sector at all — this destroys data that was
        // never replicated, which `account_eviction` records as a loss.
        //
        // These select the same sector in every state reachable today, because
        // replication proceeds oldest-first and so the replicated set is always a
        // prefix of the ring by sequence. The tiers are written out anyway: they
        // make the choice explicit rather than incidental, and they are where a
        // refuse-to-overwrite policy would hook in.
        self.oldest_sealed(true)
            .or_else(|| self.oldest_sealed(false))
            .ok_or(Error::NoSpace)
    }

    // -------------------------------------------------------------------------
    // Replication bookkeeping (pure; shared by both flavours)
    // -------------------------------------------------------------------------

    pub(crate) fn head_position(&self) -> LogPosition {
        match self.active_sector {
            Some(idx) => LogPosition {
                sequence: self.sectors[idx as usize].sequence,
                offset: self.sectors[idx as usize].write_offset,
            },
            None => LogPosition::BEGINNING,
        }
    }

    pub(crate) fn tail_position(&self) -> LogPosition {
        let mut oldest: Option<u32> = None;
        for i in 0..self.sector_count {
            let summary = &self.sectors[i as usize];
            if summary.state != SectorState::Erased
                && oldest.is_none_or(|seq| summary.sequence < seq)
            {
                oldest = Some(summary.sequence);
            }
        }
        match oldest {
            Some(sequence) => LogPosition {
                sequence,
                offset: SECTOR_HEADER_SIZE as u32,
            },
            None => LogPosition::BEGINNING,
        }
    }

    pub(crate) fn note_spooled(&mut self, upto: LogPosition, moved: Replicated) {
        if upto <= self.spool_watermark {
            return;
        }
        self.spool_watermark = upto;
        self.add_spooled(moved);
    }

    /// Index of the retained sector carrying `sequence`, if the ring still holds it.
    pub(crate) fn sector_at_sequence(&self, sequence: u32) -> Option<u16> {
        (0..self.sector_count).find(|i| {
            let summary = &self.sectors[*i as usize];
            summary.state != SectorState::Erased && summary.sequence == sequence
        })
    }

    /// Set the watermark and recompute accounting from whole sectors alone.
    ///
    /// Returns the sector the watermark falls *inside*, whose entries below it
    /// this cannot count from the in-RAM index — sector summaries record how many
    /// entries a sector holds, not where each one starts. Refining that is one
    /// bounded scan, which only the flash-holding caller can perform; until it
    /// does, the accounting under-reports what has been replicated, which is the
    /// safe direction.
    pub(crate) fn restore_spool_watermark(&mut self, upto: LogPosition) -> Option<u16> {
        if upto <= self.spool_watermark {
            return None;
        }
        self.spool_watermark = upto;
        self.spooled_entries = self.spooled_in_whole_sectors().min(self.total_entries);
        self.spooled_samples = self
            .spooled_samples_in_whole_sectors()
            .min(self.total_samples);

        // The sector the watermark falls inside, if it holds anything below it.
        self.sector_at_sequence(upto.sequence).filter(|i| {
            upto.offset > SECTOR_HEADER_SIZE as u32 && self.sectors[*i as usize].entry_count > 0
        })
    }

    /// Credit more as replicated, never past what the log still holds.
    pub(crate) fn add_spooled(&mut self, moved: Replicated) {
        self.spooled_entries = self
            .spooled_entries
            .saturating_add(moved.entries)
            .min(self.total_entries);
        self.spooled_samples = self
            .spooled_samples
            .saturating_add(moved.samples)
            .min(self.total_samples);
    }

    pub(crate) fn spool_stats(&self) -> SpoolStats {
        SpoolStats {
            unspooled_entries: self.total_entries.saturating_sub(self.spooled_entries),
            unspooled_samples: self.total_samples.saturating_sub(self.spooled_samples),
            watermark: self.spool_watermark,
            head: self.head_position(),
            dropped_unspooled: self.dropped_unspooled,
            data_lost: self.dropped_unspooled > 0,
        }
    }

    /// First byte of the page buffer that flash does not yet have.
    ///
    /// Everything below `page_buf_durable` is on flash; everything from here to
    /// `page_buf_offset` exists only in RAM.
    ///
    /// The flags byte deliberately plays no part. `flush_page` sets flags to
    /// committed in the buffer *before* writing it, so a commit pass that failed
    /// leaves entries marked committed in RAM while flash still has them
    /// uncommitted — invisible to a later `mount`. Trusting the flag would
    /// silently skip exactly the entries this boundary exists to identify.
    fn unflushed_start(&self) -> usize {
        self.page_buf_scan_start().max(self.page_buf_durable)
    }

    /// Walk the RAM-only tail of the page buffer without changing it.
    ///
    /// Stops at the first byte that is not the start of a whole entry, which is
    /// how a partially written tail is bounded.
    /// Walks *entries*, not samples: this is the replication and rescue side,
    /// where a run must stay a run so the copy keeps its amortisation.
    fn walk_unflushed<C>(&self, mut callback: C) -> Result<Replicated, Error>
    where
        C: FnMut(&EntryHeader, &[u8]) -> Result<(), Error>,
    {
        let end = self.page_buf_offset;
        let mut seen = Replicated::NONE;
        let mut pos = self.unflushed_start();
        while let Some(entry) = self.next_buffered(&mut pos, end) {
            let payload = self.buffered_payload(&entry);
            callback(&entry.header.to_header(), payload)?;
            seen.push(samples_in(entry.is_run(), payload));
        }
        Ok(seen)
    }

    pub(crate) fn peek_unflushed<C>(&self, callback: C) -> Result<u32, Error>
    where
        C: FnMut(&EntryHeader, &[u8]) -> Result<(), Error>,
    {
        if !self.mounted {
            return Err(Error::NotMounted);
        }
        Ok(self.walk_unflushed(callback)?.entries)
    }

    pub(crate) fn drain_unflushed<C>(&mut self, callback: C) -> Result<u32, Error>
    where
        C: FnMut(&EntryHeader, &[u8]) -> Result<(), Error>,
    {
        if !self.mounted {
            return Err(Error::NotMounted);
        }

        let scan_start = self.unflushed_start();
        let end = self.page_buf_offset;
        if scan_start >= end {
            return Ok(0);
        }

        let drained = self.walk_unflushed(callback)?;
        if drained.entries == 0 {
            return Ok(0);
        }
        let truncate_to = scan_start;

        // Drop the non-durable suffix from the page buffer and undo its
        // contribution to the in-RAM index.
        let bytes_dropped = (end - truncate_to) as u32;
        self.page_buf[truncate_to..].fill(0xFF);
        self.page_buf_offset = truncate_to;

        if let Some(active_idx) = self.active_sector {
            let summary = &mut self.sectors[active_idx as usize];
            summary.entry_count = summary.entry_count.saturating_sub(drained.entries);
            summary.sample_count = summary.sample_count.saturating_sub(drained.samples);
            summary.write_offset = summary.write_offset.saturating_sub(bytes_dropped);
        }
        self.total_entries = self.total_entries.saturating_sub(drained.entries);
        self.total_samples = self.total_samples.saturating_sub(drained.samples);

        Ok(drained.entries)
    }

    /// Index of the oldest sealed sector, optionally restricted to sectors whose
    /// contents are fully replicated.
    fn oldest_sealed(&self, require_spooled: bool) -> Option<u16> {
        let mut oldest_idx = None;
        let mut oldest_seq = u32::MAX;
        for i in 0..self.sector_count {
            let summary = &self.sectors[i as usize];
            if summary.state != SectorState::Sealed || summary.sequence >= oldest_seq {
                continue;
            }
            if require_spooled && !self.is_fully_spooled(summary) {
                continue;
            }
            oldest_seq = summary.sequence;
            oldest_idx = Some(i);
        }
        oldest_idx
    }

    // -------------------------------------------------------------------------
    // Page buffer scanning helpers (flush-free reads, no flash needed)
    // -------------------------------------------------------------------------

    /// Returns the starting offset within `page_buf` for entry scanning.
    pub(crate) fn page_buf_scan_start(&self) -> usize {
        let active_idx = match self.active_sector {
            Some(idx) => idx,
            None => return self.page_buf_offset, // no active sector, nothing to scan
        };
        if self.page_flash_offset == self.sector_offset(active_idx) {
            SECTOR_HEADER_SIZE
        } else {
            0
        }
    }

    /// Step the cursor `pos` over one whole entry in the page buffer.
    ///
    /// Returns `None` at the first byte that does not begin one, which is how a
    /// partially written tail is bounded — and is why every page-buffer walk
    /// goes through here rather than repeating the arithmetic. Committed entries
    /// are returned too: whether to skip them differs by caller (a reader has
    /// them from flash already; a rescue must not assume flash does).
    fn next_buffered(&self, pos: &mut usize, end: usize) -> Option<BufferedEntry> {
        if *pos + ENTRY_HEADER_SIZE > end || !is_entry_marker(self.page_buf[*pos]) {
            return None;
        }
        let header =
            EntryHeaderWire::read_from_bytes(&self.page_buf[*pos..*pos + ENTRY_HEADER_SIZE])
                .ok()?;
        let payload_len = header.payload_len.get() as usize;
        if *pos + ENTRY_OVERHEAD + payload_len > end {
            return None;
        }
        let payload_start = *pos + ENTRY_HEADER_SIZE;
        *pos += ENTRY_OVERHEAD + payload_len;
        Some(BufferedEntry {
            header,
            payload_start,
            payload_len,
        })
    }

    /// The payload of a buffered entry.
    fn buffered_payload(&self, entry: &BufferedEntry) -> &[u8] {
        &self.page_buf[entry.payload_start..entry.payload_start + entry.payload_len]
    }

    /// The sample at one `edge` of a buffered entry, and the header it would
    /// have carried had it been appended alone.
    fn buffered_sample(&self, entry: &BufferedEntry, edge: Edge) -> (EntryHeader, BufferedSample) {
        let located = |run| BufferedSample {
            payload_start: entry.payload_start,
            payload_len: entry.payload_len,
            run,
        };

        match RunFrame::parse(self.buffered_payload(entry)).filter(|_| entry.is_run()) {
            Some(frame) => {
                let index = match edge {
                    Edge::First => 0,
                    Edge::Last => frame.count() - 1,
                };
                (
                    frame.header_at(entry.sensor_id(), entry.timestamp(), index),
                    located(Some((frame, index))),
                )
            }
            None => (entry.header.to_header(), located(None)),
        }
    }

    /// Write a located sample into `out` as a schema-tagged payload.
    fn copy_buffered_sample(
        &self,
        sample: &BufferedSample,
        out: &mut [u8],
    ) -> Result<usize, Error> {
        let payload =
            &self.page_buf[sample.payload_start..sample.payload_start + sample.payload_len];
        match sample.run {
            Some((frame, index)) => frame
                .write_tagged_sample(payload, index, out)
                .ok_or(Error::BufferTooSmall),
            None => {
                if payload.len() > out.len() {
                    return Err(Error::BufferTooSmall);
                }
                out[..payload.len()].copy_from_slice(payload);
                Ok(payload.len())
            }
        }
    }

    /// The newest unflushed entry for a sensor, if it beats `min_ts`.
    ///
    /// Reports `BufferTooSmall` when the winner does not fit `buf`, matching
    /// [`find_latest_in_sector`](Self::find_latest_in_sector). Skipping it
    /// instead — as this used to — meant a caller with a small buffer was
    /// handed an *older* entry, or `None`, and told it was the latest.
    pub(crate) fn scan_page_buf_for_latest(
        &self,
        sensor_id: u16,
        min_ts: u64,
        buf: &mut [u8],
    ) -> Result<Option<(EntryHeader, usize)>, Error> {
        let scan_start = self.page_buf_scan_start();
        if scan_start >= self.page_buf_offset {
            return Ok(None);
        }

        let mut best: Option<(EntryHeader, BufferedSample)> = None;
        let mut best_ts: u64 = min_ts;
        let mut pos = scan_start;

        while let Some(entry) = self.next_buffered(&mut pos, self.page_buf_offset) {
            // Skip committed entries — they are already on flash
            if entry.is_committed() || entry.sensor_id() != sensor_id {
                continue;
            }

            // The buffer bound is deliberately *not* part of this test: an
            // entry that wins on timestamp wins, and its size is reported
            // below rather than letting an older entry take its place.
            let (header, sample) = self.buffered_sample(&entry, Edge::Last);
            if header.timestamp >= best_ts {
                best_ts = header.timestamp;
                best = Some((header, sample));
            }
        }

        // Copy payload only for the final winner
        let Some((header, sample)) = best else {
            return Ok(None);
        };
        let len = self.copy_buffered_sample(&sample, buf)?;
        Ok(Some((header, len)))
    }

    /// Deliver unflushed samples in a time range.
    ///
    /// `scratch` receives a copy of each entry's payload, because
    /// [`deliver_samples`] frames a run's samples by writing through the buffer
    /// it is given and the page buffer is behind a shared reference. The caller
    /// lends the same buffer the sector scan used, so this costs no stack.
    pub(crate) fn scan_page_buf_for_query<C>(
        &self,
        sensor_filter: Option<u16>,
        t_start: u64,
        t_end: u64,
        scratch: &mut [u8],
        count: &mut u32,
        callback: &mut C,
    ) -> bool
    where
        C: FnMut(&EntryHeader, &[u8]) -> bool,
    {
        let mut pos = self.page_buf_scan_start();

        while let Some(entry) = self.next_buffered(&mut pos, self.page_buf_offset) {
            // Skip committed entries — already visible via flash reads
            let sensor = entry.sensor_id();
            if entry.is_committed() || sensor_filter.is_some_and(|f| f != sensor) {
                continue;
            }

            let payload = self.buffered_payload(&entry);
            // Cannot fail: `scratch` is a page and a payload is smaller.
            let Some(dst) = scratch.get_mut(..payload.len()) else {
                continue;
            };
            dst.copy_from_slice(payload);

            if deliver_samples(
                entry.is_run(),
                sensor,
                entry.timestamp(),
                dst,
                t_start,
                t_end,
                count,
                callback,
            ) {
                return true; // stopped early
            }
        }

        false
    }

    pub(crate) fn scan_page_buf_for_oldest(
        &self,
        sensor_id: u16,
        buf: &mut [u8],
    ) -> Option<(EntryHeader, usize)> {
        let mut pos = self.page_buf_scan_start();

        while let Some(entry) = self.next_buffered(&mut pos, self.page_buf_offset) {
            // Skip committed entries — already visible via flash reads
            if entry.is_committed() || entry.sensor_id() != sensor_id {
                continue;
            }

            let (header, sample) = self.buffered_sample(&entry, Edge::First);
            if let Ok(len) = self.copy_buffered_sample(&sample, buf) {
                return Some((header, len));
            }
        }

        None
    }

    pub(crate) fn count_sensor_in_page_buf(&self, sensor_id: u16) -> u32 {
        let mut count = 0u32;
        let mut pos = self.page_buf_scan_start();

        while let Some(entry) = self.next_buffered(&mut pos, self.page_buf_offset) {
            // Skip committed entries — already counted via sector scanning
            if entry.is_committed() || entry.sensor_id() != sensor_id {
                continue;
            }
            count += samples_in(entry.is_run(), self.buffered_payload(&entry));
        }

        count
    }

    // -------------------------------------------------------------------------
    // Flash-accessing helpers (take explicit `flash: &mut F` parameter)
    // -------------------------------------------------------------------------

    fn erase_sector<F: NorFlash>(&mut self, flash: &mut F, sector_idx: u16) -> Result<(), Error> {
        let offset = self.sector_offset(sector_idx);
        flash.erase(offset, offset + self.sector_size)?;
        // 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.sectors_erased = self.sectors_erased.saturating_add(1);
        Ok(())
    }

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

        // Write header (padded to page size)
        let mut page = [0xFFu8; PAGE_SIZE];
        page[..SECTOR_HEADER_SIZE].copy_from_slice(header.as_bytes());
        flash.write(offset, &page)?;

        Ok(())
    }

    /// Read and validate the footer of `sector_idx`.
    ///
    /// Returns `None` for anything that does not describe this sector's current
    /// incarnation — an erased page, a torn write, a stale summary — which the
    /// caller answers with a body scan.
    fn read_sector_footer<F: ReadNorFlash>(
        &self,
        flash: &mut F,
        sector_idx: u16,
    ) -> Result<Option<SectorFooter>, Error> {
        let offset = self.sector_offset(sector_idx) + self.footer_offset();
        let mut buf = [0u8; SECTOR_FOOTER_SIZE];
        flash.read(offset, &mut buf)?;

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

    /// Write `sector_idx`'s summary into its reserved final page.
    ///
    /// Called once per sector, when it is sealed and its contents are final.
    fn write_sector_footer<F: NorFlash>(
        &self,
        flash: &mut F,
        sector_idx: u16,
    ) -> Result<(), Error> {
        // Nothing buffered may be missing from the summary being frozen. Every
        // path into `seal_and_advance` either has just flushed or is holding a
        // page whose contents are already on flash, so this holds — but it is
        // the invariant the footer's correctness rests on, so state it.
        debug_assert_eq!(
            self.page_buf_offset, self.page_buf_durable,
            "a sector is sealed only with a page buffer that flash already has"
        );

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

    /// What must happen before an entry of `entry_size` bytes can be staged.
    ///
    /// The sector-room test comes first and subsumes the old separate
    /// "cursor sat on the data boundary" pre-check: a page never straddles the
    /// footer, so whenever an entry fits the *current page* the sector has at
    /// least `PAGE_SIZE` left, and the only way `sector_remaining` can fall
    /// short is the cursor having already passed the boundary — which is
    /// precisely the case that pre-check existed for.
    pub(crate) fn plan_append(&self, entry_size: usize) -> Result<AppendStep, Error> {
        let active = self.active_sector.ok_or(Error::NoSpace)?;

        // Against the footer offset, not the sector size: the last page is
        // reserved for the summary written at seal time.
        let used = self.page_flash_offset - self.sector_offset(active);
        let sector_remaining = self.footer_offset().saturating_sub(used) as usize;

        if sector_remaining < entry_size || sector_remaining < ENTRY_OVERHEAD {
            return Ok(AppendStep::Seal);
        }

        if entry_size > PAGE_SIZE - self.page_buf_offset {
            return Ok(AppendStep::FlushPage);
        }

        Ok(AppendStep::Stage)
    }

    /// Write the entry into the page buffer and record it in the sector index.
    ///
    /// Pure, and only correct once [`plan_append`](Self::plan_append) has
    /// answered [`Stage`](AppendStep::Stage).
    ///
    /// The payload arrives in two pieces so a run costs no staging buffer — the
    /// frame header and the sample bytes go straight into the page buffer, which
    /// is also where the entry CRC is then computed from.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn stage_entry(
        &mut self,
        kind: EntryKind,
        sensor_id: u16,
        timestamp: u64,
        span_end: u64,
        samples: u32,
        head: &[u8],
        tail: &[u8],
    ) -> Result<(), Error> {
        let payload_len = head.len() + tail.len();
        let entry_size = ENTRY_OVERHEAD + payload_len;

        let header = match kind {
            EntryKind::Single => EntryHeaderWire::new(sensor_id, timestamp, payload_len as u16),
            EntryKind::Run => EntryHeaderWire::new_run(sensor_id, timestamp, payload_len as u16),
        };

        // Compute offset_in_sector for CRC: where this entry sits within its sector
        let active_idx = self.active_sector.ok_or(Error::NoSpace)?;
        let sector_offset = self.sector_offset(active_idx);
        let offset_in_sector =
            (self.page_flash_offset - sector_offset) + self.page_buf_offset as u32;

        // The payload is assembled in the page buffer first, so the CRC is
        // computed over one contiguous slice however many pieces it arrived in.
        let offset = self.page_buf_offset;
        let body = offset + ENTRY_HEADER_SIZE;
        self.page_buf[offset..body].copy_from_slice(header.as_bytes());
        self.page_buf[body..body + head.len()].copy_from_slice(head);
        self.page_buf[body + head.len()..body + payload_len].copy_from_slice(tail);

        let crc = compute_entry_crc(
            &header,
            &self.page_buf[body..body + payload_len],
            offset_in_sector,
        );
        self.page_buf[body + payload_len..offset + entry_size].copy_from_slice(&crc.to_le_bytes());

        self.page_buf_offset += entry_size;

        // Update sector summary
        let summary = &mut self.sectors[active_idx as usize];
        summary.entry_count += 1;
        summary.sample_count += samples;
        summary.write_offset += entry_size as u32;
        summary.record_span(timestamp, span_end);
        summary.record_sensor(sensor_id);
        self.total_entries += 1;
        self.total_samples += samples;

        Ok(())
    }

    /// Where the page buffer must be written, or `None` if there is nothing to
    /// flush.
    ///
    /// The three `commit_*`/`*_page` helpers exist so both drivers can express
    /// the two-phase commit as *write, mark, write, advance* without either of
    /// them restating what marking or advancing means.
    pub(crate) fn commit_target(&self) -> Option<u32> {
        (self.page_buf_offset > 0).then_some(self.page_flash_offset)
    }

    /// Flip the buffered entries' flags to committed, in RAM.
    ///
    /// Phase 2 of the two-phase commit: the caller re-writes the same page
    /// afterwards, which only clears bits (1→0) and so needs no erase.
    ///
    /// Note this makes the buffer claim a durability flash does not yet have —
    /// which is exactly why `page_buf_durable`, and not the flags byte, is what
    /// [`drain_unflushed`](Self::drain_unflushed) trusts.
    pub(crate) fn mark_page_committed(&mut self) {
        let scan_start =
            if self.page_flash_offset == self.sector_offset(self.active_sector.unwrap_or(0)) {
                // First page of sector: entries start after the sector header
                SECTOR_HEADER_SIZE
            } else {
                0
            };

        let mut pos = scan_start;
        while pos + ENTRY_HEADER_SIZE <= self.page_buf_offset {
            if is_entry_marker(self.page_buf[pos]) {
                // Set flags byte to COMMITTED (0x00)
                self.page_buf[pos + 1] = FLAGS_COMMITTED;

                // Skip past this entry
                let payload_len =
                    u16::from_le_bytes([self.page_buf[pos + 12], self.page_buf[pos + 13]]) as usize;
                let entry_size = ENTRY_OVERHEAD + payload_len;
                pos += entry_size;
            } else {
                break;
            }
        }
    }

    /// Move past the page just made durable and empty the buffer.
    pub(crate) fn advance_page(&mut self) {
        self.page_flash_offset += PAGE_SIZE as u32;
        self.page_buf.fill(0xFF);
        self.page_buf_offset = 0;
        self.page_buf_durable = 0;

        // Update the sector's write_offset to reflect the new page boundary
        // so that subsequent appends and reads see the correct position
        if let Some(active_idx) = self.active_sector {
            let sector_offset = self.sector_offset(active_idx);
            self.sectors[active_idx as usize].write_offset = self.page_flash_offset - sector_offset;
        }
    }

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

    /// Sector-index statistics.
    ///
    /// Pure — both drivers forward to this rather than each walking the sector
    /// array themselves, which they used to do in 30 identical lines apiece.
    pub(crate) fn stats(&self) -> DbStats {
        let mut used = 0u16;
        let mut free = 0u16;
        let mut min_erase = u32::MAX;
        let mut max_erase = 0u32;
        let mut total_erase = 0u64;

        for i in 0..self.sector_count as usize {
            let ec = self.sectors[i].erase_count;
            if ec < min_erase {
                min_erase = ec;
            }
            if ec > max_erase {
                max_erase = ec;
            }
            total_erase += ec as u64;
            match self.sectors[i].state {
                SectorState::Erased => free += 1,
                SectorState::Active | SectorState::Sealed => used += 1,
            }
        }

        if self.sector_count == 0 {
            min_erase = 0;
        }

        DbStats {
            total_entries: self.total_entries,
            total_samples: self.total_samples,
            used_sectors: used,
            free_sectors: free,
            reserved_sectors: self.reserved_sectors,
            min_erase_count: min_erase,
            max_erase_count: max_erase,
            total_erase_count: total_erase,
        }
    }

    /// Whether this mount mode wants a footer read for this sector.
    ///
    /// The newest sector's footer is read in **every** mode: there it is not an
    /// optimisation but the signal that the sector is already sealed, and
    /// appending into it would make its frozen summary a lie.
    pub(crate) fn wants_footer(&self, mode: MountMode, is_newest: bool) -> bool {
        mode == MountMode::Full || is_newest
    }

    /// Index a sector from its footer.
    pub(crate) fn adopt_footer(&mut self, i: u16, footer: &SectorFooter, stats: &mut MountStats) {
        footer.apply_to(&mut self.sectors[i as usize]);
        stats.total_entries += footer.entry_count.get();
        stats.total_samples += footer.sample_count.get();
    }

    /// Index a sector from a body scan.
    pub(crate) fn adopt_scan(
        &mut self,
        i: u16,
        scanned: &ScannedSector,
        corrupt: u32,
        stats: &mut MountStats,
    ) {
        scanned.apply_to(&mut self.sectors[i as usize]);
        stats.total_entries += scanned.entries;
        stats.total_samples += scanned.samples;
        stats.corrupt_entries += corrupt;
        stats.scanned_sectors += 1;
    }

    /// Record a sector known to exist and be sealed, but not indexed.
    ///
    /// `HeadersOnly` with no footer. `write_offset` covers the whole data region
    /// so a later `read_from` still streams it end to end, and the bounds are
    /// set wide open so nothing prunes it.
    pub(crate) fn adopt_unindexed(&mut self, i: u16) {
        let data_limit = self.footer_offset();
        let summary = &mut self.sectors[i as usize];
        summary.entry_count = 0;
        summary.sample_count = 0;
        summary.write_offset = data_limit;
        summary.min_timestamp = 0;
        summary.max_timestamp = u64::MAX;
        summary.sensor_bloom = u64::MAX;
    }

    /// Adopt the totals a mount established, before the active sector is chosen.
    pub(crate) fn finish_mount(
        &mut self,
        mode: MountMode,
        max_sequence: u32,
        max_epoch: u32,
        stats: &MountStats,
    ) {
        self.total_entries = stats.total_entries;
        self.total_samples = stats.total_samples;
        self.next_sequence = max_sequence + 1;
        self.epoch = max_epoch.saturating_add(1);
        self.mount_mode = mode;
        // The replica holds the replication watermark, not this log. Until it is
        // restored, everything reads as un-replicated — the safe direction.
        self.spool_watermark = LogPosition::BEGINNING;
        self.spooled_entries = 0;
        self.spooled_samples = 0;
        self.dropped_unspooled = 0;
    }

    /// The sector a seal is about to close.
    pub(crate) fn sealing(&self) -> Result<u16, Error> {
        self.active_sector.ok_or(Error::NoSpace)
    }

    /// Seal the active sector and choose its successor.
    ///
    /// **Order is load-bearing.** Marking `old_active` sealed has to happen
    /// before [`find_next_sector`](Self::find_next_sector), which counts sealed
    /// sectors against `reserved_sectors` and may pick this very one as the
    /// victim. Call this only *after* the footer write, which is where the
    /// blocking driver had it.
    pub(crate) fn begin_seal(&mut self, old_active: u16) -> Result<SealPlan, Error> {
        // Seal current sector
        self.sectors[old_active as usize].state = SectorState::Sealed;

        // Find next sector: prefer erased, otherwise erase oldest sealed
        let new_active = self.find_next_sector()?;

        // Snapshot the victim before anything touches it: if it was sealed, its
        // entries are about to be destroyed and must be accounted for.
        let victim = self.sectors[new_active as usize];

        // Increment erase count from the target sector (preserving wear history)
        let erase_count = victim.erase_count.saturating_add(1);

        Ok(SealPlan {
            new_active,
            erase_count,
            victim,
        })
    }

    /// Charge the ring for what the erase just destroyed.
    ///
    /// Must follow a **successful** erase. Doing it earlier would leave the
    /// index claiming a loss that never happened if `erase` failed.
    pub(crate) fn account_seal(&mut self, plan: &SealPlan) {
        if plan.victim.state == SectorState::Sealed {
            self.account_eviction(&plan.victim);
        }
    }

    /// Adopt the freshly initialised sector, after its header has been written.
    pub(crate) fn finish_seal(&mut self, plan: &SealPlan) {
        // That header carries the current epoch, so any debt from `mount` is paid.
        self.epoch_pending = false;

        self.sectors[plan.new_active as usize] = SectorSummary {
            state: SectorState::Active,
            sequence: self.next_sequence,
            entry_count: 0,
            sample_count: 0,
            write_offset: SECTOR_HEADER_SIZE as u32,
            min_timestamp: u64::MAX,
            max_timestamp: 0,
            sensor_bloom: 0,
            erase_count: plan.erase_count,
        };

        self.active_sector = Some(plan.new_active);
        self.next_sequence += 1;

        // Reset page buffer
        let sector_offset = self.sector_offset(plan.new_active);
        self.page_flash_offset = sector_offset;
        self.page_buf.fill(0xFF);
        let header = self.sector_header(
            self.sectors[plan.new_active as usize].sequence,
            plan.erase_count,
        );
        self.page_buf[..SECTOR_HEADER_SIZE].copy_from_slice(header.as_bytes());
        self.page_buf_offset = SECTOR_HEADER_SIZE;
        self.page_buf_durable = SECTOR_HEADER_SIZE;
    }

    fn seal_and_advance<F: NorFlash>(&mut self, flash: &mut F) -> Result<(), Error> {
        let old_active = self.sealing()?;

        // The sector's contents are final, so record its summary in the
        // reserved final page: that is what lets the next mount index it with a
        // single page read instead of a body scan.
        //
        // A failure here is deliberately not propagated. The footer is an
        // optimisation and must never make the log less usable than it would be
        // without one — and the failure that matters is exactly the persistent
        // kind. A footer page left dirty by an earlier torn write answers
        // `NotErased` forever, which would wedge every subsequent append for the
        // sake of metadata a body scan reconstructs anyway. Flash that is
        // genuinely broken still reports it: the erase and header write below
        // are on the same device and are not forgiving.
        let _ = self.write_sector_footer(flash, old_active);

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

        Ok(())
    }

    fn scan_sector_entries<F: ReadNorFlash>(
        &mut self,
        flash: &mut F,
        sector_idx: u16,
    ) -> Result<(ScannedSector, u32), Error> {
        let sector_offset = self.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.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) = scanner.next_entry(flash, &mut header_buf, PAGE_SIZE)? {
            if !accept_entry(flash, sector_offset, &entry, &mut buf)? {
                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()))
    }

    fn find_latest_in_sector<F: ReadNorFlash>(
        &self,
        flash: &mut F,
        sector_idx: u16,
        target_sensor: u16,
        buf: &mut [u8],
    ) -> Result<Option<(EntryHeader, usize)>, Error> {
        let sector_offset = self.sector_offset(sector_idx);
        let write_offset = self.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) = scanner.next_entry(flash, &mut header_buf, PAGE_SIZE)? {
            if !accept_entry(flash, sector_offset, &entry, &mut payload_buf)? {
                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)]
    fn scan_sector_for_query<F: ReadNorFlash, C>(
        &self,
        flash: &mut F,
        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.sector_offset(sector_idx);
        let write_offset = self.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) = scanner.next_entry(flash, &mut header_buf, PAGE_SIZE)? {
            if !accept_entry(flash, sector_offset, &entry, buf)? {
                scanner.skip(1);
                continue;
            }

            let sensor = entry.sensor_id();
            let base = entry.timestamp();

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

            scanner.skip(entry.entry_size);
        }

        Ok(false)
    }

    fn find_oldest_in_sector<F: ReadNorFlash>(
        &self,
        flash: &mut F,
        sector_idx: u16,
        target_sensor: u16,
        buf: &mut [u8],
    ) -> Result<Option<(EntryHeader, usize)>, Error> {
        let sector_offset = self.sector_offset(sector_idx);
        let write_offset = self.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) = scanner.next_entry(flash, &mut header_buf, PAGE_SIZE)? {
            if !accept_entry(flash, sector_offset, &entry, &mut payload_buf)? {
                scanner.skip(1);
                continue;
            }

            let sensor = entry.sensor_id();

            if sensor == 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`.
    ///
    /// Uses the same acceptance test as the mount scan — committed flags and a
    /// matching CRC — so the result is always a subset of the sector's
    /// `entry_count`, and the accounting it feeds stays comparable with the one
    /// `note_spooled` builds incrementally.
    ///
    /// An entry that straddles `offset_limit` is not counted: the scanner stops
    /// when the next entry would cross its limit. Watermarks land on entry
    /// boundaries, so that case does not arise from a well-formed position.
    pub(crate) fn count_entries_before<F: ReadNorFlash>(
        &self,
        flash: &mut F,
        sector_idx: u16,
        offset_limit: u32,
    ) -> Result<Replicated, Error> {
        let summary = &self.sectors[sector_idx as usize];
        let sector_offset = self.sector_offset(sector_idx);
        let entry_start = SECTOR_HEADER_SIZE as u32;
        let limit = offset_limit.min(summary.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) = scanner.next_entry(flash, &mut header_buf, PAGE_SIZE)? {
            if !accept_entry(flash, sector_offset, &entry, &mut buf)? {
                scanner.skip(1);
                continue;
            }
            found.push(samples_in(entry.is_run(), &buf[..entry.payload_len]));
            scanner.skip(entry.entry_size);
        }

        // A prefix cannot hold more than the whole. The clamp matters for a
        // `HeadersOnly` mount, where an unscanned sector reports `entry_count = 0`
        // and contributes nothing to `total_entries`.
        Ok(Replicated {
            entries: found.entries.min(summary.entry_count),
            samples: found.samples.min(summary.sample_count),
        })
    }

    /// Count the entries in `sector_idx` belonging to `target_sensor`.
    ///
    /// Uses the same acceptance test as [`scan_sector_for_query`] — a matching
    /// entry CRC, and a one-byte resync on failure — because `count` and
    /// `query_range` disagreeing about how many entries exist is a defect, not
    /// an optimisation. This costs a payload read per entry, and it is the same
    /// read `query_range` performs, paid only on sectors the bloom filter did
    /// not reject.
    ///
    /// [`scan_sector_for_query`]: Self::scan_sector_for_query
    fn count_sensor_in_sector<F: ReadNorFlash>(
        &self,
        flash: &mut F,
        sector_idx: u16,
        target_sensor: u16,
    ) -> Result<u32, Error> {
        let sector_offset = self.sector_offset(sector_idx);
        let write_offset = self.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) = scanner.next_entry(flash, &mut header_buf, PAGE_SIZE)? {
            // Every entry is verified, not only the matching ones: a failure
            // resyncs by one byte, so skipping the check for a non-matching
            // sensor would walk the sector differently from the read path and
            // reintroduce the disagreement from the other side.
            if !accept_entry(flash, sector_offset, &entry, &mut payload_buf)? {
                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. Written as `self.append(..)` these would
// be ambiguous to read — the inherent method and the trait method share a name
// — and a future signature change on the inherent one would silently turn the
// call into unbounded recursion.

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

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

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

impl<F, const PAGE_SIZE: usize, const MAX_SECTORS: usize> crate::port::LogSource
    for SensorDb<F, PAGE_SIZE, MAX_SECTORS>
where
    F: NorFlash + ReadNorFlash,
{
    fn latest(
        &mut self,
        sensor_id: u16,
        buf: &mut [u8],
    ) -> Result<Option<(EntryHeader, usize)>, Error> {
        SensorDb::latest(self, sensor_id, buf)
    }

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

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

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

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

    use super::*;
    use crate::mock::MockFlash;

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

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

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

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

        // Latest for sensor 1 should be the third entry
        let mut buf = [0u8; 16];
        let (hdr, n) = db.latest(1, &mut buf).unwrap().unwrap();
        assert_eq!(hdr.sensor_id, 1);
        assert_eq!(hdr.timestamp, 1002);
        assert_eq!(&buf[..n], &[0x01, 0x02]);

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

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

        // Query sensor 1, time range 100..250
        let mut results = alloc::vec::Vec::new();
        let count = 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 survives_remount() {
        let flash = MockFlash::<PAGE, SECTOR>::new(SECTORS * SECTOR);
        let mut db: SensorDb<_, PAGE, SECTORS> =
            SensorDb::new(flash, 0, SECTORS as u16, 1).unwrap();
        db.format().unwrap();

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

        let _stats_before = db.stats();

        // Simulate power cycle: extract flash, create new DB, mount
        let flash = db.into_inner();
        let mut db2: SensorDb<_, PAGE, SECTORS> =
            SensorDb::new(flash, 0, SECTORS as u16, 1).unwrap();
        let mount_stats = db2.mount().unwrap();

        assert_eq!(mount_stats.total_entries, 2);

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

    #[test]
    fn circular_wrap_reclaims_old_sectors() {
        // Use only 4 sectors to force wrapping quickly
        const SMALL: usize = 4;
        let flash = MockFlash::<PAGE, SECTOR>::new(SMALL * SECTOR);
        let mut db: SensorDb<_, PAGE, SMALL> = SensorDb::new(flash, 0, SMALL as u16, 1).unwrap();
        db.format().unwrap();

        // Fill enough entries to wrap around. Each entry is ~20 bytes.
        // Each 4KB sector fits roughly (4096 - 8) / 20 ≈ 204 entries per page,
        // but entries can't span pages so per page (256 - 8 first page) / 20 ≈ 12 entries.
        // With 16 pages per sector, ~192 entries per sector × 4 sectors = ~768 entries.
        // But we have 1 reserved sector so usable = 3 sectors ≈ 576 entries.
        for i in 0..800u64 {
            let payload = (i as u32).to_le_bytes();
            db.append(1, i * 100, &payload).unwrap();
        }

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

        // Most recent entry should still be queryable
        let mut buf = [0u8; 4];
        let (hdr, _) = db.latest(1, &mut buf).unwrap().unwrap();
        assert_eq!(hdr.timestamp, 799 * 100);
    }

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

        let before = db.stats();
        let freed = 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 max_payload_works() {
        let mut db = make_db();
        let max = db.max_payload_size();
        let payload = vec![0x42u8; max];
        db.append(1, 999, &payload).unwrap();
        db.sync().unwrap();

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

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

    // =========================================================================
    // Typed API Tests
    // =========================================================================

    mod typed_api {
        use super::*;
        use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};

        /// Example sensor type for testing: temperature reading
        #[derive(Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable)]
        #[repr(C)]
        struct Temperature {
            celsius: f32,
        }

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

        /// Example sensor type: accelerometer reading
        #[derive(Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable)]
        #[repr(C)]
        struct Accelerometer {
            x: i16,
            y: i16,
            z: i16,
        }

        impl SensorData for Accelerometer {
            const SENSOR_ID: u16 = 0x02;
        }

        #[test]
        fn typed_roundtrip_layer1() {
            let mut db = make_db();

            let temp = Temperature { celsius: 25.5 };
            db.append_value(0x01, 1000, &temp).unwrap();

            let (hdr, retrieved) = db.latest_value::<Temperature>(0x01).unwrap().unwrap();
            assert_eq!(hdr.sensor_id, 0x01);
            assert_eq!(hdr.timestamp, 1000);
            assert_eq!(retrieved.celsius, 25.5);
        }

        #[test]
        fn typed_roundtrip_layer2() {
            let mut db = make_db();

            let temp = Temperature { celsius: -10.0 };
            db.append_sensor(2000, &temp).unwrap();

            let (hdr, retrieved) = db.latest_sensor::<Temperature>().unwrap().unwrap();
            assert_eq!(hdr.sensor_id, Temperature::SENSOR_ID);
            assert_eq!(hdr.timestamp, 2000);
            assert_eq!(retrieved.celsius, -10.0);
        }

        #[test]
        fn typed_multiple_sensors() {
            let mut db = make_db();

            let temp = Temperature { celsius: 22.5 };
            let accel = Accelerometer {
                x: 100,
                y: -50,
                z: 980,
            };

            db.append_sensor(1000, &temp).unwrap();
            db.append_sensor(1001, &accel).unwrap();

            // Retrieve each type independently
            let (_, t) = db.latest_sensor::<Temperature>().unwrap().unwrap();
            let (_, a) = db.latest_sensor::<Accelerometer>().unwrap().unwrap();

            assert_eq!(t.celsius, 22.5);
            assert_eq!(a.x, 100);
            assert_eq!(a.y, -50);
            assert_eq!(a.z, 980);
        }

        #[test]
        fn cross_api_raw_write_typed_read() {
            let mut db = make_db();

            // A bare value written raw is *not* a Temperature: the typed API
            // frames a schema tag in front, so the untagged bytes are a byte
            // short of what it expects.
            db.append(Temperature::SENSOR_ID, 3000, &30.0f32.to_ne_bytes())
                .unwrap();
            assert_eq!(
                db.latest_sensor::<Temperature>(),
                Err(Error::SizeMismatch {
                    expected: 5,
                    actual: 4
                })
            );

            // Include the tag and the raw route reaches the typed one.
            let mut framed = [0u8; 5];
            framed[0] = Temperature::SCHEMA_VERSION;
            framed[1..].copy_from_slice(&31.0f32.to_ne_bytes());
            db.append(Temperature::SENSOR_ID, 3100, &framed).unwrap();

            let (hdr, temp) = db.latest_sensor::<Temperature>().unwrap().unwrap();
            assert_eq!(hdr.timestamp, 3100);
            assert_eq!(temp.celsius, 31.0);
        }

        #[test]
        fn cross_api_typed_write_raw_read() {
            let mut db = make_db();

            // Write using typed API
            let temp = Temperature { celsius: 42.0 };
            db.append_sensor(4000, &temp).unwrap();

            // Read using raw API: the schema tag is the first payload byte, so
            // the entry is one longer than the value.
            let mut buf = [0u8; 16];
            let (hdr, n) = db
                .latest(Temperature::SENSOR_ID, &mut buf)
                .unwrap()
                .unwrap();
            assert_eq!(hdr.timestamp, 4000);
            assert_eq!(n, crate::SCHEMA_TAG_SIZE + 4);
            assert_eq!(hdr.payload_len as usize, n);
            assert_eq!(buf[0], Temperature::SCHEMA_VERSION);
            let celsius = f32::from_ne_bytes([buf[1], buf[2], buf[3], buf[4]]);
            assert_eq!(celsius, 42.0);
        }

        #[test]
        fn size_mismatch_detection() {
            let mut db = make_db();

            // A lone tag byte: the right schema version, the wrong length. That
            // is what SizeMismatch now means — the struct changed and
            // SCHEMA_VERSION did not.
            db.append(Temperature::SENSOR_ID, 5000, &[Temperature::SCHEMA_VERSION])
                .unwrap();

            let result = db.latest_sensor::<Temperature>();
            match result {
                Err(Error::SizeMismatch { expected, actual }) => {
                    assert_eq!(expected, 5);
                    assert_eq!(actual, 1);
                }
                _ => panic!("Expected SizeMismatch error"),
            }
        }

        #[test]
        fn a_foreign_first_byte_is_reported_as_the_version_it_claims() {
            let mut db = make_db();
            db.append(Temperature::SENSOR_ID, 5000, &[0x42]).unwrap();

            assert_eq!(
                db.latest_sensor::<Temperature>(),
                Err(Error::SchemaMismatch {
                    expected: 0,
                    found: 0x42
                })
            );
        }

        #[test]
        fn an_entry_of_another_schema_version_is_named_not_misread() {
            // Same layout, different meaning — the case a length check cannot
            // catch, and the whole reason the tag exists.
            #[derive(FromBytes, IntoBytes, KnownLayout, Immutable, Debug, PartialEq)]
            #[repr(C)]
            struct Fahrenheit {
                degrees: f32,
            }

            impl SensorData for Fahrenheit {
                const SENSOR_ID: u16 = Temperature::SENSOR_ID;
                const SCHEMA_VERSION: u8 = 1;
            }

            let mut db = make_db();
            db.append_sensor(1000, &Temperature { celsius: 100.0 })
                .unwrap();

            assert_eq!(
                db.latest_sensor::<Fahrenheit>(),
                Err(Error::SchemaMismatch {
                    expected: 1,
                    found: 0
                })
            );

            // Both eras live in one log under one sensor ID, and each type
            // queries its own.
            db.append_sensor(2000, &Fahrenheit { degrees: 212.0 })
                .unwrap();

            let mut celsius = alloc::vec::Vec::new();
            db.query_all_sensor::<Temperature, _>(|_, t| {
                celsius.push(t.celsius);
                true
            })
            .unwrap();

            let mut degrees = alloc::vec::Vec::new();
            db.query_all_sensor::<Fahrenheit, _>(|_, f| {
                degrees.push(f.degrees);
                true
            })
            .unwrap();

            assert_eq!(celsius, [100.0]);
            assert_eq!(degrees, [212.0]);

            // And the newest entry now is a Fahrenheit.
            let (_, f) = db.latest_sensor::<Fahrenheit>().unwrap().unwrap();
            assert_eq!(f.degrees, 212.0);
        }

        #[test]
        fn query_sensor_typed() {
            let mut db = make_db();

            // Write several temperature readings
            for i in 0..5 {
                let temp = Temperature {
                    celsius: 20.0 + i as f32,
                };
                db.append_sensor(100 + i * 10, &temp).unwrap();
            }
            db.sync().unwrap();

            // Query a time range
            let mut readings = alloc::vec::Vec::new();
            let count = db
                .query_sensor::<Temperature, _>(110, 130, |hdr, temp| {
                    readings.push((hdr.timestamp, temp.celsius));
                    true
                })
                .unwrap();

            assert_eq!(count, 3); // timestamps 110, 120, 130
            assert_eq!(readings.len(), 3);
            assert_eq!(readings[0], (110, 21.0));
            assert_eq!(readings[1], (120, 22.0));
            assert_eq!(readings[2], (130, 23.0));
        }

        #[test]
        fn query_sensor_skips_wrong_size() {
            let mut db = make_db();

            // Write a valid temperature
            let temp = Temperature { celsius: 25.0 };
            db.append_sensor(1000, &temp).unwrap();

            // Write raw data with wrong size using Temperature's sensor ID
            db.append(Temperature::SENSOR_ID, 2000, &[0x01, 0x02])
                .unwrap();

            // Write another valid temperature
            let temp2 = Temperature { celsius: 30.0 };
            db.append_sensor(3000, &temp2).unwrap();

            db.sync().unwrap();

            // Query should skip the malformed entry
            let mut readings = alloc::vec::Vec::new();
            let count = db
                .query_sensor::<Temperature, _>(0, 10000, |hdr, temp| {
                    readings.push((hdr.timestamp, temp.celsius));
                    true
                })
                .unwrap();

            assert_eq!(count, 2);
            assert_eq!(readings[0], (1000, 25.0));
            assert_eq!(readings[1], (3000, 30.0));
        }

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

            let temp = Temperature { celsius: 99.9 };
            db.append_sensor(6000, &temp).unwrap();
            db.sync().unwrap();

            // Simulate power cycle
            let flash = db.into_inner();
            let mut db2: SensorDb<_, PAGE, SECTORS> =
                SensorDb::new(flash, 0, SECTORS as u16, 1).unwrap();
            db2.mount().unwrap();

            // Verify typed data survived
            let (hdr, retrieved) = db2.latest_sensor::<Temperature>().unwrap().unwrap();
            assert_eq!(hdr.timestamp, 6000);
            assert_eq!(retrieved.celsius, 99.9);
        }

        #[test]
        fn latest_returns_most_recent() {
            let mut db = make_db();

            db.append_sensor(100, &Temperature { celsius: 10.0 })
                .unwrap();
            db.append_sensor(200, &Temperature { celsius: 20.0 })
                .unwrap();
            db.append_sensor(300, &Temperature { celsius: 30.0 })
                .unwrap();

            let (hdr, temp) = db.latest_sensor::<Temperature>().unwrap().unwrap();
            assert_eq!(hdr.timestamp, 300);
            assert_eq!(temp.celsius, 30.0);
        }

        #[test]
        fn no_entries_returns_none() {
            let mut db = make_db();

            // No entries written
            let result = db.latest_sensor::<Temperature>().unwrap();
            assert!(result.is_none());
        }

        #[test]
        fn oldest_returns_first_entry() {
            let mut db = make_db();

            db.append_sensor(100, &Temperature { celsius: 10.0 })
                .unwrap();
            db.append_sensor(200, &Temperature { celsius: 20.0 })
                .unwrap();
            db.append_sensor(300, &Temperature { celsius: 30.0 })
                .unwrap();

            let (hdr, temp) = db.oldest_sensor::<Temperature>().unwrap().unwrap();
            assert_eq!(hdr.timestamp, 100);
            assert_eq!(temp.celsius, 10.0);
        }

        #[test]
        fn oldest_returns_none_when_empty() {
            let mut db = make_db();

            let result = db.oldest_sensor::<Temperature>().unwrap();
            assert!(result.is_none());
        }

        #[test]
        fn count_sensor_counts_correctly() {
            let mut db = make_db();

            // Write some temperature entries
            for i in 0..5 {
                db.append_sensor(i * 100, &Temperature { celsius: i as f32 })
                    .unwrap();
            }

            // Write some accelerometer entries
            for i in 0..3 {
                db.append_sensor(
                    i * 100 + 50,
                    &Accelerometer {
                        x: i as i16,
                        y: 0,
                        z: 0,
                    },
                )
                .unwrap();
            }

            db.sync().unwrap();

            // Count each sensor type
            let temp_count = db.count_sensor::<Temperature>().unwrap();
            let accel_count = db.count_sensor::<Accelerometer>().unwrap();
            let total = db.count(None).unwrap();

            assert_eq!(temp_count, 5);
            assert_eq!(accel_count, 3);
            assert_eq!(total, 8);
        }

        #[test]
        fn query_all_sensor_gets_all_entries() {
            let mut db = make_db();

            for i in 0..5 {
                db.append_sensor(
                    i * 100,
                    &Temperature {
                        celsius: i as f32 * 10.0,
                    },
                )
                .unwrap();
            }
            db.sync().unwrap();

            let mut readings = alloc::vec::Vec::new();
            let count = db
                .query_all_sensor::<Temperature, _>(|hdr, temp| {
                    readings.push((hdr.timestamp, temp.celsius));
                    true
                })
                .unwrap();

            assert_eq!(count, 5);
            assert_eq!(readings.len(), 5);
            assert_eq!(readings[0], (0, 0.0));
            assert_eq!(readings[4], (400, 40.0));
        }
    }

    // =========================================================================
    // Raw API Tests for new methods
    // =========================================================================

    #[test]
    fn query_all_gets_all_entries() {
        let mut db = make_db();

        db.append(1, 100, &[0x01]).unwrap();
        db.append(1, 200, &[0x02]).unwrap();
        db.append(2, 150, &[0x0A]).unwrap();
        db.sync().unwrap();

        // Query all entries for sensor 1
        let mut results = alloc::vec::Vec::new();
        let count = db
            .query_all(Some(1), |hdr, payload| {
                results.push((hdr.timestamp, payload[0]));
                true
            })
            .unwrap();

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

        // Query all entries (no filter)
        let mut all_results = alloc::vec::Vec::new();
        let total = db
            .query_all(None, |hdr, _| {
                all_results.push(hdr.timestamp);
                true
            })
            .unwrap();

        assert_eq!(total, 3);
    }

    #[test]
    fn oldest_gets_first_entry() {
        let mut db = make_db();

        db.append(1, 300, &[0x03]).unwrap();
        db.append(1, 100, &[0x01]).unwrap();
        db.append(1, 200, &[0x02]).unwrap();
        db.sync().unwrap();

        let mut buf = [0u8; 16];
        // oldest() returns by sequence order (write order), not timestamp
        let (hdr, n) = db.oldest(1, &mut buf).unwrap().unwrap();
        assert_eq!(hdr.timestamp, 300); // First written entry
        assert_eq!(&buf[..n], &[0x03]);
    }

    #[test]
    fn oldest_returns_none_for_missing_sensor() {
        let mut db = make_db();

        db.append(1, 100, &[0x01]).unwrap();
        db.sync().unwrap();

        let mut buf = [0u8; 16];
        let result = db.oldest(99, &mut buf).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn count_works_correctly() {
        let mut db = make_db();

        db.append(1, 100, &[0x01]).unwrap();
        db.append(1, 200, &[0x02]).unwrap();
        db.append(2, 150, &[0x0A]).unwrap();
        db.sync().unwrap();

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

    #[test]
    fn count_uses_cached_total_for_none() {
        let mut db = make_db();

        for i in 0..10 {
            db.append(1, i, &[i as u8]).unwrap();
        }

        // count(None) should use cached total without scanning
        assert_eq!(db.count(None).unwrap(), 10);
        assert_eq!(db.stats().total_entries, 10);
    }

    // =========================================================================
    // Sector rotation
    // =========================================================================

    #[test]
    fn a_long_run_of_appends_rotates_sectors() {
        // Small enough that 500 entries cannot fit without rotating.
        const SMALL: usize = 4;
        let flash = MockFlash::<PAGE, SECTOR>::new(SMALL * SECTOR);
        let mut db: SensorDb<_, PAGE, SMALL> = SensorDb::new(flash, 0, SMALL as u16, 1).unwrap();
        db.format().unwrap();

        let payload = [0x42u8; 4];
        for i in 0..500u64 {
            db.append(1, i * 10, &payload).unwrap();
        }
        db.sync().unwrap();

        let stats = db.stats();
        assert!(stats.total_entries > 0);
        assert!(stats.used_sectors > 1);

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

    // =========================================================================
    // Auto traits
    // =========================================================================

    #[test]
    fn a_database_is_sync_when_its_driver_is() {
        // The whole payoff of dropping the `RefCell`. It was `!Sync`, so the
        // only way to share a `SensorDb` was a `Mutex` — which yields `&mut`,
        // making the `&self` reads it bought unreachable in exactly the setting
        // they were for. A compile-time check, so it cannot rot into a comment.
        fn assert_sync<T: Sync>() {}
        fn assert_send<T: Send>() {}

        assert_sync::<SensorDb<MockFlash<PAGE, SECTOR>, PAGE, SECTORS>>();
        assert_send::<SensorDb<MockFlash<PAGE, SECTOR>, PAGE, SECTORS>>();
    }

    // =========================================================================
    // Flush-free read tests
    // =========================================================================

    #[test]
    fn read_without_sync_sees_buffered_entries() {
        let mut db = make_db();

        db.append(1, 100, &[0x01]).unwrap();
        db.append(1, 200, &[0x02]).unwrap();
        db.append(2, 150, &[0x0A]).unwrap();
        // No sync!

        // latest sees the buffered entry
        let mut buf = [0u8; 16];
        let (hdr, n) = db.latest(1, &mut buf).unwrap().unwrap();
        assert_eq!(hdr.timestamp, 200);
        assert_eq!(&buf[..n], &[0x02]);

        // oldest sees the first buffered entry
        let (hdr, n) = db.oldest(1, &mut buf).unwrap().unwrap();
        assert_eq!(hdr.timestamp, 100);
        assert_eq!(&buf[..n], &[0x01]);

        // count sees all buffered entries
        assert_eq!(db.count(Some(1)).unwrap(), 2);
        assert_eq!(db.count(Some(2)).unwrap(), 1);
        assert_eq!(db.count(None).unwrap(), 3);

        // query_range sees all buffered entries
        let mut results = alloc::vec::Vec::new();
        let count = db
            .query_range(Some(1), 0, u64::MAX, |hdr, payload| {
                results.push((hdr.timestamp, payload[0]));
                true
            })
            .unwrap();
        assert_eq!(count, 2);
        assert_eq!(results, vec![(100, 0x01), (200, 0x02)]);
    }

    #[test]
    fn read_after_sync_sees_committed_and_buffered() {
        let mut db = make_db();

        // Write and sync (committed)
        db.append(1, 100, &[0x01]).unwrap();
        db.append(1, 200, &[0x02]).unwrap();
        db.sync().unwrap();

        // Write more without sync (buffered)
        db.append(1, 300, &[0x03]).unwrap();
        db.append(2, 250, &[0x0B]).unwrap();

        // latest sees the newest buffered entry
        let mut buf = [0u8; 16];
        let (hdr, n) = db.latest(1, &mut buf).unwrap().unwrap();
        assert_eq!(hdr.timestamp, 300);
        assert_eq!(&buf[..n], &[0x03]);

        // oldest sees the oldest committed entry
        let (hdr, n) = db.oldest(1, &mut buf).unwrap().unwrap();
        assert_eq!(hdr.timestamp, 100);
        assert_eq!(&buf[..n], &[0x01]);

        // count sees committed + buffered
        assert_eq!(db.count(Some(1)).unwrap(), 3);
        assert_eq!(db.count(Some(2)).unwrap(), 1);
        assert_eq!(db.count(None).unwrap(), 4);

        // query_range sees both committed and buffered
        let mut results = alloc::vec::Vec::new();
        db.query_range(Some(1), 0, u64::MAX, |hdr, payload| {
            results.push((hdr.timestamp, payload[0]));
            true
        })
        .unwrap();
        assert_eq!(results, vec![(100, 0x01), (200, 0x02), (300, 0x03)]);
    }

    #[test]
    fn query_range_order_with_buffered() {
        let mut db = make_db();

        // Committed entries
        db.append(1, 100, &[0x01]).unwrap();
        db.append(1, 200, &[0x02]).unwrap();
        db.sync().unwrap();

        // Buffered entries
        db.append(1, 300, &[0x03]).unwrap();
        db.append(1, 400, &[0x04]).unwrap();

        // Verify committed entries come first, buffered entries come after
        let mut timestamps = alloc::vec::Vec::new();
        db.query_range(Some(1), 0, u64::MAX, |hdr, _| {
            timestamps.push(hdr.timestamp);
            true
        })
        .unwrap();
        assert_eq!(timestamps, vec![100, 200, 300, 400]);
    }

    #[test]
    fn page_buf_empty_after_sync() {
        let mut db = make_db();

        db.append(1, 100, &[0x01]).unwrap();
        db.append(1, 200, &[0x02]).unwrap();
        db.sync().unwrap();

        // After sync, page buffer scanning should find nothing
        // (all entries are committed on flash). Verify by checking
        // that count(Some(1)) matches the sector-scanned count.
        assert_eq!(db.count(Some(1)).unwrap(), 2);

        // Verify with query_range too
        let mut results = alloc::vec::Vec::new();
        db.query_range(Some(1), 0, u64::MAX, |hdr, payload| {
            results.push((hdr.timestamp, payload[0]));
            true
        })
        .unwrap();
        assert_eq!(results, vec![(100, 0x01), (200, 0x02)]);
    }
}