happenstance-sqlite 0.4.4

SQLite event store and projection store adapters for happenstance.
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
//! SQLite-backed [`SendEventStore`].
//!
//! # Status: every event-store path is real
//!
//! Migration 1, the persisted identity, the connection settings, `append`,
//! `read`, `head` and `contains_event_id` all have real bodies, and four test
//! targets read them back out of SQLite — `tests/migration.rs`,
//! `tests/append.rs`, `tests/read.rs` and `tests/wide_query.rs`. The *types*
//! were never stubbed: the connection is a real [`rusqlite::Connection`], the
//! error enum wraps [`rusqlite::Error`], and [`SqliteReadStream`] is the state
//! machine the real read path uses. A skeleton that stubs its associated types
//! has stubbed the only part of it a type checker can disagree with.
//!
//! # Why the stream is a hand-written state machine
//!
//! `rusqlite` is synchronous. The only correct way to call it from an async
//! context is [`tokio::task::spawn_blocking`], and `spawn_blocking` **panics**
//! when there is no runtime in thread-local scope. Meanwhile
//! [`EventStore::read`](happenstance_core::EventStore::read) is deliberately
//! *not* `async` — it returns the stream at the top level so that the `Send`
//! flavour can mark the *stream* `Send` rather than merely the future that
//! produces it (ADR-0001, ADR-0008).
//!
//! Put those together and the consequence is forced: `read` runs on whatever
//! thread called it, possibly outside any runtime, so it must not spawn. The
//! spawn has to be deferred to the first `poll_next`, which by definition runs
//! under an executor. **Laziness stops being a nicety and becomes load-bearing**
//! — it is what makes the two constraints compatible at all.
//!
//! One residual risk survives that, and it is why
//! [`SqliteEventStoreError::NoRuntime`] exists: a `poll` under a *non-tokio*
//! executor (`futures::executor::block_on`, say) is still runtime-less.
//! [`tokio::runtime::Handle::try_current`] turns that from a panic into an
//! ordinary stream error, which is what a lazy stream's contract already
//! promises — failures surface as `Err` items rather than up front.
//!
//! # Intended schema
//!
//! Migration 1, exactly as [`SqliteEventStore::open`] applies it on every
//! connect — through a private `migrate`, which is why this block and not a
//! rustdoc link is what a reader has. It is compared object-by-object against
//! `sqlite_master` by
//! `tests/migration.rs::module_doc_schema_matches_sqlite_master`, because a
//! reviewer reading SQL prose against SQL code is the check that passes by
//! fatigue.
//!
//! ```sql
//! CREATE TABLE event (
//!     position        INTEGER PRIMARY KEY AUTOINCREMENT, -- monotonic, gaps allowed
//!     event_type      TEXT    NOT NULL,
//!     data            BLOB    NOT NULL,
//!     metadata        BLOB,                              -- nullable on purpose
//!     tags            BLOB    NOT NULL,                  -- canonical sorted encoding
//!     origin_store    BLOB,
//!     origin_position INTEGER,
//!     recorded_at     INTEGER NOT NULL,
//!     UNIQUE (origin_store, origin_position)
//! );
//!
//! CREATE INDEX event_type_idx ON event(event_type, position);
//!
//! CREATE TABLE event_tag (
//!     tag        TEXT    NOT NULL,
//!     position   INTEGER NOT NULL REFERENCES event(position),
//!     event_type TEXT    NOT NULL,  -- covering column, deliberately not in the key
//!     PRIMARY KEY (tag, position)
//! ) WITHOUT ROWID;
//!
//! CREATE TABLE tag_cardinality (
//!     tag    TEXT    PRIMARY KEY,
//!     events INTEGER NOT NULL
//! ) WITHOUT ROWID;
//!
//! CREATE TABLE store_meta (
//!     k TEXT PRIMARY KEY,
//!     v BLOB NOT NULL
//! ) WITHOUT ROWID;
//! ```
//!
//! Every line of it is load-bearing, and the two amendments in the middle are
//! the reason this block was rewritten rather than merely filled in:
//!
//! * **`event_type` on `event_tag` is a covering column and not part of the
//!   key.** In the key it would break the position ordering that makes a tag's
//!   range already sorted; *absent* — which is what this block published while
//!   the bodies were `todo!()` — it forces a query item constraining both type
//!   and tags into a join back to `event`, walked while the `BEGIN IMMEDIATE`
//!   write lock is held, with every other writer queued behind it. That is a
//!   conformant adapter that serialises every writer, and it passes every rule
//!   (ADR-0022 §7).
//! * **`tag_cardinality` is a requirement rather than a convenience.**
//!   Multi-tag items must be probed most-selective-tag-first and SQLite cannot
//!   supply per-value cardinality: `ANALYZE` stores an *average*, which is
//!   exactly wrong for a tag set where one value matches a third of the log and
//!   another matches one percent.
//!
//!   That requirement is only true because the intersection chain is
//!   **correlated** — `query_sql.rs`'s module documentation is the long form,
//!   and it is a private module, so this is a path rather than a link. On the
//!   uncorrelated shape this crate emitted until then, obeying it cost 37x–42x
//!   rather than earning anything, because the chained arm was materialised and
//!   the seed's selectivity could not reach it. A future edit that returns the
//!   chain to `position IN (…)` must delete this bullet in the same change, or
//!   the crate will be requiring the slower ordering in its own public
//!   documentation. Measured in `experiments/correlated-exists-guard/`.
//!
//! And three that predate them:
//!
//! * **`AUTOINCREMENT` is deliberate.** It guarantees positions are never
//!   reused after a delete, which plain `rowid` does not, and the specification
//!   requires uniqueness across the store's whole lifetime. It also *permits
//!   gaps*, which is why nothing here and no rule may assume `+ 1`.
//! * **`metadata` is nullable.** `None` and `Some(<empty>)` are two values the
//!   contract keeps apart, and a store that folds them has lost one.
//! * **The `EventId` origin pair is `UNIQUE` together**, not separately: one
//!   constraint serving two jobs, the index
//!   [`contains_event_id`](SendEventStore::contains_event_id) probes and the
//!   guard that stops ingest storing one event twice.
//!
//! `store_meta` carries this store's own [`StoreId`], minted once at schema
//! creation and read back on every open, beside the schema-version marker that
//! gives migration 2 something to test against. See
//! [`SqliteEventStore::remint_identity`] for what that mint-once choice costs.
//!
//! # Cancellation
//!
//! **What a dropped `append` future does here: nothing, because there is nothing
//! to drop.** `append` refuses an empty batch, checks this store's declared
//! ceilings, locks the connection and calls `append_locked` inline. There is no
//! `.await` anywhere in that body — none anywhere in this module at all — so
//! a future polled once has already run to completion by the time `poll` returns,
//! and no outcome depends on whether the caller then drops it. **A dropped
//! `append` future cannot be cancelled by this adapter.**
//!
//! This is the statement **ES-23** obliges every adapter to make. The clause is
//! `[FROZEN]`, its two outcomes are *the append committed* and *it did not*, and
//! the port refuses to choose between them on a caller's behalf
//! ([`EventStore::append`](happenstance_core::EventStore::append)'s own
//! `# Cancellation` section) precisely so that each adapter has to answer.
//!
//! **It does not license the opposite reading either.** A caller MUST NOT treat a
//! dropped future as evidence about *any* store, this one included: generic code
//! binds the port rather than this crate, and the next store in the same program
//! may answer differently. Where an outcome genuinely has to be resolved, ES-24
//! is the mechanism — a conditional append is at-most-once under verbatim
//! reissue, so reissuing the identical batch settles it with no identity and no
//! idempotency key.
//!
//! **The answer survives the move this crate is most likely to make.** ADR-0012
//! and the port's own documentation both name a pooled `rusqlite` adapter working
//! in `tokio::task::spawn_blocking` as *"the shape that looks cancellation-safe
//! and is not"* — dropping the `JoinHandle` does not cancel the closure, so the
//! `COMMIT` still runs. That is the same answer as the one above reached by a
//! different route: moving the work would change *where* it happens, not whether
//! a drop can stop it. What such a change would owe this section is the new
//! reason, not a new verdict.
//!
//! It is checked rather than promised. `tests/cancellation_statement.rs` fails if
//! this section goes missing, and fails again if `append` acquires a suspension
//! point and the section stops being true — the half ADR-0012 recorded that a
//! heading-check alone could not have.
//!

use std::future::Future;
use std::path::Path;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};
use std::vec;

use futures_core::Stream;
use happenstance_core::{
    AppendCondition, AppendError, ConditionViolated, Event, EventId, Guard, InvalidEventType,
    InvalidTag, Query, ReadOptions, RecordedAt, SendEventStore, SequencePosition, SequencedEvent,
    StoreId,
};
use rusqlite::Connection;
use rusqlite::types::Value;
use tokio::runtime::{Handle, TryCurrentError};
use tokio::task::{JoinError, JoinHandle};

use crate::connection::ConnectionSettings;
use crate::query_sql::Selectivity;

/// How many **rows** one statement of a page fetches.
///
/// The point of paging at all is that a replay of a million events must not be
/// buffered, which is the promise
/// [`EventStore::read`](happenstance_core::EventStore::read) makes. This is one
/// of the two budgets that keeps it, and it is the one stated in rows;
/// [`MAX_PAGE_BYTES_PER_STATEMENT`](SqliteEventStore::MAX_PAGE_BYTES_PER_STATEMENT)
/// is the other. **Neither is derivable from the other**, which is the whole
/// reason there are two: a row is not a bounded quantity, so a row count bounds
/// a page's cardinality and says nothing about its size.
///
/// # It is no longer a placeholder, and the measurement refused to settle it
///
/// This doc used to end *"a placeholder until it is measured"*.
/// `experiments/one-connection-latency` measured it, across a 32x range — 64 to
/// 2,048 — over a one-million-event log, and what it found is that the three
/// things this number moves do not agree.
///
/// * **The per-page lock hold barely depends on it.** 1.06–1.15x across the
///   whole range, inside the run's own noise (`results/raw/page-lock-hold.txt`).
///   What moves it is query *width*: 146.6 → 203.3 → 684.2 ms at 1, 400 and
///   1,200 items, because the statements per page go 1 → 1 → 3.
/// * **The aggregate held-mutex time over a whole replay scales as `1/PAGE`** —
///   2,929.2 s at 64 against 99.1 s at 2,048, extrapolated from the same run and
///   labelled as an extrapolation there. That argues for raising it.
/// * **Residency scales linearly with it, and residency is the quantity with no
///   ceiling of its own.** One page of 512 events at
///   [`MAX_EVENT_DATA_LEN`](SqliteEventStore::MAX_EVENT_DATA_LEN) peaked at
///   537,036,800 live bytes — 512.2 MiB — before one row reached the caller
///   (`results/raw/ceiling-residency.txt`). At 2,048 the same page would be
///   about 2 GiB. That argues for lowering it.
///
/// **No value of a row count settles both**, which is why the byte budget sits
/// beside it rather than replacing it, and why this number did not move: moving
/// it is the decision the measurement declined to make, and it is not this
/// constant's to take. Whether a read page should be budgeted in rows, in bytes,
/// or by the caller belongs with phase 8's owner and adds public surface to a
/// crate about to be published; the brief is staged in `.kb/_intake/`.
const PAGE_SIZE: usize = 512;

/// A SQLite-backed event store.
///
/// The connection lives behind a [`Mutex`] because [`rusqlite::Connection`] is
/// [`Send`] but **not** [`Sync`]: without the mutex, `&SqliteEventStore` would
/// not be `Send`, and every future in the [`SendEventStore`] flavour captures
/// `&self`. The mutex is what buys `Self: Sync`, and `Self: Sync` is what makes
/// the `Send` flavour implementable at all. It also means this adapter
/// **serialises its writers** by construction — that is the shape it is here to
/// represent, not an accident.
///
/// The [`Arc`] is not for sharing the store; it is so that a
/// [`SqliteReadStream`] can outlive the `&self` borrow that produced it, which
/// it must, because `read` is not `async` and hands the stream back to the
/// caller.
#[derive(Debug, Clone)]
pub struct SqliteEventStore {
    connection: Arc<Mutex<Connection>>,
    /// This database's incarnation, minted once at schema creation and read
    /// back on every open.
    ///
    /// Sixteen plain bytes, so it costs the `Send`/`Sync` assertions nothing —
    /// unlike a cached `rusqlite::Statement` or `Transaction<'_>`, both of which
    /// borrow the connection and are `!Send`. See [`SqliteReadStream`]'s docs.
    store_id: StoreId,
    /// The fallback runtime for a read's `spawn_blocking`, used only when the
    /// poll is not executing on a runtime of its own, which is preferred.
    ///
    /// ADR-0081 put that order on ADR-0022 §9. Captured-first strands a store
    /// that outlives the runtime it was built in (`tests/runtime_seam.rs`). The
    /// fallback exists for the concurrency family: its contenders are **bare OS
    /// threads** under the testkit's park-loop `block_on`, with no tokio context
    /// at poll time, and a store constructed inside the harness's runtime
    /// carries a handle out to them. Without it every read there would fail as
    /// `NoRuntime`, a red family that is not about this adapter's logic.
    ///
    /// A [`Handle`] is `Clone`, `Send`, `Sync` and `Unpin`, so carrying one in
    /// the store, the cursor and the stream costs the shape assertions nothing.
    ///
    /// The rejected alternative was to run the statement inline on the calling
    /// thread when no runtime is found. It is not unsound — it is what the
    /// experiment's candidates did, and sixty-four bare threads completed
    /// correctly — but it keeps blocking work on an executor's thread whenever
    /// there *is* one, and it makes [`SqliteEventStoreError::NoRuntime`]
    /// unreachable. Under the option that won, the variant keeps a real meaning:
    /// a store both constructed *and* driven with no runtime anywhere.
    runtime: Option<Handle>,
}

/// The migration this build knows how to operate.
///
/// Persisted in `store_meta` so that migration 2 has something to test against:
/// a schema with no version marker cannot be migrated later without guessing.
pub const SCHEMA_VERSION: u32 = 1;

/// Migration 1, verbatim. Mirrored in the [module documentation](self), which
/// `tests/migration.rs` compares against `sqlite_master`.
///
/// `IF NOT EXISTS` throughout, because `open` runs `migrate` on **every**
/// connect and a fixture connects more than once onto one file.
const MIGRATION_1: &str = "\
CREATE TABLE IF NOT EXISTS event (
    position        INTEGER PRIMARY KEY AUTOINCREMENT,
    event_type      TEXT    NOT NULL,
    data            BLOB    NOT NULL,
    metadata        BLOB,
    tags            BLOB    NOT NULL,
    origin_store    BLOB,
    origin_position INTEGER,
    recorded_at     INTEGER NOT NULL,
    UNIQUE (origin_store, origin_position)
);
CREATE INDEX IF NOT EXISTS event_type_idx ON event(event_type, position);
CREATE TABLE IF NOT EXISTS event_tag (
    tag        TEXT    NOT NULL,
    position   INTEGER NOT NULL REFERENCES event(position),
    event_type TEXT    NOT NULL,
    PRIMARY KEY (tag, position)
) WITHOUT ROWID;
CREATE TABLE IF NOT EXISTS tag_cardinality (
    tag    TEXT    PRIMARY KEY,
    events INTEGER NOT NULL
) WITHOUT ROWID;
CREATE TABLE IF NOT EXISTS store_meta (
    k TEXT PRIMARY KEY,
    v BLOB NOT NULL
) WITHOUT ROWID;";

/// The `store_meta` key holding this database's incarnation.
const STORE_ID_KEY: &str = "store_id";

/// The `store_meta` key holding the migration the file is at.
const SCHEMA_VERSION_KEY: &str = "schema_version";

impl SqliteEventStore {
    /// The largest `data` payload this store accepts, in **bytes of
    /// [`Event::data`]** — not of an encoded row, and not of `data` and
    /// `metadata` together.
    ///
    /// A **fact about this adapter**, not a trade: SQLite's own ceiling is near
    /// a gigabyte, and this is the number below it that keeps the conformance
    /// suite runnable, because the rule that checks a ceiling allocates it plus
    /// one byte twice per run. It is sixteen times VT-21's 65,536-byte floor.
    pub const MAX_EVENT_DATA_LEN: usize = 1_048_576;

    /// The largest number of tags on one event this store accepts.
    ///
    /// Twice VT-22's floor of 64. Every tag costs a row in `event_tag` and an
    /// upsert in `tag_cardinality`, both inside the write transaction, so the
    /// number is bounded by lock hold time rather than by storage.
    pub const MAX_TAGS_PER_EVENT: usize = 128;

    /// The largest number of events this store accepts in one append.
    ///
    /// Twice VT-24's floor of 128. At this ceiling with
    /// [`MAX_TAGS_PER_EVENT`](Self::MAX_TAGS_PER_EVENT) tags on every event, a
    /// single multi-row tag insert would bind 98,304 of SQLite's 32,766 bound
    /// parameters — which is why the insert is chunked to the parameter budget
    /// and the transaction is not.
    pub const MAX_EVENTS_PER_BATCH: usize = 256;

    /// How many bytes of event payload one statement of a page may accumulate
    /// before it stops taking rows.
    ///
    /// **A row is not a bounded quantity, and the row budget could not say so.**
    /// Each row of a page owns its `data`, up to
    /// [`MAX_EVENT_DATA_LEN`](Self::MAX_EVENT_DATA_LEN), and its `metadata`,
    /// which `check_ceilings` does not bound at all — so a page bounded only in
    /// rows is bounded, in bytes, by SQLite's own near-gigabyte blob limit
    /// rather than by anything this crate states. Measured rather than argued:
    /// one page of 512 events at the data ceiling peaked at **537,036,800 live
    /// bytes — 512.2 MiB** — in one buffer before a single row reached the
    /// caller
    /// (`experiments/one-connection-latency/results/raw/ceiling-residency.txt`).
    ///
    /// **Per statement, which is what the name says and what the bound is.** A
    /// wide query is several statements merged, so the honest ceiling on one
    /// page's payload residency is this number times
    /// [`planned_statement_count`](Self::planned_statement_count) — computable
    /// by a caller, which is the point of it being public, and stated here
    /// rather than left to be discovered. The alternative, one budget shared
    /// across the page, was rejected: the first statement would spend it and
    /// every later one would be cut to a single row, which turns a wide query
    /// into a page-per-event replay.
    ///
    /// **It is checked after the row is taken**, so a page always makes
    /// progress. That is not hypothetical tidiness: `metadata` is unbounded, so
    /// one row can exceed this on its own, and a page that refused it would
    /// stall the read forever.
    ///
    /// Eight maximal payloads. It is a **fact this adapter states**, in the
    /// sense [`MAX_EVENT_DATA_LEN`](Self::MAX_EVENT_DATA_LEN) is one, and not a
    /// measured optimum: it is large enough that a page of maximal events still
    /// carries eight of them, and small enough that a page's cost is stated in
    /// megabytes. Whether the pair of budgets should be stated by the adapter at
    /// all or asked of the caller is a decision this constant does not make;
    /// the brief is staged in `.kb/_intake/`.
    pub const MAX_PAGE_BYTES_PER_STATEMENT: usize = 8 * Self::MAX_EVENT_DATA_LEN;

