datum-persistence 0.11.3

Event sourcing, durable state, and CQRS persistence for Datum
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
//! Cassandra/ScyllaDB-backed journal, snapshot store, and durable-state store.
//!
//! Construction with [`CassandraPersistence::new`] is side-effect-free. Use
//! [`CassandraPersistence::connect`] to connect, create the keyspace and tables
//! when missing, and prepare every runtime statement. A blueprint created with
//! `new` may instead be initialized later with
//! [`CassandraPersistence::initialize`]. The pure-Rust `scylla` driver is
//! Tokio-native; this module contains no blocking adapter, `block_on`, or
//! `spawn_blocking` seam.
//!
//! With the default names, initialization settles the following CQL schema
//! (the configured keyspace prefixes every table):
//!
//! ```sql
//! CREATE KEYSPACE IF NOT EXISTS datum_persistence
//!   WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}
//!   AND durable_writes = true;
//!
//! CREATE TABLE IF NOT EXISTS datum_persistence.event_journal (
//!   persistence_id text,
//!   partition_nr bigint,
//!   sequence_nr bigint,
//!   writer text,
//!   adapter_manifest text,
//!   ser_id bigint,
//!   ser_manifest text,
//!   payload blob,
//!   meta_ser_id bigint,
//!   meta_manifest text,
//!   meta_payload blob,
//!   tags set<text>,
//!   timestamp_ms bigint,
//!   PRIMARY KEY ((persistence_id, partition_nr), sequence_nr)
//! ) WITH CLUSTERING ORDER BY (sequence_nr ASC);
//!
//! CREATE TABLE IF NOT EXISTS datum_persistence.journal_head (
//!   persistence_id text PRIMARY KEY,
//!   highest_seq_nr bigint,
//!   deleted_to bigint
//! );
//!
//! CREATE TABLE IF NOT EXISTS datum_persistence.snapshot (
//!   persistence_id text,
//!   sequence_nr bigint,
//!   timestamp_ms bigint,
//!   adapter_manifest text,
//!   ser_id bigint,
//!   ser_manifest text,
//!   payload blob,
//!   PRIMARY KEY (persistence_id, sequence_nr)
//! ) WITH CLUSTERING ORDER BY (sequence_nr DESC);
//!
//! CREATE TABLE IF NOT EXISTS datum_persistence.durable_state (
//!   persistence_id text PRIMARY KEY,
//!   revision bigint,
//!   ser_id bigint,
//!   ser_manifest text,
//!   payload blob,
//!   tag text
//! );
//!
//! CREATE TABLE IF NOT EXISTS datum_persistence.tag_events (
//!   tag text,
//!   timestamp_ms bigint,
//!   sequence_nr bigint,
//!   persistence_id text,
//!   writer text,
//!   adapter_manifest text,
//!   ser_id bigint,
//!   ser_manifest text,
//!   payload blob,
//!   meta_ser_id bigint,
//!   meta_manifest text,
//!   meta_payload blob,
//!   tags set<text>,
//!   PRIMARY KEY (tag, timestamp_ms, sequence_nr, persistence_id)
//! ) WITH CLUSTERING ORDER BY (timestamp_ms ASC, sequence_nr ASC, persistence_id ASC);
//!
//! CREATE TABLE IF NOT EXISTS datum_persistence.durable_state_changes (
//!   tag text,
//!   persistence_id text,
//!   revision bigint,
//!   timestamp_ms bigint,
//!   ser_id bigint,
//!   ser_manifest text,
//!   payload blob,
//!   deleted boolean,
//!   PRIMARY KEY (tag, persistence_id)
//! );
//!
//! CREATE TABLE IF NOT EXISTS datum_persistence.durable_state_change_log (
//!   tag text,
//!   timestamp_ms bigint,
//!   revision bigint,
//!   persistence_id text,
//!   ser_id bigint,
//!   ser_manifest text,
//!   payload blob,
//!   deleted boolean,
//!   PRIMARY KEY (tag, timestamp_ms, revision, persistence_id)
//! ) WITH CLUSTERING ORDER BY (timestamp_ms ASC, revision ASC, persistence_id ASC);
//! ```
//!
//! Journal sequence numbers are split with
//! `(sequence_nr - 1) / partition_size`, so a partition size of 100,000 puts
//! sequence numbers 1 through 100,000 in partition zero. One `AtomicWrite` is
//! emitted as one single-partition UNLOGGED batch. A write crossing that
//! boundary is rejected before storage. The event batch and subsequent head
//! update are deliberately not one cross-table transaction: a failure after
//! the event batch can leave stored rows ahead of `journal_head`, matching the
//! limitation of akka-persistence-cassandra. The persistence SPI requires the
//! stored head to remain an optimization hint rather than the source of truth,
//! so reads reconcile it against the event partition containing the head and
//! the following partition. Such uncertainty is returned as `Err`, never as a
//! rejection.
//!
//! The runtime normally enforces one in-process writer per persistence id.
//! Journal-head transitions nevertheless use lightweight transactions as a
//! cross-process backstop when that assumption is violated, for example in a
//! multi-node deployment. A failed LWT is write contention with an uncertain
//! outcome and therefore maps to `Err`, not [`AppendOutcome::Rejected`].
//!
//! [`CassandraWriteMode`] selects between that default (`Lwt`) and an opt-in
//! `SingleWriter` mode. Every measured Cassandra persist pays a Paxos round
//! for the journal-head LWT transition plus the head read that precedes it;
//! `SingleWriter` replaces the head *write* with a plain (non-conditional)
//! `INSERT`/`UPDATE`, removing the Paxos round while leaving the preceding
//! reconciliation read untouched. Crash safety still comes from that
//! unchanged read path: [`Journal::append`]/[`Journal::delete_to`] always call
//! the internal head-reconciliation read, which recomputes the true head from
//! the event partitions themselves rather than trusting the stored row, so a crash
//! between the event batch and the (now unguarded) head write is still healed
//! on the next read or append. What `SingleWriter` gives up is the
//! *cross-process* backstop: two runtimes concurrently believing they are the
//! sole writer for the same persistence id can race a plain head write and
//! silently regress it (unlike the LWT path, which would surface that race as
//! an `Err`). `SingleWriter` is therefore only safe under the same
//! single-writer-per-entity discipline the in-process runtime already
//! provides (e.g. one `EventSourcedBehavior`/`DurableStateBehavior` actor per
//! persistence id) and is **not** safe with concurrent cross-process writers
//! to the same persistence id — that deployment shape must stay on the
//! default `Lwt` mode. Durable-state `upsert`/`delete` are unaffected by this
//! setting: their revision is the CAS source of truth (not an optimization
//! hint), so they always use an LWT in both modes.
//!
//! `delete_to` issues partition-local range deletes, then advances the head's
//! `deleted_to` marker only through the high watermark observed by the delete.
//! That cap preserves point-in-time delete semantics when `u64::MAX` is used.
//! Range tombstones are efficient for replay but still contribute to Cassandra
//! tombstone pressure; operators should compact and size partitions with their
//! retention workload in mind.
//!
//! Durable state is a Datum extension: Akka ships no Cassandra durable-state
//! plugin. Revision one uses `INSERT .. IF NOT EXISTS`; later upserts and
//! tombstones use `UPDATE .. IF revision = ?`. A false `[applied]` result maps
//! to [`PersistenceError::RevisionConflict`], while transport or CQL errors
//! remain storage failures.
//!
//! Per-persistence-id queries walk journal partitions. Live queries poll the
//! head with adaptive backoff. `persistence_ids(Current)` scans distinct keys
//! from `journal_head`; live persistence-id discovery remains unsupported
//! (`QueryMode::Live` is rejected) pending a schema with a suitable global
//! ordering/index table.
//!
//! `events_by_tag` is served from `tag_events`, a dedicated per-tag index: on
//! append, every tagged event is additionally inserted into `tag_events`
//! *in the same unlogged batch* as the event-journal rows, keyed by
//! `(tag, timestamp_ms, sequence_nr, persistence_id)` so a live query can page
//! forward with a native clustering-key range comparison (no `ALLOW
//! FILTERING`). Because `event_journal`/`tag_events` are different
//! partitions, `AtomicWrite`'s single-partition constraint means this batch
//! cannot be atomic across both tables the way a same-partition conditional
//! batch would be: a crash between the two partition mutations can leave an
//! event durably journaled without (yet, or ever) a matching tag row. This
//! mirrors the eventual-consistency window akka-persistence-cassandra
//! documents for its own `tag_views` table. Re-emission on resume is allowed
//! and expected (per the query conformance contract); silently dropping an
//! already-accepted event's tag row is not repaired automatically today — an
//! operator-run tag-repair pass is the equivalent of akka's tooling for the
//! same gap and is a documented follow-up, not silently accepted.
//!
//! `tag_events` rows are not removed by [`Journal::delete_to`] (only the
//! `event_journal` partition is range-tombstoned), so a tag read must
//! independently filter out anything at or below the id's current
//! `deleted_to` marker — otherwise a deleted event would still surface
//! through the tag stream. `cassandra_events_by_tag` does this by batching one
//! journal-head lookup per *distinct* persistence id observed in the page
//! (cached in a map so a page touching many rows for the same id pays for one
//! lookup, not one per row) and dropping any row at or below that id's
//! `deleted_to`. This mirrors the RocksDB backend's `query_events_by_tag`
//! rule; re-emission on resume stays allowed, but a deleted event must never
//! be (re-)emitted.
//!
//! `DurableStateChangesQuery::changes` is served from two tables. A per-tag
//! *coalesced* table, `durable_state_changes`, holds one row per persistence
//! id (upserted or tombstoned right after the authoritative `durable_state`
//! LWT succeeds) and serves `QueryMode::Current`, whose "coalesce to one
//! latest value per id" contract it satisfies natively. Retagging an id (an
//! upsert whose `tag` differs from the row's previous tag, including a
//! transition to `None`) reads the previous tag first (the same
//! `durable_state` row a plain, non-conditional read touches right before the
//! CAS a caller would otherwise pay for anyway) and removes the stale
//! `(previous_tag, persistence_id)` row from `durable_state_changes` once the
//! CAS succeeds, so a consumer of the previous tag stops seeing the id as
//! live — it is not repeated as a `Deleted` change under the old tag, only a
//! genuine [`DurableStateStore::delete`] produces that; this matches the
//! in-memory backend's semantics, where retagging an entry simply moves it
//! out of the old tag's filtered view with no separate tombstone event.
//!
//! `QueryMode::Live` instead polls a second, *append-only* table,
//! `durable_state_change_log`, written in the same request as every
//! `durable_state_changes` upsert/tombstone with an identical timestamp and
//! revision. Its primary key, `(tag, timestamp_ms, revision, persistence_id)`,
//! lets a live cursor resume with a native clustering-key range comparison —
//! the same shape as `tag_events` — instead of re-scanning the whole
//! coalesced table with `ALLOW FILTERING` on every poll. `revision` (strictly
//! monotonic per id) is the second clustering column specifically so two
//! updates to the same id landing in the same source millisecond still sort
//! and resume correctly; relying on `(timestamp_ms, persistence_id)` alone,
//! as the coalesced table's boundary filter used to, cannot distinguish that
//! case and can silently drop the later change for a resuming consumer. A
//! `Live` subscription bootstraps once from the coalesced table (giving the
//! immediately-current per-id state, matching what `Current` would see) and
//! then continues polling `durable_state_change_log` from the bootstrap
//! instant onward; because retagging never rewrites `durable_state_change_log`
//! rows, an id's entries under a previous tag simply stop growing once it
//! moves to a new tag, the same "just stops appearing" semantics as the
//! coalesced table. `delete` preserves the row's internal `tag` column
//! (needed to route the tombstone into both change tables) even though the
//! *observable* [`VersionedState::tag`] returned by [`DurableStateStore::get`]
//! is forced to `None` on a tombstone, matching the documented public
//! contract.

#![forbid(unsafe_code)]

use std::{
    collections::{HashMap, HashSet, VecDeque},
    fmt,
    sync::Arc,
    time::{Duration, SystemTime, UNIX_EPOCH},
};

use futures_util::{StreamExt, stream};
use scylla::{
    client::{session::Session, session_builder::SessionBuilder},
    response::{PagingState, PagingStateResponse, query_result::QueryResult},
    serialize::{
        SerializationError,
        row::{RowSerializationContext, SerializeRow},
        writers::RowWriter,
    },
    statement::{
        Consistency, SerialConsistency,
        batch::{Batch, BatchType},
        prepared::PreparedStatement,
    },
    value::{CqlValue, Row},
};
use tokio::sync::OnceCell;

use crate::{
    AppendOutcome, AtomicWrite, DurableStateStore, EventStream, Journal, PersistenceError,
    PersistenceId, PersistenceResult, ReplayRange, Revision, SelectedSnapshot, SequenceNr,
    SerializedPayload, SerializerId, SnapshotCriteria, SnapshotMetadata, SnapshotStore,
    StoredEvent, Tag, VersionedState,
    query::{
        DeletedDurableState, DurableStateChange, DurableStateChangesQuery, EventEnvelope,
        EventsByPersistenceIdQuery, EventsByTagQuery, Offset, PersistenceIdsQuery, QueryMode,
        QueryStream, UpdatedDurableState,
    },
};

const DEFAULT_REPLICATION_FACTOR: u32 = 1;
const DEFAULT_PARTITION_SIZE: u64 = 100_000;
const DEFAULT_REPLAY_PAGE_SIZE: i32 = 256;
const DEFAULT_POLL_MIN_INTERVAL: Duration = Duration::from_millis(50);
const DEFAULT_POLL_MAX_INTERVAL: Duration = Duration::from_secs(2);
const DEFAULT_POLL_BATCH_SIZE: u32 = 256;
const MAX_CQL_IDENTIFIER_BYTES: usize = 48;

/// Adaptive polling settings for live Cassandra per-id queries.
///
/// An empty poll sleeps for [`Self::min_interval`] and doubles the delay up to
/// [`Self::max_interval`]. Emitting any event resets the delay.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CassandraPollingConfig {
    /// Initial delay after a poll observes no new event.
    pub min_interval: Duration,
    /// Maximum adaptive delay between empty polls.
    pub max_interval: Duration,
    /// Maximum events buffered by one live-query poll.
    pub batch_size: u32,
}

impl Default for CassandraPollingConfig {
    fn default() -> Self {
        Self {
            min_interval: DEFAULT_POLL_MIN_INTERVAL,
            max_interval: DEFAULT_POLL_MAX_INTERVAL,
            batch_size: DEFAULT_POLL_BATCH_SIZE,
        }
    }
}