    /// How many index arms one prepared statement carries before the query is
    /// split across several.
    ///
    /// SQLite compiles a `UNION` of *n* arms as one compound `SELECT`, and
    /// `SQLITE_MAX_COMPOUND_SELECT` defaults to **500** terms. A `Query` bounds
    /// nothing by design — the specification requires every store to evaluate at
    /// least 128 items and puts no ceiling above that — so a wide query is
    /// **chunked and merged, never refused**: there is no `MAX_QUERY_ITEMS`
    /// anywhere in this crate and no `QueryItems` `StoreLimit` variant to report one
    /// through, because a query-item refusal is not an append outcome.
    ///
    /// The number is public so that a test can compute the boundary rather than
    /// guess at it: a merge that never executes is dead code behind a green
    /// suite, which is the failure mode this whole project exists to retire.
    ///
    /// It is **one of two** axes, and it is not the one that binds first on a
    /// query of wide items — see
    /// [`MAX_QUERY_PARAMETERS_PER_STATEMENT`](Self::MAX_QUERY_PARAMETERS_PER_STATEMENT).
    pub const MAX_QUERY_ARMS_PER_STATEMENT: usize = 400;

    /// How many bound parameters one query statement carries before the query is
    /// split across several.
    ///
    /// SQLite's `SQLITE_MAX_VARIABLE_NUMBER` is 32,766, and the translation binds
    /// one parameter per tag and one per type of every item in a chunk. So this
    /// and [`MAX_QUERY_ARMS_PER_STATEMENT`](Self::MAX_QUERY_ARMS_PER_STATEMENT)
    /// are **independent** axes rather than two spellings of one width: 400 items
    /// of a single tag each is 400 arms and 400 parameters, while the same 400
    /// items at [`MAX_TAGS_PER_EVENT`](Self::MAX_TAGS_PER_EVENT) tags apiece is
    /// still 400 arms and 51,200 parameters. Partitioning on arms alone planned
    /// that second query as one statement and `prepare` refused it with SQLite's
    /// own *"too many SQL variables"* — on the append path, inside
    /// `BEGIN IMMEDIATE`, with the caller's decision already made, which is the
    /// timing VT-24 rejects by name.
    ///
    /// The number is the same budget the multi-row tag insert has chunked to
    /// since the write path was written, and it sits below SQLite's ceiling with
    /// headroom rather than at it, for the reason given where it is defined: a
    /// statement that binds one extra parameter per row should not be within
    /// rounding distance of the wall. A query is not a different kind of
    /// statement.
    ///
    /// Public for the same reason the arm width is public — a test that has to
    /// guess the boundary is a test that stops crossing it — and it is the
    /// ceiling `tests/wide_tags.rs` computes its under, at and over cases from.
    pub const MAX_QUERY_PARAMETERS_PER_STATEMENT: usize = PARAMETER_BUDGET;

    /// How many prepared statements one page of `query` will take.
    ///
    /// Never zero: [`Query::all`] is one statement, straight to the `event`
    /// table.
    ///
    /// This is the seam a test uses to observe a wide query genuinely crossing
    /// the boundary, so it is **the same call** the read path makes —
    /// `query_sql::page_statements`, counted — never a second `ceil(arms /
    /// width)` that would go on reporting a boundary `fetch_page` had stopped
    /// taking. It followed `chunks` until the read path stopped using it, and
    /// moving it was not optional: the two partition identically today, so a
    /// count left behind would have agreed by arithmetic rather than by
    /// construction and gone on agreeing right up until it mattered.
    ///
    /// It counts **the real partition**, which is both ceilings and not the arm
    /// one alone. That changes what the number says for a query of wide items:
    /// it used to report `1` for a plan of 51,200 bound parameters, a statement
    /// that cannot be prepared. A caller sizing a query against this seam is
    /// asking how many statements will run, not how many the arm arithmetic on
    /// its own would allow.
    ///
    /// Only the *shape* of the `Window` below reaches the count, never its
    /// values — it is `pub(crate)`, so this says its name rather than linking to
    /// it: the partition prices the two bounds
    /// every arm binds and the one budget every chunk binds, and is otherwise
    /// indifferent to what `lo`, `hi` and `budget` hold. A default
    /// `Selectivity` likewise orders tags inside an arm, never the partition.
    #[must_use]
    pub fn planned_statement_count(query: &Query) -> usize {
        let window = crate::query_sql::Window {
            lo: 0,
            hi: i64::MAX,
            budget: i64::try_from(PAGE_SIZE).unwrap_or(i64::MAX),
            backwards: false,
        };
        crate::query_sql::page_statements(
            query,
            &Selectivity::default(),
            Self::MAX_QUERY_ARMS_PER_STATEMENT,
            Self::MAX_QUERY_PARAMETERS_PER_STATEMENT,
            window,
            crate::row::COLUMNS,
        )
        .len()
    }

    /// Wraps an already-open connection onto an **already-migrated** database.
    ///
    /// The caller is responsible for having applied the schema — use
    /// [`open`](Self::open) to have that done — and this constructor is
    /// fallible because it is not merely taking the caller's word for it: the
    /// store carries the database's incarnation, so it reads it back here. A
    /// `StoreId`-less store would mint every [`EventId`] under a zero origin,
    /// which has no error path and no observable symptom.
    ///
    /// The connection is used as it is given. It is **not** reconfigured, so a
    /// caller reaching this constructor directly should have opened it through
    /// [`crate::connection::open_configured`].
    ///
    /// # Errors
    ///
    /// * [`SqliteEventStoreError::Sqlite`] if the database cannot be queried —
    ///   which for an unmigrated database is the missing `store_meta` table.
    /// * [`SqliteEventStoreError::MissingIdentity`] if the schema is present and
    ///   the incarnation row is not.
    /// * [`SqliteEventStoreError::MalformedIdentity`] if that row is not the
    ///   sixteen bytes a [`StoreId`] is.
    /// * [`SqliteEventStoreError::UnsupportedSchemaVersion`] if the file was
    ///   written by a newer build.
    pub fn new(connection: Connection) -> Result<Self, SqliteEventStoreError> {
        let store_id = read_identity(&connection)?;
        Ok(Self::with_store_id(connection, store_id))
    }

    /// Pairs a connection with an incarnation already read off it.
    ///
    /// The fallback runtime handle is captured **here**, at construction, because
    /// this is the point a caller is most likely to be inside one — and the
    /// concurrency family's contenders, which are bare OS threads, never are.
    fn with_store_id(connection: Connection, store_id: StoreId) -> Self {
        Self {
            connection: Arc::new(Mutex::new(connection)),
            store_id,
            runtime: Handle::try_current().ok(),
        }
    }

    /// Opens (creating if absent) a store at `path` and applies the schema.
    ///
    /// The connection is configured before anything is written to it — WAL, a
    /// stated `synchronous`, and a finite busy timeout — through the one path
    /// [`crate::connection::open_configured`] both stores in this crate share.
    /// Migration is idempotent and safe under a concurrent open: re-opening an
    /// already-migrated file adds no schema object and mints no second
    /// incarnation.
    ///
    /// # Errors
    ///
    /// * [`SqliteEventStoreError::Sqlite`] if the file cannot be opened or
    ///   created — a missing directory, a permission refusal, a corrupt header
    ///   — or if the schema cannot be applied. Nothing partially migrated is
    ///   left behind: every statement runs inside one transaction.
    /// * [`SqliteEventStoreError::UnsupportedSchemaVersion`] if the file was
    ///   written by a build that knows a later migration. Operating on an
    ///   unknown schema is how a later migration loses data.
    /// * [`SqliteEventStoreError::MissingIdentity`] or
    ///   [`SqliteEventStoreError::MalformedIdentity`] if the schema is present
    ///   and its incarnation row is not readable. Silently minting a
    ///   replacement is the worst available behaviour — it re-issues
    ///   [`EventId`]s under a new origin for events that already exist.
    pub fn open(path: impl AsRef<Path>) -> Result<Self, SqliteEventStoreError> {
        let mut connection = crate::connection::open_configured(path)?;
        let store_id = Self::migrate(&mut connection)?;
        Ok(Self::with_store_id(connection, store_id))
    }

    /// Opens a private in-memory store and applies the schema.
    ///
    /// A convenience for a single-handle caller, and **not** what a
    /// [`Fixture`](https://docs.rs/happenstance-testkit) should reach for: a
    /// private in-memory database is per-*connection*, so a second connect would
    /// open a second, empty database rather than a second handle onto this one.
    /// WAL has nothing to switch to here, so this connection runs under the
    /// journal mode SQLite keeps for memory databases.
    ///
    /// # Errors
    ///
    /// Returns [`SqliteEventStoreError::Sqlite`] if SQLite refuses the
    /// connection or the schema cannot be applied, and the identity errors
    /// [`open`](Self::open) documents.
    pub fn open_in_memory() -> Result<Self, SqliteEventStoreError> {
        let mut connection = Connection::open_in_memory()?;
        crate::connection::configure(&connection)?;
        let store_id = Self::migrate(&mut connection)?;
        Ok(Self::with_store_id(connection, store_id))
    }

    /// The incarnation this store mints identities under.
    ///
    /// The same value before and after a close-and-reopen of the file, which is
    /// what makes `reopened_store_does_not_reissue_an_event_id` askable: with
    /// the incarnation held fixed, the *position* is what must never repeat, and
    /// `AUTOINCREMENT` is the mechanism.
    #[must_use]
    pub const fn store_id(&self) -> StoreId {
        self.store_id
    }

    /// What this handle's connection is actually running under.
    ///
    /// The values are read off the live connection rather than restated from
    /// the constants that set them: SQLite silently accepts a pragma it does not
    /// recognise, so a statement that executed is not a setting that took.
    ///
    /// # Errors
    ///
    /// * [`SqliteEventStoreError::ConnectionPoisoned`] if another thread
    ///   panicked while holding the connection.
    /// * [`SqliteEventStoreError::Sqlite`] if the connection cannot answer.
    pub fn settings(&self) -> Result<ConnectionSettings, SqliteEventStoreError> {
        let connection = self
            .connection
            .lock()
            .map_err(|_| SqliteEventStoreError::ConnectionPoisoned)?;
        Ok(ConnectionSettings::read_back(&connection)?)
    }

    /// Replaces the database's persisted incarnation with a freshly minted one.
    ///
    /// # When a deployment invokes this
    ///
    /// **After restoring this file from a backup, or after copying it.** This
    /// adapter mints its incarnation once, at schema creation, and reads it back
    /// on every open — the mechanism VT-6 permits *only* for an adapter that can
    /// detect its state was restored or cloned, **or** whose deployment is
    /// documented to invoke a re-mint. A SQLite file copied from Friday's backup
    /// is undetectable from inside SQLite, so this operation is the second half
    /// of that permission rather than a convenience: without it, mint-once here
    /// would not be legitimate and this adapter would owe a fresh incarnation on
    /// every open.
    ///
    /// Two copies of one file that keep one incarnation are two stores minting
    /// [`EventId`]s that collide — a failure with no error path and no
    /// observable symptom until a replication peer sees the same identity twice.
    ///
    /// Run it with nothing else holding the database open, and *before* the
    /// restored copy accepts its first append: events already in the file keep
    /// the origin they were stamped with, which is correct — they were written
    /// by the incarnation that is being retired.
    ///
    /// # Errors
    ///
    /// * [`SqliteEventStoreError::Sqlite`] if the file cannot be opened, or if
    ///   another connection holds the write lock for longer than the configured
    ///   busy timeout.
    /// * [`SqliteEventStoreError::UnsupportedSchemaVersion`] if the file was
    ///   written by a newer build — a re-mint is refused rather than applied
    ///   blind to a schema this build does not know.
    /// * [`SqliteEventStoreError::MissingIdentity`] or
    ///   [`SqliteEventStoreError::MalformedIdentity`] if the freshly written row
    ///   cannot be read back, in which case nothing is committed.
    pub fn remint_identity(path: impl AsRef<Path>) -> Result<StoreId, SqliteEventStoreError> {
        let mut connection = crate::connection::open_configured(path)?;
        // Migrating first is what makes this operation total rather than
        // conditional on the caller having opened the store already.
        Self::migrate(&mut connection)?;

        let transaction =
            connection.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
        transaction.execute(
            "UPDATE store_meta SET v = randomblob(16) WHERE k = ?",
            [STORE_ID_KEY],
        )?;
        let minted = read_identity(&transaction)?;
        transaction.commit()?;
        Ok(minted)
    }

    /// The three ceilings, checked before any transaction opens.
    ///
    /// # Errors
    ///
    /// A [`CeilingExceeded`] naming which ceiling was exceeded and by what
    /// magnitude, which `append` reports as `AppendError::ExceedsStoreLimit`
    /// and an ingest as `IngestError::ExceedsStoreLimit`. Never a store error:
    /// a caller that cannot tell "this will never fit here, park it and tell a
    /// human" from "the disk is full, retry" has to guess, and a sync runner
    /// that guesses wrong drops an event permanently.
    ///
    /// `len` is the number of events the transaction will write, and `events`
    /// yields them. Two arguments rather than one slice because an ingest's
    /// events are spread across its groups and are not one slice anywhere; an
    /// append passes `events.len()` and `events`.
    fn check_ceilings<'e>(
        len: usize,
        events: impl IntoIterator<Item = &'e Event>,
    ) -> Result<(), CeilingExceeded> {
        if len > Self::MAX_EVENTS_PER_BATCH {
            return Err(CeilingExceeded {
                limit: happenstance_core::StoreLimit::EventsPerBatch,
                len,
            });
        }
        for event in events {
            if event.data().len() > Self::MAX_EVENT_DATA_LEN {
                return Err(CeilingExceeded {
                    limit: happenstance_core::StoreLimit::EventDataLen,
                    len: event.data().len(),
                });
            }
            if event.tags().len() > Self::MAX_TAGS_PER_EVENT {
                return Err(CeilingExceeded {
                    limit: happenstance_core::StoreLimit::TagsPerEvent,
                    len: event.tags().len(),
                });
            }
        }
        Ok(())
    }

    /// Everything that happens inside the one `BEGIN IMMEDIATE`.
    ///
    /// In order: the file's own incarnation checked against this handle's, then
    /// every guard probed against the state the store already held — which is
    /// free, because no row of this batch exists yet — then the rows inserted,
    /// then the identity stamped, then commit. A guard violation drops the
    /// transaction without committing, which is what "a rejected append leaves
    /// the file byte-identical" means, and the identity check answers the same
    /// way.
    ///
    /// # Why the incarnation is re-read here and not trusted from construction
    ///
    /// [`remint_identity`](Self::remint_identity) documents *"run it with
    /// nothing else holding the database open"*, and VT-6 rests half of its
    /// mint-once permission on that documented procedure. A precondition nobody
    /// can check is a precondition somebody will violate: a handle from before a
    /// restore, or a health check that reopened the store early, keeps the
    /// `store_id` it read at construction and goes on stamping [`EventId`]s
    /// under an incarnation the file has retired.
    ///
    /// **This is one indexed read on a four-row `WITHOUT ROWID` table, under a
    /// lock the writer already holds**, which is why it is affordable on the
    /// path where everything else waits. Guarding inside `remint_identity`
    /// instead cannot work and was not attempted: a process-wide open-path
    /// registry needs a canonical path key that symlinks, hardlinks, `file:`
    /// URIs, UNC paths and two paths to one inode all defeat, and it would still
    /// see nothing at all when the re-mint is another process. Here, the
    /// persisted identity is simply a row, and it is as true for a restore from
    /// backup as for the in-process case R-3 was narrowest about.
    ///
    /// What it does **not** buy: an event already written under the retired
    /// incarnation keeps it, which is correct — it was written by the
    /// incarnation being retired, and `remint_identity` says so.
    ///
    /// It goes through [`read_identity`] rather than a bespoke `SELECT`, which
    /// costs one extra row read — the schema version, which that function checks
    /// first — and buys the property this crate keeps insisting on elsewhere:
    /// **one spelling of what identity a file carries**, so `open`, `new`,
    /// `migrate`, `remint_identity` and this cannot disagree. The extra check
    /// has a second effect worth naming rather than discovering: an append now
    /// also refuses with
    /// [`UnsupportedSchemaVersion`](SqliteEventStoreError::UnsupportedSchemaVersion)
    /// if a newer build migrated the file while this handle was open, which is
    /// the same class of stale-handle bug one field over.
    fn append_locked(
        connection: &mut Connection,
        store_id: StoreId,
        events: &[Event],
        condition: Option<&AppendCondition>,
        recorded_at: RecordedAt,
    ) -> Result<SequencePosition, AppendError<SqliteEventStoreError>> {
        let transaction = connection
            .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
            .map_err(begin_error)?;

        // First, and before the guards: a condition evaluated against a file
        // this handle no longer speaks for answers a question nobody asked.
        check_identity(&transaction, store_id).map_err(AppendError::Store)?;

        if let Some(condition) = condition
            && let Some(conflict) = evaluate(&transaction, condition).map_err(store_error)?
        {
            drop(transaction);
            return Err(AppendError::ConditionViolated(ConditionViolated::at(
                conflict,
            )));
        }

        let rows: Vec<NewRow<'_>> = events
            .iter()
            .map(|event| NewRow {
                event,
                origin: Origin::Local { recorded_at },
            })
            .collect();
        let Written { last, .. } =
            write_batch(&transaction, store_id, &rows).map_err(store_error)?;
        // Every row of an append is local and none is ever skipped, so `None`
        // means the batch was empty — which step 1 of `append` has already
        // refused. Spelled as the decode of position zero because that is what
        // this line did before the writer was shared with ingest.
        let last = last.ok_or(AppendError::Store(SqliteEventStoreError::InvalidPosition(
            0,
        )))?;
        transaction.commit().map_err(store_error)?;
        Ok(last)
    }

    /// Everything an ingest does inside its one `BEGIN IMMEDIATE`: the
    /// replication counterpart of [`append_locked`](Self::append_locked), over
    /// the **same** row writer.
    ///
    /// In order: the incarnation checked, exactly as an append checks it; then,
    /// per group, the foreign rows written with their origin identity and
    /// recorded time, deduplicated inside the insert against the origin pair's
    /// `UNIQUE` constraint (VT-8); then the group's compensation, as ordinary
    /// local rows, **only if** at least one foreign row of that group went in
    /// (SY-11); then commit. The whole call is one transaction, which is
    /// stronger than the per-group atomicity the port asks for and costs nothing
    /// here, because this adapter serialises its writers anyway.
    ///
    /// What is absent is the point: **no condition is evaluated** (SY-1). An
    /// ingest records a decision another store already took.
    ///
    /// One refusal is not about the events, and it is decided by the same
    /// insert: a foreign row that **lands** while carrying this store's own
    /// identity was not held, so the store was restored or rewound without a
    /// re-mint (VT-6). The transaction is dropped uncommitted and the call fails
    /// as `IngestError::UnheldOwnIdentity` (SY-38). An own-identity row the
    /// store does hold meets the `UNIQUE` constraint and is an ordinary skip.
    /// No lookup runs ahead of the insert, so the check costs nothing on the
    /// path every echoed event takes.
    ///
    /// A skip is not always a hold, though. This call's own compensation is
    /// stamped with this store's identity, so a claim on the position a
    /// compensation just took meets *that* row under `UNIQUE` and reads as a
    /// re-delivery. So the head is read once when the transaction begins, and
    /// an own-identity skip above it is refused too: only this call can have
    /// written a row there.
    ///
    /// Behind `sync`, because the trait it serves is `happenstance-sync`'s;
    /// see `src/ingest_spike.rs`. A gate, not test code, since #108 part E
    /// published that crate.
    #[cfg(feature = "sync")]
    fn ingest_locked(
        connection: &mut Connection,
        store_id: StoreId,
        groups: &[happenstance_sync::IngestGroup<'_>],
        recorded_at: RecordedAt,
    ) -> Result<happenstance_sync::Ingested, happenstance_sync::IngestError<SqliteEventStoreError>>
    {
        use happenstance_sync::IngestError;

        let transaction = connection
            .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
            .map_err(ingest_begin_error)?;
        check_identity(&transaction, store_id).map_err(IngestError::Store)?;
        // The head before this call wrote anything, read once under the write
        // lock. An own identity above it was not held when the call began,
        // whatever the insert says, because only this call can have put a row
        // there. `max` over the `INTEGER PRIMARY KEY` is one B-tree seek.
        let started_at: i64 = transaction
            .query_row("SELECT coalesce(max(position), 0) FROM event", [], |row| {
                row.get(0)
            })
            .map_err(|error| IngestError::Store(error.into()))?;
        let write = |rows: &[NewRow<'_>]| {
            write_batch(&transaction, store_id, rows).map_err(IngestError::Store)
        };

        let mut ingested = happenstance_sync::Ingested::default();
        for group in groups {
            let foreign: Vec<NewRow<'_>> = group
                .events
                .iter()
                .map(|replicated| NewRow {
                    event: &replicated.event,
                    origin: Origin::Foreign {
                        id: replicated.id,
                        recorded_at: replicated.recorded_at,
                    },
                })
                .collect();
            let written = write(&foreign)?;
            // Landed, so not held; or skipped against a row this call wrote.
            let hidden = written
                .highest_own_echo
                .filter(|echo| claimed_after(*echo, started_at));
            if let Some(id) = written.unheld_own.or(hidden) {
                // Dropping the transaction uncommitted rolls back every group
                // this call has written so far, not only this one.
                drop(transaction);
                return Err(IngestError::unheld_own_identity(id));
            }
            ingested.appended += written.inserted;
            ingested.skipped += foreign.len() - written.inserted;

            if written.inserted > 0 && !group.compensation.is_empty() {
                let compensation: Vec<NewRow<'_>> = group
                    .compensation
                    .iter()
                    .map(|event| NewRow {
                        event,
                        origin: Origin::Local { recorded_at },
                    })
                    .collect();
                ingested.compensated += write(&compensation)?.inserted;
            }
        }

        transaction
            .commit()
            .map_err(|error| IngestError::Store(error.into()))?;
        Ok(ingested)
    }

    /// An ingest through this handle: the ceilings, one stamp for the
    /// compensation, the connection, then [`ingest_locked`](Self::ingest_locked)
    /// — `append`'s steps 2 to 4 in `append`'s order.
    ///
    /// The ceilings are checked against the **worst case**, every compensation
    /// event written, because they are checked before the transaction opens and
    /// whether a group's compensation lands is only known inside it. The event
    /// count is the whole call's, because the whole call is one transaction:
    /// [`MAX_EVENTS_PER_BATCH`](Self::MAX_EVENTS_PER_BATCH) bounds lock hold
    /// time, and a runner chunks its pulled batch to it.
    ///
    /// # Errors
    ///
    /// `IngestError::ExceedsStoreLimit` for a capacity refusal,
    /// `UnheldOwnIdentity` for an event claiming this store's identity that it
    /// does not hold, `Busy` when the write lock went elsewhere, and `Store`
    /// for everything else. Nothing is written in any of them.
    #[cfg(feature = "sync")]
    pub(crate) fn ingest_groups(
        &self,
        groups: &[happenstance_sync::IngestGroup<'_>],
    ) -> Result<happenstance_sync::Ingested, happenstance_sync::IngestError<SqliteEventStoreError>>
    {
        let len = groups
            .iter()
            .map(|group| group.events.len() + group.compensation.len())
            .sum();
        Self::check_ceilings(
            len,
            groups.iter().flat_map(|group| {
                group
                    .events
                    .iter()
                    .map(|replicated| &replicated.event)
                    .chain(group.compensation)
            }),
        )?;

        let recorded_at = now();
        let mut connection = self.connection.lock().map_err(|_| {
            happenstance_sync::IngestError::Store(SqliteEventStoreError::ConnectionPoisoned)
        })?;
        Self::ingest_locked(&mut connection, self.store_id, groups, recorded_at)
    }

    /// The highest origin position held from each origin store, this store's
    /// own included, derived from the log.
    ///
    /// One `GROUP BY` on the leading column of the `UNIQUE (origin_store,
    /// origin_position)` index, which is what lets the index serve it:
    /// [`WATERMARK_SQL`], whose plan
    /// `plan_tests::watermark_reads_the_origin_index_without_a_sort` asserts.
    /// Nothing is cached: a counter kept beside the log is a counter that can
    /// drift from it.
    ///
    /// # Errors
    ///
    /// The connection was poisoned, the driver failed, or a stored origin is not
    /// one the contract can represent.
    #[cfg(feature = "sync")]
    pub(crate) fn origin_watermark(
        &self,
    ) -> Result<happenstance_sync::Watermark, SqliteEventStoreError> {
        let connection = self
            .connection
            .lock()
            .map_err(|_| SqliteEventStoreError::ConnectionPoisoned)?;
        let mut statement = connection.prepare(WATERMARK_SQL)?;
        let mut rows = statement.query([])?;
        let mut watermark = happenstance_sync::Watermark::new();
        while let Some(row) = rows.next()? {
            let store: Vec<u8> = row.get(0)?;
            let highest: i64 = row.get(1)?;
            let bytes: [u8; 16] = store
                .as_slice()
                .try_into()
                .map_err(|_| SqliteEventStoreError::MalformedIdentity { len: store.len() })?;
            watermark.advance(StoreId::from_bytes(bytes), position_from_row(highest)?);
        }
        Ok(watermark)
    }

    /// Applies the schema in the module documentation, and returns the
    /// incarnation the file carries afterwards.
    ///
    /// Called on **every** connect, so it is a bounded number of
    /// `IF NOT EXISTS` statements and one read-back — no `ANALYZE`, no table
    /// scan, no schema introspection loop.
    ///
    /// # Why one `BEGIN IMMEDIATE`, and why the read-back is the load-bearing
    /// half
    ///
    /// Two connects onto a *fresh* file can race, and both would otherwise mint
    /// an incarnation. `INSERT OR IGNORE` makes only one of them land; reading
    /// the row back **inside the same transaction** is what makes the loser
    /// adopt the winner's value rather than keep the one it generated. A store
    /// that skipped the read-back would hold two different `StoreId`s for one
    /// file and every reopen rule downstream would go non-deterministic in a way
    /// that looks like flakiness.
    fn migrate(connection: &mut Connection) -> Result<StoreId, SqliteEventStoreError> {
        let transaction =
            connection.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;

        transaction.execute_batch(MIGRATION_1)?;
        transaction.execute(
            "INSERT OR IGNORE INTO store_meta (k, v) VALUES (?, ?)",
            rusqlite::params![SCHEMA_VERSION_KEY, SCHEMA_VERSION],
        )?;
        // `randomblob` is SQLite's own CSPRNG. Sixteen bytes of entropy from the
        // driver already in the tree, weighed against adding a crate for them
        // and chosen deliberately — `happenstance-core` mints nothing because it
        // is `no_std`-capable and has no entropy source, so the adapter must.
        transaction.execute(
            "INSERT OR IGNORE INTO store_meta (k, v) VALUES (?, randomblob(16))",
            [STORE_ID_KEY],
        )?;

        let store_id = read_identity(&transaction)?;
        transaction.commit()?;
        Ok(store_id)
    }
}

/// How many bound parameters one statement may carry.
///
/// SQLite's `SQLITE_MAX_VARIABLE_NUMBER` is 32,766. This sits below it with
/// headroom rather than at it, because the arithmetic that matters is done once
/// in `happenstance-core`'s `limits.rs` and an adapter that binds one extra
/// parameter per row should not be within rounding distance of the wall.
///
/// **Three consumers, not one.** It was written for the multi-row tag insert and
/// for a while that was its only caller, while the query path — which spends
/// parameters the same way, one per tag — partitioned on arms alone and reached
/// the wall at the adapter's own documented chunk width. The other two are
/// `query_sql::chunks`, through
/// [`MAX_QUERY_PARAMETERS_PER_STATEMENT`](SqliteEventStore::MAX_QUERY_PARAMETERS_PER_STATEMENT),
/// and the selectivity lookup that runs before it.
const PARAMETER_BUDGET: usize = 30_000;

/// Bound parameters one `event_tag` row costs.
const TAG_ROW_PARAMETERS: usize = 3;

/// The highest origin position held per origin store: the watermark's one
/// statement.
///
/// A constant so that [`SqliteEventStore::origin_watermark`] and the plan test
/// that holds it to the origin index read the same text and cannot drift. The
/// `GROUP BY` names the index's leading column bare. Any expression over it,
/// `origin_store || ''` for one, hides the column from the planner and costs a
/// temporary B-tree sort of every foreign row on every watermark.
#[cfg(feature = "sync")]
const WATERMARK_SQL: &str = "SELECT origin_store, max(origin_position) FROM event \
     WHERE origin_store IS NOT NULL GROUP BY origin_store";

/// Milliseconds since the Unix epoch, stamped **once**, at append.
///
/// ADR-0014's whole point is that the stamp is a property of the append rather
/// than of the read: a store that re-stamps on reopen hands every auditor the
/// time of the last restart.
fn now() -> RecordedAt {
    use std::time::{SystemTime, UNIX_EPOCH};

    let millis = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .ok()
        .and_then(|since| i64::try_from(since.as_millis()).ok())
        .unwrap_or(0);
    RecordedAt::from_millis(millis)
}

/// What one row of a page costs in resident bytes.
///
/// The two **opaque** payloads and nothing else: `data`, which this store bounds
/// at [`SqliteEventStore::MAX_EVENT_DATA_LEN`], and `metadata`, which it does
/// not bound at all. They are the two quantities a caller controls and the only
/// two that can make a row arbitrarily large; the type, the tags and the fixed
/// fields are bounded by their own ceilings and are noise beside a megabyte
/// blob.
///
/// It is deliberately **not** the event's full heap footprint. Counting the
/// allocator's size-class rounding, the `Vec` headers and the tag strings would
/// be a truer number and a less useful budget: a ceiling a caller can compute
/// from what they appended is worth more than one only a profiler can predict.
/// The residency measurement made the same choice and says so —
/// `experiments/one-connection-latency/results/raw/ceiling-residency.txt`
/// reports a lower bound.
fn payload_bytes(event: &SequencedEvent) -> usize {
    event.event.data().len()
        + event
            .event
            .metadata()
            .map_or(0, happenstance_core::bytes::Bytes::len)
}

/// A [`SequencePosition`] as the integer SQLite stores.
fn as_i64(position: SequencePosition) -> i64 {
    i64::try_from(position.get()).unwrap_or(i64::MAX)
}

/// A stored position as a [`SequencePosition`], or the error that says why not.
///
/// **Zero and negatives are rejected rather than resolved**, and the rejection
/// is `u64::try_from` rather than `i64::unsigned_abs`. That is the whole of the
/// decision, and it is worth spelling out because the absolutising form reads
/// like a guard and is not one: [`SequencePosition`] wraps a `NonZeroU64`, so
/// `SequencePosition::new` refuses exactly one value, and
/// `SequencePosition::new(stored.unsigned_abs())` hands it a value it accepts
/// for every negative there is. A stored `-3` decoded that way becomes position
/// 3 — a second row at a position another row already holds, which VT-11
/// forbids, and, because [`crate::row::to_event`] rebuilds the identity from the
/// stored origin pair, a second event carrying an [`EventId`] another event
/// already holds, which VT-8 forbids. The `ok_or` beside it fires for one input
/// in 2^64 and reads, in review, like a guard that fires for all of them.
///
/// The stored value is carried into the error **unmodified**, so an operator
/// reading the log sees the number that is in the file rather than the number
/// the decode wished were there.
///
/// This is `projection_store::position_from_row` verbatim, and deliberately so:
/// both halves of this crate answer to the same rule, and one of them answering
/// it a different way is how the halves drift.
///
/// # Errors
///
/// Returns [`SqliteEventStoreError::InvalidPosition`] if `stored` is zero or
/// negative.
pub(crate) fn position_from_row(stored: i64) -> Result<SequencePosition, SqliteEventStoreError> {
    u64::try_from(stored)
        .ok()
        .and_then(SequencePosition::new)
        .ok_or(SqliteEventStoreError::InvalidPosition(stored))
}

/// Wraps an adapter failure as the port's store-error arm.
fn store_error(error: impl Into<SqliteEventStoreError>) -> AppendError<SqliteEventStoreError> {
    AppendError::Store(error.into())
}

/// Classifies a failed `BEGIN IMMEDIATE`: [`AppendError::Busy`] when the write
/// lock was not acquired, [`AppendError::Store`] for anything else.
///
/// # Why here, and only here
///
/// `SQLITE_BUSY` or `SQLITE_LOCKED` from `BEGIN IMMEDIATE` means the busy
/// handler waited out [`BUSY_TIMEOUT_MS`](crate::connection::BUSY_TIMEOUT_MS)
/// and the lock went elsewhere. No statement of this append has run, so nothing
/// was written, and the same call can succeed once the holder lets go — which
/// is all three parts of `Busy`'s contract, known rather than inferred.
///
/// Every later failure stays `Store`, including a busy code, and that is a
/// choice rather than an oversight. Under WAL, once `BEGIN IMMEDIATE` holds the
/// write lock nothing after it waits on another writer, so a busy code there is
/// not the contention this variant names; and a failure at or after the first
/// inserted row is one this function would have to prove rolled back, which the
/// contract makes the adapter's burden. `AppendError::Busy`'s rule is that a
/// store that cannot tell is not busy, and one call site is the whole of what
/// this store can tell.
fn begin_error(error: rusqlite::Error) -> AppendError<SqliteEventStoreError> {
    if crate::connection::is_busy(&error) {
        AppendError::Busy(error.into())
    } else {
        store_error(error)
    }
}

/// Whether `id` names a position above `head`, a stored position. A position
/// past `i64::MAX` is above every stored one.
#[cfg(feature = "sync")]
fn claimed_after(id: EventId, head: i64) -> bool {
    i64::try_from(id.position().get()).map_or(true, |position| position > head)
}

/// [`begin_error`] for an ingest: `IngestError::Busy` when the write lock was
/// not acquired, `IngestError::Store` for anything else, by the same reasoning
/// and at the same one call site.
#[cfg(feature = "sync")]
fn ingest_begin_error(
    error: rusqlite::Error,
) -> happenstance_sync::IngestError<SqliteEventStoreError> {
    if crate::connection::is_busy(&error) {
        happenstance_sync::IngestError::Busy(error.into())
    } else {
        happenstance_sync::IngestError::Store(error.into())
    }
}

/// The position violating a guard of `condition`, if one exists.
///
/// **One `SELECT max(position)` per guard statement**, which is ADR-0022's
/// decision and the one that measured fastest on the *rejection* path — the path
/// a DCB command loop takes every time it loses a race. The insight it trades
/// on: a guard asks *"is there anything matching after this boundary"*, which
/// reads like an existence question and is an inequality on the **highest**
/// matching position. One `max()` answers both halves at once — whether the
/// condition is violated, and by which event — so the rejection path needs no
/// second query, where an `EXISTS` probe would need a follow-up `min(position)`
/// to name the conflict.
///
/// # Chunk and merge, on this path too
///
/// A wide guard goes through [`crate::query_sql::chunks`], the same
/// decomposition the read path plans with, and the per-chunk maxima are merged
/// by `max` — which is **exact** rather than approximate precisely because the
/// guard is an inequality on the highest match, so `max(max(a), max(b))` is
/// `max(a ∪ b)`.
///
/// The alternative was to leave this path on the unchunked translation, and it
/// is not a smaller version of the same thing: a `Query` bounds nothing by
/// design, so a guard carrying more than
/// [`MAX_QUERY_ARMS_PER_STATEMENT`](SqliteEventStore::MAX_QUERY_ARMS_PER_STATEMENT)
/// arms failed with SQLite's own *"too many terms in compound SELECT"* wrapped
/// as `AppendError::Store`. That is a refusal at the pushdown limit — VT-23's
/// named wrong implementation — arriving on the *write* path, where
/// `crates/happenstance-core/src/limits.rs:46-52` gives it no variant to be
/// honestly reported through. `tests/wide_query.rs::a_wide_append_condition_guard_is_not_refused`
/// is the standing guard; the conformance suite cannot reach it, because
/// `MIN_SUPPORTED_QUERY_ITEMS` is 128 and the chunk width is 400.
///
/// The same argument runs a second time on the **parameter** axis, and it took
/// longer to see because a partition on arms looks like a partition. A guard of
/// 400 items — the arm width exactly, therefore one chunk — carrying
/// [`MAX_TAGS_PER_EVENT`](SqliteEventStore::MAX_TAGS_PER_EVENT) tags apiece
/// binds 51,200 of SQLite's 32,766 bound parameters, and the selectivity lookup
/// in [`guard_statements`] reaches the same wall earlier still, on a query of ordinary
/// two-tag items, because it accumulates across the whole query rather than
/// across a chunk. Both are bounded by
/// [`MAX_QUERY_PARAMETERS_PER_STATEMENT`](SqliteEventStore::MAX_QUERY_PARAMETERS_PER_STATEMENT)
/// now, and `tests/wide_tags.rs` crosses that axis here as well as on the read
/// path, because this is the caller that holds the write lock.
///
/// `after: None` is a boundary of zero, because positions start at one. Guards
/// are checked in order and the first violation ends the evaluation.
fn evaluate(
    connection: &Connection,
    condition: &AppendCondition,
) -> Result<Option<SequencePosition>, SqliteEventStoreError> {
    // X-3, on the append path, and it runs before any guard rather than inside
    // one. Every arm below carries `position > ?`, so SQLite discards a corrupt
    // *negative* position before `max(position)` sees it — and a guard whose
    // only match is corrupt then reports no violation at all, which is the
    // silence the decode-before-compare fix below exists to break. The boundary
    // pushdown reintroduced it one layer down, in SQL, where no decode can
    // reach.
    //
    // One index endpoint seek, once per condition rather than once per guard,
    // inside a transaction that is about to do far more work than this.
    let lowest: Option<i64> =
        connection.query_row("SELECT min(position) FROM event", [], |row| row.get(0))?;
    if let Some(stored) = lowest {
        position_from_row(stored)?;
    }

    for guard in condition.guards() {
        // The boundary reaches SQLite rather than only Rust. See
        // `query_sql::chunks`: the comparison below stays, and the bound makes
        // it trivially true rather than load-bearing.
        let boundary = guard_boundary(guard);

        // `Option<i64>`'s own ordering is what merges the chunks: `None` sorts
        // below every `Some`, so an empty chunk contributes nothing and the fold
        // is the global maximum without a special case for "no match yet".
        let mut highest: Option<i64> = None;
        for (statement, params) in guard_statements(connection, guard)? {
            let chunk: Option<i64> = connection.query_row(
                &statement,
                rusqlite::params_from_iter(params.iter()),
                |row| row.get(0),
            )?;
            highest = highest.max(chunk);
        }

        if let Some(stored) = highest {
            // Decoded **before** the comparison, never after it. The order is
            // the whole point: comparing the stored `i64` first is what makes a
            // corrupt row invisible to the one check whose job is to see it. A
            // guard whose highest match is stored at `-3` fails `-3 > 0`, so the
            // guard reports no violation about a row that matches it, and the
            // append it waves through is the append the condition existed to
            // refuse. Decoding first turns that silence into a refusal naming
            // the row.
            let conflict = position_from_row(stored)?;
            if stored > boundary {
                return Ok(Some(conflict));
            }
        }
    }
    Ok(None)
}

/// A guard's `after` as the bound its statements carry: `None` is zero,
/// because positions start at one.
fn guard_boundary(guard: &Guard) -> i64 {
    guard.after.map_or(0, as_i64)
}

/// The statements [`evaluate`] runs for one guard, exactly as it runs them:
/// each chunk of the guard's arms, wrapped by [`guard_statement`], with its
/// bind values.
///
/// A function of its own so that `plan_tests` can plan the very text `append`
/// executes under `BEGIN IMMEDIATE`, rather than a second spelling of it that
/// could pass while this one drifts.
fn guard_statements(
    connection: &Connection,
    guard: &Guard,
) -> rusqlite::Result<Vec<(String, Vec<Value>)>> {
    let selectivity = Selectivity::read_for(
        connection,
        &guard.query,
        SqliteEventStore::MAX_QUERY_PARAMETERS_PER_STATEMENT,
    )?;
    let plan = crate::query_sql::chunks(
        &guard.query,
        &selectivity,
        SqliteEventStore::MAX_QUERY_ARMS_PER_STATEMENT,
        SqliteEventStore::MAX_QUERY_PARAMETERS_PER_STATEMENT,
        Some(guard_boundary(guard)),
    );
    Ok(plan
        .into_iter()
        .map(|(matched, params)| (guard_statement(&matched), params))
        .collect())
}

/// One chunk's matched positions reduced to the highest, which is all a guard
/// needs to know.
fn guard_statement(matched: &str) -> String {
    format!("SELECT max(position) FROM ({matched})")
}

/// Checks the file's persisted incarnation against the one this handle stamps
/// with, inside the write transaction. See
/// [`append_locked`](SqliteEventStore::append_locked) for why it is re-read
/// rather than trusted from construction; an ingest asks it for the same reason.
///
/// # Errors
///
/// `IdentityMoved` when the two differ, or the driver's failure to read the
/// row. The bare adapter error, so that `append` and an ingest each wrap it in
/// their own port's `Store` arm.
fn check_identity(connection: &Connection, store_id: StoreId) -> Result<(), SqliteEventStoreError> {
    let persisted = read_identity(connection)?;
    if persisted != store_id {
        return Err(SqliteEventStoreError::IdentityMoved {
            handle: store_id,
            persisted,
        });
    }
    Ok(())
}

/// Which declared ceiling a write exceeded, and by what magnitude: what
/// [`SqliteEventStore::check_ceilings`] finds.
///
/// Its own type rather than either port's error, because `append` and an
/// ingest report it through different enums, and neither may report it as a
/// store failure (VT-25). Building either port's error inside the check would
/// leave the other path converting an arm it can never receive.
struct CeilingExceeded {
    limit: happenstance_core::StoreLimit,
    len: usize,
}

impl From<CeilingExceeded> for AppendError<SqliteEventStoreError> {
    fn from(CeilingExceeded { limit, len }: CeilingExceeded) -> Self {
        Self::ExceedsStoreLimit { limit, len }
    }
}

#[cfg(feature = "sync")]
impl From<CeilingExceeded> for happenstance_sync::IngestError<SqliteEventStoreError> {
    fn from(CeilingExceeded { limit, len }: CeilingExceeded) -> Self {
        Self::exceeds_store_limit(limit, len)
    }
}

/// One row for [`write_batch`]: the event, and where its identity comes from.
struct NewRow<'a> {
    event: &'a Event,
    origin: Origin,
}