/// Selects how journal-head transitions are written.
///
/// `Lwt` (the default) guards every head transition with a lightweight
/// transaction, a correct backstop against concurrent cross-process writers
/// to the same persistence id but a Paxos round on every append. `SingleWriter`
/// switches head writes to plain (non-conditional) `INSERT`/`UPDATE`
/// statements, removing that Paxos round. It is only safe under the
/// single-writer-per-entity discipline the in-process runtime already
/// provides (see the module documentation for the full crash-safety
/// rationale) and must not be used when more than one process can write the
/// same persistence id concurrently. Durable-state `upsert`/`delete` always
/// use an LWT in both modes; their revision is a CAS source of truth, not an
/// optimization hint.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum CassandraWriteMode {
    /// Guard every journal-head transition with a lightweight transaction.
    #[default]
    Lwt,
    /// Write journal-head transitions as plain, non-conditional statements.
    ///
    /// Requires single-writer-per-entity discipline; see the type docs.
    SingleWriter,
}

/// Configurable Cassandra persistence table names.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CassandraTableNames {
    /// Partitioned event-journal table.
    pub event_journal: String,
    /// Journal high-watermark and deletion-marker table.
    pub journal_head: String,
    /// Snapshot table.
    pub snapshot: String,
    /// LWT-backed durable-state table.
    pub durable_state: String,
    /// Per-tag event index table backing `events_by_tag`.
    pub tag_events: String,
    /// Per-tag coalesced durable-state change table backing `changes`
    /// (`QueryMode::Current`).
    pub durable_state_changes: String,
    /// Per-tag append-only durable-state change log backing `changes`
    /// (`QueryMode::Live` polling resume).
    pub durable_state_change_log: String,
}

impl Default for CassandraTableNames {
    fn default() -> Self {
        Self {
            event_journal: "event_journal".into(),
            journal_head: "journal_head".into(),
            snapshot: "snapshot".into(),
            durable_state: "durable_state".into(),
            tag_events: "tag_events".into(),
            durable_state_changes: "durable_state_changes".into(),
            durable_state_change_log: "durable_state_change_log".into(),
        }
    }
}

/// Side-effect-free Cassandra persistence configuration.
#[derive(Clone, PartialEq, Eq)]
pub struct CassandraPersistenceConfig {
    /// Seed nodes used by the driver to discover the cluster.
    pub contact_points: Vec<String>,
    /// Keyspace created on initialization when it does not already exist.
    pub keyspace: String,
    /// SimpleStrategy replication factor used only when creating the keyspace.
    pub replication_factor: u32,
    /// Persistence table names inside [`Self::keyspace`].
    pub tables: CassandraTableNames,
    /// Maximum event count assigned to one journal partition.
    pub partition_size: u64,
    /// Consistency applied to journal, snapshot, durable-state, and head writes.
    ///
    /// [`Consistency::Any`] is rejected because it may acknowledge only a
    /// hinted handoff, without any replica storing the mutation, which can
    /// silently lose an acknowledged persistence write if the hint is lost.
    pub write_consistency: Consistency,
    /// Consistency applied to reads and query polling.
    pub read_consistency: Consistency,
    /// Serial consistency applied to journal-head and durable-state LWTs and
    /// conditional snapshot deletes.
    pub serial_consistency: SerialConsistency,
    /// Maximum event rows requested in one replay page.
    pub replay_page_size: i32,
    /// Adaptive live-query polling settings.
    pub polling: CassandraPollingConfig,
    /// Journal-head write strategy; see [`CassandraWriteMode`].
    pub write_mode: CassandraWriteMode,
}

impl fmt::Debug for CassandraPersistenceConfig {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CassandraPersistenceConfig")
            .field("contact_points", &self.contact_points)
            .field("keyspace", &self.keyspace)
            .field("replication_factor", &self.replication_factor)
            .field("tables", &self.tables)
            .field("partition_size", &self.partition_size)
            .field("write_consistency", &self.write_consistency)
            .field("read_consistency", &self.read_consistency)
            .field("serial_consistency", &self.serial_consistency)
            .field("replay_page_size", &self.replay_page_size)
            .field("polling", &self.polling)
            .field("write_mode", &self.write_mode)
            .finish()
    }
}

impl CassandraPersistenceConfig {
    /// Creates a single-seed configuration with Cassandra-safe defaults.
    #[must_use]
    pub fn new(contact_point: impl Into<String>, keyspace: impl Into<String>) -> Self {
        Self {
            contact_points: vec![contact_point.into()],
            keyspace: keyspace.into(),
            replication_factor: DEFAULT_REPLICATION_FACTOR,
            tables: CassandraTableNames::default(),
            partition_size: DEFAULT_PARTITION_SIZE,
            write_consistency: Consistency::LocalQuorum,
            read_consistency: Consistency::LocalQuorum,
            serial_consistency: SerialConsistency::LocalSerial,
            replay_page_size: DEFAULT_REPLAY_PAGE_SIZE,
            polling: CassandraPollingConfig::default(),
            write_mode: CassandraWriteMode::default(),
        }
    }
}

/// Unified Cassandra journal, snapshot, durable-state, and query provider.
pub struct CassandraPersistence {
    config: CassandraPersistenceConfig,
    schema: CassandraSchema,
    connected: OnceCell<Arc<ConnectedCassandra>>,
}

impl fmt::Debug for CassandraPersistence {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CassandraPersistence")
            .field("config", &self.config)
            .field("connected", &self.connected.get().is_some())
            .finish_non_exhaustive()
    }
}

impl CassandraPersistence {
    /// Validates and creates a side-effect-free Cassandra backend blueprint.
    pub fn new(config: CassandraPersistenceConfig) -> PersistenceResult<Self> {
        validate_config(&config)?;
        let schema = CassandraSchema::new(&config);
        Ok(Self {
            config,
            schema,
            connected: OnceCell::new(),
        })
    }

    /// Connects to the cluster, bootstraps the schema, and prepares statements.
    pub async fn connect(config: CassandraPersistenceConfig) -> PersistenceResult<Self> {
        let backend = Self::new(config)?;
        backend.initialize().await?;
        Ok(backend)
    }

    /// Connects and initializes a blueprint created with [`Self::new`].
    ///
    /// Concurrent calls share the initialization attempt. A failed attempt is
    /// not cached and may be retried.
    pub async fn initialize(&self) -> PersistenceResult<()> {
        self.connected
            .get_or_try_init(|| connect_cassandra(&self.config, &self.schema))
            .await
            .map(|_| ())
    }

    /// Returns the immutable backend configuration.
    #[must_use]
    pub fn config(&self) -> &CassandraPersistenceConfig {
        &self.config
    }

    /// Returns the exact idempotent CQL emitted during schema bootstrap.
    #[must_use]
    pub fn schema_ddl(&self) -> String {
        let mut ddl = self.schema.ddl.join(";\n");
        ddl.push(';');
        ddl
    }

    async fn ready(&self) -> PersistenceResult<Arc<ConnectedCassandra>> {
        self.initialize().await?;
        self.connected.get().cloned().ok_or_else(|| {
            PersistenceError::Connection(
                "Cassandra session unavailable after successful initialization".into(),
            )
        })
    }

    async fn append_write(&self, write: AtomicWrite) -> PersistenceResult<AppendOutcome> {
        let prepared = match PreparedAtomicWrite::new(write, self.config.partition_size) {
            Ok(prepared) => prepared,
            Err(reason) => return Ok(AppendOutcome::Rejected { reason }),
        };
        let connected = self.ready().await?;
        let reconciled = read_reconciled_head(
            &connected,
            &prepared.persistence_id,
            self.config.partition_size,
        )
        .await?;
        let head = repair_reconciled_head(
            &connected,
            &prepared.persistence_id,
            reconciled,
            self.config.write_mode,
            "repair Cassandra journal head before append",
        )
        .await?;
        let expected = head
            .highest_seq_nr
            .checked_add(1)
            .ok_or_else(|| PersistenceError::Failure("Cassandra journal head exhausted".into()))?;
        if prepared.first_sequence_nr != expected {
            return Ok(AppendOutcome::Rejected {
                reason: format!(
                    "expected first sequence number {expected} after journal head {}, got {}",
                    head.highest_seq_nr, prepared.first_sequence_nr
                ),
            });
        }

        let mut batch = Batch::new(BatchType::Unlogged);
        batch.set_consistency(self.config.write_consistency);
        for _ in &prepared.events {
            batch.append_statement(connected.statements.insert_event.clone());
        }
        for _ in &prepared.tag_events {
            batch.append_statement(connected.statements.insert_tag_event.clone());
        }
        let mut values = Vec::with_capacity(prepared.events.len() + prepared.tag_events.len());
        values.extend(prepared.events.into_iter().map(JournalBatchValues::Event));
        values.extend(prepared.tag_events.into_iter().map(JournalBatchValues::Tag));
        connected
            .session
            .batch(&batch, values)
            .await
            .map_err(|error| storage_error("execute atomic Cassandra journal batch", error))?;

        transition_head(
            &connected,
            &prepared.persistence_id,
            head,
            prepared.last_sequence_nr,
            head.logical_deleted_to(),
            self.config.write_mode,
            "advance Cassandra journal head after append",
        )
        .await?;
        Ok(AppendOutcome::Accepted)
    }

    async fn revision_conflict(
        &self,
        persistence_id: &PersistenceId,
        actual: Revision,
    ) -> PersistenceError {
        match self.current_revision(persistence_id).await {
            Ok(stored) if stored.as_u64() == i64::MAX as u64 => {
                PersistenceError::RevisionExhausted {
                    persistence_id: persistence_id.clone(),
                }
            }
            Ok(stored) => match stored.as_u64().checked_add(1) {
                Some(expected) => PersistenceError::RevisionConflict {
                    persistence_id: persistence_id.clone(),
                    expected: Revision::new(expected),
                    actual,
                },
                None => PersistenceError::RevisionExhausted {
                    persistence_id: persistence_id.clone(),
                },
            },
            Err(error) => error,
        }
    }

    async fn current_revision(
        &self,
        persistence_id: &PersistenceId,
    ) -> PersistenceResult<Revision> {
        Ok(self.get(persistence_id).await?.revision)
    }
}

#[async_trait::async_trait]
impl Journal for CassandraPersistence {
    async fn append(&self, writes: Vec<AtomicWrite>) -> PersistenceResult<Vec<AppendOutcome>> {
        let mut outcomes = Vec::with_capacity(writes.len());
        for write in writes {
            outcomes.push(self.append_write(write).await?);
        }
        Ok(outcomes)
    }

    async fn append_one(&self, write: AtomicWrite) -> PersistenceResult<AppendOutcome> {
        self.append_write(write).await
    }

    async fn highest_sequence_nr(
        &self,
        persistence_id: &PersistenceId,
        _from_hint: SequenceNr,
    ) -> PersistenceResult<SequenceNr> {
        let connected = self.ready().await?;
        let head =
            read_reconciled_head(&connected, persistence_id, self.config.partition_size).await?;
        Ok(SequenceNr::new(non_negative_u64(
            head.highest_seq_nr,
            "Cassandra journal head",
        )?))
    }

    async fn replay(&self, range: ReplayRange) -> PersistenceResult<EventStream> {
        if range.from > range.to || range.max == 0 || range.from.as_u64() > i64::MAX as u64 {
            return Ok(Box::pin(stream::empty()));
        }
        let connected = self.ready().await?;
        let head = read_reconciled_head(
            &connected,
            &range.persistence_id,
            self.config.partition_size,
        )
        .await?;
        let highest = SequenceNr::new(non_negative_u64(
            head.highest_seq_nr,
            "Cassandra replay journal head",
        )?);
        let to = range.to.min(highest);
        if range.from > to {
            return Ok(Box::pin(stream::empty()));
        }
        Ok(cassandra_event_stream(
            connected,
            range.persistence_id,
            range.from,
            to,
            range.max,
            head.logical_deleted_to(),
            self.config.partition_size,
        ))
    }

    async fn delete_to(
        &self,
        persistence_id: &PersistenceId,
        inclusive: SequenceNr,
    ) -> PersistenceResult<()> {
        let connected = self.ready().await?;
        let reconciled =
            read_reconciled_head(&connected, persistence_id, self.config.partition_size).await?;
        let head = repair_reconciled_head(
            &connected,
            persistence_id,
            reconciled,
            self.config.write_mode,
            "repair Cassandra journal head before delete",
        )
        .await?;
        if head.highest_seq_nr == 0 {
            return Ok(());
        }
        let inclusive = i64::try_from(inclusive.as_u64()).unwrap_or(i64::MAX);
        let effective = inclusive.min(head.highest_seq_nr);
        if effective <= head.logical_deleted_to() {
            return Ok(());
        }

        let first_partition = partition_nr(
            u64::try_from(head.logical_deleted_to().saturating_add(1)).unwrap_or_default(),
            self.config.partition_size,
        );
        let last_partition = partition_nr(
            u64::try_from(effective).expect("positive Cassandra sequence fits u64"),
            self.config.partition_size,
        );
        for partition in first_partition..=last_partition {
            connected
                .session
                .execute_unpaged(
                    &connected.statements.delete_event_range,
                    (persistence_id.id(), partition, effective),
                )
                .await
                .map_err(|error| {
                    storage_error("delete Cassandra journal partition range", error)
                })?;
        }

        transition_head(
            &connected,
            persistence_id,
            head,
            head.highest_seq_nr,
            effective,
            self.config.write_mode,
            "advance Cassandra journal deletion marker",
        )
        .await?;
        Ok(())
    }
}

#[async_trait::async_trait]
impl SnapshotStore for CassandraPersistence {
    async fn load(
        &self,
        persistence_id: &PersistenceId,
        criteria: &SnapshotCriteria,
    ) -> PersistenceResult<Option<SelectedSnapshot>> {
        let Some((min_sequence_nr, max_sequence_nr)) = snapshot_sequence_bounds(criteria) else {
            return Ok(None);
        };
        if criteria.min_timestamp_ms > criteria.max_timestamp_ms {
            return Ok(None);
        }
        let connected = self.ready().await?;
        let result = connected
            .session
            .execute_unpaged(
                &connected.statements.load_snapshot,
                (
                    persistence_id.id(),
                    min_sequence_nr,
                    max_sequence_nr,
                    criteria.min_timestamp_ms,
                    criteria.max_timestamp_ms,
                ),
            )
            .await
            .map_err(|error| storage_error("load Cassandra snapshot", error))?;
        let rows = result
            .into_rows_result()
            .map_err(|error| storage_error("decode Cassandra snapshot result", error))?;
        let row = rows
            .maybe_first_row::<SnapshotRow>()
            .map_err(|error| storage_error("decode Cassandra snapshot row", error))?;
        row.map(|row| decode_snapshot(persistence_id, row))
            .transpose()
    }

    async fn save(
        &self,
        metadata: SnapshotMetadata,
        adapter_manifest: String,
        state: SerializedPayload,
    ) -> PersistenceResult<()> {
        let sequence_nr = sql_i64(metadata.sequence_nr.as_u64(), "snapshot sequence number")?;
        let connected = self.ready().await?;
        connected
            .session
            .execute_unpaged(
                &connected.statements.save_snapshot,
                (
                    metadata.persistence_id.id(),
                    sequence_nr,
                    metadata.timestamp_ms,
                    adapter_manifest,
                    i64::from(state.serializer_id.as_u32()),
                    state.manifest,
                    state.payload,
                ),
            )
            .await
            .map_err(|error| storage_error("save Cassandra snapshot", error))?;
        Ok(())
    }