/// Where a row's [`EventId`] and [`RecordedAt`] come from.
///
/// The one fact that separates an append's row from an ingest's, and the only
/// thing the shared writer branches on.
#[derive(Clone, Copy)]
enum Origin {
    /// Minted here. The identity is this store's incarnation and the position
    /// the row is given, known only once the row exists, so it is stamped after
    /// the inserts through the `origin_position IS NULL` marker.
    Local {
        /// The one stamp the whole write shares.
        recorded_at: RecordedAt,
    },
    /// Minted by another store, and carried here unchanged: the identity and
    /// recorded time its origin gave it, written with the row, never restamped.
    ///
    /// Behind `sync` with everything else ingest-only, the gate the trait it
    /// serves needs; see `src/ingest_spike.rs`.
    #[cfg(feature = "sync")]
    Foreign {
        /// The origin's identity for this event.
        id: EventId,
        /// When the origin accepted it.
        recorded_at: RecordedAt,
    },
}

/// What one [`write_batch`] did.
///
/// A struct rather than a tuple because an ingest needs a third fact the
/// writer alone can see, and the fields only an ingest reads are behind
/// `sync` with the rest of the ingest path.
struct Written {
    /// The position of the last row that went in, if any did.
    last: Option<SequencePosition>,
    /// How many rows went in. A skipped re-delivery is not counted.
    #[cfg(feature = "sync")]
    inserted: usize,
    /// The first foreign row that **went in** while carrying this store's own
    /// identity.
    ///
    /// It went in, so the store did not hold it: the store was restored or
    /// rewound under an identity it should have re-minted (VT-6). The insert
    /// decides it, against the `UNIQUE` constraint, as it decides a skip.
    ///
    /// A field rather than a [`SqliteEventStoreError`] variant. A variant
    /// would make `IngestError::Store(UnheldOwnIdentity)` representable beside
    /// the port's own `IngestError::UnheldOwnIdentity`, two spellings of one
    /// fact that the ingest would have to keep apart at runtime.
    #[cfg(feature = "sync")]
    unheld_own: Option<EventId>,
    /// The highest-positioned foreign row carrying this store's own identity
    /// that was **skipped** as already held.
    ///
    /// Held by the store, or only by a row this same call already wrote: a
    /// compensation stamped with that identity a moment earlier meets the claim
    /// under `UNIQUE` exactly as a held row does. The writer cannot tell the
    /// two apart, so it reports the highest, and the caller compares it with
    /// the head the store had when its transaction began.
    #[cfg(feature = "sync")]
    highest_own_echo: Option<EventId>,
}

/// Writes every row of the batch, and returns how many rows went in and the
/// position of the last of them.
///
/// **The one row writer, for append and ingest alike**, and one `INSERT`
/// statement inside it. Every row goes in under `ON CONFLICT (origin_store,
/// origin_position) DO NOTHING`. A local row binds its origin `NULL`, which
/// never conflicts, and is stamped afterwards; a foreign row binds the origin
/// its peer gave it, and one already held is a skip rather than an error —
/// decided by the insert against the `UNIQUE` constraint (VT-8), never by a
/// lookup ahead of it. Everything after the inserts is shared and runs over the
/// rows that went in: the tag rows, the cardinality, the stamp.
///
/// The conflict clause names its target rather than being `INSERT OR IGNORE`,
/// and that is not a style choice: `OR IGNORE` ignores *every* constraint, so a
/// `NOT NULL` or `CHECK` violation on a foreign row would be counted as a
/// re-delivery and the event silently dropped. The target limits the silence to
/// the one constraint whose violation means "already held".
///
/// The `event` rows go in one at a time so that each one's assigned position is
/// read from `last_insert_rowid()` rather than inferred: `AUTOINCREMENT` permits
/// gaps and nothing may assume `+ 1`. That is also why a skip is read from the
/// statement's change count and not from the rowid, which a `DO NOTHING` leaves
/// where the previous insert put it. The `event_tag` rows are where the
/// parameter pressure actually is — at the declared ceilings a single multi-row
/// statement would bind 98,304 of SQLite's 32,766 — so they are batched into
/// statements sized from the budget, and the buffer is bounded by the chunk
/// rather than by the batch.
///
/// **Chunking the statements is not chunking the transaction.** Committing
/// between chunks would produce a partially applied batch, which is the one way
/// to fail atomicity that a single-threaded read-back would happily confirm.
fn write_batch(
    connection: &Connection,
    store_id: StoreId,
    rows: &[NewRow<'_>],
) -> Result<Written, SqliteEventStoreError> {
    let mut written: Vec<(&Event, i64)> = Vec::with_capacity(rows.len());
    let mut first_local: Option<i64> = None;
    #[cfg(feature = "sync")]
    let mut unheld_own: Option<EventId> = None;
    #[cfg(feature = "sync")]
    let mut highest_own_echo: Option<EventId> = None;
    {
        // One statement for every row, local or foreign. A local row binds its
        // origin as `NULL`, and SQLite's `UNIQUE` treats NULLs as distinct, so
        // the conflict clause can never fire for it: an append's rows all land,
        // exactly as they did before the clause was there. Only the values
        // bound differ between the two kinds of row — not the statement, the
        // columns or the order they are bound in.
        let mut insert = connection.prepare(
            "INSERT INTO event (event_type, data, metadata, tags, \
             origin_store, origin_position, recorded_at) \
             VALUES (?, ?, ?, ?, ?, ?, ?) \
             ON CONFLICT (origin_store, origin_position) DO NOTHING",
        )?;
        for row in rows {
            let event = row.event;
            let (origin_store, origin_position, recorded_at): (
                Option<[u8; 16]>,
                Option<i64>,
                RecordedAt,
            ) = match row.origin {
                Origin::Local { recorded_at } => (None, None, recorded_at),
                // Converted exactly, never through `as_i64`: that helper
                // saturates, which is harmless for a query bound and not for an
                // identity. Two events from one origin past `i64::MAX` would both
                // be written at `i64::MAX`, and the second would be counted as a
                // re-delivery — the silent drop the conflict target exists to
                // rule out. Refusing here rolls the whole ingest back.
                #[cfg(feature = "sync")]
                Origin::Foreign { id, recorded_at } => (
                    Some(id.store().to_bytes()),
                    Some(i64::try_from(id.position().get()).map_err(|_| {
                        SqliteEventStoreError::OriginPositionOutOfRange {
                            position: id.position(),
                        }
                    })?),
                    recorded_at,
                ),
            };
            let changed = insert.execute(rusqlite::params![
                event.event_type().as_str(),
                &event.data()[..],
                event.metadata().map(|metadata| &metadata[..]),
                crate::row::encode_tags(event.tags()),
                origin_store.as_ref().map(|bytes| &bytes[..]),
                origin_position,
                recorded_at.as_millis(),
            ])?;
            // Held already: a skip, and nothing below — no tag row, no
            // cardinality, no stamp — may count it.
            if changed == 0 {
                // An own identity skipped as held: the caller decides whether
                // it was held before this call or only by this call's own
                // compensation, which the insert alone cannot tell apart.
                #[cfg(feature = "sync")]
                if let Origin::Foreign { id, .. } = row.origin
                    && id.store() == store_id
                    && highest_own_echo.is_none_or(|seen: EventId| seen.position() < id.position())
                {
                    highest_own_echo = Some(id);
                }
                continue;
            }
            // Went in, so not held, and yet minted here: the VT-6 breach. The
            // caller refuses the ingest and rolls the transaction back.
            #[cfg(feature = "sync")]
            if let Origin::Foreign { id, .. } = row.origin
                && id.store() == store_id
            {
                unheld_own.get_or_insert(id);
            }
            let position = connection.last_insert_rowid();
            if origin_position.is_none() && first_local.is_none() {
                first_local = Some(position);
            }
            written.push((event, position));
        }
    }

    write_tag_rows(connection, &written)?;
    bump_cardinality(connection, &written)?;

    // One statement at the end of the batch rather than a value bound per row:
    // a locally appended event's identity is *this store's incarnation paired
    // with the position it was just given*, and that position is not known until
    // the row exists. `origin_position IS NULL` is the marker, and the
    // `UNIQUE (origin_store, origin_position)` constraint tolerates it because
    // SQLite treats NULLs as distinct — which is what lets a multi-row batch
    // stamp itself without tripping it.
    //
    // The marker alone is not a predicate a planner can seek: the only index
    // over the column is `UNIQUE (origin_store, origin_position)` and
    // `origin_store` leads it, so `WHERE origin_position IS NULL` on its own
    // scans the whole `event` table — under the `BEGIN IMMEDIATE` write lock,
    // with every other writer queued behind it, at a cost that grows with the
    // log. That is the defect class ADR-0022 §7's amendment exists to remove and
    // that NF-001 forbids in the write path. Bounding it by the batch's own
    // first assigned position turns it into a rowid seek, because `position` is
    // the `INTEGER PRIMARY KEY`; the write lock is what guarantees no row was
    // assigned in between.
    //
    // The marker stays beside the bound rather than being replaced by it. A
    // replication ingest writes rows carrying *another* store's origin, and one
    // landing inside this positional range must not be restamped under this
    // incarnation. No caller builds that batch today — `ingest_locked` writes a
    // group's foreign rows and its compensation in separate calls — so the
    // marker is defence for a writer that takes a mixed batch, and
    // `a_mixed_batch_does_not_restamp_its_foreign_rows` calls this function with
    // one directly, because that is the only arrangement that can fail without it.
    //
    // The bound is the first *local* row this call wrote. For an append that is
    // every row's first, as it always was; for an ingest's foreign rows there is
    // none and the statement does not run.
    if let Some(first) = first_local {
        connection.execute(
            "UPDATE event SET origin_store = ?, origin_position = position \
             WHERE position >= ? AND origin_position IS NULL",
            rusqlite::params![&store_id.to_bytes()[..], first],
        )?;
    }

    // `AUTOINCREMENT` continues from `max(largest rowid, sqlite_sequence)`, so a
    // file whose rows are already negative hands the next insert a negative
    // rowid — and absolutising it would acknowledge the write at a position no
    // row holds and the next honest append will. Refusing inside the
    // transaction is what makes that a rollback rather than a forged receipt.
    let last = written
        .last()
        .map(|&(_, position)| position_from_row(position))
        .transpose()?;
    Ok(Written {
        last,
        #[cfg(feature = "sync")]
        inserted: written.len(),
        #[cfg(feature = "sync")]
        unheld_own,
        #[cfg(feature = "sync")]
        highest_own_echo,
    })
}

/// Inserts every `(tag, position, event_type)` row, chunked to the parameter
/// budget.
///
/// `written` is the rows that went in, each beside the position it was given;
/// a skipped foreign row is not in it, so it gets no tag row.
fn write_tag_rows(connection: &Connection, written: &[(&Event, i64)]) -> rusqlite::Result<()> {
    let rows_per_statement = (PARAMETER_BUDGET / TAG_ROW_PARAMETERS).max(1);
    let mut buffer: Vec<Value> = Vec::with_capacity(rows_per_statement * TAG_ROW_PARAMETERS);
    let mut buffered = 0usize;

    for &(event, position) in written {
        for tag in event.tags() {
            buffer.push(Value::Text(tag.as_str().to_owned()));
            buffer.push(Value::Integer(position));
            buffer.push(Value::Text(event.event_type().as_str().to_owned()));
            buffered += 1;
            if buffered == rows_per_statement {
                flush_tag_rows(connection, &buffer, buffered)?;
                buffer.clear();
                buffered = 0;
            }
        }
    }
    if buffered > 0 {
        flush_tag_rows(connection, &buffer, buffered)?;
    }
    Ok(())
}

/// One multi-row `event_tag` insert.
fn flush_tag_rows(connection: &Connection, buffer: &[Value], rows: usize) -> rusqlite::Result<()> {
    let tuples = (0..rows).map(|_| "(?,?,?)").collect::<Vec<_>>().join(",");
    connection.execute(
        &format!("INSERT INTO event_tag (tag, position, event_type) VALUES {tuples}"),
        rusqlite::params_from_iter(buffer.iter()),
    )?;
    Ok(())
}

/// Maintains `tag_cardinality`, which is what orders a multi-tag probe.
///
/// Migration 1 creates the table; this is what writes to it. A table created and
/// never updated silently restores the plan the schema amendment was made to
/// avoid, and nothing in the conformance suite would notice. Counted over the
/// rows that went in, so a re-delivered event does not count its tags twice.
fn bump_cardinality(connection: &Connection, written: &[(&Event, i64)]) -> rusqlite::Result<()> {
    let mut statement = connection.prepare(
        "INSERT INTO tag_cardinality (tag, events) VALUES (?, 1) \
         ON CONFLICT(tag) DO UPDATE SET events = events + 1",
    )?;
    for &(event, _) in written {
        for tag in event.tags() {
            statement.execute([tag.as_str()])?;
        }
    }
    Ok(())
}

/// Reads the schema version and the incarnation back out of `store_meta`.
///
/// Refuses a file a newer build wrote, and refuses to invent an incarnation for
/// a migrated file that has lost one — silently minting a replacement re-issues
/// [`EventId`]s under a new origin for events that already exist, which is the
/// failure mode with no error path and no observable symptom.
fn read_identity(connection: &Connection) -> Result<StoreId, SqliteEventStoreError> {
    let version: u32 = connection.query_row(
        "SELECT CAST(v AS INTEGER) FROM store_meta WHERE k = ?",
        [SCHEMA_VERSION_KEY],
        |row| row.get(0),
    )?;
    if version > SCHEMA_VERSION {
        return Err(SqliteEventStoreError::UnsupportedSchemaVersion {
            found: version,
            supported: SCHEMA_VERSION,
        });
    }

    let raw: Vec<u8> = connection
        .query_row(
            "SELECT CAST(v AS BLOB) FROM store_meta WHERE k = ?",
            [STORE_ID_KEY],
            |row| row.get(0),
        )
        .map_err(|err| match err {
            rusqlite::Error::QueryReturnedNoRows => SqliteEventStoreError::MissingIdentity,
            other => SqliteEventStoreError::Sqlite(other),
        })?;

    let bytes: [u8; 16] = raw
        .as_slice()
        .try_into()
        .map_err(|_| SqliteEventStoreError::MalformedIdentity { len: raw.len() })?;
    Ok(StoreId::from_bytes(bytes))
}

/// How [`SqliteEventStore`] fails.
///
/// Every variant names something `rusqlite` or the surrounding runtime can
/// actually produce. Append-condition violations are **not** here: they travel
/// through [`AppendError::ConditionViolated`], so a caller can tell "rebuild the
/// decision model and retry" from "something broke" without knowing which
/// adapter it holds.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum SqliteEventStoreError {
    /// The driver failed: I/O, `SQLITE_BUSY`, a constraint, a bad statement.
    ///
    /// On an append this arrives in one of two arms. A `SQLITE_BUSY` or
    /// `SQLITE_LOCKED` from `BEGIN IMMEDIATE` — the write lock not acquired
    /// within the busy timeout, before anything was written — is carried by
    /// [`AppendError::Busy`]; every other driver failure, a busy code raised
    /// later included, by [`AppendError::Store`].
    #[error("SQLite failed: {0}")]
    Sqlite(#[from] rusqlite::Error),

    /// A thread panicked while holding the connection mutex.
    ///
    /// Carried as a unit variant rather than wrapping
    /// [`std::sync::PoisonError`], because that type is generic over the guard
    /// and the guard borrows the connection — it is neither `'static` nor
    /// `Send`, and [`EventStore::Error`](happenstance_core::EventStore::Error)
    /// requires `'static`.
    #[error("the SQLite connection mutex was poisoned by a panicking thread")]
    ConnectionPoisoned,

    /// The blocking task carrying a query panicked or was cancelled.
    #[error("the blocking SQLite task did not complete: {0}")]
    Worker(#[from] JoinError),

    /// A stream was polled outside a tokio runtime, so no blocking task could
    /// be spawned.
    ///
    /// See the [module documentation](self) for why this is an error rather
    /// than the panic `spawn_blocking` would otherwise raise.
    #[error("no tokio runtime is available to run the blocking SQLite query: {0}")]
    NoRuntime(#[from] TryCurrentError),

    /// A stored row carried a position SQLite accepted and the contract does
    /// not: [`SequencePosition`] wraps a `NonZeroU64`, so zero and negatives
    /// are unrepresentable.
    #[error("stored position {0} is not a valid sequence position")]
    InvalidPosition(i64),

    /// A stored row carried an event type that no longer validates.
    #[error("stored event type is invalid: {0}")]
    StoredEventType(#[from] InvalidEventType),

    /// A stored row carried a tag that no longer validates.
    #[error("stored tag is invalid: {0}")]
    StoredTag(#[from] InvalidTag),

    /// The file was written by a build that knows a later migration.
    ///
    /// Refusing is the point: operating on an unknown schema is how a later
    /// migration loses data, and the version marker exists precisely so that
    /// migration 2 has something to test against.
    #[error(
        "this build understands schema version {supported}, and the database is \
         at version {found}"
    )]
    UnsupportedSchemaVersion {
        /// The version the file carries.
        found: u32,
        /// The version this build knows.
        supported: u32,
    },

    /// The schema is present and its incarnation row is not.
    ///
    /// A **distinct** variant rather than a driver error, because the honest
    /// alternative — minting a replacement — re-issues [`EventId`]s under a new
    /// origin for events that already exist, and that failure has no error path
    /// and no observable symptom until a replication peer sees one identity
    /// twice.
    #[error(
        "the database has been migrated but carries no store identity; minting \
         a replacement would re-issue event identities for events that already \
         exist"
    )]
    MissingIdentity,

    /// The incarnation row is present and is not sixteen bytes.
    #[error("the stored store identity is {len} bytes, and a StoreId is sixteen")]
    MalformedIdentity {
        /// How many bytes the row actually held.
        len: usize,
    },

    /// This handle mints identities under an incarnation the file has retired.
    ///
    /// [`remint_identity`](SqliteEventStore::remint_identity)'s documented
    /// procedure says to run it *"with nothing else holding the database open"*,
    /// and until this variant existed nothing enforced it. A handle reads the
    /// incarnation once, at construction, so a handle that outlives a re-mint
    /// goes on stamping [`EventId`]s under the retired one — which is the
    /// failure VT-6's own `Rejects:` paragraph calls *"the one failure mode in
    /// the replication design with no error path and no observable symptom"*.
    ///
    /// **The narrow case, and it is deliberately narrow.** VT-6 accepts the
    /// undetectable ones — a file restored from a backup by another process, a
    /// copy taken while nothing was running — because SQLite cannot see them.
    /// This is the one a program *can* see: the split happened inside this
    /// process, and the persisted identity is readable under the lock the writer
    /// is already holding.
    ///
    /// Both incarnations are carried because one of them is not actionable: the
    /// answer is *drop this handle and reopen*, and knowing which handle is
    /// stale is the whole of the diagnosis.
    #[error(
        "this handle mints identities under store {handle}, and the database now \
         carries {persisted}: it was re-minted while this handle was open, so the \
         handle must be dropped and the store reopened"
    )]
    IdentityMoved {
        /// What this handle read at construction, and would have stamped with.
        handle: StoreId,
        /// What the file carries now.
        persisted: StoreId,
    },

    /// A stored row carries no event identity.
    ///
    /// Unreachable if the write path is correct — `append` stamps the origin
    /// pair onto every row of the batch before it commits — and reported rather
    /// than panicked so that a schema mistake surfaces as a failing rule naming
    /// this store rather than as a crash naming the suite.
    #[error("the event at position {position} carries no origin identity")]
    UnstampedEvent {
        /// Where the unstamped row sits.
        position: SequencePosition,
    },

    /// The canonical tag column of a stored row is not UTF-8.
    #[error("a stored tag column is not valid UTF-8")]
    CorruptTags,

    /// A replicated event's origin position does not fit SQLite's `INTEGER`.
    ///
    /// Refused rather than saturated, because on the ingest path a position is
    /// half an [`EventId`]: two such events from one origin would collapse onto
    /// one stored identity and the second would be counted as a re-delivery.
    /// Produced only by ingest, behind `sync`. The enum is `#[non_exhaustive]`,
    /// so a variant that appears under a feature breaks no exhaustive match.
    #[cfg(feature = "sync")]
    #[cfg_attr(docsrs, doc(cfg(feature = "sync")))]
    #[error("origin position {position} does not fit SQLite's INTEGER column")]
    OriginPositionOutOfRange {
        /// The position the origin assigned.
        position: SequencePosition,
    },
}

impl SendEventStore for SqliteEventStore {
    type Error = SqliteEventStoreError;

    fn read(
        &self,
        query: &Query,
        options: ReadOptions,
    ) -> impl Stream<Item = Result<SequencedEvent, Self::Error>> + Send {
        // Nothing is executed here on purpose. See the module documentation:
        // `read` may legally be called with no runtime in scope, and
        // `spawn_blocking` panics there. No lock is taken either — a guard
        // parked in the cursor would deadlock the next `append` through this
        // same handle.
        SqliteReadStream {
            state: ReadState::Idle(Box::new(ReadCursor {
                connection: Arc::clone(&self.connection),
                runtime: self.runtime.clone(),
                query: query.clone(),
                options,
                resume_from: options.from,
                remaining: options.limit,
                ceiling: Ceiling::Unsampled,
                finished: false,
            })),
        }
    }

    /// Appends `events`, refusing the write if `condition` is violated.
    ///
    /// The body is mostly *order*, and the order is the specification rather
    /// than a style: two of its four steps decide what happens **before** any
    /// SQL runs, and the fourth decides that everything remaining happens inside
    /// exactly one `BEGIN IMMEDIATE` transaction — the write lock taken before
    /// the condition is read and held to commit, so the snapshot the guard sees
    /// is the snapshot the insert writes into and no second writer can fit
    /// between the two halves.
    ///
    /// A probe followed by an unrelated insert is the wrong implementation this
    /// whole port exists to reject: it passes every single-threaded rule
    /// forever, and fails only when two writers decide from the same state.
    ///
    /// Returns the position assigned to the **last event of this batch**, in
    /// slice order — never the store head, which is a different number the
    /// moment another connection commits.
    ///
    /// # Errors
    ///
    /// Named by condition rather than by type:
    ///
    /// * the batch was empty — decided first, before the condition is read,
    ///   because *rebuild the decision model and retry* is not advice a caller
    ///   can act on for an empty batch;
    /// * one event's `data` was larger than
    ///   [`MAX_EVENT_DATA_LEN`](Self::MAX_EVENT_DATA_LEN), one event carried
    ///   more tags than [`MAX_TAGS_PER_EVENT`](Self::MAX_TAGS_PER_EVENT), or the
    ///   batch held more events than
    ///   [`MAX_EVENTS_PER_BATCH`](Self::MAX_EVENTS_PER_BATCH) — each reported as
    ///   a capacity refusal carrying the magnitude that exceeded it, never as a
    ///   store failure and never by truncating, so that a caller can tell *this
    ///   will never fit here* from *the disk is full, retry*;
    /// * a guard of the condition matched an event strictly after its boundary,
    ///   in which case the transaction rolls back and the file is unchanged;
    /// * the write lock was not acquired before the configured busy timeout
    ///   elapsed — `SQLITE_BUSY` or `SQLITE_LOCKED` from `BEGIN IMMEDIATE` —
    ///   which is reported as [`AppendError::Busy`]: contention, before any
    ///   statement of this append ran, so nothing was written and deciding again
    ///   is safe. It is neither a condition violation nor a store failure;
    /// * the driver failed in any other way, a busy code raised after
    ///   `BEGIN IMMEDIATE` succeeded included, which is [`AppendError::Store`];
    /// * another thread panicked while holding this store's connection.
    async fn append(
        &self,
        events: &[Event],
        condition: Option<&AppendCondition>,
    ) -> Result<SequencePosition, AppendError<Self::Error>> {
        // Step 1. An empty batch is the caller's own bug, and it is decided
        // above everything else. ES-20 is not a stylistic ordering: a caller
        // whose retry loop branches on `is_condition_violated` and receives
        // `ConditionViolated` for an empty batch never terminates, because an
        // empty batch will still be empty next time.
        if events.is_empty() {
            return Err(AppendError::NoEvents);
        }

        // Step 2. The declared ceilings, still before any transaction exists.
        // A caller must be able to learn a value will never fit *here* without
        // the store having to try, which is what keeps a quarantine path open
        // for a sync runner.
        Self::check_ceilings(events.len(), events)?;

        let recorded_at = now();
        let mut connection = self
            .connection
            .lock()
            .map_err(|_| AppendError::Store(SqliteEventStoreError::ConnectionPoisoned))?;

        // Steps 3 and 4 are one transaction, and that is the whole of the
        // atomicity claim.
        Self::append_locked(
            &mut connection,
            self.store_id,
            events,
            condition,
            recorded_at,
        )
    }

    /// The highest position any reader can currently observe, or `None` on an
    /// empty store.
    ///
    /// Asked of the database **every time**, and that is the whole of it. What
    /// this must never become is a field the store caches and `append` updates:
    /// one file backs several handles, so a second connection would then report
    /// a head that predates the first connection's commit — the stale head ES-30
    /// exists to reject, and the defect a single-handle test cannot see.
    ///
    /// # Errors
    ///
    /// * another thread panicked while holding this store's connection;
    /// * the driver failed, or a stored position is not one the contract can
    ///   represent.
    async fn head(&self) -> Result<Option<SequencePosition>, Self::Error> {
        let connection = self
            .connection
            .lock()
            .map_err(|_| SqliteEventStoreError::ConnectionPoisoned)?;
        // `NULL` on an empty table is the `None` arm, not an error.
        let highest: Option<i64> =
            connection.query_row("SELECT max(position) FROM event", [], |row| row.get(0))?;
        // `transpose`, not `and_then`. The distinction is the whole of it: the
        // `None` this returns must mean *the table is empty* and nothing else,
        // and an `and_then` here gives a failed decode the same spelling — so a
        // store holding a row at position 0 reports itself empty, and the caller
        // that believes it appends against a boundary of zero into a log that
        // already has events in it.
        highest.map(position_from_row).transpose()
    }

    /// Whether this store already holds the event `id` names.
    ///
    /// The probe seeks the `UNIQUE (origin_store, origin_position)` index
    /// migration 1 created — one constraint serving two jobs: this lookup, and
    /// the guard that keeps ingest from storing one event twice.
    ///
    /// # Errors
    ///
    /// * another thread panicked while holding this store's connection;
    /// * the driver failed.
    async fn contains_event_id(&self, id: EventId) -> Result<bool, Self::Error> {
        let connection = self
            .connection
            .lock()
            .map_err(|_| SqliteEventStoreError::ConnectionPoisoned)?;
        let found: Option<i64> = connection
            .query_row(
                "SELECT 1 FROM event WHERE origin_store = ? AND origin_position = ? LIMIT 1",
                rusqlite::params![&id.store().to_bytes()[..], as_i64(id.position())],
                |row| row.get(0),
            )
            .or_else(|err| match err {
                rusqlite::Error::QueryReturnedNoRows => Ok(None),
                other => Err(other),
            })?;
        Ok(found.is_some())
    }
}

/// The stream [`SqliteEventStore::read`](SendEventStore::read) returns.
///
/// # Why this type is `Send`
///
/// Nothing here is `Send` by accident, and each piece earns it separately:
///
/// * the cursor holds `Arc<Mutex<Connection>>`, and `Mutex<T>: Sync` whenever
///   `T: Send` — so wrapping the `!Sync` [`Connection`] is what makes the whole
///   cursor `Send`;
/// * [`JoinHandle<T>`] is `Send` when `T` is, and `T` here is the cursor plus a
///   `Result<Page, SqliteEventStoreError>`, whose error wraps `rusqlite::Error`
///   ([`Send`] + [`Sync`]) and [`JoinError`];
/// * the drain state holds `vec::IntoIter<SequencedEvent>`, `Send` because
///   [`SequencedEvent`] is.
///
/// No `rusqlite` handle that borrows the connection — `Statement`, `Rows`,
/// `Transaction` — ever appears in a field, and that is the load-bearing part:
/// all three are `!Send`, so holding one across the `poll_next` boundary would
/// cost the stream its `Send`-ness and with it the `SendEventStore` impl.
/// Confining them to the inside of the blocking closure is not a style choice.
///
/// The type is also [`Unpin`] — every field is — so `poll_next` needs no pin
/// projection and no `unsafe`, which matters because `unsafe_code` is
/// `forbid`den workspace-wide.
#[derive(Debug)]
pub struct SqliteReadStream {
    state: ReadState,
}

/// Where a [`SqliteReadStream`] is in its life.
#[derive(Debug)]
enum ReadState {
    /// No query in flight; the next poll spawns one.
    Idle(Box<ReadCursor>),
    /// A blocking fetch is running on a `spawn_blocking` thread.
    Fetching(JoinHandle<FetchOutcome>),
    /// Yielding rows already fetched, with the cursor parked for the next page.
    Draining {
        cursor: Box<ReadCursor>,
        rows: vec::IntoIter<SequencedEvent>,
    },
    /// Terminal: exhausted, or errored and not resumable.
    Done,
}

/// What one blocking hop hands back: the cursor it borrowed, and its result.
///
/// The cursor makes the round trip because `spawn_blocking` demands a `'static`
/// closure, so the only way to mutate it on the blocking thread is to move it
/// there and back.
type FetchOutcome = (Box<ReadCursor>, Result<Page, SqliteEventStoreError>);

/// One page of rows, plus whether the query is spent.
#[derive(Debug)]
struct Page {
    rows: Vec<SequencedEvent>,
    exhausted: bool,
}

/// ADR-0011's position ceiling, and whether it has been taken yet.
///
/// Three states rather than an `Option<Option<SequencePosition>>`, because the
/// two `None`s mean genuinely different things and conflating them is how the
/// registered defect gets written: *not sampled yet* is a thing to do, and
/// *sampled, and the store was empty* is an answer.
#[derive(Debug, Clone, Copy)]
enum Ceiling {
    /// No statement has run yet. The next `fetch_page` takes the sample.
    Unsampled,
    /// Nothing was in the store when the sample was taken, so this read is
    /// spent. **Not an error**: it is the state every adapter is in before it
    /// works, and computing arithmetic on it is the defect
    /// `reading_an_empty_store_yields_nothing` exists to reject.
    Empty,
    /// Every statement of this read is bounded at or below this position.
    At(SequencePosition),
}

/// Everything the blocking thread needs to fetch the next page.
#[derive(Debug)]
struct ReadCursor {
    connection: Arc<Mutex<Connection>>,
    /// The runtime the store captured, carried for a hop that is polled with no
    /// runtime of its own. See [`SqliteEventStore`]'s field of the same name.
    runtime: Option<Handle>,
    query: Query,
    options: ReadOptions,
    /// Where the next page resumes, **inclusive** — the same sense as
    /// [`ReadOptions::from`], which is what seeds it.
    ///
    /// The name matters. It was `resume_after` and it was seeded from an
    /// *inclusive* `from` and then advanced to `last.position`, which is two
    /// different senses in one field: page two would have re-read the last row
    /// of page one, once per page boundary. `AppendCondition::after` is the
    /// exclusive one in this contract and `ReadOptions::from` is the inclusive
    /// one, and they sit two types apart — mixing them is the easiest mistake
    /// in the port and this field made it. The multi-page criteria in
    /// `tests/read.rs` seed past `2 × PAGE_SIZE` rows precisely so that a return
    /// of that bug is visible.
    resume_from: Option<SequencePosition>,
    /// What is left of [`ReadOptions::limit`], or `None` for unlimited.
    remaining: Option<usize>,
    /// ADR-0011's ceiling: sampled no later than the first poll, never
    /// re-sampled.
    ceiling: Ceiling,
    finished: bool,
}

#[cfg(test)]
thread_local! {
    /// How many times **this thread** has taken a read's connection, counted only
    /// under `cfg(test)`.
    ///
    /// The one thing about a lock hold that is neither a duration nor a property of
    /// the machine is **how many times it is taken**, and it is not observable from
    /// outside this module: the mutex is private, and a prober racing it from
    /// another thread would be asserting on the scheduler. CF-33's `Rejects:`
    /// paragraph rules out the wall-clock alternative for exactly the reason that
    /// makes this the right instrument.
    ///
    /// **Thread-local rather than a process-wide counter**, and that is not a
    /// detail: a `static AtomicUsize` is shared by every test in the binary, and
    /// they run in parallel — the first spelling of this read `4` where it meant
    /// `2`, and would have read differently on the next run. The test that uses it
    /// drives `fetch_page` on its own thread; in production the same call runs on a
    /// `spawn_blocking` thread, which is why this could never become a production
    /// counter without moving somewhere the answer is collected.
    static PAGE_CONNECTION_ACQUISITIONS: std::cell::Cell<usize> =
        const { std::cell::Cell::new(0) };
}