    async fn delete(&self, metadata: SnapshotMetadata) -> PersistenceResult<()> {
        let Ok(sequence_nr) = i64::try_from(metadata.sequence_nr.as_u64()) else {
            return Ok(());
        };
        let connected = self.ready().await?;
        connected
            .session
            .execute_unpaged(
                &connected.statements.delete_snapshot_exact,
                (
                    metadata.persistence_id.id(),
                    sequence_nr,
                    metadata.timestamp_ms,
                ),
            )
            .await
            .map_err(|error| storage_error("delete exact Cassandra snapshot", error))?;
        Ok(())
    }

    async fn delete_matching(
        &self,
        persistence_id: &PersistenceId,
        criteria: &SnapshotCriteria,
    ) -> PersistenceResult<()> {
        let Some((min_sequence_nr, max_sequence_nr)) = snapshot_sequence_bounds(criteria) else {
            return Ok(());
        };
        if criteria.min_timestamp_ms > criteria.max_timestamp_ms {
            return Ok(());
        }
        let connected = self.ready().await?;
        let pager = connected
            .session
            .execute_iter(
                connected.statements.select_matching_snapshots.clone(),
                (
                    persistence_id.id(),
                    min_sequence_nr,
                    max_sequence_nr,
                    criteria.min_timestamp_ms,
                    criteria.max_timestamp_ms,
                ),
            )
            .await
            .map_err(|error| storage_error("select matching Cassandra snapshots", error))?;
        let mut rows = pager
            .rows_stream::<SnapshotMetadataRow>()
            .map_err(|error| storage_error("decode matching Cassandra snapshots", error))?;
        while let Some(row) = rows.next().await {
            let row = row
                .map_err(|error| storage_error("decode matching Cassandra snapshot row", error))?;
            connected
                .session
                .execute_unpaged(
                    &connected.statements.delete_snapshot_exact,
                    (persistence_id.id(), row.sequence_nr, row.timestamp_ms),
                )
                .await
                .map_err(|error| storage_error("delete matching Cassandra snapshot", error))?;
        }
        Ok(())
    }
}

#[async_trait::async_trait]
impl DurableStateStore for CassandraPersistence {
    async fn get(&self, persistence_id: &PersistenceId) -> PersistenceResult<VersionedState> {
        let connected = self.ready().await?;
        let result = connected
            .session
            .execute_unpaged(
                &connected.statements.get_durable_state,
                (persistence_id.id(),),
            )
            .await
            .map_err(|error| storage_error("get Cassandra durable state", error))?;
        let rows = result
            .into_rows_result()
            .map_err(|error| storage_error("decode Cassandra durable-state result", error))?;
        rows.maybe_first_row::<DurableStateRow>()
            .map_err(|error| storage_error("decode Cassandra durable-state row", error))?
            .map_or(Ok(VersionedState::default()), decode_durable_state)
    }

    async fn upsert(
        &self,
        persistence_id: &PersistenceId,
        new_revision: Revision,
        state: SerializedPayload,
        tag: Option<Tag>,
    ) -> PersistenceResult<()> {
        let Ok(revision) = i64::try_from(new_revision.as_u64()) else {
            return Err(self.revision_conflict(persistence_id, new_revision).await);
        };
        if revision == 0 {
            return Err(self.revision_conflict(persistence_id, new_revision).await);
        }
        let connected = self.ready().await?;
        // Read the previous tag before the CAS so a retag (or an untag) can
        // clean up the stale `durable_state_changes` row it would otherwise
        // leave behind (see the module documentation). `revision == 1` means
        // there is no previous row at all, so there is nothing to read or
        // clean up. The read costs nothing extra in spirit: the CAS below
        // reads this same row internally to evaluate its condition.
        let previous_tag = if revision > 1 {
            read_raw_durable_tag(&connected, persistence_id).await?
        } else {
            None
        };
        let change_state = tag.as_ref().map(|_| state.clone());
        let result = if revision == 1 {
            connected
                .session
                .execute_unpaged(
                    &connected.statements.insert_durable_state,
                    (
                        persistence_id.id(),
                        revision,
                        i64::from(state.serializer_id.as_u32()),
                        state.manifest,
                        state.payload,
                        tag.as_ref().map(Tag::as_str),
                    ),
                )
                .await
        } else {
            connected
                .session
                .execute_unpaged(
                    &connected.statements.update_durable_state,
                    (
                        revision,
                        i64::from(state.serializer_id.as_u32()),
                        state.manifest,
                        state.payload,
                        tag.as_ref().map(Tag::as_str),
                        persistence_id.id(),
                        revision - 1,
                    ),
                )
                .await
        }
        .map_err(|error| storage_error("upsert Cassandra durable state with LWT", error))?;
        if !lwt_applied(result)? {
            return Err(self.revision_conflict(persistence_id, new_revision).await);
        }
        // The id moved to a different tag (or lost its tag entirely): the
        // previous tag's `durable_state_changes` row is now stale — nothing
        // will ever overwrite or remove it otherwise — so remove it. This is
        // a plain delete, not a `Deleted` tombstone: the id did not stop
        // existing, it just stopped living under the previous tag, matching
        // the in-memory backend's retag semantics.
        if let Some(old_tag) = &previous_tag
            && Some(old_tag) != tag.as_ref()
        {
            remove_durable_state_change(&connected, old_tag, persistence_id).await?;
        }
        if let (Some(tag), Some(change_state)) = (tag, change_state) {
            write_durable_state_upsert_change(
                &connected,
                &tag,
                persistence_id,
                new_revision,
                change_state,
            )
            .await?;
        }
        Ok(())
    }

    async fn delete(
        &self,
        persistence_id: &PersistenceId,
        new_revision: Revision,
    ) -> PersistenceResult<()> {
        let Ok(revision) = i64::try_from(new_revision.as_u64()) else {
            return Err(self.revision_conflict(persistence_id, new_revision).await);
        };
        if revision == 0 {
            return Err(self.revision_conflict(persistence_id, new_revision).await);
        }
        let connected = self.ready().await?;
        let result = if revision == 1 {
            connected
                .session
                .execute_unpaged(
                    &connected.statements.insert_durable_tombstone,
                    (persistence_id.id(), revision),
                )
                .await
        } else {
            connected
                .session
                .execute_unpaged(
                    &connected.statements.update_durable_tombstone,
                    (revision, persistence_id.id(), revision - 1),
                )
                .await
        }
        .map_err(|error| storage_error("delete Cassandra durable state with LWT", error))?;
        if !lwt_applied(result)? {
            return Err(self.revision_conflict(persistence_id, new_revision).await);
        }
        if let Some(tag) = read_raw_durable_tag(&connected, persistence_id).await? {
            write_durable_state_delete_change(&connected, &tag, persistence_id, new_revision)
                .await?;
        }
        Ok(())
    }
}

#[async_trait::async_trait]
impl EventsByPersistenceIdQuery for CassandraPersistence {
    async fn events_by_persistence_id(
        &self,
        persistence_id: &PersistenceId,
        from_sequence_nr: SequenceNr,
        to_sequence_nr: SequenceNr,
        mode: QueryMode,
    ) -> PersistenceResult<QueryStream<EventEnvelope>> {
        if from_sequence_nr > to_sequence_nr || from_sequence_nr.as_u64() > i64::MAX as u64 {
            return Ok(Box::pin(stream::empty()));
        }
        let connected = self.ready().await?;
        let head =
            read_reconciled_head(&connected, persistence_id, self.config.partition_size).await?;
        let highest = SequenceNr::new(non_negative_u64(
            head.highest_seq_nr,
            "Cassandra query journal head",
        )?);
        let boundary = highest.min(to_sequence_nr);
        let initial = (from_sequence_nr <= boundary).then(|| {
            cassandra_event_stream(
                connected.clone(),
                persistence_id.clone(),
                from_sequence_nr,
                boundary,
                u64::MAX,
                head.logical_deleted_to(),
                self.config.partition_size,
            )
        });
        if mode == QueryMode::Current {
            return Ok(initial.map_or_else(
                || Box::pin(stream::empty()) as QueryStream<EventEnvelope>,
                |events| Box::pin(events.map(|event| event.map(event_envelope))),
            ));
        }

        let after_highest = highest.as_u64().checked_add(1).map(SequenceNr::new);
        let next_sequence_nr = after_highest.map(|next| next.max(from_sequence_nr));
        let cursor = CassandraLiveCursor {
            connected,
            persistence_id: persistence_id.clone(),
            initial,
            next_sequence_nr,
            to_sequence_nr,
            reached_end: highest >= to_sequence_nr,
            partition_size: self.config.partition_size,
            polling: self.config.polling.clone(),
            delay: self.config.polling.min_interval,
            buffered: VecDeque::new(),
        };
        Ok(Box::pin(stream::unfold(cursor, next_cassandra_live_event)))
    }
}

#[async_trait::async_trait]
impl PersistenceIdsQuery for CassandraPersistence {
    async fn persistence_ids(
        &self,
        mode: QueryMode,
    ) -> PersistenceResult<QueryStream<PersistenceId>> {
        if mode == QueryMode::Live {
            return Err(PersistenceError::Rejected(
                "Cassandra live persistence-id discovery is unsupported; use QueryMode::Current"
                    .into(),
            ));
        }
        let connected = self.ready().await?;
        let result = connected
            .session
            .execute_unpaged(&connected.statements.select_persistence_ids, ())
            .await
            .map_err(|error| storage_error("query Cassandra persistence ids", error))?;
        let rows = result
            .into_rows_result()
            .map_err(|error| storage_error("decode Cassandra persistence ids", error))?;
        let persistence_ids = rows
            .rows::<PersistenceIdRow>()
            .map_err(|error| storage_error("decode Cassandra persistence-id rows", error))?
            .map(|row| {
                row.map_err(|error| storage_error("decode Cassandra persistence-id row", error))
                    .and_then(|row| PersistenceId::from_unique(row.persistence_id))
            })
            .collect::<Vec<_>>();
        Ok(Box::pin(stream::iter(persistence_ids)))
    }
}

#[async_trait::async_trait]
impl EventsByTagQuery for CassandraPersistence {
    async fn events_by_tag(
        &self,
        tag: &Tag,
        offset: Offset,
        mode: QueryMode,
    ) -> PersistenceResult<QueryStream<EventEnvelope>> {
        let resume = cassandra_tag_resume(offset)?;
        let connected = self.ready().await?;
        let events = cassandra_events_by_tag(&connected, tag, &resume, None).await?;
        if mode == QueryMode::Current {
            return Ok(Box::pin(stream::iter(events.into_iter().map(Ok))));
        }
        let resume = events
            .last()
            .map(cassandra_tag_resume_after)
            .unwrap_or(resume);
        let cursor = CassandraTagCursor {
            connected,
            tag: tag.clone(),
            resume,
            buffered: VecDeque::from(events),
            polling: self.config.polling.clone(),
            delay: self.config.polling.min_interval,
        };
        Ok(Box::pin(stream::unfold(cursor, next_cassandra_tag_event)))
    }
}

#[async_trait::async_trait]
impl DurableStateChangesQuery for CassandraPersistence {
    async fn changes(
        &self,
        tag: &Tag,
        offset: Offset,
        mode: QueryMode,
    ) -> PersistenceResult<QueryStream<DurableStateChange>> {
        let since_timestamp_ms = cassandra_change_since_timestamp_ms(offset)?;
        let connected = self.ready().await?;
        // Captured *before* the coalesced-table read below so that anything
        // committed while (or after) that read executes is guaranteed to
        // have a `durable_state_change_log` timestamp at or after this value
        // — the subsequent `Live` poll resumes here, inclusive, so a write
        // racing the bootstrap read is re-delivered rather than lost.
        let bootstrap_timestamp_ms = current_timestamp_ms();
        let changes =
            cassandra_current_durable_state_changes(&connected, tag, since_timestamp_ms).await?;
        if mode == QueryMode::Current {
            return Ok(Box::pin(stream::iter(changes.into_iter().map(Ok))));
        }
        let cursor = CassandraDurableChangeLogCursor {
            connected,
            tag: tag.clone(),
            resume: CassandraDurableChangeLogResume::Inclusive {
                timestamp_ms: bootstrap_timestamp_ms,
                revision: i64::MIN,
            },
            buffered: VecDeque::from(changes),
            polling: self.config.polling.clone(),
            delay: self.config.polling.min_interval,
        };
        Ok(Box::pin(stream::unfold(
            cursor,
            next_cassandra_durable_change_log,
        )))
    }
}

#[derive(Debug)]
struct ConnectedCassandra {
    session: Arc<Session>,
    statements: CassandraStatements,
}

#[derive(Debug)]
struct CassandraStatements {
    insert_event: PreparedStatement,
    select_head: PreparedStatement,
    select_partition_highest: PreparedStatement,
    insert_head: PreparedStatement,
    update_head: PreparedStatement,
    insert_head_plain: PreparedStatement,
    update_head_plain: PreparedStatement,
    replay_partition: PreparedStatement,
    delete_event_range: PreparedStatement,
    load_snapshot: PreparedStatement,
    save_snapshot: PreparedStatement,
    delete_snapshot_exact: PreparedStatement,
    select_matching_snapshots: PreparedStatement,
    get_durable_state: PreparedStatement,
    insert_durable_state: PreparedStatement,
    update_durable_state: PreparedStatement,
    insert_durable_tombstone: PreparedStatement,
    update_durable_tombstone: PreparedStatement,
    select_persistence_ids: PreparedStatement,
    insert_tag_event: PreparedStatement,
    select_tag_events_all: PreparedStatement,
    select_tag_events_inclusive: PreparedStatement,
    select_tag_events_after: PreparedStatement,
    upsert_durable_state_change: PreparedStatement,
    delete_durable_state_change: PreparedStatement,
    remove_durable_state_change: PreparedStatement,
    select_durable_state_changes: PreparedStatement,
    insert_durable_state_change_log: PreparedStatement,
    select_durable_state_change_log_inclusive: PreparedStatement,
    select_durable_state_change_log_after: PreparedStatement,
}

#[derive(Debug)]
struct CassandraSchema {
    event_journal: String,
    journal_head: String,
    snapshot: String,
    durable_state: String,
    tag_events: String,
    durable_state_changes: String,
    durable_state_change_log: String,
    ddl: Vec<String>,
}