impl ReadCursor {
    /// Takes the connection, and counts having done so when testing.
    ///
    /// Every acquisition a read makes goes through here, which is what makes the
    /// count meaningful: a second `self.connection.lock()` spelled out somewhere
    /// else would be invisible to it.
    ///
    /// # Errors
    ///
    /// Returns [`SqliteEventStoreError::ConnectionPoisoned`] if another thread
    /// panicked while holding it.
    fn lock_connection(
        &self,
    ) -> Result<std::sync::MutexGuard<'_, Connection>, SqliteEventStoreError> {
        #[cfg(test)]
        PAGE_CONNECTION_ACQUISITIONS.with(|taken| taken.set(taken.get() + 1));
        self.connection
            .lock()
            .map_err(|_| SqliteEventStoreError::ConnectionPoisoned)
    }

    /// Takes ADR-0011's position ceiling, once, and does nothing thereafter.
    ///
    /// # Why this runs on the polling thread rather than on the blocking one
    ///
    /// ES-11 says the sample is taken **no later than the first poll**, and that
    /// is stricter than it looks: a sample taken inside the `spawn_blocking`
    /// hop is taken *after* the first poll returned, so a caller that polls once
    /// — which is legal, and may legitimately answer `Pending` — and then
    /// appends can have its append land **before** the sample. The event is then
    /// below the ceiling and the read observes it.
    ///
    /// That is not theoretical and it is not flakiness. It is exactly what
    /// `read_result_is_stable_under_concurrent_append` and
    /// `query_items_share_one_snapshot` were written to catch, and this adapter
    /// failed both intermittently — roughly one run in two — until the sample
    /// moved here.
    ///
    /// The cost is one `SELECT max(position)` on the executor's thread. It is
    /// an O(1) seek to the end of an integer primary key, and it is the same
    /// lock `append` and `head` already take synchronously, so it adds no shape
    /// this crate did not already have.
    fn sample_ceiling(&mut self) -> Result<(), SqliteEventStoreError> {
        if !matches!(self.ceiling, Ceiling::Unsampled) {
            return Ok(());
        }
        // Scoped so the guard is released before `self.ceiling` is written: the
        // guard borrows `self`, and holding it across the assignment is
        // `error[E0506]`. It is also the smaller hold, which is the point.
        // Both endpoints, in one statement, because both are one seek to an end
        // of the `position` index and the second is therefore free.
        //
        // `min` is here for X-3 and is not decoration. Every arm of a paged read
        // now carries `position >= ?` — that is what turns a walk from the start
        // of a tag range into a seek into its interior, and it is most of what
        // the merge-join shape buys. It also means SQLite filters a corrupt
        // *negative* position out before any row reaches `row::to_event`, so the
        // decode that exists to reject it never sees it and the read quietly
        // returns a log with a row missing. Testing the low end once, here,
        // restores the property the pushdown removed, and restores it *wider*:
        // it fails on a corrupt row anywhere in the file rather than only on one
        // the query happened to match.
        //
        // The alternative that does not work is widening the arms to
        // `(position >= ? OR position < 1)`. It reads as the smaller change and
        // it is the more expensive one: SQLite answers the disjunction by
        // dropping the lower bound from the seek entirely —
        // `SEARCH seed USING PRIMARY KEY (tag=? AND position<?)`, measured — so
        // every page late in a replay pays for the prefix beneath it again.
        let (lowest, highest): (Option<i64>, Option<i64>) = {
            let connection = self.lock_connection()?;
            connection.query_row(
                "SELECT min(position), max(position) FROM event",
                [],
                |row| Ok((row.get(0)?, row.get(1)?)),
            )?
        };
        if let Some(stored) = lowest {
            position_from_row(stored)?;
        }
        // `Ceiling::Empty` is reserved for a table with no rows. Letting a
        // failed decode land there too is the same swallow `head` carried: the
        // read then returns an exhausted first page and the caller sees an empty
        // log rather than a store that cannot describe itself.
        self.ceiling = match highest {
            Some(stored) => Ceiling::At(position_from_row(stored)?),
            None => Ceiling::Empty,
        };
        Ok(())
    }

    /// The cursor's bounds resolved into position order, for
    /// [`query_sql::page_statements`](crate::query_sql).
    ///
    /// **`resume_from` and `to` swap ends under `backwards`, and only here.**
    /// `resume_from` is inclusive in both directions; which side of the position
    /// order it sits on is what `backwards` decides. Under `backwards`, `from`
    /// stays the *starting* — and therefore higher — bound and `to` the stopping
    /// one: they swap roles in position order, not in meaning. Copying
    /// `position <= ?` into the descending branch is correct forwards, passes
    /// two of the three read-bound rules, and returns the oldest events where
    /// the newest were asked for.
    ///
    /// The ceiling **composes** with `to` rather than replacing it — `min`, not
    /// an alternative — because *H* is an upper bound whichever way the read
    /// runs: forwards it tightens the stopping end, backwards the starting one.
    /// Every chunk inherits it through this one field, which is how ES-12
    /// survives a read becoming multi-statement, and there is deliberately no
    /// second mechanism for it.
    ///
    /// `lo` falls back to `0` rather than to `resume_from`'s absence being a
    /// missing clause: a position is a `NonZeroU64`, so `position >= 0` is
    /// vacuous, and an arm shape that carried the window on some reads and not
    /// others would be two shapes wearing one name.
    ///
    /// It is applied per hop and never carried as per-chunk state across one:
    /// `advance()` folds only the *merged* page back into `resume_from`, which
    /// is what stops the historical `resume_after` bug returning in a new
    /// disguise.
    fn page_window(&self, ceiling: SequencePosition, budget: usize) -> crate::query_sql::Window {
        let ceiling = as_i64(ceiling);
        let resume_from = self.resume_from.map(as_i64);
        let to = self.options.to.map(as_i64);

        let (lower, upper) = if self.options.backwards {
            (to, resume_from)
        } else {
            (resume_from, to)
        };

        crate::query_sql::Window {
            lo: lower.unwrap_or(0),
            hi: upper.map_or(ceiling, |bound| bound.min(ceiling)),
            budget: i64::try_from(budget).unwrap_or(i64::MAX),
            backwards: self.options.backwards,
        }
    }

    /// Runs one page's worth of SQL. Called only on a blocking thread.
    ///
    /// # The ceiling, and why one `max(position)` is a snapshot
    ///
    /// ADR-0011 requires an adapter issuing more than one statement per `read`
    /// to capture a position ceiling no later than the first poll and bound
    /// every later statement by it. At `PAGE_SIZE = 512` that is every log over
    /// 512 events, so it is not a corner.
    ///
    /// It is sound because position order **is** visibility order (ADR-0013):
    /// nothing that commits after *H* is captured can ever land at or below *H*,
    /// which is what makes one cheap `max(position)` equivalent to a snapshot
    /// and why ES-11 and ES-12 reduce to ES-10 plus a ceiling. A store that
    /// re-samples per page instead grows under the caller's feet, and the
    /// consequence is not a wrong read — it is an **accepted append that should
    /// have been rejected**, because the caller derives its condition's boundary
    /// from the maximum position the read observed, and that maximum sits above
    /// an event the read silently missed.
    ///
    /// Every item of one query shares this one predicate, which is how ES-12 is
    /// discharged. There is deliberately no second mechanism for it.
    ///
    /// # The connection is taken per statement, not per page
    ///
    /// The mutex used to be taken once here and held to the end of the function
    /// — across the selectivity lookup, every chunk of the plan, and the merge,
    /// sort, dedup and truncate. That is `planned_statement_count` statements'
    /// worth of held mutex, and every `append` sharing the handle waits behind
    /// all of it: measured at 640.7 ms held against 1.7 ms waited, a **371x**
    /// asymmetry, with the sharing appender's p50 untouched at 0.148 ms and its
    /// p99 at 799.041 ms
    /// (`experiments/one-connection-latency/results/raw/page-lock-hold.txt`).
    /// Nothing in the median warns anyone.
    ///
    /// Releasing it between statements is sound **because of the ceiling and not
    /// in spite of it**: every statement carries `position <= H`, so what a
    /// concurrent writer commits between two of them is above *H* and invisible
    /// to all of them. ES-11 is discharged by the sample, never by the hold —
    /// which is the whole point of ADR-0011, and is why this was free to change.
    fn fetch_page(&mut self) -> Result<Page, SqliteEventStoreError> {
        // A no-op if `poll_next` already took it, which it always has — the
        // sample is not allowed to wait for this thread. See `sample_ceiling`.
        self.sample_ceiling()?;

        let Ceiling::At(ceiling) = self.ceiling else {
            return Ok(Page {
                rows: Vec::new(),
                exhausted: true,
            });
        };

        let budget = self.remaining.map_or(PAGE_SIZE, |left| left.min(PAGE_SIZE));
        if budget == 0 {
            return Ok(Page {
                rows: Vec::new(),
                exhausted: true,
            });
        }

        // One acquisition, released before the plan is built: the lookup is one
        // statement per 30,000 tags and the planning that follows it is pure
        // Rust, which has no business holding a database connection.
        let selectivity = {
            let connection = self.lock_connection()?;
            Selectivity::read_for(
                &connection,
                &self.query,
                SqliteEventStore::MAX_QUERY_PARAMETERS_PER_STATEMENT,
            )?
        };

        // **Chunk and merge, never refuse.** A `Query` bounds nothing by design;
        // SQLite compiles a `UNION` of n arms as one compound `SELECT` and stops
        // at `SQLITE_MAX_COMPOUND_SELECT`, which is 500 by default. An adapter
        // that returned an error at its own pushdown limit would be inventing a
        // refusal the contract has no way to report, so a wide query becomes
        // several statements merged here. The partition is over *both* of
        // SQLite's pushdown limits, because the second one —
        // `SQLITE_MAX_VARIABLE_NUMBER`, one bound parameter per tag and per type
        // — is reached by a query of 400 wide items that the arm count alone
        // calls a single statement.
        //
        // Every chunk statement is **identical in shape** — same window, same
        // direction, same page budget — which is what makes merging them sound
        // rather than approximate.
        //
        // The bounds go **into** the statement rather than around it, which is
        // the whole of finding I-3's repair: `query_sql::page_statements` puts
        // them on each arm and the budget on the compound, so SQLite merges the
        // arms as co-routines and abandons them when the page is full. There is
        // no `WHERE position IN (<matched>)` wrapper here any more — it was not
        // replaced, it stopped existing.
        let plan = crate::query_sql::page_statements(
            &self.query,
            &selectivity,
            SqliteEventStore::MAX_QUERY_ARMS_PER_STATEMENT,
            SqliteEventStore::MAX_QUERY_PARAMETERS_PER_STATEMENT,
            self.page_window(ceiling, budget),
            crate::row::COLUMNS,
        );
        let mut merged: Vec<SequencedEvent> = Vec::with_capacity(budget);

        // The row budget every statement that was cut short by the **byte**
        // budget agrees on, and the page is truncated to it.
        //
        // The soundness argument is the one `truncate(budget)` already rested
        // on, generalised. A statement returns its matching rows in position
        // order, so a statement that stopped early is complete up to its own
        // last row and says nothing below it; keeping a prefix no longer than
        // the *shortest* such statement therefore keeps only positions every
        // statement had a chance to contribute to. Keeping more would drop
        // events silently — `advance()` moves `resume_from` past the page's last
        // position, so a row another chunk would have supplied below it is never
        // asked for again.
        //
        // It survives the merge-join rewrite unchanged, and had to: the byte
        // budget is about how much of a row `metadata` can be, which no amount
        // of pushing the window into the arms bounds. The rewrite removed the
        // reason a statement returns too *many* rows, not the reason one row can
        // be too *large*.
        let mut effective = budget;

        for (sql, params) in plan {
            // One acquisition per statement, released before the next is built.
            // See this function's `# The connection is taken per statement`.
            let (taken, cut) = {
                let connection = self.lock_connection()?;
                let mut statement = connection.prepare(&sql)?;
                let mut rows = statement.query(rusqlite::params_from_iter(params.iter()))?;

                // The **byte** budget, beside the row budget, because a row is
                // not a bounded quantity. It is checked *after* the row is
                // taken, which is what guarantees a page of at least one row —
                // `metadata` is unbounded, so one row can exceed the whole
                // budget on its own, and a page that refused it would stall the
                // read forever.
                let mut resident = 0usize;
                let mut taken = 0usize;
                let mut cut = false;
                while let Some(row) = rows.next()? {
                    let event = crate::row::to_event(row)?;
                    resident += payload_bytes(&event);
                    merged.push(event);
                    taken += 1;
                    if resident >= SqliteEventStore::MAX_PAGE_BYTES_PER_STATEMENT {
                        cut = true;
                        break;
                    }
                }
                (taken, cut)
            };

            if cut {
                effective = effective.min(taken);
            }
        }

        // The merge, and the two things it has to get right: one order for the
        // whole page regardless of how the items were partitioned, and each
        // event exactly once however many arms matched it.
        if self.options.backwards {
            merged.sort_by_key(|event| core::cmp::Reverse(event.position));
        } else {
            merged.sort_by_key(|event| event.position);
        }
        merged.dedup_by_key(|event| event.position);

        // Computed **before** truncation, and it now has two ways to be false.
        // Every chunk returned fewer rows than the budget exactly when the
        // merged set is short of it: a chunk's rows are already distinct, so a
        // chunk that filled its budget puts that many distinct positions into
        // the merge. A chunk stopped by the **byte** budget is the second way,
        // and it is not exhaustion at all — it is a page that ended early with
        // rows still behind it, so it must resume however short it looks.
        let exhausted = effective == budget && merged.len() < budget;
        merged.truncate(effective);

        Ok(Page {
            rows: merged,
            exhausted,
        })
    }

    /// Folds a fetched page back into the cursor's position and budget.
    ///
    /// `resume_from` stays inclusive, so it must step *strictly past* the last
    /// row — and "past" is direction-dependent, which is why this is not a
    /// `+ 1`. Running out of positions in either direction means the log has no
    /// more rows that way, so the cursor is spent rather than wrapped.
    fn advance(&mut self, page: &Page) {
        let mut exhausted_by_position = false;
        if let Some(last) = page.rows.last() {
            let next = if self.options.backwards {
                // No `SequencePosition::prev`: positions are `NonZeroU64`, so
                // stepping below `FIRST` is the same fact as being spent.
                SequencePosition::new(last.position.get().saturating_sub(1))
            } else {
                last.position.next()
            };
            exhausted_by_position = next.is_none();
            self.resume_from = next;
        }
        if let Some(remaining) = self.remaining.as_mut() {
            *remaining = remaining.saturating_sub(page.rows.len());
        }
        self.finished = page.exhausted || exhausted_by_position || self.remaining == Some(0);
    }
}

impl Stream for SqliteReadStream {
    type Item = Result<SequencedEvent, SqliteEventStoreError>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        // Safe without projection because `Self: Unpin`; see the type's docs.
        let this = Pin::into_inner(self);

        loop {
            // Taking the state by value is what lets the cursor be *moved* into
            // the `'static` closure `spawn_blocking` demands. `Done` is the
            // right placeholder: every arm either restores a live state or is
            // genuinely terminal.
            match std::mem::replace(&mut this.state, ReadState::Done) {
                ReadState::Idle(mut cursor) => {
                    if cursor.finished {
                        return Poll::Ready(None);
                    }
                    // ES-11's sample, taken **on this thread, before the spawn**.
                    // Deferring it into the blocking hop would put it after this
                    // poll returned, and a caller that polls once and then
                    // appends would see its own later event. See
                    // `ReadCursor::sample_ceiling` for the failing runs that
                    // moved this line.
                    if let Err(err) = cursor.sample_ceiling() {
                        return Poll::Ready(Some(Err(err)));
                    }
                    // The deferred spawn. This is the line that could not have
                    // been written inside `read`.
                    //
                    // The runtime this poll executes on is preferred, the handle
                    // captured at construction is the fallback: ADR-0081's
                    // reordering of ADR-0022 §9, as captured-first stranded a store that
                    // outlived its runtime (`tests/runtime_seam.rs`). The fallback
                    // serves the concurrency family's bare-thread contenders, with
                    // no tokio context at poll time. `NoRuntime` stays reachable,
                    // for a store constructed *and* driven with no runtime at all.
                    let runtime = match Handle::try_current() {
                        Ok(runtime) => runtime,
                        Err(err) => match cursor.runtime.clone() {
                            Some(runtime) => runtime,
                            None => return Poll::Ready(Some(Err(err.into()))),
                        },
                    };
                    this.state = ReadState::Fetching(runtime.spawn_blocking(move || {
                        let mut cursor = cursor;
                        let page = cursor.fetch_page();
                        (cursor, page)
                    }));
                }
                ReadState::Fetching(mut handle) => match Pin::new(&mut handle).poll(cx) {
                    Poll::Pending => {
                        this.state = ReadState::Fetching(handle);
                        return Poll::Pending;
                    }
                    Poll::Ready(Err(join)) => return Poll::Ready(Some(Err(join.into()))),
                    Poll::Ready(Ok((_cursor, Err(err)))) => return Poll::Ready(Some(Err(err))),
                    Poll::Ready(Ok((mut cursor, Ok(page)))) => {
                        cursor.advance(&page);
                        this.state = ReadState::Draining {
                            cursor,
                            rows: page.rows.into_iter(),
                        };
                    }
                },
                ReadState::Draining { cursor, mut rows } => match rows.next() {
                    Some(event) => {
                        this.state = ReadState::Draining { cursor, rows };
                        return Poll::Ready(Some(Ok(event)));
                    }
                    None => this.state = ReadState::Idle(cursor),
                },
                ReadState::Done => return Poll::Ready(None),
            }
        }
    }
}

#[cfg(test)]
mod tests {
    //! What one page of a read costs, measured where the page is built.
    //!
    //! [`ReadCursor`] and [`Page`] are private, and deliberately: a page is an
    //! implementation detail *beneath* `ReadOptions::limit`, and the stream a
    //! caller gets hands back events rather than pages. So no target in `tests/`
    //! can see a page boundary at all — it can only observe that a read returned
    //! everything, which is the property a page of any size satisfies. The two
    //! ceilings below bound the page and nothing else can see them.
    //!
    //! **No clock, and no duration.** The two quantities asserted here are a row
    //! count and an acquisition count, both exact. CF-33 forbids a conformance
    //! rule to assert on an operation count, and this is not one — it is the
    //! adapter's own unit test, and the count is what makes the ceiling a bound
    //! rather than a number.

    #![allow(clippy::unwrap_used)]

    use happenstance_core::{QueryItem, Tags};

    use super::*;

    /// The two events a page-budget case is built from: `count` of them, each
    /// carrying `data` bytes of payload and `metadata` bytes beside it.
    fn seeded(count: usize, data: usize, metadata: usize) -> Vec<Event> {
        (0..count)
            .map(|n| {
                let mut event = Event::new("Sized", vec![b'd'; data])
                    .unwrap()
                    .with_tags(Tags::from_pairs([("page", "p1")]).unwrap());
                if metadata > 0 {
                    event = event.with_metadata(vec![b'm'; metadata]);
                }
                let _ = n;
                event
            })
            .collect()
    }

    /// A cursor over everything in `store`, in the shape `read` builds.
    fn cursor(store: &SqliteEventStore, query: &Query) -> ReadCursor {
        let options = ReadOptions::default();
        ReadCursor {
            connection: Arc::clone(&store.connection),
            runtime: store.runtime.clone(),
            query: query.clone(),
            options,
            resume_from: options.from,
            remaining: options.limit,
            ceiling: Ceiling::Unsampled,
            finished: false,
        }
    }

    /// The payload bytes one page actually holds.
    fn resident(page: &Page) -> usize {
        page.rows
            .iter()
            .map(|event| {
                event.event.data().len()
                    + event
                        .event
                        .metadata()
                        .map_or(0, happenstance_core::bytes::Bytes::len)
            })
            .sum()
    }

    /// A page is bounded in **bytes**, not only in rows.
    ///
    /// `PAGE_SIZE` is a row count, and a row is not a bounded quantity: each one
    /// owns its `data`, up to [`SqliteEventStore::MAX_EVENT_DATA_LEN`], and its
    /// `metadata`, which this store does not bound at all. At the shipped 512
    /// rows and the shipped data ceiling one page peaks at **512.2 MiB** in a
    /// single buffer before one row reaches the caller — measured, at
    /// `experiments/one-connection-latency/results/raw/ceiling-residency.txt`.
    ///
    /// Under, at, and one over the budget, in rows of exactly one eighth of it.
    /// The middle case is the one a row budget alone cannot express.
    #[tokio::test]
    async fn a_page_stops_at_the_byte_budget_rather_than_at_the_row_budget() {
        let per_row = SqliteEventStore::MAX_EVENT_DATA_LEN;
        let fits = SqliteEventStore::MAX_PAGE_BYTES_PER_STATEMENT / per_row;
        let query = Query::all();

        for (seed, expected_first_page, expected_exhausted) in [
            (fits - 1, fits - 1, true),
            (fits, fits, false),
            (fits + 1, fits, false),
        ] {
            let store = SqliteEventStore::open_in_memory().unwrap();
            store.append(&seeded(seed, per_row, 0), None).await.unwrap();

            let page = cursor(&store, &query).fetch_page().unwrap();
            assert_eq!(
                page.rows.len(),
                expected_first_page,
                "a log of {seed} rows of {per_row} B produced a first page of {} rows",
                page.rows.len()
            );
            assert!(
                resident(&page) <= SqliteEventStore::MAX_PAGE_BYTES_PER_STATEMENT,
                "a log of {seed} rows produced a page of {} B, over the {} B budget",
                resident(&page),
                SqliteEventStore::MAX_PAGE_BYTES_PER_STATEMENT
            );
            assert_eq!(
                page.exhausted, expected_exhausted,
                "a log of {seed} rows reported exhausted = {}",
                page.exhausted
            );
        }
    }