impl CassandraSchema {
    fn new(config: &CassandraPersistenceConfig) -> Self {
        let event_journal = qualified(&config.keyspace, &config.tables.event_journal);
        let journal_head = qualified(&config.keyspace, &config.tables.journal_head);
        let snapshot = qualified(&config.keyspace, &config.tables.snapshot);
        let durable_state = qualified(&config.keyspace, &config.tables.durable_state);
        let tag_events = qualified(&config.keyspace, &config.tables.tag_events);
        let durable_state_changes =
            qualified(&config.keyspace, &config.tables.durable_state_changes);
        let durable_state_change_log =
            qualified(&config.keyspace, &config.tables.durable_state_change_log);
        let ddl = vec![
            format!(
                "CREATE KEYSPACE IF NOT EXISTS {} WITH replication = {{'class': \
                 'SimpleStrategy', 'replication_factor': {}}} AND durable_writes = true",
                config.keyspace, config.replication_factor
            ),
            format!(
                "CREATE TABLE IF NOT EXISTS {event_journal} (\
                 persistence_id text, partition_nr bigint, sequence_nr bigint, writer text, \
                 adapter_manifest text, ser_id bigint, ser_manifest text, payload blob, \
                 meta_ser_id bigint, meta_manifest text, meta_payload blob, tags set<text>, \
                 timestamp_ms bigint, PRIMARY KEY ((persistence_id, partition_nr), sequence_nr)) \
                 WITH CLUSTERING ORDER BY (sequence_nr ASC)"
            ),
            format!(
                "CREATE TABLE IF NOT EXISTS {journal_head} (persistence_id text PRIMARY KEY, \
                 highest_seq_nr bigint, deleted_to bigint)"
            ),
            format!(
                "CREATE TABLE IF NOT EXISTS {snapshot} (persistence_id text, sequence_nr bigint, \
                 timestamp_ms bigint, adapter_manifest text, ser_id bigint, ser_manifest text, \
                 payload blob, PRIMARY KEY (persistence_id, sequence_nr)) \
                 WITH CLUSTERING ORDER BY (sequence_nr DESC)"
            ),
            format!(
                "CREATE TABLE IF NOT EXISTS {durable_state} (persistence_id text PRIMARY KEY, \
                 revision bigint, ser_id bigint, ser_manifest text, payload blob, tag text)"
            ),
            format!(
                "CREATE TABLE IF NOT EXISTS {tag_events} (\
                 tag text, timestamp_ms bigint, sequence_nr bigint, persistence_id text, \
                 writer text, adapter_manifest text, ser_id bigint, ser_manifest text, \
                 payload blob, meta_ser_id bigint, meta_manifest text, meta_payload blob, \
                 tags set<text>, \
                 PRIMARY KEY (tag, timestamp_ms, sequence_nr, persistence_id)) \
                 WITH CLUSTERING ORDER BY (timestamp_ms ASC, sequence_nr ASC, persistence_id ASC)"
            ),
            format!(
                "CREATE TABLE IF NOT EXISTS {durable_state_changes} (\
                 tag text, persistence_id text, revision bigint, timestamp_ms bigint, \
                 ser_id bigint, ser_manifest text, payload blob, deleted boolean, \
                 PRIMARY KEY (tag, persistence_id))"
            ),
            format!(
                "CREATE TABLE IF NOT EXISTS {durable_state_change_log} (\
                 tag text, timestamp_ms bigint, revision bigint, persistence_id text, \
                 ser_id bigint, ser_manifest text, payload blob, deleted boolean, \
                 PRIMARY KEY (tag, timestamp_ms, revision, persistence_id)) \
                 WITH CLUSTERING ORDER BY (timestamp_ms ASC, revision ASC, persistence_id ASC)"
            ),
        ];
        Self {
            event_journal,
            journal_head,
            snapshot,
            durable_state,
            tag_events,
            durable_state_changes,
            durable_state_change_log,
            ddl,
        }
    }
}

async fn connect_cassandra(
    config: &CassandraPersistenceConfig,
    schema: &CassandraSchema,
) -> PersistenceResult<Arc<ConnectedCassandra>> {
    let session = SessionBuilder::new()
        .known_nodes(config.contact_points.iter().map(String::as_str))
        .build()
        .await
        .map_err(|error| connection_error("connect Cassandra session", error))?;
    let session = Arc::new(session);
    for ddl in &schema.ddl {
        session
            .query_unpaged(ddl.as_str(), ())
            .await
            .map_err(|error| storage_error("execute Cassandra schema bootstrap", error))?;
    }
    let statements = prepare_statements(&session, config, schema).await?;
    Ok(Arc::new(ConnectedCassandra {
        session,
        statements,
    }))
}

async fn prepare_statements(
    session: &Session,
    config: &CassandraPersistenceConfig,
    schema: &CassandraSchema,
) -> PersistenceResult<CassandraStatements> {
    let insert_event = prepare(
        session,
        format!(
            "INSERT INTO {} (persistence_id, partition_nr, sequence_nr, writer, \
             adapter_manifest, ser_id, ser_manifest, payload, meta_ser_id, meta_manifest, \
             meta_payload, tags, timestamp_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
            schema.event_journal
        ),
        config.write_consistency,
        None,
        None,
    )
    .await?;
    let select_head = prepare(
        session,
        format!(
            "SELECT highest_seq_nr, deleted_to FROM {} WHERE persistence_id = ?",
            schema.journal_head
        ),
        config.read_consistency,
        None,
        None,
    )
    .await?;
    let select_partition_highest = prepare(
        session,
        format!(
            "SELECT sequence_nr FROM {} WHERE persistence_id = ? AND partition_nr = ? \
             AND sequence_nr > ? ORDER BY sequence_nr DESC LIMIT 1",
            schema.event_journal
        ),
        config.read_consistency,
        None,
        None,
    )
    .await?;
    let insert_head = prepare(
        session,
        format!(
            "INSERT INTO {} (persistence_id, highest_seq_nr, deleted_to) VALUES (?, ?, ?) \
             IF NOT EXISTS",
            schema.journal_head
        ),
        config.write_consistency,
        None,
        Some(config.serial_consistency),
    )
    .await?;
    let update_head = prepare(
        session,
        format!(
            "UPDATE {} SET highest_seq_nr = ?, deleted_to = ? WHERE persistence_id = ? \
             IF highest_seq_nr = ? AND deleted_to = ?",
            schema.journal_head
        ),
        config.write_consistency,
        None,
        Some(config.serial_consistency),
    )
    .await?;
    let replay_partition = prepare(
        session,
        format!(
            "SELECT sequence_nr, writer, adapter_manifest, ser_id, ser_manifest, payload, \
             meta_ser_id, meta_manifest, meta_payload, tags, timestamp_ms FROM {} \
             WHERE persistence_id = ? AND partition_nr = ? \
             AND sequence_nr >= ? AND sequence_nr <= ?",
            schema.event_journal
        ),
        config.read_consistency,
        Some(config.replay_page_size),
        None,
    )
    .await?;
    let delete_event_range = prepare(
        session,
        format!(
            "DELETE FROM {} WHERE persistence_id = ? AND partition_nr = ? \
             AND sequence_nr <= ?",
            schema.event_journal
        ),
        config.write_consistency,
        None,
        None,
    )
    .await?;
    let load_snapshot = prepare(
        session,
        format!(
            "SELECT sequence_nr, timestamp_ms, adapter_manifest, ser_id, ser_manifest, payload \
             FROM {} WHERE persistence_id = ? AND sequence_nr >= ? AND sequence_nr <= ? \
             AND timestamp_ms >= ? AND timestamp_ms <= ? LIMIT 1 ALLOW FILTERING",
            schema.snapshot
        ),
        config.read_consistency,
        None,
        None,
    )
    .await?;
    let save_snapshot = prepare(
        session,
        format!(
            "INSERT INTO {} (persistence_id, sequence_nr, timestamp_ms, adapter_manifest, \
             ser_id, ser_manifest, payload) VALUES (?, ?, ?, ?, ?, ?, ?)",
            schema.snapshot
        ),
        config.write_consistency,
        None,
        None,
    )
    .await?;
    let delete_snapshot_exact = prepare(
        session,
        format!(
            "DELETE FROM {} WHERE persistence_id = ? AND sequence_nr = ? IF timestamp_ms = ?",
            schema.snapshot
        ),
        config.write_consistency,
        None,
        Some(config.serial_consistency),
    )
    .await?;
    let select_matching_snapshots = prepare(
        session,
        format!(
            "SELECT sequence_nr, timestamp_ms FROM {} WHERE persistence_id = ? \
             AND sequence_nr >= ? AND sequence_nr <= ? AND timestamp_ms >= ? \
             AND timestamp_ms <= ? ALLOW FILTERING",
            schema.snapshot
        ),
        config.read_consistency,
        Some(config.replay_page_size),
        None,
    )
    .await?;
    let get_durable_state = prepare(
        session,
        format!(
            "SELECT revision, ser_id, ser_manifest, payload, tag FROM {} WHERE persistence_id = ?",
            schema.durable_state
        ),
        config.read_consistency,
        None,
        None,
    )
    .await?;
    let insert_durable_state = prepare(
        session,
        format!(
            "INSERT INTO {} (persistence_id, revision, ser_id, ser_manifest, payload, tag) \
             VALUES (?, ?, ?, ?, ?, ?) IF NOT EXISTS",
            schema.durable_state
        ),
        config.write_consistency,
        None,
        Some(config.serial_consistency),
    )
    .await?;
    let update_durable_state = prepare(
        session,
        format!(
            "UPDATE {} SET revision = ?, ser_id = ?, ser_manifest = ?, payload = ?, tag = ? \
             WHERE persistence_id = ? IF revision = ?",
            schema.durable_state
        ),
        config.write_consistency,
        None,
        Some(config.serial_consistency),
    )
    .await?;
    let insert_durable_tombstone = prepare(
        session,
        format!(
            "INSERT INTO {} (persistence_id, revision) VALUES (?, ?) IF NOT EXISTS",
            schema.durable_state
        ),
        config.write_consistency,
        None,
        Some(config.serial_consistency),
    )
    .await?;
    let update_durable_tombstone = prepare(
        session,
        format!(
            // `tag` is deliberately left unset (not nulled) so the durable-state
            // change index can still route this tombstone under its previous
            // tag; `get`/`decode_durable_state` force the *observable* tag to
            // `None` on a tombstone regardless of this preserved column.
            "UPDATE {} SET revision = ?, ser_id = null, ser_manifest = null, payload = null \
             WHERE persistence_id = ? IF revision = ?",
            schema.durable_state
        ),
        config.write_consistency,
        None,
        Some(config.serial_consistency),
    )
    .await?;
    let select_persistence_ids = prepare(
        session,
        format!(
            "SELECT DISTINCT persistence_id FROM {}",
            schema.journal_head
        ),
        config.read_consistency,
        Some(config.replay_page_size),
        None,
    )
    .await?;
    let insert_head_plain = prepare(
        session,
        format!(
            "INSERT INTO {} (persistence_id, highest_seq_nr, deleted_to) VALUES (?, ?, ?)",
            schema.journal_head
        ),
        config.write_consistency,
        None,
        None,
    )
    .await?;
    let update_head_plain = prepare(
        session,
        format!(
            "UPDATE {} SET highest_seq_nr = ?, deleted_to = ? WHERE persistence_id = ?",
            schema.journal_head
        ),
        config.write_consistency,
        None,
        None,
    )
    .await?;
    let insert_tag_event = prepare(
        session,
        format!(
            "INSERT INTO {} (tag, timestamp_ms, sequence_nr, persistence_id, writer, \
             adapter_manifest, ser_id, ser_manifest, payload, meta_ser_id, meta_manifest, \
             meta_payload, tags) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
            schema.tag_events
        ),
        config.write_consistency,
        None,
        None,
    )
    .await?;
    let tag_event_columns = "timestamp_ms, sequence_nr, persistence_id, writer, \
         adapter_manifest, ser_id, ser_manifest, payload, meta_ser_id, meta_manifest, \
         meta_payload, tags";
    let select_tag_events_all = prepare(
        session,
        format!(
            "SELECT {tag_event_columns} FROM {} WHERE tag = ?",
            schema.tag_events
        ),
        config.read_consistency,
        Some(config.replay_page_size),
        None,
    )
    .await?;
    let select_tag_events_inclusive = prepare(
        session,
        format!(
            "SELECT {tag_event_columns} FROM {} WHERE tag = ? \
             AND (timestamp_ms, sequence_nr) >= (?, ?)",
            schema.tag_events
        ),
        config.read_consistency,
        Some(config.replay_page_size),
        None,
    )
    .await?;
    let select_tag_events_after = prepare(
        session,
        format!(
            "SELECT {tag_event_columns} FROM {} WHERE tag = ? \
             AND (timestamp_ms, sequence_nr, persistence_id) > (?, ?, ?)",
            schema.tag_events
        ),
        config.read_consistency,
        Some(config.replay_page_size),
        None,
    )
    .await?;
    let upsert_durable_state_change = prepare(
        session,
        format!(
            "UPDATE {} SET revision = ?, timestamp_ms = ?, ser_id = ?, ser_manifest = ?, \
             payload = ?, deleted = false WHERE tag = ? AND persistence_id = ?",
            schema.durable_state_changes
        ),
        config.write_consistency,
        None,
        None,
    )
    .await?;
    let delete_durable_state_change = prepare(
        session,
        format!(
            "UPDATE {} SET revision = ?, timestamp_ms = ?, ser_id = null, ser_manifest = null, \
             payload = null, deleted = true WHERE tag = ? AND persistence_id = ?",
            schema.durable_state_changes
        ),
        config.write_consistency,
        None,
        None,
    )
    .await?;
    let remove_durable_state_change = prepare(
        session,
        format!(
            "DELETE FROM {} WHERE tag = ? AND persistence_id = ?",
            schema.durable_state_changes
        ),
        config.write_consistency,
        None,
        None,
    )
    .await?;
    let select_durable_state_changes = prepare(
        session,
        format!(
            "SELECT persistence_id, revision, timestamp_ms, ser_id, ser_manifest, payload, \
             deleted FROM {} WHERE tag = ? AND timestamp_ms >= ? ALLOW FILTERING",
            schema.durable_state_changes
        ),
        config.read_consistency,
        Some(config.replay_page_size),
        None,
    )
    .await?;
    let insert_durable_state_change_log = prepare(
        session,
        format!(
            "INSERT INTO {} (tag, timestamp_ms, revision, persistence_id, ser_id, \
             ser_manifest, payload, deleted) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
            schema.durable_state_change_log
        ),
        config.write_consistency,
        None,
        None,
    )
    .await?;
    let durable_state_change_log_columns =
        "persistence_id, revision, timestamp_ms, ser_id, ser_manifest, payload, deleted";
    let select_durable_state_change_log_inclusive = prepare(
        session,
        format!(
            "SELECT {durable_state_change_log_columns} FROM {} WHERE tag = ? \
             AND (timestamp_ms, revision) >= (?, ?)",
            schema.durable_state_change_log
        ),
        config.read_consistency,
        Some(config.replay_page_size),
        None,
    )
    .await?;
    let select_durable_state_change_log_after = prepare(
        session,
        format!(
            "SELECT {durable_state_change_log_columns} FROM {} WHERE tag = ? \
             AND (timestamp_ms, revision, persistence_id) > (?, ?, ?)",
            schema.durable_state_change_log
        ),
        config.read_consistency,
        Some(config.replay_page_size),
        None,
    )
    .await?;

    Ok(CassandraStatements {
        insert_event,
        select_head,
        select_partition_highest,
        insert_head,
        update_head,
        insert_head_plain,
        update_head_plain,
        replay_partition,
        delete_event_range,
        load_snapshot,
        save_snapshot,
        delete_snapshot_exact,
        select_matching_snapshots,
        get_durable_state,
        insert_durable_state,
        update_durable_state,
        insert_durable_tombstone,
        update_durable_tombstone,
        select_persistence_ids,
        insert_tag_event,
        select_tag_events_all,
        select_tag_events_inclusive,
        select_tag_events_after,
        upsert_durable_state_change,
        delete_durable_state_change,
        remove_durable_state_change,
        select_durable_state_changes,
        insert_durable_state_change_log,
        select_durable_state_change_log_inclusive,
        select_durable_state_change_log_after,
    })
}

async fn prepare(
    session: &Session,
    cql: String,
    consistency: Consistency,
    page_size: Option<i32>,
    serial_consistency: Option<SerialConsistency>,
) -> PersistenceResult<PreparedStatement> {
    let mut statement = session
        .prepare(cql)
        .await
        .map_err(|error| storage_error("prepare Cassandra statement", error))?;
    statement.set_consistency(consistency);
    if let Some(page_size) = page_size {
        statement.set_page_size(page_size);
    }
    if let Some(serial_consistency) = serial_consistency {
        statement.set_serial_consistency(Some(serial_consistency));
    }
    Ok(statement)
}

#[derive(Debug, Clone, Copy)]
struct JournalHead {
    exists: bool,
    highest_seq_nr: i64,
    deleted_to: i64,
}

impl JournalHead {
    fn logical_deleted_to(self) -> i64 {
        self.deleted_to.min(self.highest_seq_nr)
    }
}

#[derive(Debug, Clone, Copy)]
struct ReconciledJournalHead {
    stored: JournalHead,
    highest_seq_nr: i64,
}

impl ReconciledJournalHead {
    fn logical_deleted_to(self) -> i64 {
        self.stored.logical_deleted_to().min(self.highest_seq_nr)
    }
}

async fn read_head(
    connected: &ConnectedCassandra,
    persistence_id: &PersistenceId,
) -> PersistenceResult<JournalHead> {
    let result = connected
        .session
        .execute_unpaged(&connected.statements.select_head, (persistence_id.id(),))
        .await
        .map_err(|error| storage_error("read Cassandra journal head", error))?;
    let rows = result
        .into_rows_result()
        .map_err(|error| storage_error("decode Cassandra journal-head result", error))?;
    let row = rows
        .maybe_first_row::<HeadRow>()
        .map_err(|error| storage_error("decode Cassandra journal-head row", error))?;
    match row {
        Some(row) if row.highest_seq_nr >= 0 && row.deleted_to >= 0 => Ok(JournalHead {
            exists: true,
            highest_seq_nr: row.highest_seq_nr,
            deleted_to: row.deleted_to,
        }),
        Some(row) => Err(PersistenceError::Failure(format!(
            "Cassandra journal head contains negative values ({}, {})",
            row.highest_seq_nr, row.deleted_to
        ))),
        None => Ok(JournalHead {
            exists: false,
            highest_seq_nr: 0,
            deleted_to: 0,
        }),
    }
}

async fn read_reconciled_head(
    connected: &ConnectedCassandra,
    persistence_id: &PersistenceId,
    partition_size: u64,
) -> PersistenceResult<ReconciledJournalHead> {
    let stored = read_head(connected, persistence_id).await?;
    let head_partition = partition_nr(
        u64::try_from(stored.highest_seq_nr)
            .expect("validated Cassandra journal head is non-negative"),
        partition_size,
    );
    let mut highest_seq_nr = stored.highest_seq_nr;
    if let Some(highest) = read_partition_highest(
        connected,
        persistence_id,
        head_partition,
        stored.highest_seq_nr,
    )
    .await?
    {
        highest_seq_nr = highest_seq_nr.max(highest);
    }
    // One AtomicWrite cannot cross a journal partition. Looking at the next
    // partition covers the crash window when the recorded head is exactly on
    // a boundary, while also reconciling a head lowered within one boundary.
    if let Some(next_partition) = head_partition.checked_add(1)
        && let Some(highest) = read_partition_highest(
            connected,
            persistence_id,
            next_partition,
            stored.highest_seq_nr,
        )
        .await?
    {
        highest_seq_nr = highest_seq_nr.max(highest);
    }
    Ok(ReconciledJournalHead {
        stored,
        highest_seq_nr,
    })
}

async fn read_partition_highest(
    connected: &ConnectedCassandra,
    persistence_id: &PersistenceId,
    partition_nr: i64,
    above_sequence_nr: i64,
) -> PersistenceResult<Option<i64>> {
    let result = connected
        .session
        .execute_unpaged(
            &connected.statements.select_partition_highest,
            (persistence_id.id(), partition_nr, above_sequence_nr),
        )
        .await
        .map_err(|error| storage_error("reconcile Cassandra journal head", error))?;
    let rows = result
        .into_rows_result()
        .map_err(|error| storage_error("decode Cassandra journal reconciliation result", error))?;
    let row = rows
        .maybe_first_row::<SequenceNrRow>()
        .map_err(|error| storage_error("decode Cassandra journal reconciliation row", error))?;
    row.map(|row| {
        if row.sequence_nr <= above_sequence_nr {
            return Err(PersistenceError::Failure(format!(
                "Cassandra journal reconciliation returned sequence {} at or below bound {}",
                row.sequence_nr, above_sequence_nr
            )));
        }
        Ok(row.sequence_nr)
    })
    .transpose()
}

async fn repair_reconciled_head(
    connected: &ConnectedCassandra,
    persistence_id: &PersistenceId,
    reconciled: ReconciledJournalHead,
    write_mode: CassandraWriteMode,
    context: &str,
) -> PersistenceResult<JournalHead> {
    if reconciled.highest_seq_nr == reconciled.stored.highest_seq_nr {
        return Ok(reconciled.stored);
    }
    transition_head(
        connected,
        persistence_id,
        reconciled.stored,
        reconciled.highest_seq_nr,
        reconciled.logical_deleted_to(),
        write_mode,
        context,
    )
    .await?;
    Ok(JournalHead {
        exists: true,
        highest_seq_nr: reconciled.highest_seq_nr,
        deleted_to: reconciled.logical_deleted_to(),
    })
}

async fn transition_head(
    connected: &ConnectedCassandra,
    persistence_id: &PersistenceId,
    expected: JournalHead,
    highest_seq_nr: i64,
    deleted_to: i64,
    write_mode: CassandraWriteMode,
    context: &str,
) -> PersistenceResult<()> {
    match write_mode {
        CassandraWriteMode::Lwt => {
            // Datum's runtime supplies the normal in-process
            // single-writer-per-entity guarantee. This LWT is the
            // cross-process backstop for deployments where two runtimes
            // accidentally write the same entity concurrently.
            let result = if expected.exists {
                connected
                    .session
                    .execute_unpaged(
                        &connected.statements.update_head,
                        (
                            highest_seq_nr,
                            deleted_to,
                            persistence_id.id(),
                            expected.highest_seq_nr,
                            expected.deleted_to,
                        ),
                    )
                    .await
            } else {
                connected
                    .session
                    .execute_unpaged(
                        &connected.statements.insert_head,
                        (persistence_id.id(), highest_seq_nr, deleted_to),
                    )
                    .await
            }
            .map_err(|error| storage_error(context, error))?;
            if lwt_applied(result)? {
                Ok(())
            } else {
                Err(PersistenceError::Failure(format!(
                    "{context}: journal-head LWT contention for {persistence_id}; write outcome \
                     is uncertain"
                )))
            }
        }
        CassandraWriteMode::SingleWriter => {
            // No Paxos round: a plain write, safe only under the
            // single-writer-per-entity discipline documented on
            // `CassandraWriteMode::SingleWriter`. `read_reconciled_head`
            // (called by every caller of this function before it reaches
            // here) still recomputes the true head from the event
            // partitions on every read/append, so a crash between the event
            // batch and this write is healed on the next read regardless of
            // which write path was used here.
            // A plain (non-conditional) write returns a `Void` result, not a
            // `Rows` result; there is nothing to decode, only the transport
            // error already mapped below.
            if expected.exists {
                connected
                    .session
                    .execute_unpaged(
                        &connected.statements.update_head_plain,
                        (highest_seq_nr, deleted_to, persistence_id.id()),
                    )
                    .await
            } else {
                connected
                    .session
                    .execute_unpaged(
                        &connected.statements.insert_head_plain,
                        (persistence_id.id(), highest_seq_nr, deleted_to),
                    )
                    .await
            }
            .map_err(|error| storage_error(context, error))?;
            Ok(())
        }
    }
}

#[derive(Debug, scylla::SerializeRow)]
#[scylla(flavor = "enforce_order", skip_name_checks)]
struct JournalInsertValues {
    persistence_id: String,
    partition_nr: i64,
    sequence_nr: i64,
    writer: String,
    adapter_manifest: String,
    serializer_id: i64,
    serializer_manifest: String,
    payload: Vec<u8>,
    metadata_serializer_id: Option<i64>,
    metadata_manifest: Option<String>,
    metadata_payload: Option<Vec<u8>>,
    tags: HashSet<String>,
    timestamp_ms: i64,
}

#[derive(Debug, scylla::SerializeRow)]
#[scylla(flavor = "enforce_order", skip_name_checks)]
struct TagEventInsertValues {
    tag: String,
    timestamp_ms: i64,
    sequence_nr: i64,
    persistence_id: String,
    writer: String,
    adapter_manifest: String,
    serializer_id: i64,
    serializer_manifest: String,
    payload: Vec<u8>,
    metadata_serializer_id: Option<i64>,
    metadata_manifest: Option<String>,
    metadata_payload: Option<Vec<u8>>,
    tags: HashSet<String>,
}

/// Row values for one statement position in the mixed event/tag-index append
/// batch. Both statements are executed together in the same unlogged batch
/// (see the module documentation for the resulting eventual-consistency
/// caveat); this enum lets [`scylla::statement::batch::Batch`] carry
/// per-position heterogeneous values via the blanket `Vec<T: SerializeRow>`
/// `BatchValues` impl.
enum JournalBatchValues {
    Event(JournalInsertValues),
    Tag(TagEventInsertValues),
}

impl SerializeRow for JournalBatchValues {
    fn serialize(
        &self,
        ctx: &RowSerializationContext<'_>,
        writer: &mut RowWriter,
    ) -> Result<(), SerializationError> {
        match self {
            Self::Event(values) => values.serialize(ctx, writer),
            Self::Tag(values) => values.serialize(ctx, writer),
        }
    }

    fn is_empty(&self) -> bool {
        match self {
            Self::Event(values) => values.is_empty(),
            Self::Tag(values) => values.is_empty(),
        }
    }
}

#[derive(Debug)]
struct PreparedAtomicWrite {
    persistence_id: PersistenceId,
    first_sequence_nr: i64,
    last_sequence_nr: i64,
    events: Vec<JournalInsertValues>,
    tag_events: Vec<TagEventInsertValues>,
}

impl PreparedAtomicWrite {
    fn new(write: AtomicWrite, partition_size: u64) -> Result<Self, String> {
        let source = write.into_events();
        let first = source
            .first()
            .expect("AtomicWrite guarantees at least one event");
        let last = source.last().expect("AtomicWrite guarantees events");
        let first_sequence_nr = i64::try_from(first.sequence_nr.as_u64()).map_err(|_| {
            format!(
                "Cassandra sequence number {} exceeds bigint range",
                first.sequence_nr.as_u64()
            )
        })?;
        let last_sequence_nr = i64::try_from(last.sequence_nr.as_u64()).map_err(|_| {
            format!(
                "Cassandra sequence number {} exceeds bigint range",
                last.sequence_nr.as_u64()
            )
        })?;
        let first_partition = partition_nr(first.sequence_nr.as_u64(), partition_size);
        let last_partition = partition_nr(last.sequence_nr.as_u64(), partition_size);
        if first_partition != last_partition {
            return Err(format!(
                "atomic write from sequence {} through {} crosses Cassandra journal partitions \
                 {first_partition} and {last_partition}",
                first.sequence_nr.as_u64(),
                last.sequence_nr.as_u64()
            ));
        }
        let persistence_id = first.persistence_id.clone();
        let mut events = Vec::with_capacity(source.len());
        let mut tag_events = Vec::new();
        for event in source {
            let (journal_values, mut event_tag_rows) =
                journal_insert_values(event, first_partition);
            tag_events.append(&mut event_tag_rows);
            events.push(journal_values);
        }
        Ok(Self {
            persistence_id,
            first_sequence_nr,
            last_sequence_nr,
            events,
            tag_events,
        })
    }
}

fn journal_insert_values(
    event: StoredEvent,
    partition_nr: i64,
) -> (JournalInsertValues, Vec<TagEventInsertValues>) {
    let persistence_id = event.persistence_id.id().to_owned();
    let sequence_nr = i64::try_from(event.sequence_nr.as_u64())
        .expect("atomic write sequence range was validated");
    let tag_names: Vec<String> = event
        .tags
        .iter()
        .map(|tag| tag.as_str().to_owned())
        .collect();
    let tags_set: HashSet<String> = tag_names.iter().cloned().collect();
    let tag_rows = tag_names
        .iter()
        .map(|tag| TagEventInsertValues {
            tag: tag.clone(),
            timestamp_ms: event.timestamp_ms,
            sequence_nr,
            persistence_id: persistence_id.clone(),
            writer: event.writer_uuid.clone(),
            adapter_manifest: event.adapter_manifest.clone(),
            serializer_id: i64::from(event.payload.serializer_id.as_u32()),
            serializer_manifest: event.payload.manifest.clone(),
            payload: event.payload.payload.clone(),
            metadata_serializer_id: event
                .metadata
                .as_ref()
                .map(|metadata| i64::from(metadata.serializer_id.as_u32())),
            metadata_manifest: event
                .metadata
                .as_ref()
                .map(|metadata| metadata.manifest.clone()),
            metadata_payload: event
                .metadata
                .as_ref()
                .map(|metadata| metadata.payload.clone()),
            tags: tags_set.clone(),
        })
        .collect::<Vec<_>>();

    let (metadata_serializer_id, metadata_manifest, metadata_payload) =
        event.metadata.map_or((None, None, None), |metadata| {
            (
                Some(i64::from(metadata.serializer_id.as_u32())),
                Some(metadata.manifest),
                Some(metadata.payload),
            )
        });
    let journal_values = JournalInsertValues {
        persistence_id,
        partition_nr,
        sequence_nr,
        writer: event.writer_uuid,
        adapter_manifest: event.adapter_manifest,
        serializer_id: i64::from(event.payload.serializer_id.as_u32()),
        serializer_manifest: event.payload.manifest,
        payload: event.payload.payload,
        metadata_serializer_id,
        metadata_manifest,
        metadata_payload,
        tags: tags_set,
        timestamp_ms: event.timestamp_ms,
    };
    (journal_values, tag_rows)
}