    /// A row larger than the whole budget still makes progress.
    ///
    /// The budget is applied **after** the row is taken, which is what keeps a
    /// page from being empty and the read from stalling forever. The row that
    /// reaches this case is not exotic: `check_ceilings` bounds `data` and does
    /// **not** bound `metadata` at all — AE-4 — so metadata is the quantity that
    /// can exceed the page budget on its own.
    #[tokio::test]
    async fn one_row_over_the_whole_budget_still_makes_progress() {
        let oversized = SqliteEventStore::MAX_PAGE_BYTES_PER_STATEMENT + 1;
        let store = SqliteEventStore::open_in_memory().unwrap();
        store.append(&seeded(2, 1, oversized), None).await.unwrap();

        let mut cursor = cursor(&store, &Query::all());
        let first = cursor.fetch_page().unwrap();
        assert_eq!(
            first.rows.len(),
            1,
            "a row bigger than the budget must still be yielded, one at a time"
        );
        assert!(!first.exhausted, "there is a second row to come");

        cursor.advance(&first);
        let second = cursor.fetch_page().unwrap();
        assert_eq!(second.rows.len(), 1, "the second row followed the first");
    }

    /// The connection is taken per **statement**, not per page.
    ///
    /// `PAGE_SIZE`'s doc comment said *"one `spawn_blocking` hop"* while the code
    /// took the mutex once and held it across the selectivity lookup, every chunk
    /// of the plan, and the merge. On a query wide enough to be several
    /// statements that is `ceil(arms / 400)` statements' worth of held mutex, and
    /// every `append` sharing the handle waits behind all of it: measured at
    /// 640.7 ms held against 1.7 ms waited, a 371x asymmetry
    /// (`experiments/one-connection-latency/results/raw/page-lock-hold.txt`).
    ///
    /// The count is exact rather than a bound: the ceiling sample, the
    /// selectivity lookup, and one acquisition per planned statement. Asserting
    /// equality is what makes this reject *both* wrong implementations — one
    /// acquisition for the whole page, and one for the whole read.
    #[tokio::test]
    async fn a_page_takes_the_connection_once_per_statement() {
        let store = SqliteEventStore::open_in_memory().unwrap();

        // Wide enough that the arm partition genuinely splits: the width is
        // computed from the public ceiling rather than guessed, so the test
        // follows the constant if it moves.
        let items = SqliteEventStore::MAX_QUERY_ARMS_PER_STATEMENT * 2 + 1;
        let query = Query::from_items((0..items).map(|n| {
            QueryItem::new(
                Vec::<String>::new(),
                Tags::from_pairs([("item", &format!("i{n}")[..])]).unwrap(),
            )
            .unwrap()
        }))
        .unwrap();
        let statements = SqliteEventStore::planned_statement_count(&query);
        assert!(statements > 1, "the fixture must cross the arm width");

        store.append(&seeded(1, 1, 0), None).await.unwrap();

        PAGE_CONNECTION_ACQUISITIONS.with(|taken| taken.set(0));
        let _ = cursor(&store, &query).fetch_page().unwrap();
        let taken = PAGE_CONNECTION_ACQUISITIONS.with(std::cell::Cell::get);

        assert_eq!(
            taken,
            2 + statements,
            "one page of a {statements}-statement plan took the connection {taken} times; \
             the ceiling sample and the selectivity lookup are one each, and every statement \
             of the plan is one more"
        );
    }

    /// A byte-cut page loses nothing, on a plan of several statements.
    ///
    /// This is the assertion the truncation argument has to survive, and the one
    /// a naive byte budget fails. Two statements each stop early, at different
    /// points in position order; the page keeps a prefix no longer than the
    /// shorter of the two, because `advance()` moves `resume_from` past the
    /// page's last row and anything the *other* statement would have supplied
    /// below that row is never asked for again.
    ///
    /// The two matching items are placed at index 0 and at index
    /// `MAX_QUERY_ARMS_PER_STATEMENT`, so the partition is what separates them
    /// rather than the test asserting where the boundary is.
    #[tokio::test]
    async fn a_byte_cut_page_drops_no_event_across_statements() {
        let per_row = SqliteEventStore::MAX_EVENT_DATA_LEN;
        let fits = SqliteEventStore::MAX_PAGE_BYTES_PER_STATEMENT / per_row;
        let store = SqliteEventStore::open_in_memory().unwrap();

        // Alternating tags, so consecutive positions land in different chunks.
        let seeded: Vec<Event> = (0..fits * 3)
            .map(|n| {
                let side = if n % 2 == 0 { "a" } else { "b" };
                Event::new("Sized", vec![b'd'; per_row])
                    .unwrap()
                    .with_tags(Tags::from_pairs([("side", side)]).unwrap())
            })
            .collect();
        let expected: Vec<SequencePosition> = {
            store.append(&seeded, None).await.unwrap();
            let head = store.head().await.unwrap().unwrap();
            (1..=head.get()).filter_map(SequencePosition::new).collect()
        };

        let arms = SqliteEventStore::MAX_QUERY_ARMS_PER_STATEMENT;
        let items = (0..=arms).map(|n| {
            let tag = match n {
                0 => "a".to_owned(),
                n if n == arms => "b".to_owned(),
                other => format!("absent{other}"),
            };
            QueryItem::new(
                Vec::<String>::new(),
                Tags::from_pairs([("side", &tag[..])]).unwrap(),
            )
            .unwrap()
        });
        let query = Query::from_items(items).unwrap();
        assert!(
            SqliteEventStore::planned_statement_count(&query) > 1,
            "the fixture must span more than one statement"
        );

        let mut cursor = cursor(&store, &query);
        let mut observed = Vec::new();
        let mut pages = 0;
        while !cursor.finished {
            let page = cursor.fetch_page().unwrap();
            assert!(
                resident(&page) <= SqliteEventStore::MAX_PAGE_BYTES_PER_STATEMENT,
                "page {pages} held {} B, over the budget",
                resident(&page)
            );
            observed.extend(page.rows.iter().map(|event| event.position));
            cursor.advance(&page);
            pages += 1;
            assert!(pages < 100, "the read stopped making progress");
        }

        assert_eq!(
            observed, expected,
            "a page cut by the byte budget dropped events the other statement              would have supplied"
        );
        assert!(pages > 1, "the fixture must take more than one page");
    }

    /// The `origin_position IS NULL` marker in `write_batch`'s stamp, pinned by
    /// the one batch shape that needs it: a local row, then a foreign row.
    ///
    /// The stamp is bounded by the batch's first local position, and here the
    /// foreign row sits above that bound, so only the marker keeps it from being
    /// restamped under this store's incarnation. No caller builds this batch
    /// today — an ingest writes foreign rows and compensation in separate calls
    /// — which is why every test through the port passes with the marker
    /// deleted, and why this one calls the writer directly.
    #[cfg(feature = "sync")]
    #[test]
    fn a_mixed_batch_does_not_restamp_its_foreign_rows() {
        let mut connection = Connection::open_in_memory().unwrap();
        let own = SqliteEventStore::migrate(&mut connection).unwrap();
        let peer = StoreId::from_bytes([0x5E; 16]);
        let foreign = EventId::new(peer, SequencePosition::new(42).unwrap());
        let local = Event::new("Local", b"l".to_vec()).unwrap();
        let replicated = Event::new("Replicated", b"r".to_vec()).unwrap();
        let rows = [
            NewRow {
                event: &local,
                origin: Origin::Local {
                    recorded_at: RecordedAt::from_millis(1),
                },
            },
            NewRow {
                event: &replicated,
                origin: Origin::Foreign {
                    id: foreign,
                    recorded_at: RecordedAt::from_millis(2),
                },
            },
        ];

        let written = write_batch(&connection, own, &rows).unwrap();
        assert_eq!(written.inserted, 2);

        let origins: Vec<(String, Vec<u8>, i64, i64)> = connection
            .prepare("SELECT event_type, origin_store, origin_position, position FROM event")
            .unwrap()
            .query_map([], |row| {
                Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
            })
            .unwrap()
            .collect::<Result<_, _>>()
            .unwrap();
        for (kind, store, origin_position, position) in origins {
            if kind == "Local" {
                assert_eq!(store, own.to_bytes(), "the local row went unstamped");
                assert_eq!(origin_position, position);
            } else {
                assert_eq!(
                    store,
                    peer.to_bytes(),
                    "the foreign row was restamped under this store"
                );
                assert_eq!(origin_position, 42);
            }
        }
    }

    /// A file of its own, so a second connection can hold its write lock.
    /// Removed on drop, after the store and the holder that used it, because
    /// Windows will not unlink an open file.
    struct LockedFile(std::path::PathBuf);

    impl LockedFile {
        fn new() -> Self {
            static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
            let mut path = std::env::temp_dir();
            path.push(format!(
                "happenstance-sqlite-busy-{}-{}.db",
                std::process::id(),
                NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
            ));
            let file = Self(path);
            file.remove();
            file
        }

        fn remove(&self) {
            for suffix in ["", "-wal", "-shm"] {
                let mut path = self.0.clone().into_os_string();
                path.push(suffix);
                let _ = std::fs::remove_file(std::path::PathBuf::from(path));
            }
        }
    }

    impl Drop for LockedFile {
        fn drop(&mut self) {
            self.remove();
        }
    }

    /// A write lock held by another connection past the busy timeout is
    /// [`AppendError::Busy`], nothing is written, and the same append lands
    /// once the lock is released — all three parts of the variant's contract,
    /// on the one path `begin_error` classifies.
    ///
    /// The timeout is lowered on this handle's connection rather than waited
    /// out: fifty milliseconds is the same code path as fifteen seconds, and the
    /// test is about which arm the refusal arrives in, not how long it took.
    /// A wrong implementation this rejects is the one this crate shipped until
    /// `0.4.0` — `store_error` at `BEGIN IMMEDIATE` — which reports the same
    /// refusal as `Store`.
    #[tokio::test]
    async fn a_write_lock_held_elsewhere_is_busy_and_writes_nothing() {
        let file = LockedFile::new();
        let store = SqliteEventStore::open(&file.0).unwrap();
        store
            .connection
            .lock()
            .unwrap()
            .busy_timeout(core::time::Duration::from_millis(50))
            .unwrap();
        let holder = Connection::open(&file.0).unwrap();
        holder.execute_batch("BEGIN IMMEDIATE").unwrap();

        let event = Event::new("Blocked", b"b".to_vec()).unwrap();
        let refused = store.append(core::slice::from_ref(&event), None).await;
        assert!(refused.as_ref().is_err_and(AppendError::is_busy));
        match refused {
            Err(AppendError::Busy(SqliteEventStoreError::Sqlite(driver))) => assert!(
                crate::connection::is_busy(&driver),
                "the payload is the driver's own busy code: {driver}"
            ),
            other => panic!("a write lock held elsewhere must be `Busy`, got {other:?}"),
        }

        holder.execute_batch("ROLLBACK").unwrap();
        assert_eq!(
            store.head().await.unwrap(),
            None,
            "a busy refusal must have written nothing"
        );
        let landed = store.append(&[event], None).await.unwrap();
        assert_eq!(
            store.head().await.unwrap(),
            Some(landed),
            "the same append succeeds once the holder lets go"
        );

        drop(holder);
        drop(store);
    }

    /// The ingest counterpart: a write lock held elsewhere past the busy
    /// timeout is `IngestError::Busy`, class `Transient`, and nothing is
    /// written. Here rather than in `ingest_spike.rs` because lowering the
    /// timeout reaches the store's private connection, which only this module
    /// can, the way the append case above does.
    ///
    /// Rejects an ingest that wraps a failed `BEGIN IMMEDIATE` as `Store`, the
    /// mistake the append path shipped until `0.4.0`: a runner would then stop
    /// an edge that one retry would have cleared.
    #[cfg(feature = "sync")]
    #[tokio::test]
    async fn ingest_while_another_connection_holds_the_write_lock_is_busy() {
        use happenstance_sync::{
            Classify, FailureClass, IngestError, IngestGroup, ReplicatedEvent,
        };

        let file = LockedFile::new();
        let store = SqliteEventStore::open(&file.0).unwrap();
        store
            .connection
            .lock()
            .unwrap()
            .busy_timeout(core::time::Duration::from_millis(50))
            .unwrap();
        let holder = Connection::open(&file.0).unwrap();
        holder.execute_batch("BEGIN IMMEDIATE").unwrap();

        let sent = [ReplicatedEvent::new(
            EventId::new(StoreId::from_bytes([0xB5; 16]), SequencePosition::FIRST),
            RecordedAt::from_millis(1),
            Event::new("Shipped", b"s".to_vec()).unwrap(),
        )];
        let refused = store
            .ingest_groups(&[IngestGroup::new(&sent, &[])])
            .expect_err("a write lock held elsewhere must refuse the ingest");
        match &refused {
            IngestError::Busy(SqliteEventStoreError::Sqlite(driver)) => assert!(
                crate::connection::is_busy(driver),
                "the payload is the driver's own busy code: {driver}"
            ),
            other => panic!("a write lock held elsewhere must be `Busy`, got {other:?}"),
        }
        assert_eq!(refused.class(), FailureClass::Transient);

        holder.execute_batch("ROLLBACK").unwrap();
        assert!(
            !store.contains_event_id(sent[0].id).await.unwrap(),
            "a busy refusal must have written nothing"
        );
        assert_eq!(store.head().await.unwrap(), None);

        drop(holder);
        drop(store);
    }
}

#[cfg(test)]
mod plan_tests {
    use happenstance_core::{AppendCondition, Query, QueryItem, SequencePosition, Tags};
    use rusqlite::Connection;
    use rusqlite::types::Value;

    use super::SqliteEventStore;
    use crate::query_sql::{Selectivity, Window, page_statements};

    /// A store with enough rows for the planner to have an opinion.
    ///
    /// Two tags per event over a hundred `subject:` values, so a two-item query
    /// names two arms of about fifty rows each out of five thousand. Small
    /// enough to build in a test and large enough that a plan is a choice: on a
    /// table of ten rows SQLite may reach the same answer by a route that says
    /// nothing about what it does on a real log.
    fn seeded() -> Connection {
        let mut connection = Connection::open_in_memory().expect("an in-memory database");
        SqliteEventStore::migrate(&mut connection).expect("migrating must succeed");

        let transaction = connection.transaction().expect("a transaction");
        for position in 1..=5_000i64 {
            transaction
                .execute(
                    "INSERT INTO event (position, event_type, data, metadata, tags, \
                     origin_store, origin_position, recorded_at) \
                     VALUES (?, 'Seeded', X'00', NULL, X'1f', X'00000000000000000000000000000000', ?, 0)",
                    rusqlite::params![position, position],
                )
                .expect("an event row");
            for tag in [
                format!("subject:s{}", position % 100),
                "shard:cold".to_owned(),
            ] {
                transaction
                    .execute(
                        "INSERT INTO event_tag (tag, position, event_type) VALUES (?, ?, 'Seeded')",
                        rusqlite::params![tag, position],
                    )
                    .expect("a tag row");
            }
        }
        transaction.commit().expect("the seed must commit");
        connection
    }

    /// `EXPLAIN QUERY PLAN` as `(id, parent, detail)` rows.
    fn plan_rows(connection: &Connection, sql: &str, params: &[Value]) -> Vec<(i64, i64, String)> {
        let mut statement = connection
            .prepare(&format!("EXPLAIN QUERY PLAN {sql}"))
            .expect("the plan must prepare");
        statement
            .query_map(rusqlite::params_from_iter(params.iter()), |row| {
                Ok((row.get(0)?, row.get(1)?, row.get(3)?))
            })
            .expect("the plan must run")
            .map(|row| row.expect("a plan row"))
            .collect()
    }

    /// Whether `node` is `ancestor` or sits beneath it.
    fn descends_from(rows: &[(i64, i64, String)], node: i64, ancestor: i64) -> bool {
        let mut current = node;
        // The tree is shallow and finite; the bound is a guard against a
        // malformed plan rather than an expected case.
        for _ in 0..=rows.len() {
            if current == ancestor {
                return true;
            }
            match rows.iter().find(|(id, _, _)| *id == current) {
                Some((_, parent, _)) if *parent != current => current = *parent,
                _ => return false,
            }
        }
        false
    }

    /// **The falsifier for the whole read shape.**
    ///
    /// `page_statements` is built so that SQLite *may* run the compound's arms
    /// as co-routines and merge them, stopping when the page is full. It cannot
    /// be asked to: the merge is a planner choice, and the same statement is
    /// still correct — same rows, same order — when the planner declines and
    /// sorts the whole matched set instead. What changes is the cost class, and
    /// nothing else in this crate would notice.
    ///
    /// So the plan is asserted directly. Two claims, and the second is the one
    /// that would catch a regression:
    ///
    /// * the compound is merged (`MERGE`), rather than unioned into a transient
    ///   table;
    /// * **no sorter sits beneath the co-routine.** A `USE TEMP B-TREE FOR ORDER
    ///   BY` at the top level is expected and cheap — it orders at most `budget`
    ///   joined rows, because SQLite does not know a co-routine's order survives
    ///   the join. One *inside* the co-routine means the arms were collected and
    ///   sorted, which is the shape this design exists to avoid, and it is why
    ///   this test walks the parent chain rather than grepping the whole plan.
    ///
    /// Measured consequence of getting this wrong, at 500,000 events:
    /// `experiments/correlated-exists-guard/results/merge-join.md`.
    #[test]
    fn the_page_plan_is_a_merge_and_not_a_sort() {
        let connection = seeded();

        let items = ["s1", "s2"]
            .into_iter()
            .map(|subject| {
                let tags = Tags::from_pairs([("subject", subject), ("shard", "cold")])
                    .expect("two non-empty pairs");
                QueryItem::tagged(tags).expect("a non-empty tag set")
            })
            .collect::<Vec<_>>();
        let query = Query::from_items(items).expect("a non-empty item list");
        let selectivity = Selectivity::read_for(
            &connection,
            &query,
            SqliteEventStore::MAX_QUERY_PARAMETERS_PER_STATEMENT,
        )
        .expect("the lookup must succeed");

        let plan = page_statements(
            &query,
            &selectivity,
            SqliteEventStore::MAX_QUERY_ARMS_PER_STATEMENT,
            SqliteEventStore::MAX_QUERY_PARAMETERS_PER_STATEMENT,
            Window {
                lo: 1,
                hi: 5_000,
                budget: 512,
                backwards: false,
            },
            crate::row::COLUMNS,
        );
        assert_eq!(plan.len(), 1);
        let rows = plan_rows(&connection, &plan[0].0, &plan[0].1);
        let rendered = rows
            .iter()
            .map(|(id, parent, detail)| format!("id={id} parent={parent} {detail}"))
            .collect::<Vec<_>>()
            .join("\n");

        assert!(
            rows.iter().any(|(_, _, detail)| detail.contains("MERGE")),
            "the compound was not merged — the arms are being collected before \
             the page is taken:\n{rendered}"
        );

        let Some(&(coroutine, _, _)) = rows
            .iter()
            .find(|(_, _, detail)| detail.contains("CO-ROUTINE"))
        else {
            panic!("no co-routine in the plan:\n{rendered}")
        };

        for (id, _, detail) in &rows {
            assert!(
                !(detail.contains("TEMP B-TREE") && descends_from(&rows, *id, coroutine)),
                "a sorter sits inside the co-routine, so the whole matched set is \
                 being ordered before the page is taken:\n{rendered}"
            );
        }
    }