#[derive(Debug, scylla::DeserializeRow)]
#[scylla(flavor = "enforce_order", skip_name_checks)]
struct HeadRow {
    highest_seq_nr: i64,
    deleted_to: i64,
}

#[derive(Debug, scylla::DeserializeRow)]
#[scylla(flavor = "enforce_order", skip_name_checks)]
struct SequenceNrRow {
    sequence_nr: i64,
}

#[derive(Debug, scylla::DeserializeRow)]
#[scylla(flavor = "enforce_order", skip_name_checks)]
struct JournalRow {
    sequence_nr: i64,
    writer: String,
    adapter_manifest: String,
    serializer_id: i64,
    serializer_manifest: String,
    payload: Vec<u8>,
    metadata_serializer_id: Option<i64>,
    metadata_manifest: Option<String>,
    metadata_payload: Option<Vec<u8>>,
    tags: HashSet<String>,
    timestamp_ms: i64,
}

struct CassandraReplayState {
    connected: Arc<ConnectedCassandra>,
    persistence_id: PersistenceId,
    current_partition: i64,
    last_partition: i64,
    from_sequence_nr: i64,
    to_sequence_nr: i64,
    remaining: u64,
    partition_size: u64,
    paging_state: PagingState,
    buffered: VecDeque<StoredEvent>,
    finished: bool,
}

fn cassandra_event_stream(
    connected: Arc<ConnectedCassandra>,
    persistence_id: PersistenceId,
    from: SequenceNr,
    to: SequenceNr,
    max: u64,
    deleted_to: i64,
    partition_size: u64,
) -> EventStream {
    let deleted_from = deleted_to
        .checked_add(1)
        .map_or(u64::MAX, |value| u64::try_from(value).unwrap_or_default());
    let from = from.as_u64().max(deleted_from);
    let to = to.as_u64().min(i64::MAX as u64);
    if from > to || max == 0 || from > i64::MAX as u64 {
        return Box::pin(stream::empty());
    }
    let state = CassandraReplayState {
        connected,
        persistence_id,
        current_partition: partition_nr(from, partition_size),
        last_partition: partition_nr(to, partition_size),
        from_sequence_nr: i64::try_from(from).expect("replay bound was capped"),
        to_sequence_nr: i64::try_from(to).expect("replay bound was capped"),
        remaining: max,
        partition_size,
        paging_state: PagingState::start(),
        buffered: VecDeque::new(),
        finished: false,
    };
    Box::pin(stream::unfold(state, next_replay_event))
}

async fn next_replay_event(
    mut state: CassandraReplayState,
) -> Option<(PersistenceResult<StoredEvent>, CassandraReplayState)> {
    loop {
        if state.finished || state.remaining == 0 {
            return None;
        }
        if let Some(event) = state.buffered.pop_front() {
            state.remaining -= 1;
            return Some((Ok(event), state));
        }
        if state.current_partition > state.last_partition {
            return None;
        }

        let partition_start = partition_start(state.current_partition, state.partition_size);
        let partition_end = partition_end(state.current_partition, state.partition_size);
        let from = state.from_sequence_nr.max(partition_start);
        let to = state.to_sequence_nr.min(partition_end);
        let paging_state = std::mem::replace(&mut state.paging_state, PagingState::start());
        let page = state
            .connected
            .session
            .execute_single_page(
                &state.connected.statements.replay_partition,
                (state.persistence_id.id(), state.current_partition, from, to),
                paging_state,
            )
            .await;
        let (result, next_page) = match page {
            Ok(page) => page,
            Err(error) => {
                state.finished = true;
                return Some((
                    Err(storage_error("page Cassandra journal replay", error)),
                    state,
                ));
            }
        };
        let rows = match decode_journal_page(&state.persistence_id, result) {
            Ok(rows) => rows,
            Err(error) => {
                state.finished = true;
                return Some((Err(error), state));
            }
        };
        state.buffered = VecDeque::from(rows);
        match next_page {
            PagingStateResponse::HasMorePages {
                state: paging_state,
            } => {
                state.paging_state = paging_state;
            }
            PagingStateResponse::NoMorePages => {
                state.current_partition += 1;
                state.paging_state = PagingState::start();
            }
        }
    }
}

fn decode_journal_page(
    persistence_id: &PersistenceId,
    result: QueryResult,
) -> PersistenceResult<Vec<StoredEvent>> {
    let rows = result
        .into_rows_result()
        .map_err(|error| storage_error("decode Cassandra journal page", error))?;
    rows.rows::<JournalRow>()
        .map_err(|error| storage_error("decode Cassandra journal page rows", error))?
        .map(|row| {
            row.map_err(|error| storage_error("decode Cassandra journal row", error))
                .and_then(|row| decode_stored_event(persistence_id, row))
        })
        .collect()
}

fn decode_stored_event(
    persistence_id: &PersistenceId,
    row: JournalRow,
) -> PersistenceResult<StoredEvent> {
    let sequence_nr = SequenceNr::new(non_negative_u64(
        row.sequence_nr,
        "Cassandra journal sequence number",
    )?);
    let metadata = decode_optional_frame(
        row.metadata_serializer_id,
        row.metadata_manifest,
        row.metadata_payload,
        "Cassandra journal metadata",
    )?;
    let mut tags = row.tags.into_iter().map(Tag::new).collect::<Vec<_>>();
    tags.sort_by(|left, right| left.as_str().cmp(right.as_str()));
    Ok(StoredEvent {
        persistence_id: persistence_id.clone(),
        sequence_nr,
        adapter_manifest: row.adapter_manifest,
        writer_uuid: row.writer,
        timestamp_ms: row.timestamp_ms,
        metadata,
        payload: decode_frame(
            row.serializer_id,
            row.serializer_manifest,
            row.payload,
            "Cassandra journal payload",
        )?,
        tags,
    })
}

struct CassandraLiveCursor {
    connected: Arc<ConnectedCassandra>,
    persistence_id: PersistenceId,
    initial: Option<EventStream>,
    next_sequence_nr: Option<SequenceNr>,
    to_sequence_nr: SequenceNr,
    reached_end: bool,
    partition_size: u64,
    polling: CassandraPollingConfig,
    delay: Duration,
    buffered: VecDeque<EventEnvelope>,
}

async fn next_cassandra_live_event(
    mut cursor: CassandraLiveCursor,
) -> Option<(PersistenceResult<EventEnvelope>, CassandraLiveCursor)> {
    loop {
        if let Some(initial) = &mut cursor.initial {
            match initial.next().await {
                Some(event) => return Some((event.map(event_envelope), cursor)),
                None => cursor.initial = None,
            }
        }
        if let Some(event) = cursor.buffered.pop_front() {
            return Some((Ok(event), cursor));
        }
        let next_sequence_nr = cursor.next_sequence_nr?;
        if cursor.reached_end {
            return None;
        }

        let head = match read_reconciled_head(
            &cursor.connected,
            &cursor.persistence_id,
            cursor.partition_size,
        )
        .await
        {
            Ok(head) => head,
            Err(error) => return Some((Err(error), cursor)),
        };
        let highest = SequenceNr::new(
            match non_negative_u64(head.highest_seq_nr, "Cassandra live-query journal head") {
                Ok(highest) => highest,
                Err(error) => return Some((Err(error), cursor)),
            },
        );
        let boundary = highest.min(cursor.to_sequence_nr);
        if next_sequence_nr <= boundary {
            let events = cassandra_event_stream(
                cursor.connected.clone(),
                cursor.persistence_id.clone(),
                next_sequence_nr,
                boundary,
                u64::from(cursor.polling.batch_size),
                head.logical_deleted_to(),
                cursor.partition_size,
            );
            let mut events = events;
            let mut buffered = VecDeque::new();
            while let Some(event) = events.next().await {
                match event {
                    Ok(event) => buffered.push_back(event_envelope(event)),
                    Err(error) => return Some((Err(error), cursor)),
                }
            }
            if let Some(last) = buffered.back() {
                cursor.next_sequence_nr = last
                    .sequence_nr
                    .as_u64()
                    .checked_add(1)
                    .map(SequenceNr::new);
                cursor.reached_end = last.sequence_nr >= cursor.to_sequence_nr;
                cursor.buffered = buffered;
                cursor.delay = cursor.polling.min_interval;
                continue;
            }
            cursor.next_sequence_nr = highest.as_u64().checked_add(1).map(SequenceNr::new);
        }
        cursor.reached_end = highest >= cursor.to_sequence_nr;
        if cursor.reached_end {
            return None;
        }
        tokio::time::sleep(cursor.delay).await;
        cursor.delay = cursor
            .delay
            .saturating_mul(2)
            .min(cursor.polling.max_interval);
    }
}

fn event_envelope(event: StoredEvent) -> EventEnvelope {
    EventEnvelope {
        offset: Offset::Sequence(event.sequence_nr.as_u64()),
        persistence_id: event.persistence_id,
        sequence_nr: event.sequence_nr,
        timestamp_ms: event.timestamp_ms,
        adapter_manifest: event.adapter_manifest,
        payload: event.payload,
        metadata: event.metadata,
        tags: event.tags,
    }
}

/// Resume position for `events_by_tag`, parsed from an [`Offset::Timestamp`].
///
/// `Inclusive` is used for a fresh external resume (only `(timestamp_ms,
/// sequence_nr)` is known — [`Offset`] carries no persistence id) and may
/// therefore re-emit an event sharing that exact pair; `After` is the
/// precise, gap-free continuation used internally once this cursor has
/// observed a concrete row.
#[derive(Debug, Clone, PartialEq, Eq)]
enum CassandraTagResume {
    None,
    Inclusive {
        timestamp_ms: i64,
        sequence_nr: i64,
    },
    After {
        timestamp_ms: i64,
        sequence_nr: i64,
        persistence_id: String,
    },
}

fn cassandra_tag_resume(offset: Offset) -> PersistenceResult<CassandraTagResume> {
    match offset {
        Offset::NoOffset => Ok(CassandraTagResume::None),
        Offset::Timestamp {
            epoch_micros,
            seq_nr,
        } => Ok(CassandraTagResume::Inclusive {
            timestamp_ms: epoch_micros.div_euclid(1000),
            sequence_nr: sql_i64(seq_nr, "Cassandra tag-query offset sequence number")?,
        }),
        Offset::Sequence(_) => Err(PersistenceError::Rejected(
            "Cassandra tag queries require a Timestamp offset produced by the same backend".into(),
        )),
    }
}

fn cassandra_tag_resume_after(last: &EventEnvelope) -> CassandraTagResume {
    let Offset::Timestamp {
        epoch_micros,
        seq_nr,
    } = last.offset
    else {
        unreachable!("Cassandra tag envelopes always carry timestamp offsets")
    };
    CassandraTagResume::After {
        timestamp_ms: epoch_micros.div_euclid(1000),
        sequence_nr: i64::try_from(seq_nr).expect("Cassandra sequence numbers fit i64"),
        persistence_id: last.persistence_id.id().to_owned(),
    }
}

async fn cassandra_events_by_tag(
    connected: &ConnectedCassandra,
    tag: &Tag,
    resume: &CassandraTagResume,
    limit: Option<u32>,
) -> PersistenceResult<Vec<EventEnvelope>> {
    let pager = match resume {
        CassandraTagResume::None => {
            connected
                .session
                .execute_iter(
                    connected.statements.select_tag_events_all.clone(),
                    (tag.as_str(),),
                )
                .await
        }
        CassandraTagResume::Inclusive {
            timestamp_ms,
            sequence_nr,
        } => {
            connected
                .session
                .execute_iter(
                    connected.statements.select_tag_events_inclusive.clone(),
                    (tag.as_str(), *timestamp_ms, *sequence_nr),
                )
                .await
        }
        CassandraTagResume::After {
            timestamp_ms,
            sequence_nr,
            persistence_id,
        } => {
            connected
                .session
                .execute_iter(
                    connected.statements.select_tag_events_after.clone(),
                    (
                        tag.as_str(),
                        *timestamp_ms,
                        *sequence_nr,
                        persistence_id.as_str(),
                    ),
                )
                .await
        }
    }
    .map_err(|error| storage_error("query Cassandra tag events", error))?;
    let mut rows = pager
        .rows_stream::<TagEventRow>()
        .map_err(|error| storage_error("decode Cassandra tag-query rows", error))?;
    let cap = limit.map_or(usize::MAX, |limit| limit as usize);
    let mut candidates = Vec::new();
    while candidates.len() < cap {
        match rows.next().await {
            Some(Ok(row)) => candidates.push(decode_tag_event(row)?),
            Some(Err(error)) => {
                return Err(storage_error("decode Cassandra tag-query row", error));
            }
            None => break,
        }
    }
    filter_deleted_tag_events(connected, candidates).await
}

/// Drops candidate tag-index rows at or below their persistence id's current
/// `deleted_to` marker.
///
/// `delete_to` only range-tombstones `event_journal`; `tag_events` rows for
/// the deleted range are left in place (see the module documentation), so a
/// tag read must independently filter them out here. One journal-head lookup
/// is issued per *distinct* persistence id in `candidates` (cached in `seen`),
/// not one per row, mirroring the RocksDB backend's `query_events_by_tag`
/// rule.
async fn filter_deleted_tag_events(
    connected: &ConnectedCassandra,
    candidates: Vec<StoredEvent>,
) -> PersistenceResult<Vec<EventEnvelope>> {
    let mut seen: HashMap<String, i64> = HashMap::new();
    let mut events = Vec::with_capacity(candidates.len());
    for candidate in candidates {
        let deleted_to = match seen.get(candidate.persistence_id.id()) {
            Some(deleted_to) => *deleted_to,
            None => {
                let head = read_head(connected, &candidate.persistence_id).await?;
                let deleted_to = head.logical_deleted_to();
                seen.insert(candidate.persistence_id.id().to_owned(), deleted_to);
                deleted_to
            }
        };
        if candidate.sequence_nr.as_u64() <= u64::try_from(deleted_to).unwrap_or(0) {
            continue;
        }
        events.push(tag_event_envelope(candidate));
    }
    Ok(events)
}

struct CassandraTagCursor {
    connected: Arc<ConnectedCassandra>,
    tag: Tag,
    resume: CassandraTagResume,
    buffered: VecDeque<EventEnvelope>,
    polling: CassandraPollingConfig,
    delay: Duration,
}