    /// Each arm reaches the `(tag, position)` index through **both** of its
    /// columns.
    ///
    /// `SEARCH … (tag=?)` alone means the window did not reach the index and
    /// every co-routine rewinds to the start of its tag range, so a page late in
    /// a replay pays for the whole prefix beneath it — the defect
    /// `results/all-query-wrapper.md` measured at 56,310 µs against 182 µs.
    /// The distinguishing text is the range constraint on the second column.
    /// The plan names the **alias**, `seed`, and not `event_tag`, which is worth
    /// knowing before writing an assertion against it.
    #[test]
    fn every_arm_seeks_into_its_tag_range_rather_than_rewinding() {
        let connection = seeded();

        let tags = Tags::from_pairs([("subject", "s1")]).expect("one non-empty pair");
        let query = Query::from_item(QueryItem::tagged(tags).expect("a non-empty tag set"));
        let selectivity = Selectivity::read_for(
            &connection,
            &query,
            SqliteEventStore::MAX_QUERY_PARAMETERS_PER_STATEMENT,
        )
        .expect("the lookup must succeed");

        let plan = page_statements(
            &query,
            &selectivity,
            SqliteEventStore::MAX_QUERY_ARMS_PER_STATEMENT,
            SqliteEventStore::MAX_QUERY_PARAMETERS_PER_STATEMENT,
            Window {
                lo: 2_500,
                hi: 5_000,
                budget: 512,
                backwards: false,
            },
            crate::row::COLUMNS,
        );
        let rows = plan_rows(&connection, &plan[0].0, &plan[0].1);
        let rendered = rows
            .iter()
            .map(|(_, _, detail)| detail.clone())
            .collect::<Vec<_>>()
            .join("\n");

        assert!(
            rows.iter().any(|(_, _, detail)| {
                detail.contains("SEARCH seed")
                    && detail.contains("tag=?")
                    && detail.contains("position>")
            }),
            "the arm's window did not reach the index:\n{rendered}"
        );
    }

    /// `seeded()`, plus a third tag per event and the cardinalities a real
    /// store would have recorded.
    ///
    /// `seeded()` writes no `tag_cardinality` rows, so its seed choice falls
    /// back to canonical order and starts from `shard:cold`, the unselective
    /// tag. That suits the read-path tests and would misrepresent the guard: on
    /// a store built through `append`, `bump_cardinality` keeps the table, and
    /// `most_selective_first` seeds from `subject:*`. The rows are written here
    /// rather than in `seeded()` so the two read-path tests keep the plan they
    /// were written against.
    fn guard_seeded() -> Connection {
        let mut connection = seeded();
        let transaction = connection.transaction().expect("a transaction");
        for position in 1..=5_000i64 {
            transaction
                .execute(
                    "INSERT INTO event_tag (tag, position, event_type) VALUES (?, ?, 'Seeded')",
                    rusqlite::params![format!("region:r{}", position % 7), position],
                )
                .expect("a tag row");
        }
        for (tag, events) in [
            ("subject:s1", 50i64),
            ("subject:s2", 50),
            ("region:r1", 714),
            ("region:r2", 714),
            ("shard:cold", 5_000),
        ] {
            transaction
                .execute(
                    "INSERT INTO tag_cardinality (tag, events) VALUES (?, ?)",
                    rusqlite::params![tag, events],
                )
                .expect("a cardinality row");
        }
        transaction.commit().expect("the seed must commit");
        connection
    }

    /// One query item over `pairs`, optionally restricted to `types`.
    fn guard_item(pairs: &[(&str, &str)], types: &[&str]) -> QueryItem {
        let tags = Tags::from_pairs(pairs.iter().copied()).expect("non-empty pairs");
        QueryItem::new(types.iter().copied(), tags).expect("a constrained item")
    }

    /// A plan as one line per row, for a failure message.
    fn render(rows: &[(i64, i64, String)]) -> String {
        rows.iter()
            .map(|(id, parent, detail)| format!("id={id} parent={parent} {detail}"))
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// The guard shapes the assertion runs over, by name.
    ///
    /// (a) is the shape ADR-0068 measured; (b) is the unanchored guard an
    /// idempotency key or a unique name writes; (c) chains twice, so `m1`
    /// exists; (d) is two items, so the arms meet in a `UNION`; (e) carries
    /// the value-list `IN` a typed item puts on the seed.
    fn guard_cases() -> Vec<(&'static str, AppendCondition)> {
        let after = SequencePosition::new(2_500).expect("non-zero");
        let two = || guard_item(&[("subject", "s1"), ("shard", "cold")], &[]);
        vec![
            (
                "(a) two tags, after",
                AppendCondition::new(Query::from_item(two())).after_every_guard(after),
            ),
            (
                "(b) two tags, no boundary",
                AppendCondition::new(Query::from_item(two())),
            ),
            (
                "(c) three tags, after",
                AppendCondition::new(Query::from_item(guard_item(
                    &[("subject", "s1"), ("region", "r1"), ("shard", "cold")],
                    &[],
                )))
                .after_every_guard(after),
            ),
            (
                "(d) two two-tag items, after",
                AppendCondition::new(
                    Query::from_items([
                        two(),
                        guard_item(&[("subject", "s2"), ("shard", "cold")], &[]),
                    ])
                    .expect("a non-empty item list"),
                )
                .after_every_guard(after),
            ),
            (
                "(e) two tags and two types, after",
                AppendCondition::new(Query::from_item(guard_item(
                    &[("subject", "s1"), ("shard", "cold")],
                    &["Seeded", "Other"],
                )))
                .after_every_guard(after),
            ),
        ]
    }

    /// The plan of every statement `evaluate` would run for `condition`.
    fn guard_plans(
        connection: &Connection,
        condition: &AppendCondition,
    ) -> Vec<Vec<(i64, i64, String)>> {
        condition
            .guards()
            .iter()
            .flat_map(|guard| {
                super::guard_statements(connection, guard).expect("the guard must render")
            })
            .map(|(sql, params)| plan_rows(connection, &sql, &params))
            .collect()
    }

    /// **ADR-0068 §16, limb 1: the falsifier for the guard's seed-driven
    /// shape, asserted rather than run by hand.**
    ///
    /// Each chained tag is an `EXISTS` correlated to `seed.position`, so the
    /// seed is the outer loop and every chained test is a point seek. A `LIST
    /// SUBQUERY` anywhere in the guard's plan means a chained test was
    /// materialised once in full and the seed demoted to the probe side: the
    /// pre-`8c8b215` uncorrelated chain from our side, or a planner that
    /// decorrelates the `EXISTS` from SQLite's. Same rows either way, and a
    /// cost proportional to the *least* selective tag, which no conformance
    /// rule can see.
    ///
    /// The second limb catches what the first cannot: a chained test that
    /// lost its alias still plans no `LIST SUBQUERY`, but its `SEARCH m{i}`
    /// row then seeks on `tag=?` alone. So every such row must carry
    /// `position=?`.
    ///
    /// Scoped to guard statements on purpose: the windowed read path carries a
    /// harmless `LIST SUBQUERY` of its own. Row text is otherwise not pinned,
    /// because it varies between SQLite versions; these substrings do not.
    #[test]
    fn the_guard_plan_has_no_list_subquery() {
        let connection = guard_seeded();

        for (case, condition) in guard_cases() {
            let plans = guard_plans(&connection, &condition);
            assert!(!plans.is_empty(), "{case}: the guard rendered no statement");

            for rows in &plans {
                let rendered = render(rows);
                assert!(
                    rows.iter()
                        .any(|(_, _, detail)| detail.contains("SEARCH seed")),
                    "{case}: the plan never searches the seed, so it says nothing \
                     about the shape under test:\n{rendered}"
                );
                assert!(
                    !rows
                        .iter()
                        .any(|(_, _, detail)| detail.contains("LIST SUBQUERY")),
                    "{case}: a chained test was materialised, so the seed no \
                     longer drives the guard:\n{rendered}"
                );

                let chained = rows
                    .iter()
                    .filter(|(_, _, detail)| detail.contains("SEARCH m"))
                    .collect::<Vec<_>>();
                assert!(
                    !chained.is_empty(),
                    "{case}: no chained test in the plan:\n{rendered}"
                );
                for (_, _, detail) in chained {
                    assert!(
                        detail.contains("position=?"),
                        "{case}: a chained test seeks without the seed's \
                         position, so it is no longer correlated:\n{rendered}"
                    );
                }
            }
        }
    }

    /// The pre-`8c8b215` chain, kept verbatim so the instrument above can be
    /// shown to fire: each chained tag as an **uncorrelated** `IN` list rather
    /// than a correlated `EXISTS`. Same seed, same boundary, same wrapper —
    /// shape from `experiments/correlated-exists-guard/src/chain.rs:341-352`.
    fn uncorrelated_guard_statement(
        seed: &str,
        chained: &[&str],
        boundary: i64,
    ) -> (String, Vec<Value>) {
        let mut matched = String::from(
            "SELECT seed.position AS position FROM event_tag AS seed \
             WHERE seed.tag = ? AND seed.position > ?",
        );
        let mut params = vec![Value::Text(seed.to_owned()), Value::Integer(boundary)];
        for tag in chained {
            matched
                .push_str(" AND seed.position IN (SELECT position FROM event_tag WHERE tag = ?)");
            params.push(Value::Text((*tag).to_owned()));
        }
        (super::guard_statement(&matched), params)
    }

    /// **The instrument is not decorative.** The uncorrelated chain returns
    /// the same rows and passes every conformance rule; only its plan and its
    /// cost class differ (about 580,000 µs against 33 µs at 10^6 events,
    /// ADR-0068). The predicate `the_guard_plan_has_no_list_subquery` asserts
    /// absent must be present here, or that test could not fail.
    #[test]
    fn the_guard_plan_instrument_fires_on_the_uncorrelated_chain() {
        let connection = guard_seeded();
        let (sql, params) = uncorrelated_guard_statement("subject:s1", &["shard:cold"], 2_500);
        let rows = plan_rows(&connection, &sql, &params);

        assert!(
            rows.iter()
                .any(|(_, _, detail)| detail.contains("LIST SUBQUERY")),
            "the uncorrelated chain planned no `LIST SUBQUERY`, so the guard-plan \
             assertion cannot tell it from the shipped shape:\n{}",
            render(&rows)
        );
    }

    /// The correlated chain with its alias dropped: `m0.position = position`
    /// binds the inner table's own column, so the `EXISTS` is true whenever the
    /// tag exists at all and the chain no longer filters the seed.
    fn dropped_alias_guard_statement(
        seed: &str,
        chained: &str,
        boundary: i64,
    ) -> (String, Vec<Value>) {
        let matched = "SELECT seed.position AS position FROM event_tag AS seed \
             WHERE seed.tag = ? AND seed.position > ? \
             AND EXISTS (SELECT 1 FROM event_tag AS m0 WHERE m0.tag = ? AND m0.position = position)";
        let params = vec![
            Value::Text(seed.to_owned()),
            Value::Integer(boundary),
            Value::Text(chained.to_owned()),
        ];
        (super::guard_statement(matched), params)
    }

    /// **The correlation limb is not decorative either.** The dropped-alias
    /// chain plans no `LIST SUBQUERY`, so only the `position=?` check on its
    /// `SEARCH m0` row can tell it from the shipped shape.
    #[test]
    fn the_guard_plan_correlation_limb_fires_on_a_dropped_alias() {
        let connection = guard_seeded();
        let (sql, params) = dropped_alias_guard_statement("subject:s1", "shard:cold", 2_500);
        let rows = plan_rows(&connection, &sql, &params);

        assert!(
            !rows
                .iter()
                .any(|(_, _, detail)| detail.contains("LIST SUBQUERY")),
            "the dropped-alias chain planned a `LIST SUBQUERY`, so it does not isolate \
             the correlation limb:\n{}",
            render(&rows)
        );
        let chained: Vec<&String> = rows
            .iter()
            .map(|(_, _, detail)| detail)
            .filter(|detail| detail.contains("SEARCH m0"))
            .collect();
        assert!(
            !chained.is_empty() && chained.iter().all(|detail| !detail.contains("position=?")),
            "the dropped-alias chain's `SEARCH m0` row carries `position=?`, so the \
             correlation limb cannot tell it from the shipped shape:\n{}",
            render(&rows)
        );
    }

    /// The watermark reads the `UNIQUE (origin_store, origin_position)` index
    /// and nothing else: a covering scan in the index's own order, so the
    /// `GROUP BY` needs no sorter and the table is never visited.
    ///
    /// **Named wrong query, checked red:** `GROUP BY origin_store || ''`. The
    /// expression hides the leading column from the planner, which then plans
    /// `USE TEMP B-TREE FOR GROUP BY`, a sort of every foreign row on every
    /// watermark, and this test fails on its second assertion.
    #[cfg(feature = "sync")]
    #[test]
    fn watermark_reads_the_origin_index_without_a_sort() {
        let connection = seeded();
        let rows = plan_rows(&connection, super::WATERMARK_SQL, &[]);

        assert!(
            rows.iter().any(|(_, _, detail)| {
                detail.contains("USING COVERING INDEX sqlite_autoindex_event_1")
            }),
            "the watermark does not read the origin pair's index:\n{}",
            render(&rows)
        );
        assert!(
            !rows
                .iter()
                .any(|(_, _, detail)| detail.contains("TEMP B-TREE")),
            "the watermark sorts to group, so it pays for every foreign row:\n{}",
            render(&rows)
        );
        assert!(
            // Any table scan, however a SQLite release words it: a `SCAN` row
            // that names no index reads every row of `event`.
            !rows
                .iter()
                .any(|(_, _, detail)| detail.starts_with("SCAN") && !detail.contains("INDEX")),
            "the watermark scans the table rather than the index:\n{}",
            render(&rows)
        );
    }
}

#[cfg(test)]
mod busy_conformance {
    //! The concurrency family against a store that is **really** busy.
    //!
    //! `tests/concurrency.rs` runs the family at the shipped
    //! [`BUSY_TIMEOUT_MS`](crate::connection::BUSY_TIMEOUT_MS), where fifteen
    //! seconds absorbs 64 contenders and no contender is ever refused — so it
    //! proves the rules pass and says nothing about how they treat a
    //! [`AppendError::Busy`] this adapter produced. This fixture lowers each
    //! handle's timeout to one millisecond after opening it, which turns the
    //! same race into one where most losers of the write lock are refused as
    //! `Busy` at `BEGIN IMMEDIATE`. Every rule must still pass: ES-43's
    //! `a_busy_append_left_nothing_behind` checks each refused contender wrote
    //! nothing, and the other five accept `Busy` under their floors.
    //!
    //! **That the refusals really happen was measured, not assumed**, with a
    //! throwaway count in `begin_error` that is not left in the tree: 258–262
    //! `Busy` answers across the six rules in each of three runs, and 61 of the
    //! 64 contenders in `a_busy_append_left_nothing_behind` alone. Ten further
    //! runs of the family were green. The count is not asserted, because CF-33
    //! denies a rule an operation count and a test here that demanded one would
    //! be timing-dependent. The deterministic half is
    //! `every_handle_the_impatient_fixture_connects_is_refused_as_busy`, below,
    //! which holds the two facts the count rests on: this fixture's handles
    //! carry the one-millisecond bound, and such a handle is refused as `Busy`
    //! by a write lock held elsewhere.
    //!
    //! In `src/` rather than `tests/` because lowering the timeout reaches the
    //! store's private connection, and a public knob for it would be a knob an
    //! application could turn the wrong way.
    //!
    //! One millisecond rather than zero: with no handler at all, a WAL
    //! *reader* can be refused on the wal-index lock too, and the reader rule
    //! would then report a failed read — a verdict about the fixture, not the
    //! store. One millisecond keeps the handler present, which is the shipped
    //! shape, and only shortens its bound.

    #![allow(clippy::unwrap_used)]

    use std::path::PathBuf;
    use std::sync::atomic::{AtomicU64, Ordering};

    use happenstance_testkit::{Capability, Fixture};

    use super::SqliteEventStore;

    /// One temporary file, and each `connect` a new impatient connection onto
    /// it.
    struct ImpatientFixture(PathBuf);

    impl ImpatientFixture {
        fn new() -> Self {
            static NEXT: AtomicU64 = AtomicU64::new(1);
            let mut path = std::env::temp_dir();
            path.push(format!(
                "happenstance-sqlite-impatient-{}-{}.db",
                std::process::id(),
                NEXT.fetch_add(1, Ordering::Relaxed)
            ));
            let fixture = Self(path);
            fixture.remove();
            fixture
        }

        fn remove(&self) {
            for suffix in ["", "-wal", "-shm"] {
                let mut path = self.0.clone().into_os_string();
                path.push(suffix);
                let _ = std::fs::remove_file(PathBuf::from(path));
            }
        }
    }

    impl Drop for ImpatientFixture {
        fn drop(&mut self) {
            self.remove();
        }
    }

    impl Fixture for ImpatientFixture {
        type Store = SqliteEventStore;

        const SECOND_HANDLE: Capability = Capability::SUPPORTED;

        const REOPEN: Capability = Capability::declined(
            "this fixture exists to make appends busy; durability across a \
             reopen is tests/conformance.rs's, at the shipped timeout",
        );

        async fn connect(&self) -> Self::Store {
            let store = SqliteEventStore::open(&self.0).unwrap();
            store
                .connection
                .lock()
                .unwrap()
                .busy_timeout(core::time::Duration::from_millis(1))
                .unwrap();
            store
        }
    }

    happenstance_testkit::event_store_concurrency_conformance!(
        mod_name = impatient,
        fixture = ImpatientFixture::new()
    );

    /// **The fixture above really is impatient, and that is what makes its
    /// run a run against `Busy`.**
    ///
    /// The family's pass says nothing on its own: against a handle that kept
    /// the shipped fifteen-second timeout, `a_busy_append_left_nothing_behind`
    /// sees no refusal and passes on its anchor. The count of refusals is not
    /// asserted, for the module doc's CF-33 reason. What is asserted instead
    /// are the two facts the count rests on, neither of which depends on how
    /// the race is scheduled: every handle the fixture connects reads its busy
    /// timeout back as one millisecond, and such a handle, meeting a write lock
    /// held elsewhere, is refused as `Busy` and writes nothing.
    ///
    /// The wrong implementations this rejects are a `connect` that stopped
    /// lowering the timeout, or lowered it on a different connection than the
    /// one the store appends through, and a `begin_error` that stopped
    /// mapping the refusal to `Busy`.
    #[tokio::test]
    async fn every_handle_the_impatient_fixture_connects_is_refused_as_busy() {
        use happenstance_core::{AppendError, Event, EventStore};

        let fixture = ImpatientFixture::new();
        let store = fixture.connect().await;
        let timeout: i64 = store
            .connection
            .lock()
            .unwrap()
            .query_row("PRAGMA busy_timeout", [], |row| row.get(0))
            .unwrap();
        assert_eq!(timeout, 1, "the fixture's handle must carry its 1 ms bound");

        let holder = rusqlite::Connection::open(&fixture.0).unwrap();
        holder.execute_batch("BEGIN IMMEDIATE").unwrap();
        let event = Event::new("Blocked", b"b".to_vec()).unwrap();
        let refused = store.append(core::slice::from_ref(&event), None).await;
        assert!(
            refused.as_ref().is_err_and(AppendError::is_busy),
            "an impatient handle meeting a held write lock must be refused as \
             `Busy`, got {refused:?}"
        );
        holder.execute_batch("ROLLBACK").unwrap();
        assert_eq!(
            store.head().await.unwrap(),
            None,
            "and the refusal must have written nothing"
        );

        drop(holder);
        drop(store);
    }
}