async fn next_cassandra_tag_event(
    mut cursor: CassandraTagCursor,
) -> Option<(PersistenceResult<EventEnvelope>, CassandraTagCursor)> {
    loop {
        if let Some(event) = cursor.buffered.pop_front() {
            return Some((Ok(event), cursor));
        }
        let events = match cassandra_events_by_tag(
            &cursor.connected,
            &cursor.tag,
            &cursor.resume,
            Some(cursor.polling.batch_size),
        )
        .await
        {
            Ok(events) => events,
            Err(error) => return Some((Err(error), cursor)),
        };
        if let Some(last) = events.last() {
            cursor.resume = cassandra_tag_resume_after(last);
            cursor.buffered = VecDeque::from(events);
            cursor.delay = cursor.polling.min_interval;
            continue;
        }
        tokio::time::sleep(cursor.delay).await;
        cursor.delay = cursor
            .delay
            .saturating_mul(2)
            .min(cursor.polling.max_interval);
    }
}

#[derive(Debug, scylla::DeserializeRow)]
#[scylla(flavor = "enforce_order", skip_name_checks)]
struct TagEventRow {
    timestamp_ms: i64,
    sequence_nr: i64,
    persistence_id: String,
    writer: String,
    adapter_manifest: String,
    serializer_id: i64,
    serializer_manifest: String,
    payload: Vec<u8>,
    metadata_serializer_id: Option<i64>,
    metadata_manifest: Option<String>,
    metadata_payload: Option<Vec<u8>>,
    tags: HashSet<String>,
}

fn decode_tag_event(row: TagEventRow) -> PersistenceResult<StoredEvent> {
    let persistence_id = PersistenceId::from_unique(row.persistence_id)?;
    let sequence_nr = SequenceNr::new(non_negative_u64(
        row.sequence_nr,
        "Cassandra tag-query sequence number",
    )?);
    let metadata = decode_optional_frame(
        row.metadata_serializer_id,
        row.metadata_manifest,
        row.metadata_payload,
        "Cassandra tag-query metadata",
    )?;
    let mut tags = row.tags.into_iter().map(Tag::new).collect::<Vec<_>>();
    tags.sort_by(|left, right| left.as_str().cmp(right.as_str()));
    Ok(StoredEvent {
        persistence_id,
        sequence_nr,
        adapter_manifest: row.adapter_manifest,
        writer_uuid: row.writer,
        timestamp_ms: row.timestamp_ms,
        metadata,
        payload: decode_frame(
            row.serializer_id,
            row.serializer_manifest,
            row.payload,
            "Cassandra tag-query payload",
        )?,
        tags,
    })
}

fn tag_event_envelope(event: StoredEvent) -> EventEnvelope {
    EventEnvelope {
        offset: Offset::Timestamp {
            epoch_micros: event.timestamp_ms.saturating_mul(1000),
            seq_nr: event.sequence_nr.as_u64(),
        },
        persistence_id: event.persistence_id,
        sequence_nr: event.sequence_nr,
        timestamp_ms: event.timestamp_ms,
        adapter_manifest: event.adapter_manifest,
        payload: event.payload,
        metadata: event.metadata,
        tags: event.tags,
    }
}

/// Parses the inclusive `timestamp_ms` boundary `DurableStateChangesQuery`
/// resumes from, out of an [`Offset::Timestamp`] (whose `seq_nr` field
/// carries the revision on other backends; the coalesced `changes` query
/// below does not need it — see the module documentation for why).
fn cassandra_change_since_timestamp_ms(offset: Offset) -> PersistenceResult<i64> {
    match offset {
        Offset::NoOffset => Ok(i64::MIN),
        Offset::Timestamp { epoch_micros, .. } => Ok(epoch_micros.div_euclid(1000)),
        Offset::Sequence(_) => Err(PersistenceError::Rejected(
            "Cassandra durable-state changes require a Timestamp offset produced by the same \
             backend"
                .into(),
        )),
    }
}

/// Serves `QueryMode::Current` (and the one-shot bootstrap of `Live`) from
/// the coalesced `durable_state_changes` table: one row per persistence id,
/// so the result is already "one latest value per id" with no in-memory
/// dedup or sort needed. `ALLOW FILTERING` on `timestamp_ms` is bounded by
/// the number of *distinct ids ever tagged*, not total revision history, and
/// runs once per subscribe/snapshot rather than on every poll — unlike the
/// `Live` continuation, which uses the native clustering-range comparison on
/// `durable_state_change_log` (see [`cassandra_durable_state_change_log`]).
async fn cassandra_current_durable_state_changes(
    connected: &ConnectedCassandra,
    tag: &Tag,
    since_timestamp_ms: i64,
) -> PersistenceResult<Vec<DurableStateChange>> {
    let pager = connected
        .session
        .execute_iter(
            connected.statements.select_durable_state_changes.clone(),
            (tag.as_str(), since_timestamp_ms),
        )
        .await
        .map_err(|error| storage_error("query Cassandra durable-state changes", error))?;
    let mut rows = pager
        .rows_stream::<DurableStateChangeRow>()
        .map_err(|error| storage_error("decode Cassandra durable-state change rows", error))?;
    let mut changes = Vec::new();
    while let Some(row) = rows.next().await {
        let row =
            row.map_err(|error| storage_error("decode Cassandra durable-state change row", error))?;
        changes.push(decode_durable_state_change(row)?);
    }
    Ok(changes)
}

/// Resume position into `durable_state_change_log`, whose primary key is
/// `(tag, timestamp_ms, revision, persistence_id)`. `revision` — strictly
/// monotonic per id — is the second clustering column specifically so two
/// updates to the same id landing in the same source millisecond still sort
/// and resume correctly; a `(timestamp_ms, persistence_id)`-only comparison
/// cannot distinguish that case and can silently drop the later change for a
/// resuming consumer.
#[derive(Debug, Clone, PartialEq, Eq)]
enum CassandraDurableChangeLogResume {
    /// `>=` comparison on `(timestamp_ms, revision)`, a prefix of the
    /// clustering key. Used for the initial poll after a `Live` subscription
    /// bootstraps from the coalesced table (see [`DurableStateChangesQuery::changes`]).
    Inclusive { timestamp_ms: i64, revision: i64 },
    /// `>` comparison on the full clustering key, the precise, gap-free
    /// continuation used once this cursor has observed a concrete row.
    After {
        timestamp_ms: i64,
        revision: i64,
        persistence_id: String,
    },
}

fn cassandra_change_log_resume_after(last: &DurableStateChange) -> CassandraDurableChangeLogResume {
    let Offset::Timestamp {
        epoch_micros,
        seq_nr,
    } = last.offset()
    else {
        unreachable!("Cassandra durable changes always carry timestamp offsets")
    };
    CassandraDurableChangeLogResume::After {
        timestamp_ms: epoch_micros.div_euclid(1000),
        revision: i64::try_from(seq_nr).expect("Cassandra revisions fit i64"),
        persistence_id: last.persistence_id().id().to_owned(),
    }
}

/// Pages `durable_state_change_log` forward with a native clustering-range
/// comparison — the same shape as `tag_events` — instead of re-scanning the
/// coalesced table with `ALLOW FILTERING` on every poll.
async fn cassandra_durable_state_change_log(
    connected: &ConnectedCassandra,
    tag: &Tag,
    resume: &CassandraDurableChangeLogResume,
    limit: Option<u32>,
) -> PersistenceResult<Vec<DurableStateChange>> {
    let pager = match resume {
        CassandraDurableChangeLogResume::Inclusive {
            timestamp_ms,
            revision,
        } => {
            connected
                .session
                .execute_iter(
                    connected
                        .statements
                        .select_durable_state_change_log_inclusive
                        .clone(),
                    (tag.as_str(), *timestamp_ms, *revision),
                )
                .await
        }
        CassandraDurableChangeLogResume::After {
            timestamp_ms,
            revision,
            persistence_id,
        } => {
            connected
                .session
                .execute_iter(
                    connected
                        .statements
                        .select_durable_state_change_log_after
                        .clone(),
                    (
                        tag.as_str(),
                        *timestamp_ms,
                        *revision,
                        persistence_id.as_str(),
                    ),
                )
                .await
        }
    }
    .map_err(|error| storage_error("query Cassandra durable-state change log", error))?;
    let mut rows = pager
        .rows_stream::<DurableStateChangeRow>()
        .map_err(|error| storage_error("decode Cassandra durable-state change log rows", error))?;
    let cap = limit.map_or(usize::MAX, |limit| limit as usize);
    let mut changes = Vec::new();
    while changes.len() < cap {
        match rows.next().await {
            Some(Ok(row)) => changes.push(decode_durable_state_change(row)?),
            Some(Err(error)) => {
                return Err(storage_error(
                    "decode Cassandra durable-state change log row",
                    error,
                ));
            }
            None => break,
        }
    }
    Ok(changes)
}

struct CassandraDurableChangeLogCursor {
    connected: Arc<ConnectedCassandra>,
    tag: Tag,
    resume: CassandraDurableChangeLogResume,
    buffered: VecDeque<DurableStateChange>,
    polling: CassandraPollingConfig,
    delay: Duration,
}

async fn next_cassandra_durable_change_log(
    mut cursor: CassandraDurableChangeLogCursor,
) -> Option<(
    PersistenceResult<DurableStateChange>,
    CassandraDurableChangeLogCursor,
)> {
    loop {
        if let Some(change) = cursor.buffered.pop_front() {
            return Some((Ok(change), cursor));
        }
        let changes = match cassandra_durable_state_change_log(
            &cursor.connected,
            &cursor.tag,
            &cursor.resume,
            Some(cursor.polling.batch_size),
        )
        .await
        {
            Ok(changes) => changes,
            Err(error) => return Some((Err(error), cursor)),
        };
        if let Some(last) = changes.last() {
            cursor.resume = cassandra_change_log_resume_after(last);
            cursor.buffered = VecDeque::from(changes);
            cursor.delay = cursor.polling.min_interval;
            continue;
        }
        tokio::time::sleep(cursor.delay).await;
        cursor.delay = cursor
            .delay
            .saturating_mul(2)
            .min(cursor.polling.max_interval);
    }
}

#[derive(Debug, scylla::DeserializeRow)]
#[scylla(flavor = "enforce_order", skip_name_checks)]
struct DurableStateChangeRow {
    persistence_id: String,
    revision: i64,
    timestamp_ms: i64,
    serializer_id: Option<i64>,
    serializer_manifest: Option<String>,
    payload: Option<Vec<u8>>,
    deleted: bool,
}

fn decode_durable_state_change(
    row: DurableStateChangeRow,
) -> PersistenceResult<DurableStateChange> {
    let persistence_id = PersistenceId::from_unique(row.persistence_id)?;
    let revision = Revision::new(non_negative_u64(
        row.revision,
        "Cassandra durable-state change revision",
    )?);
    let offset = Offset::Timestamp {
        epoch_micros: row.timestamp_ms.saturating_mul(1000),
        seq_nr: revision.as_u64(),
    };
    if row.deleted {
        return Ok(DurableStateChange::Deleted(DeletedDurableState {
            offset,
            persistence_id,
            revision,
            timestamp_ms: row.timestamp_ms,
        }));
    }
    let state = decode_optional_frame(
        row.serializer_id,
        row.serializer_manifest,
        row.payload,
        "Cassandra durable-state change",
    )?
    .ok_or_else(|| {
        PersistenceError::Failure(
            "Cassandra durable-state change is live but has no serialization frame".into(),
        )
    })?;
    Ok(DurableStateChange::Updated(UpdatedDurableState {
        offset,
        persistence_id,
        revision,
        state,
        timestamp_ms: row.timestamp_ms,
    }))
}

#[derive(Debug, scylla::DeserializeRow)]
#[scylla(flavor = "enforce_order", skip_name_checks)]
struct SnapshotRow {
    sequence_nr: i64,
    timestamp_ms: i64,
    adapter_manifest: String,
    serializer_id: i64,
    serializer_manifest: String,
    payload: Vec<u8>,
}

#[derive(Debug, scylla::DeserializeRow)]
#[scylla(flavor = "enforce_order", skip_name_checks)]
struct SnapshotMetadataRow {
    sequence_nr: i64,
    timestamp_ms: i64,
}

fn decode_snapshot(
    persistence_id: &PersistenceId,
    row: SnapshotRow,
) -> PersistenceResult<SelectedSnapshot> {
    Ok(SelectedSnapshot {
        metadata: SnapshotMetadata {
            persistence_id: persistence_id.clone(),
            sequence_nr: SequenceNr::new(non_negative_u64(
                row.sequence_nr,
                "Cassandra snapshot sequence number",
            )?),
            timestamp_ms: row.timestamp_ms,
        },
        adapter_manifest: row.adapter_manifest,
        state: decode_frame(
            row.serializer_id,
            row.serializer_manifest,
            row.payload,
            "Cassandra snapshot state",
        )?,
    })
}

#[derive(Debug, scylla::DeserializeRow)]
#[scylla(flavor = "enforce_order", skip_name_checks)]
struct DurableStateRow {
    revision: i64,
    serializer_id: Option<i64>,
    serializer_manifest: Option<String>,
    payload: Option<Vec<u8>>,
    tag: Option<String>,
}

fn decode_durable_state(row: DurableStateRow) -> PersistenceResult<VersionedState> {
    let state = decode_optional_frame(
        row.serializer_id,
        row.serializer_manifest,
        row.payload,
        "Cassandra durable state",
    )?;
    // `update_durable_tombstone` deliberately preserves the stored `tag`
    // column across a delete so `durable_state_changes` can still route the
    // tombstone under it (see the module documentation). The *observable*
    // contract (`DurableStateStore::delete` "clears the tag") is enforced
    // here instead: a tombstoned row (absent state) always reports `None`.
    let tag = state.is_some().then(|| row.tag.map(Tag::new)).flatten();
    Ok(VersionedState {
        state,
        revision: Revision::new(non_negative_u64(
            row.revision,
            "Cassandra durable-state revision",
        )?),
        tag,
    })
}

/// Reads the raw, unmassaged `tag` column of a durable-state row, bypassing
/// [`decode_durable_state`]'s "observable tag is `None` once tombstoned" rule.
/// Used both to route a just-applied delete's tombstone into
/// `durable_state_changes` under the tag the row carried before it, and (read
/// *before* an upsert's CAS) to detect a retag so the previous tag's stale
/// change-index row can be cleaned up.
async fn read_raw_durable_tag(
    connected: &ConnectedCassandra,
    persistence_id: &PersistenceId,
) -> PersistenceResult<Option<Tag>> {
    let result = connected
        .session
        .execute_unpaged(
            &connected.statements.get_durable_state,
            (persistence_id.id(),),
        )
        .await
        .map_err(|error| {
            storage_error("read Cassandra durable-state tag for change index", error)
        })?;
    let rows = result
        .into_rows_result()
        .map_err(|error| storage_error("decode Cassandra durable-state tag result", error))?;
    let row = rows
        .maybe_first_row::<DurableStateRow>()
        .map_err(|error| storage_error("decode Cassandra durable-state tag row", error))?;
    Ok(row.and_then(|row| row.tag).map(Tag::new))
}

/// Removes a stale `durable_state_changes` row after a retag (or untag).
///
/// The id did not stop existing — it just stopped living under `old_tag` —
/// so this is a plain delete, not the `deleted = true` tombstone written by
/// [`write_durable_state_delete_change`]. See the module documentation.
async fn remove_durable_state_change(
    connected: &ConnectedCassandra,
    old_tag: &Tag,
    persistence_id: &PersistenceId,
) -> PersistenceResult<()> {
    connected
        .session
        .execute_unpaged(
            &connected.statements.remove_durable_state_change,
            (old_tag.as_str(), persistence_id.id()),
        )
        .await
        .map_err(|error| storage_error("remove stale Cassandra durable-state change", error))?;
    Ok(())
}

/// Indexes a successful tagged durable-state upsert into both change tables:
/// the coalesced `durable_state_changes` (in place, keyed by `(tag,
/// persistence_id)`, serving `QueryMode::Current`) and the append-only
/// `durable_state_change_log` (keyed by `(tag, timestamp_ms, revision,
/// persistence_id)`, serving `QueryMode::Live` polling resume). Both writes
/// use the same `timestamp_ms`/`revision` pair.
///
/// Executed as plain (non-conditional) writes right after the authoritative
/// `durable_state` LWT succeeds; see the module documentation for the
/// resulting non-atomicity window between the tables.
async fn write_durable_state_upsert_change(
    connected: &ConnectedCassandra,
    tag: &Tag,
    persistence_id: &PersistenceId,
    revision: Revision,
    state: SerializedPayload,
) -> PersistenceResult<()> {
    let revision = sql_i64(revision.as_u64(), "durable-state change revision")?;
    let timestamp_ms = current_timestamp_ms();
    let serializer_id = i64::from(state.serializer_id.as_u32());
    connected
        .session
        .execute_unpaged(
            &connected.statements.upsert_durable_state_change,
            (
                revision,
                timestamp_ms,
                serializer_id,
                state.manifest.clone(),
                state.payload.clone(),
                tag.as_str(),
                persistence_id.id(),
            ),
        )
        .await
        .map_err(|error| storage_error("index Cassandra durable-state change", error))?;
    connected
        .session
        .execute_unpaged(
            &connected.statements.insert_durable_state_change_log,
            (
                tag.as_str(),
                timestamp_ms,
                revision,
                persistence_id.id(),
                serializer_id,
                state.manifest,
                state.payload,
                false,
            ),
        )
        .await
        .map_err(|error| storage_error("append Cassandra durable-state change log", error))?;
    Ok(())
}

/// Indexes a successful tagged durable-state delete (tombstone) into both
/// change tables. See [`write_durable_state_upsert_change`].
async fn write_durable_state_delete_change(
    connected: &ConnectedCassandra,
    tag: &Tag,
    persistence_id: &PersistenceId,
    revision: Revision,
) -> PersistenceResult<()> {
    let revision = sql_i64(revision.as_u64(), "durable-state change tombstone revision")?;
    let timestamp_ms = current_timestamp_ms();
    connected
        .session
        .execute_unpaged(
            &connected.statements.delete_durable_state_change,
            (revision, timestamp_ms, tag.as_str(), persistence_id.id()),
        )
        .await
        .map_err(|error| storage_error("index Cassandra durable-state change tombstone", error))?;
    connected
        .session
        .execute_unpaged(
            &connected.statements.insert_durable_state_change_log,
            (
                tag.as_str(),
                timestamp_ms,
                revision,
                persistence_id.id(),
                None::<i64>,
                None::<String>,
                None::<Vec<u8>>,
                true,
            ),
        )
        .await
        .map_err(|error| {
            storage_error("append Cassandra durable-state change log tombstone", error)
        })?;
    Ok(())
}

/// Milliseconds since the Unix epoch, used to stamp `tag_events` (indirectly,
/// via the event's own `timestamp_ms`), `durable_state_changes`, and
/// `durable_state_change_log` rows.
fn current_timestamp_ms() -> i64 {
    i64::try_from(
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|duration| duration.as_millis())
            .unwrap_or_default(),
    )
    .unwrap_or(i64::MAX)
}

#[derive(Debug, scylla::DeserializeRow)]
#[scylla(flavor = "enforce_order", skip_name_checks)]
struct PersistenceIdRow {
    persistence_id: String,
}

fn lwt_applied(result: QueryResult) -> PersistenceResult<bool> {
    let rows = result
        .into_rows_result()
        .map_err(|error| storage_error("decode Cassandra LWT result", error))?;
    let row = rows
        .first_row::<Row>()
        .map_err(|error| storage_error("decode Cassandra LWT row", error))?;
    match row.columns.first().and_then(Option::as_ref) {
        Some(CqlValue::Boolean(applied)) => Ok(*applied),
        other => Err(PersistenceError::Failure(format!(
            "Cassandra LWT result did not contain boolean [applied], got {other:?}"
        ))),
    }
}

fn decode_frame(
    serializer_id: i64,
    manifest: String,
    payload: Vec<u8>,
    context: &str,
) -> PersistenceResult<SerializedPayload> {
    let serializer_id = u32::try_from(serializer_id).map_err(|_| {
        PersistenceError::Failure(format!(
            "{context} serializer id {serializer_id} is outside the u32 range"
        ))
    })?;
    Ok(SerializedPayload::new(
        SerializerId::new(serializer_id),
        manifest,
        payload,
    ))
}

fn decode_optional_frame(
    serializer_id: Option<i64>,
    manifest: Option<String>,
    payload: Option<Vec<u8>>,
    context: &str,
) -> PersistenceResult<Option<SerializedPayload>> {
    match (serializer_id, manifest, payload) {
        (None, None, None) => Ok(None),
        (Some(serializer_id), Some(manifest), Some(payload)) => {
            decode_frame(serializer_id, manifest, payload, context).map(Some)
        }
        _ => Err(PersistenceError::Failure(format!(
            "{context} contains an incomplete serialization frame"
        ))),
    }
}

fn snapshot_sequence_bounds(criteria: &SnapshotCriteria) -> Option<(i64, i64)> {
    if criteria.min_sequence_nr > criteria.max_sequence_nr
        || criteria.min_sequence_nr.as_u64() > i64::MAX as u64
    {
        return None;
    }
    Some((
        i64::try_from(criteria.min_sequence_nr.as_u64()).expect("bound was checked"),
        i64::try_from(criteria.max_sequence_nr.as_u64()).unwrap_or(i64::MAX),
    ))
}

fn partition_nr(sequence_nr: u64, partition_size: u64) -> i64 {
    let zero_based = sequence_nr.saturating_sub(1) / partition_size;
    i64::try_from(zero_based).unwrap_or(i64::MAX)
}

fn partition_start(partition_nr: i64, partition_size: u64) -> i64 {
    let partition = u64::try_from(partition_nr).expect("partition numbers are non-negative");
    let start = partition
        .saturating_mul(partition_size)
        .saturating_add(1)
        .min(i64::MAX as u64);
    i64::try_from(start).expect("partition start was capped")
}

fn partition_end(partition_nr: i64, partition_size: u64) -> i64 {
    let partition = u64::try_from(partition_nr).expect("partition numbers are non-negative");
    let end = partition
        .saturating_add(1)
        .saturating_mul(partition_size)
        .min(i64::MAX as u64);
    i64::try_from(end).expect("partition end was capped")
}

fn validate_config(config: &CassandraPersistenceConfig) -> PersistenceResult<()> {
    if config.contact_points.is_empty()
        || config
            .contact_points
            .iter()
            .any(|contact_point| contact_point.trim().is_empty())
    {
        return Err(PersistenceError::Rejected(
            "Cassandra contact_points must contain at least one non-empty seed".into(),
        ));
    }
    validate_identifier("keyspace", &config.keyspace)?;
    validate_identifier("event journal table", &config.tables.event_journal)?;
    validate_identifier("journal-head table", &config.tables.journal_head)?;
    validate_identifier("snapshot table", &config.tables.snapshot)?;
    validate_identifier("durable-state table", &config.tables.durable_state)?;
    validate_identifier("tag-events table", &config.tables.tag_events)?;
    validate_identifier(
        "durable-state-changes table",
        &config.tables.durable_state_changes,
    )?;
    if config.replication_factor == 0 {
        return Err(PersistenceError::Rejected(
            "Cassandra replication_factor must be greater than zero".into(),
        ));
    }
    if config.partition_size == 0 {
        return Err(PersistenceError::Rejected(
            "Cassandra partition_size must be greater than zero".into(),
        ));
    }
    if config.replay_page_size <= 0 {
        return Err(PersistenceError::Rejected(
            "Cassandra replay_page_size must be greater than zero".into(),
        ));
    }
    if config.polling.batch_size == 0 || config.polling.batch_size > i32::MAX as u32 {
        return Err(PersistenceError::Rejected(
            "Cassandra polling batch_size must be in 1..=i32::MAX".into(),
        ));
    }
    if config.polling.min_interval > config.polling.max_interval {
        return Err(PersistenceError::Rejected(
            "Cassandra polling min_interval must not exceed max_interval".into(),
        ));
    }
    if matches!(
        config.write_consistency,
        Consistency::Any | Consistency::Serial | Consistency::LocalSerial
    ) {
        return Err(PersistenceError::Rejected(
            "Cassandra write_consistency cannot be ANY, SERIAL, or LOCAL_SERIAL; ANY may \
             acknowledge only a hinted handoff and silently lose an acknowledged write"
                .into(),
        ));
    }
    if matches!(
        config.read_consistency,
        Consistency::Any | Consistency::Serial | Consistency::LocalSerial
    ) {
        return Err(PersistenceError::Rejected(
            "Cassandra read_consistency must be a non-serial read consistency".into(),
        ));
    }
    Ok(())
}

fn validate_identifier(name: &str, value: &str) -> PersistenceResult<()> {
    let mut characters = value.chars();
    let valid_first = characters
        .next()
        .is_some_and(|character| character == '_' || character.is_ascii_lowercase());
    if !valid_first
        || !characters.all(|character| {
            character == '_' || character.is_ascii_lowercase() || character.is_ascii_digit()
        })
        || value.len() > MAX_CQL_IDENTIFIER_BYTES
    {
        return Err(PersistenceError::Rejected(format!(
            "invalid Cassandra {name} identifier {value:?}; expected a lowercase ASCII identifier \
             of at most {MAX_CQL_IDENTIFIER_BYTES} bytes"
        )));
    }
    Ok(())
}

fn qualified(keyspace: &str, table: &str) -> String {
    format!("{keyspace}.{table}")
}

fn sql_i64(value: u64, context: &str) -> PersistenceResult<i64> {
    i64::try_from(value).map_err(|_| {
        PersistenceError::Rejected(format!("{context} {value} exceeds Cassandra bigint range"))
    })
}

fn non_negative_u64(value: i64, context: &str) -> PersistenceResult<u64> {
    u64::try_from(value).map_err(|_| {
        PersistenceError::Failure(format!("{context} contains negative value {value}"))
    })
}

fn connection_error(context: &str, error: impl fmt::Display) -> PersistenceError {
    PersistenceError::Connection(format!("{context}: {error}"))
}

fn storage_error(context: &str, error: impl fmt::Display) -> PersistenceError {
    PersistenceError::Failure(format!("{context}: {error}"))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn defaults_and_partition_math_match_the_contract() {
        let config = CassandraPersistenceConfig::new("127.0.0.1:9042", "datum_persistence");
        assert_eq!(config.replication_factor, 1);
        assert_eq!(config.partition_size, 100_000);
        assert_eq!(config.write_consistency, Consistency::LocalQuorum);
        assert_eq!(config.read_consistency, Consistency::LocalQuorum);

        assert_eq!(partition_nr(0, 2), 0);
        assert_eq!(partition_nr(1, 2), 0);
        assert_eq!(partition_nr(2, 2), 0);
        assert_eq!(partition_nr(3, 2), 1);
        assert_eq!(partition_nr(6, 2), 2);
        assert_eq!(partition_start(2, 2), 5);
        assert_eq!(partition_end(2, 2), 6);
    }

    #[test]
    fn configuration_validation_is_side_effect_free_and_strict() {
        let valid = CassandraPersistenceConfig::new("127.0.0.1:9042", "datum_persistence");
        let backend = CassandraPersistence::new(valid.clone()).expect("default config is valid");
        assert!(backend.connected.get().is_none());

        let mut invalid = valid.clone();
        invalid.contact_points.clear();
        assert!(matches!(
            CassandraPersistence::new(invalid),
            Err(PersistenceError::Rejected(_))
        ));

        let mut invalid = valid.clone();
        invalid.partition_size = 0;
        assert!(matches!(
            CassandraPersistence::new(invalid),
            Err(PersistenceError::Rejected(_))
        ));

        let mut invalid = valid;
        invalid.keyspace = "quoted-Keyspace".into();
        assert!(matches!(
            CassandraPersistence::new(invalid),
            Err(PersistenceError::Rejected(_))
        ));
    }

    #[test]
    fn schema_ddl_contains_the_settled_tables_and_keys() {
        let backend = CassandraPersistence::new(CassandraPersistenceConfig::new(
            "127.0.0.1:9042",
            "datum_persistence",
        ))
        .expect("config is valid");
        let ddl = backend.schema_ddl();
        assert!(ddl.contains("'class': 'SimpleStrategy'"));
        assert!(ddl.contains("'replication_factor': 1"));
        assert!(ddl.contains("PRIMARY KEY ((persistence_id, partition_nr), sequence_nr)"));
        assert!(ddl.contains("CLUSTERING ORDER BY (sequence_nr ASC)"));
        assert!(ddl.contains("datum_persistence.journal_head"));
        assert!(ddl.contains("CLUSTERING ORDER BY (sequence_nr DESC)"));
        assert!(ddl.contains("datum_persistence.durable_state"));
        assert!(ddl.contains("datum_persistence.durable_state_change_log"));
        assert!(ddl.contains("PRIMARY KEY (tag, timestamp_ms, revision, persistence_id)"));
    }

    #[test]
    fn atomic_write_crossing_a_partition_is_pre_storage_rejection() {
        let persistence_id = PersistenceId::new("test", "partition").expect("id is valid");
        let event = |sequence_nr| StoredEvent {
            persistence_id: persistence_id.clone(),
            sequence_nr: SequenceNr::new(sequence_nr),
            adapter_manifest: String::new(),
            writer_uuid: "writer".into(),
            timestamp_ms: 0,
            metadata: None,
            payload: SerializedPayload::new(SerializerId::new(1), "", Vec::new()),
            tags: Vec::new(),
        };
        let write = AtomicWrite::new(vec![event(2), event(3)]).expect("write is gapless");
        let rejection = PreparedAtomicWrite::new(write, 2).expect_err("write crosses partitions");
        assert!(rejection.contains("crosses Cassandra journal partitions"));
    }
}