cqlite-core 0.11.0

Core engine for CQLite — read Apache Cassandra 5.0 SSTables locally without a cluster
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
//! Data.db writer - writes partition and row data
//!
//! Generates the Data.db component with V5CompressedLegacy (NB) format.
//! Maintains partition ordering by Murmur3 token and clustering ordering.
//! Tracks file positions for Index.db generation.
//!
//! Critical requirements:
//! - Partition ordering: By Murmur3 token, then key bytes (enforced by caller)
//! - Clustering ordering: By clustering comparator within partition (enforced by caller)
//! - Row size measurement: After VInt length bytes (Issue #237)
//! - Delta encoding: Uses Statistics.db baseline for timestamps/TTL/deletion times
//!
//! # V5CompressedLegacy Row Format
//!
//! Each row is encoded as:
//! ```text
//! [row_flags: u8]
//! [extended_flags: u8 if ROW_HAS_EXTENDED_FLAGS set]
//! [clustering_prefix: variable if present]
//! [row_size: VInt]                       ← Measured from AFTER this VInt
//! [prev_size: VInt]
//! [timestamp: VInt if ROW_HAS_TIMESTAMP]   ← Delta from min_timestamp
//! [ttl: VInt if ROW_HAS_TTL]              ← Delta from min_ttl
//! [deletion: 2 VInts if ROW_HAS_DELETION] ← local_deletion_time delta + deletion timestamp
//! [column_bitmap: VUInt bitmask of missing columns if NOT ROW_HAS_ALL_COLUMNS]
//! [cell_data...]
//! ```
//!
//! ## Row Flags
//! - `0x04` (HAS_TIMESTAMP): Timestamp delta present
//! - `0x08` (HAS_TTL): TTL delta present
//! - `0x10` (HAS_DELETION): Deletion time present (two VInts)
//! - `0x20` (HAS_ALL_COLUMNS): All columns present (no bitmap)
//! - `0x40` (HAS_COMPLEX_DELETION): Row contains complex column with deletion
//! - `0x80` (HAS_EXTENDED_FLAGS): Extended flags byte follows
//!
//! ## Cell Format
//! ```text
//! [flags: u8]
//! [timestamp: VInt if NOT USE_ROW_TIMESTAMP]  ← Delta from min_timestamp
//! [local_deletion_time: VUInt if deleted/expiring and NOT USE_ROW_TTL]
//! [ttl: VUInt if expiring and NOT USE_ROW_TTL]
//! [value_length: VInt]
//! [value_bytes]
//! ```
//!
//! ## Cell Flags
//! - `0x01` (IS_DELETED): Cell is a tombstone
//! - `0x02` (IS_EXPIRING): TTL fields follow
//! - `0x04` (HAS_EMPTY_VALUE): Zero-length value
//! - `0x08` (USE_ROW_TIMESTAMP): Use row-level timestamp (no timestamp delta)
//! - `0x10` (USE_ROW_TTL): Use row-level TTL (no TTL delta)
//!
//! References:
//! - Cassandra 5.0: `org.apache.cassandra.db.rows.UnfilteredSerializer`
//! - Parser: `cqlite-core/src/storage/sstable/reader/parsing/v5_compressed_legacy.rs`
//! - Format docs: `docs/sstables-definitive-guide/chapters/05-data-db-format.md`

use crate::error::{Error, Result};
use crate::schema::{Column, CqlType, TableSchema};
use crate::storage::serialization::types::TypeSerializer;
use crate::storage::serialization::vint::{encode_signed, encode_unsigned, unsigned_len};
use crate::storage::sstable::writer::stats_writer::StatisticsMetadata;
use crate::storage::write_engine::mutation::{
    ClusteringBound, ClusteringKey, DecoratedKey, Mutation, PartitionKey, PartitionTombstone,
    RangeTombstone, TableId,
};
use crate::types::{ComparatorType, UdtTypeDef, Value};
use std::io::Write;
use std::path::PathBuf;

// Row header flag constants (from V5CompressedLegacy parser)
const ROW_HAS_TIMESTAMP: u8 = 0x04;
const ROW_HAS_TTL: u8 = 0x08;
#[allow(dead_code)]
const ROW_HAS_DELETION: u8 = 0x10;
const ROW_HAS_ALL_COLUMNS: u8 = 0x20;
const ROW_HAS_COMPLEX_DELETION: u8 = 0x40;
const ROW_HAS_EXTENDED_FLAGS: u8 = 0x80;

// Extended flag constants (when ROW_HAS_EXTENDED_FLAGS is set)
const EXTENDED_IS_STATIC: u8 = 0x01;

// Cell flag constants (from V5CompressedLegacy parser)
const CELL_IS_DELETED: u8 = 0x01;
const CELL_IS_EXPIRING: u8 = 0x02;
const CELL_HAS_EMPTY_VALUE: u8 = 0x04;
const CELL_USE_ROW_TIMESTAMP: u8 = 0x08;
#[allow(dead_code)]
const CELL_USE_ROW_TTL: u8 = 0x10;

// Range tombstone marker constants
const IS_MARKER: u8 = 0x02;

// Range tombstone bound kinds.
//
// These are the ordinals of Cassandra's `ClusteringPrefix.Kind` enum
// (ClusteringPrefix.java) — the byte written on disk by
// `ClusteringBoundOrBoundary.Serializer.serialize()`:
//   0 = EXCL_END_BOUND, 1 = INCL_START_BOUND,
//   2 = EXCL_END_INCL_START_BOUNDARY, 3 = STATIC_CLUSTERING,
//   4 = CLUSTERING, 5 = INCL_END_EXCL_START_BOUNDARY,
//   6 = INCL_END_BOUND, 7 = EXCL_START_BOUND.
// (Issue #717: the writer previously used a private 0..5 numbering that no
// Cassandra reader understands.)
const EXCL_END_BOUND: u8 = 0;
const INCL_START_BOUND: u8 = 1;
const INCL_END_BOUND: u8 = 6;
const EXCL_START_BOUND: u8 = 7;

// Partition/row markers
const END_OF_PARTITION: u8 = 0x01;

/// Capacity of the streaming Data.db `BufWriter` (Issue #492).
///
/// Large enough that each flushed partition coalesces into a handful of big
/// `write()` syscalls instead of many small default-8 KB ones, preserving the
/// throughput of the previous single whole-file write while keeping resident
/// memory bounded (this buffer plus one partition's scratch).
const DATA_SINK_BUFFER_BYTES: usize = 1024 * 1024;

/// Data.db component writer
///
/// Writes partitions and rows in V5CompressedLegacy format with delta encoding.
/// Caller must provide partitions in token order and rows in clustering order.
///
/// # Memory model (Issue #492)
///
/// The writer supports two modes that produce **byte-identical** Data.db output:
///
/// * **In-memory mode** (`DataWriter::new`): every partition is appended to the
///   `buffer` scratch and never flushed, so `finish()` returns the full Data.db
///   bytes. Used by unit tests that inspect the produced bytes directly.
///
/// * **Streaming mode** (`DataWriter::with_sink`): each partition is built in the
///   `buffer` scratch, written to a `BufWriter<File>` over the Data.db path, and
///   the scratch is cleared. Peak heap is therefore `O(largest partition)` rather
///   than `O(file)`, keeping a multi-GB compaction within the 128 MB target.
///
/// In both modes the file offset of a partition is `position + buffer.len()`
/// measured before any bytes are written. In streaming mode `buffer` is empty at
/// that point (just cleared) so the offset is `position`; in memory mode
/// `position` is always 0 and `buffer` holds all prior partitions, so the offset
/// equals the legacy `buffer.len()`. The within-partition size math uses relative
/// deltas into `buffer`, which are identical regardless of mode.
#[derive(Debug)]
pub struct DataWriter {
    /// Per-partition scratch buffer for Data.db content.
    ///
    /// In streaming mode this is cleared at the start of every `write_partition`
    /// and flushed to `sink` at the end, so only one partition is resident.
    /// In memory mode it accumulates the entire Data.db output.
    buffer: Vec<u8>,
    /// Streaming sink over the Data.db path (streaming mode only).
    ///
    /// Lazily opened on the first `write_partition` so that the keyspace/table
    /// directory exists before the first byte is written. `None` in in-memory
    /// mode.
    sink: Option<std::io::BufWriter<std::fs::File>>,
    /// Data.db output path (streaming mode only); used for lazy sink open.
    data_path: Option<PathBuf>,
    /// Bytes already flushed to `sink`. Always 0 in in-memory mode.
    position: u64,
    /// Statistics metadata for delta encoding
    stats: StatisticsMetadata,
}

impl DataWriter {
    /// Create a new in-memory Data.db writer.
    ///
    /// All partitions accumulate in `buffer`; `finish()` returns the full bytes.
    /// Prefer [`DataWriter::with_sink`] for production writes to bound memory.
    ///
    /// # Arguments
    /// * `stats` - Statistics metadata for delta encoding baselines
    pub fn new(stats: StatisticsMetadata) -> Self {
        Self {
            buffer: Vec::new(),
            sink: None,
            data_path: None,
            position: 0,
            stats,
        }
    }

    /// Create a streaming Data.db writer that flushes each partition to `data_path`.
    ///
    /// The file is opened lazily on the first `write_partition` (creating the
    /// parent directory if needed) so the keyspace/table layout is established
    /// before any bytes are written. Memory is bounded to the largest single
    /// partition.
    ///
    /// # Arguments
    /// * `stats` - Statistics metadata for delta encoding baselines
    /// * `data_path` - Destination path for the Data.db component
    pub fn with_sink(stats: StatisticsMetadata, data_path: PathBuf) -> Self {
        Self {
            buffer: Vec::new(),
            sink: None,
            data_path: Some(data_path),
            position: 0,
            stats,
        }
    }

    /// Lazily open the streaming sink (and create the parent directory).
    ///
    /// No-op in in-memory mode or once the sink is already open.
    fn ensure_sink(&mut self) -> Result<()> {
        if self.sink.is_some() {
            return Ok(());
        }
        if let Some(path) = self.data_path.clone() {
            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent)?;
            }
            let file = std::fs::File::create(&path)?;
            // Use a large BufWriter so a partition's bytes coalesce into a few
            // big write() syscalls rather than many 8 KB-default ones, matching
            // the throughput of the old single whole-file write.
            self.sink = Some(std::io::BufWriter::with_capacity(
                DATA_SINK_BUFFER_BYTES,
                file,
            ));
        }
        Ok(())
    }

    /// In streaming mode, flush the current scratch buffer to the sink, advance
    /// `position`, and clear the scratch so only one partition is ever resident.
    /// No-op in in-memory mode (the scratch keeps accumulating).
    fn flush_partition(&mut self) -> Result<()> {
        if self.data_path.is_none() {
            // In-memory mode: keep accumulating in `buffer`.
            return Ok(());
        }
        self.ensure_sink()?;
        if let Some(sink) = self.sink.as_mut() {
            sink.write_all(&self.buffer)?;
        }
        self.position += self.buffer.len() as u64;
        self.buffer.clear();
        Ok(())
    }

    /// Update the statistics metadata
    ///
    /// This should be called after computing stats from all mutations
    /// but before writing any partition data. The stats are used for
    /// delta encoding of timestamps, TTL, and local deletion times.
    pub fn update_stats(&mut self, stats: StatisticsMetadata) {
        self.stats = stats;
    }

    /// Write a complete partition (partition key + all rows)
    ///
    /// # Arguments
    /// * `key` - Decorated partition key (token + raw bytes)
    /// * `mutations` - All mutations for this partition (must be in clustering order)
    /// * `schema` - Table schema for column metadata
    /// * `partition_tombstone` - Optional partition-level tombstone
    /// * `range_tombstones` - Range tombstones for this partition (must be in clustering order)
    ///
    /// # Returns
    /// File offset where this partition starts (for Index.db)
    pub fn write_partition(
        &mut self,
        key: &DecoratedKey,
        mutations: &[Mutation],
        schema: &TableSchema,
        partition_tombstone: Option<&PartitionTombstone>,
        range_tombstones: &[RangeTombstone],
    ) -> Result<u64> {
        // File offset of this partition = bytes already flushed (`position`) plus
        // whatever is currently buffered. In streaming mode `buffer` is empty at
        // the start of each partition (flushed + cleared by the previous call),
        // so this is `position`; in in-memory mode `position` is 0 and `buffer`
        // holds all prior partitions, matching the legacy `buffer.len()`.
        let partition_offset = self.position + self.buffer.len() as u64;

        // Write partition header (with optional tombstone)
        let header_start = self.buffer.len();
        self.write_partition_header(key, partition_tombstone)?;
        let mut prev_unfiltered_size = (self.buffer.len() - header_start) as u64;

        // SSTables must be internally reconciled: Cassandra's read path and
        // compaction only reconcile rows against deletions from OTHER sources
        // (memtables / other sstables) — a row shadowed by a partition or
        // range tombstone in the SAME sstable is served live. Cassandra's own
        // flush drops shadowed data, and so must we (Issue #716/#717).
        // `partition_floor` is the shadow timestamp from the partition
        // tombstone; per-row floors additionally account for covering range
        // tombstones.
        let partition_floor = partition_tombstone.map(|pt| pt.deletion_time);

        // Cassandra's SerializationHeader.hasStatic() returns true whenever the schema
        // declares any static column — and both the writer and reader unconditionally
        // emit/consume a static-row prelude in that case.  We must do the same.
        let schema_has_static = schema.columns.iter().any(|c| c.is_static);

        if schema_has_static {
            // Collect static-column operations from ALL mutations in this partition,
            // regardless of whether the mutation also carries a clustering key.
            // Last-write-wins by timestamp_micros when the same column appears twice.
            // Static cells shadowed by the partition tombstone are dropped.
            let merged = collect_static_operations(mutations, schema, partition_floor);

            // Mutations shadowed by the partition tombstone cannot contribute
            // the static row's liveness timestamp or TTL either.
            let unshadowed_static = |m: &&Mutation| {
                partition_floor.is_none_or(|floor| m.timestamp_micros > floor)
                    && has_static_operation(m, schema)
            };

            if merged.is_empty() {
                // Schema declares statics but this partition writes none.
                // Cassandra still expects the prelude; emit the minimal empty form.
                prev_unfiltered_size =
                    self.write_empty_static_row(prev_unfiltered_size, schema)? as u64;
            } else {
                // Build a synthetic Mutation carrying the merged static ops.
                // Use the latest timestamp seen across contributing mutations.
                // `!merged.is_empty()` implies at least one mutation contributed
                // an unshadowed static op, so the inner `.max()` is guaranteed `Some`.
                let latest_ts = mutations
                    .iter()
                    .filter(unshadowed_static)
                    .map(|m| m.timestamp_micros)
                    .max()
                    .unwrap_or(mutations.first().map(|m| m.timestamp_micros).unwrap_or(0));

                // Pick the TTL from the mutation with the latest timestamp that
                // contributed a static op (mirrors Cassandra's last-write-wins).
                let ttl = mutations
                    .iter()
                    .filter(unshadowed_static)
                    .max_by_key(|m| m.timestamp_micros)
                    .and_then(|m| m.ttl_seconds);

                let synthetic = Mutation {
                    table: mutations
                        .first()
                        .map(|m| m.table.clone())
                        .unwrap_or_else(|| TableId {
                            keyspace: schema.keyspace.clone(),
                            table: schema.table.clone(),
                        }),
                    partition_key: mutations
                        .first()
                        .map(|m| m.partition_key.clone())
                        .unwrap_or_else(|| PartitionKey {
                            columns: Vec::new(),
                        }),
                    clustering_key: None,
                    operations: merged,
                    timestamp_micros: latest_ts,
                    ttl_seconds: ttl,
                    partition_tombstone: None,
                    range_tombstones: Vec::new(),
                };

                prev_unfiltered_size =
                    self.write_static_row_with_prev_size(&synthetic, schema, prev_unfiltered_size)?
                        as u64;
            }
        }

        // Merge all mutations sharing a clustering key into a single row each
        // (Issue #716/#717: writing one row per mutation produced duplicate
        // rows with equal clustering — e.g. an INSERT row plus a phantom
        // tombstone-carrier row — which is invalid in the OA format). Rows
        // shadowed by the partition tombstone or a covering range tombstone
        // are dropped during the merge.
        let rows = self.merge_clustering_rows(
            mutations,
            schema,
            schema_has_static,
            partition_floor,
            range_tombstones,
        );

        // Interleave merged rows with range tombstone bound markers in
        // clustering order. Cassandra requires every unfiltered (row or
        // marker) of a partition to appear in clustering order; with equal
        // clustering values, inclusive-start/exclusive-end bounds sort before
        // the row and inclusive-end/exclusive-start bounds sort after it
        // (ClusteringPrefix.Kind.comparedToClustering).
        enum PartitionItem<'a> {
            Row(RowWrite<'a>),
            Marker {
                bound: &'a ClusteringBound,
                is_open: bool,
                deletion_time: i64,
                local_deletion_time: i32,
            },
        }

        let mut items: Vec<PartitionItem> = rows.into_iter().map(PartitionItem::Row).collect();
        for rt in range_tombstones {
            items.push(PartitionItem::Marker {
                bound: &rt.start,
                is_open: true,
                deletion_time: rt.deletion_time,
                local_deletion_time: rt.local_deletion_time,
            });
            items.push(PartitionItem::Marker {
                bound: &rt.end,
                is_open: false,
                deletion_time: rt.deletion_time,
                local_deletion_time: rt.local_deletion_time,
            });
        }

        // Sort key: (partition position class, clustering values, bound weight).
        // class: -1 = before all rows (Bottom), 0 = positioned by clustering
        // values, 1 = after all rows (Top).
        fn sort_class<'a, 'b>(item: &'b PartitionItem<'a>) -> (i8, Option<&'b ClusteringKey>, i8) {
            match item {
                PartitionItem::Row(row) => (0, row.clustering_key, 0),
                PartitionItem::Marker { bound, is_open, .. } => match bound {
                    ClusteringBound::Inclusive(ck) => (0, Some(ck), if *is_open { -1 } else { 1 }),
                    ClusteringBound::Exclusive(ck) => (0, Some(ck), if *is_open { 1 } else { -1 }),
                    ClusteringBound::Bottom => (-1, None, 0),
                    ClusteringBound::Top => (1, None, 0),
                },
            }
        }
        items.sort_by(|a, b| {
            let (class_a, ck_a, weight_a) = sort_class(a);
            let (class_b, ck_b, weight_b) = sort_class(b);
            class_a
                .cmp(&class_b)
                .then_with(|| match (ck_a, ck_b) {
                    (Some(x), Some(y)) => x.compare(y, schema).unwrap_or_else(|_| x.cmp(y)),
                    _ => std::cmp::Ordering::Equal,
                })
                .then(weight_a.cmp(&weight_b))
        });

        for item in items {
            prev_unfiltered_size = match item {
                PartitionItem::Row(row) => {
                    self.write_merged_row_with_prev_size(&row, schema, prev_unfiltered_size)? as u64
                }
                PartitionItem::Marker {
                    bound,
                    is_open,
                    deletion_time,
                    local_deletion_time,
                } => self.write_range_bound(
                    bound,
                    is_open,
                    deletion_time,
                    local_deletion_time,
                    schema,
                    prev_unfiltered_size,
                )? as u64,
            };
        }

        // Write end-of-partition marker
        self.buffer.push(END_OF_PARTITION);

        // Streaming mode: flush this partition to disk and clear the scratch so
        // only one partition is ever resident in memory. No-op in memory mode.
        self.flush_partition()?;

        Ok(partition_offset)
    }

    /// Write an empty static-row prelude.
    ///
    /// Required by Cassandra whenever the schema has any static column, even
    /// when this particular partition writes no static cells.
    ///
    /// Binary form:
    /// ```text
    /// [0x80]              ← row_flags = ROW_HAS_EXTENDED_FLAGS only
    /// [0x01]              ← extended_flags = EXTENDED_IS_STATIC
    /// [row_size: VUInt]   ← size of (prev_size VInt + bitmap)
    /// [prev_size: VUInt]
    /// [bitmap: VUInt]     ← all-missing bitmap: (1 << N) - 1 for N static cols
    ///                       (encoded via write_column_subset with empty present set)
    /// ```
    fn write_empty_static_row(&mut self, prev_size: u64, schema: &TableSchema) -> Result<usize> {
        let start_len = self.buffer.len();

        // flags = only HAS_EXTENDED_FLAGS; no timestamp, no TTL, no deletion,
        // no HAS_ALL_COLUMNS, no HAS_COMPLEX_DELETION.
        let flags: u8 = ROW_HAS_EXTENDED_FLAGS;
        self.buffer.push(flags);
        self.buffer.push(EXTENDED_IS_STATIC);

        // Build the row body: just prev_size VInt + column bitmap (all missing).
        let mut body = Vec::new();

        // Column bitmap: "all columns missing" for every static column.
        // write_column_subset with an empty present_set.
        let static_columns = self.static_columns(schema);
        let empty_present: std::collections::HashSet<&str> = std::collections::HashSet::new();
        self.write_column_subset(&mut body, &static_columns, &empty_present)?;

        let prev_size_vint_len = unsigned_len(prev_size);
        let row_body_size = prev_size_vint_len as u64 + body.len() as u64;

        let mut row_size_buf = Vec::new();
        encode_unsigned(row_body_size, &mut row_size_buf);
        self.buffer.extend_from_slice(&row_size_buf);

        encode_unsigned(prev_size, &mut self.buffer);
        self.buffer.extend_from_slice(&body);

        Ok(self.buffer.len() - start_len)
    }

    /// Finish writing and return the Data.db bytes (in-memory mode).
    ///
    /// Only valid for writers created via [`DataWriter::new`]. In streaming mode
    /// the bytes live on disk; use [`DataWriter::finish_streaming`] instead.
    pub fn finish(self) -> Result<Vec<u8>> {
        // Hard guard (not debug_assert!, which compiles out in release): on a
        // streaming writer the bytes live on disk and `buffer` is empty after each
        // partition flush, so returning it would silently yield a 0-byte Data.db.
        if self.data_path.is_some() {
            return Err(Error::InvalidInput(
                "DataWriter::finish() called on a streaming writer; use finish_streaming()"
                    .to_string(),
            ));
        }
        Ok(self.buffer)
    }

    /// Finish a streaming writer: flush the sink to disk and return the total
    /// number of Data.db bytes written (i.e. `data_size`).
    ///
    /// Any residual scratch (there is none in normal operation, since
    /// `write_partition` flushes per partition) is flushed first. Returns an
    /// error if the writer was created in in-memory mode.
    pub fn finish_streaming(mut self) -> Result<u64> {
        if self.data_path.is_none() {
            return Err(Error::InvalidInput(
                "finish_streaming() called on an in-memory DataWriter".to_string(),
            ));
        }
        // Flush any residual scratch (normally empty), then flush the sink so all
        // bytes reach the OS file (the subsequent Digest CRC re-read of the same
        // file sees them via the page cache). This matches the durability of the
        // previous `tokio::fs::write`, which did not fsync either.
        self.flush_partition()?;
        if let Some(mut sink) = self.sink.take() {
            sink.flush()?;
        }
        Ok(self.position)
    }

    /// Write partition header
    ///
    /// Format (V5CompressedLegacy / Cassandra BigFormat):
    /// ```text
    /// [key_length: u16 BE]           ← Partition key length (2-byte unsigned short)
    /// [key_bytes]                    ← Raw partition key bytes
    /// [local_deletion_time: i32 BE]  ← i32::MAX for LIVE (DeletionTime.LIVE)
    /// [deletion_timestamp: i64 BE]   ← i64::MIN for LIVE (DeletionTime.LIVE)
    /// ```
    ///
    /// Note: Cassandra uses `ByteBufferUtil.writeWithShortLength()` for the key,
    /// which is a 2-byte BE unsigned short. There is NO separate flags byte.
    /// DeletionTime.LIVE uses sentinel values (Integer.MAX_VALUE, Long.MIN_VALUE).
    fn write_partition_header(
        &mut self,
        key: &DecoratedKey,
        tombstone: Option<&PartitionTombstone>,
    ) -> Result<()> {
        // Partition key length (u16 BE, matching Cassandra's writeWithShortLength)
        if key.key.len() > 65535 {
            return Err(Error::InvalidInput(format!(
                "Partition key too large: {} bytes (max 65535)",
                key.key.len()
            )));
        }
        self.buffer
            .write_all(&(key.key.len() as u16).to_be_bytes())?;

        // Partition key bytes
        self.buffer.extend_from_slice(&key.key);

        // Partition deletion info
        if let Some(ts) = tombstone {
            // Local deletion time (i32 BE, in seconds)
            self.buffer
                .write_all(&ts.local_deletion_time.to_be_bytes())?;
            // Deletion timestamp (i64 BE, in microseconds)
            self.buffer.write_all(&ts.deletion_time.to_be_bytes())?;
        } else {
            // DeletionTime.LIVE: Cassandra uses (Integer.MAX_VALUE, Long.MIN_VALUE)
            self.buffer.write_all(&i32::MAX.to_be_bytes())?;
            self.buffer.write_all(&i64::MIN.to_be_bytes())?;
        }

        Ok(())
    }

    /// Write a single row
    ///
    /// This implements the V5CompressedLegacy row format with delta encoding.
    #[allow(dead_code)]
    fn write_row(&mut self, mutation: &Mutation, schema: &TableSchema) -> Result<()> {
        self.write_row_with_prev_size(mutation, schema, 0)?;
        Ok(())
    }

    /// Write a single mutation as one row. Thin adapter over the merged-row
    /// path so legacy callers (and unit tests) keep working.
    fn write_row_with_prev_size(
        &mut self,
        mutation: &Mutation,
        schema: &TableSchema,
        prev_size: u64,
    ) -> Result<usize> {
        match Self::merge_row_group(&[mutation], schema, false, None) {
            Some(row) => self.write_merged_row_with_prev_size(&row, schema, prev_size),
            // Nothing to write (e.g. a tombstone-carrier mutation with no ops)
            None => Ok(0),
        }
    }

    /// Group same-clustering mutations of a partition and merge each group
    /// into a single [`RowWrite`].
    ///
    /// Mutations must already be sorted by clustering key (the caller —
    /// `SSTableWriter::write_partition` — sorts them); grouping is by
    /// adjacency. Pure-static mutations are excluded (their cells live in the
    /// static-row prelude), and groups that merge to nothing (e.g. mutations
    /// that exist only to carry partition/range tombstones) produce no row.
    fn merge_clustering_rows<'a>(
        &self,
        mutations: &'a [Mutation],
        schema: &TableSchema,
        skip_static_ops: bool,
        partition_floor: Option<i64>,
        range_tombstones: &[RangeTombstone],
    ) -> Vec<RowWrite<'a>> {
        let row_mutations: Vec<&'a Mutation> = mutations
            .iter()
            .filter(|m| !is_static_row_mutation(m, schema))
            .collect();

        let mut rows = Vec::new();
        let mut start = 0;
        while start < row_mutations.len() {
            let mut end = start + 1;
            while end < row_mutations.len()
                && row_mutations[end].clustering_key == row_mutations[start].clustering_key
            {
                end += 1;
            }

            // Shadow floor for this row: partition tombstone plus any range
            // tombstone covering the group's clustering key.
            let clustering_key = row_mutations[start].clustering_key.as_ref();
            let mut shadow_floor = partition_floor;
            for rt in range_tombstones {
                if range_tombstone_covers(rt, clustering_key, schema) {
                    shadow_floor =
                        Some(shadow_floor.map_or(rt.deletion_time, |f| f.max(rt.deletion_time)));
                }
            }

            if let Some(row) = Self::merge_row_group(
                &row_mutations[start..end],
                schema,
                skip_static_ops,
                shadow_floor,
            ) {
                rows.push(row);
            }
            start = end;
        }
        rows
    }

    /// Merge a group of mutations sharing one clustering key into a single
    /// row, applying Cassandra reconciliation semantics at write time:
    ///
    /// - Row deletion: the newest `DeleteRow` wins; mutations at or before
    ///   the deletion timestamp are shadowed (`DeletionTime.deletes` uses
    ///   `timestamp <= markedForDeleteAt`).
    /// - Cells: last-write-wins per column by timestamp; a tombstone wins a
    ///   timestamp tie (Cassandra cell reconciliation).
    /// - Liveness: from the newest surviving mutation that writes cells, or
    ///   a pure primary-key insert (no ops and no tombstone payload). Pure
    ///   row tombstones carry NO liveness, matching Cassandra's serializer.
    ///
    /// Returns `None` when the group produces no row at all (e.g. a mutation
    /// that exists only to carry a partition or range tombstone, or a row
    /// fully shadowed by the partition/range tombstone `shadow_floor`).
    fn merge_row_group<'a>(
        group: &[&'a Mutation],
        schema: &TableSchema,
        skip_static_ops: bool,
        shadow_floor: Option<i64>,
    ) -> Option<RowWrite<'a>> {
        use crate::storage::write_engine::mutation::CellOperation;

        // Newest row deletion in the group (if any). A row deletion at or
        // before the shadow floor is redundant (the partition/range tombstone
        // already covers it) and is dropped.
        let mut row_deletion: Option<(i64, i32)> = None;
        for m in group {
            let has_delete_row = m
                .operations
                .iter()
                .any(|op| matches!(op, CellOperation::DeleteRow));
            if has_delete_row
                && shadow_floor.is_none_or(|floor| m.timestamp_micros > floor)
                && row_deletion.is_none_or(|(ts, _)| m.timestamp_micros >= ts)
            {
                row_deletion = Some((m.timestamp_micros, (m.timestamp_micros / 1_000_000) as i32));
            }
        }
        // Cells and liveness are shadowed by the strongest covering deletion:
        // the row deletion or the partition/range tombstone floor.
        let deletion_ts = match (row_deletion.map(|(ts, _)| ts), shadow_floor) {
            (Some(a), Some(b)) => Some(a.max(b)),
            (a, b) => a.or(b),
        };

        // Per-column last-write-wins; tombstones win timestamp ties.
        let mut cells: std::collections::HashMap<&'a str, MergedOp<'a>> =
            std::collections::HashMap::new();
        // Liveness: (timestamp, row-level TTL) of the newest contributing mutation
        let mut liveness: Option<(i64, Option<u32>)> = None;

        for m in group {
            // Shadowed entirely by the row deletion
            if deletion_ts.is_some_and(|dts| m.timestamp_micros <= dts) {
                continue;
            }

            let mut contributes_liveness = false;
            for op in &m.operations {
                let column = match op {
                    CellOperation::Write { column, .. }
                    | CellOperation::WriteWithTtl { column, .. }
                    | CellOperation::Delete { column } => column.as_str(),
                    CellOperation::DeleteRow => continue,
                };
                if skip_static_ops && is_static_operation(op, schema) {
                    continue;
                }
                if matches!(
                    op,
                    CellOperation::Write { .. } | CellOperation::WriteWithTtl { .. }
                ) {
                    contributes_liveness = true;
                }

                let candidate = MergedOp {
                    op,
                    timestamp_micros: m.timestamp_micros,
                    row_ttl_seconds: m.ttl_seconds,
                };
                match cells.entry(column) {
                    std::collections::hash_map::Entry::Vacant(entry) => {
                        entry.insert(candidate);
                    }
                    std::collections::hash_map::Entry::Occupied(mut entry) => {
                        let existing = entry.get();
                        let candidate_is_tombstone =
                            matches!(candidate.op, CellOperation::Delete { .. });
                        let wins = candidate.timestamp_micros > existing.timestamp_micros
                            || (candidate.timestamp_micros == existing.timestamp_micros
                                && (candidate_is_tombstone
                                    || !matches!(existing.op, CellOperation::Delete { .. })));
                        if wins {
                            entry.insert(candidate);
                        }
                    }
                }
            }

            // A mutation with no ops and no tombstone payload is a pure
            // primary-key insert: it creates row liveness but no cells.
            let pure_pk_insert = m.operations.is_empty()
                && m.partition_tombstone.is_none()
                && m.range_tombstones.is_empty();
            if (contributes_liveness || pure_pk_insert)
                && liveness.is_none_or(|(ts, _)| m.timestamp_micros >= ts)
            {
                liveness = Some((m.timestamp_micros, m.ttl_seconds));
            }
        }

        let ops: Vec<MergedOp<'a>> = cells.into_values().collect();
        if ops.is_empty() && row_deletion.is_none() && liveness.is_none() {
            return None;
        }

        Some(RowWrite {
            clustering_key: group[0].clustering_key.as_ref(),
            liveness_ts: liveness.map(|(ts, _)| ts),
            ttl_seconds: liveness.and_then(|(_, ttl)| ttl),
            row_deletion,
            ops,
        })
    }

    /// Write one merged row (flags + clustering prefix + sizes + body).
    fn write_merged_row_with_prev_size(
        &mut self,
        row: &RowWrite<'_>,
        schema: &TableSchema,
        prev_size: u64,
    ) -> Result<usize> {
        use crate::storage::write_engine::mutation::CellOperation;

        let start_len = self.buffer.len();

        // Build row header flags
        let mut flags = 0u8;

        if row.row_deletion.is_some() {
            flags |= ROW_HAS_DELETION; // 0x10
        }
        if row.liveness_ts.is_some() {
            flags |= ROW_HAS_TIMESTAMP;
            if row.ttl_seconds.is_some() {
                flags |= ROW_HAS_TTL;
            }
        }

        // All columns present if there is no deletion, all surviving ops are
        // non-NULL writes, and they cover every regular column.
        if row.row_deletion.is_none() {
            let all_writes = row.ops.iter().all(|mop| {
                matches!(
                    mop.op,
                    CellOperation::Write { .. } | CellOperation::WriteWithTtl { .. }
                )
            });
            let has_nulls = row.ops.iter().any(|mop| match mop.op {
                CellOperation::Write { value, .. } | CellOperation::WriteWithTtl { value, .. } => {
                    matches!(value, Value::Null)
                }
                _ => false,
            });
            let regular_column_count = self.regular_columns(schema).len();
            if all_writes && !has_nulls && row.ops.len() == regular_column_count {
                flags |= ROW_HAS_ALL_COLUMNS;
            }
        }

        // Check if any operation targets a complex column (non-frozen collection)
        let has_complex = row.ops.iter().any(|mop| {
            let col_name = match mop.op {
                CellOperation::Write { column, .. }
                | CellOperation::WriteWithTtl { column, .. }
                | CellOperation::Delete { column } => Some(column.as_str()),
                _ => None,
            };
            col_name.is_some_and(|name| {
                schema
                    .columns
                    .iter()
                    .find(|c| c.name == name)
                    .map(|c| is_complex_column(&c.data_type))
                    .unwrap_or(false)
            })
        });
        if has_complex {
            flags |= ROW_HAS_COMPLEX_DELETION;
        }

        // Write row flags
        self.buffer.push(flags);

        // Write clustering prefix if present (before row_size)
        if let Some(clustering_key) = row.clustering_key {
            self.write_clustering_prefix(clustering_key, schema)?;
        }

        // Calculate row body size (everything after row_size VInt)
        let row_body = self.build_merged_row_body(row, schema, flags)?;

        let prev_size_vint_len = unsigned_len(prev_size);

        // Write row_size (VInt) — Cassandra's serializedRowBodySize() includes
        // the prev_unfiltered_size VInt as part of the row body
        let row_body_size = prev_size_vint_len as u64 + row_body.len() as u64;
        let mut row_size_buf = Vec::new();
        encode_unsigned(row_body_size, &mut row_size_buf);
        self.buffer.extend_from_slice(&row_size_buf);

        // Write prev_unfiltered_size (VInt, inside the row body)
        encode_unsigned(prev_size, &mut self.buffer);

        // Write rest of row body
        self.buffer.extend_from_slice(&row_body);

        Ok(self.buffer.len() - start_len)
    }

    /// Write a static row for the current partition
    ///
    /// Static rows contain STATIC column values at partition level.
    /// They use extended flags and have NO clustering prefix.
    ///
    /// # Arguments
    /// * `mutation` - Mutation containing static column values
    /// * `schema` - Table schema for column metadata
    ///
    /// # Binary Format
    /// ```text
    /// [row_flags: u8]        ← 0x80 | other_flags (always HAS_EXTENDED_FLAGS)
    /// [extended_flags: u8]   ← 0x01 (EXTENDED_IS_STATIC)
    /// [row_size: VInt]       ← Size of body after this
    /// [prev_size: VInt]      ← 0 or previous row size
    /// [timestamp: VInt]      ← If HAS_TIMESTAMP (delta)
    /// [ttl: VInt]            ← If HAS_TTL (delta)
    /// [deletion: 2 VInts]    ← If HAS_DELETION
    /// [column_bitmap]        ← If NOT HAS_ALL_COLUMNS
    /// [cell_data...]         ← Static column cells only
    /// ```
    pub fn write_static_row(&mut self, mutation: &Mutation, schema: &TableSchema) -> Result<()> {
        self.write_static_row_with_prev_size(mutation, schema, 0)?;
        Ok(())
    }

    fn write_static_row_with_prev_size(
        &mut self,
        mutation: &Mutation,
        schema: &TableSchema,
        prev_size: u64,
    ) -> Result<usize> {
        let start_len = self.buffer.len();

        // Build row header flags - always includes HAS_EXTENDED_FLAGS for static rows
        let mut flags = ROW_HAS_EXTENDED_FLAGS;

        // Check if this is a row tombstone
        let is_row_tombstone = mutation.operations.iter().any(|op| {
            matches!(
                op,
                crate::storage::write_engine::mutation::CellOperation::DeleteRow
            )
        });

        if is_row_tombstone {
            flags |= ROW_HAS_DELETION;
        }

        // Timestamp is always present for static rows
        flags |= ROW_HAS_TIMESTAMP;

        // TTL if present (not applicable to row tombstones)
        if !is_row_tombstone && mutation.ttl_seconds.is_some() {
            flags |= ROW_HAS_TTL;
        }

        // Check if all static columns are present
        if !is_row_tombstone {
            let all_writes = mutation.operations.iter().all(|op| {
                matches!(
                    op,
                    crate::storage::write_engine::mutation::CellOperation::Write { .. }
                        | crate::storage::write_engine::mutation::CellOperation::WriteWithTtl { .. }
                )
            });
            let has_nulls = mutation.operations.iter().any(|op| match op {
                crate::storage::write_engine::mutation::CellOperation::Write { value, .. }
                | crate::storage::write_engine::mutation::CellOperation::WriteWithTtl {
                    value,
                    ..
                } => {
                    matches!(value, Value::Null)
                }
                _ => false,
            });
            // Count static columns only for static row
            let static_column_count = schema.columns.iter().filter(|c| c.is_static).count();

            if all_writes && !has_nulls && mutation.operations.len() == static_column_count {
                flags |= ROW_HAS_ALL_COLUMNS;
            }
        }

        // Write row flags
        self.buffer.push(flags);

        // Write extended flags - always EXTENDED_IS_STATIC for static rows
        self.buffer.push(EXTENDED_IS_STATIC);

        // NO clustering prefix for static rows (key difference from write_row)

        // Build row body
        let row_body = self.build_static_row_body(mutation, schema, flags)?;

        let prev_size_vint_len = unsigned_len(prev_size);

        // Write row_size (VInt) — includes prev_unfiltered_size VInt + rest of body
        let row_body_size = prev_size_vint_len as u64 + row_body.len() as u64;
        let mut row_size_buf = Vec::new();
        encode_unsigned(row_body_size, &mut row_size_buf);
        self.buffer.extend_from_slice(&row_size_buf);

        // Write prev_unfiltered_size (VInt, inside the row body)
        encode_unsigned(prev_size, &mut self.buffer);

        // Write rest of row body
        self.buffer.extend_from_slice(&row_body);

        Ok(self.buffer.len() - start_len)
    }

    /// Build static row body (everything after row_size VInt)
    ///
    /// Similar to build_row_body but only processes static columns.
    fn build_static_row_body(
        &self,
        mutation: &Mutation,
        schema: &TableSchema,
        flags: u8,
    ) -> Result<Vec<u8>> {
        let mut body = Vec::new();

        // Write timestamp delta (if HAS_TIMESTAMP)
        //
        // Fix #644 (S6): Cassandra writes UNSIGNED VInt for all temporal deltas.
        // SerializationHeader.java:167: out.writeUnsignedVInt(timestamp - stats.minTimestamp)
        if (flags & ROW_HAS_TIMESTAMP) != 0 {
            let timestamp_delta = (mutation.timestamp_micros - self.stats.min_timestamp) as u64;
            encode_unsigned(timestamp_delta, &mut body);
        }

        // Write TTL delta (if HAS_TTL)
        //
        // Fix #644 (S6): Both TTL and LDT deltas are UNSIGNED VInt.
        // SerializationHeader.java:177: out.writeUnsignedVInt32(ttl - stats.minTTL)
        // SerializationHeader.java:172: out.writeUnsignedVInt32(ldt - stats.minLocalDeletionTime)
        if (flags & ROW_HAS_TTL) != 0 {
            if let Some(ttl) = mutation.ttl_seconds {
                let ttl_delta = ttl as i64 - self.stats.min_ttl as i64;
                if ttl_delta < 0 {
                    return Err(Error::InvalidInput(format!(
                        "TTL {} is less than min_ttl {}",
                        ttl, self.stats.min_ttl
                    )));
                }
                encode_unsigned(ttl_delta as u64, &mut body);

                let local_deletion_time = self.expiring_local_deletion_time(ttl)?;
                let ldt_delta =
                    (local_deletion_time as i64) - (self.stats.min_local_deletion_time as i64);
                if ldt_delta < 0 {
                    return Err(Error::InvalidInput(format!(
                        "Local deletion time {} is less than min_local_deletion_time {}",
                        local_deletion_time, self.stats.min_local_deletion_time
                    )));
                }
                encode_unsigned(ldt_delta as u64, &mut body);
            }
        }

        // Write deletion (if HAS_DELETION)
        if (flags & ROW_HAS_DELETION) != 0 {
            // Row tombstone: Cassandra canonical order (markedForDeleteAt first, then localDeletionTime)
            // Per SerializationHeader.writeDeletionTime(): writeTimestamp() then writeLocalDeletionTime()
            // Fix #644 (S6): both are UNSIGNED VInt.
            let ts_delta = (mutation.timestamp_micros - self.stats.min_timestamp) as u64;
            encode_unsigned(ts_delta, &mut body);

            let local_deletion_time = (mutation.timestamp_micros / 1_000_000) as i32;
            let ldt_delta =
                local_deletion_time.wrapping_sub(self.stats.min_local_deletion_time) as u32;
            encode_unsigned(ldt_delta as u64, &mut body);

            // Issue #717: the columns subset is NOT optional for tombstone rows.
            // Cassandra's UnfilteredSerializer always reads it after the deletion
            // times whenever HAS_ALL_COLUMNS is unset; omitting it makes the
            // reader consume the next row's bytes as a subset bitmask
            // ("Invalid Columns subset bytes; too many bits set").
            if (flags & ROW_HAS_ALL_COLUMNS) == 0 {
                let static_columns = self.static_columns(schema);
                let empty_present: std::collections::HashSet<&str> =
                    std::collections::HashSet::new();
                self.write_column_subset(&mut body, &static_columns, &empty_present)?;
            }

            // No cells written for row tombstones
            return Ok(body);
        }

        // Write column bitmap (if NOT HAS_ALL_COLUMNS)
        // For static rows, bitmap only covers static columns
        if (flags & ROW_HAS_ALL_COLUMNS) == 0 {
            self.write_static_column_bitmap(&mut body, mutation, schema)?;
        }

        // Write cell data for static columns only
        self.write_static_cells(&mut body, mutation, schema)?;

        Ok(body)
    }

    /// Write column bitmap for static columns only.
    ///
    /// Same Cassandra `Columns.Serializer.serializeSubset()` format as
    /// `write_column_bitmap()` but scoped to static columns.
    fn write_static_column_bitmap(
        &self,
        buf: &mut Vec<u8>,
        mutation: &Mutation,
        schema: &TableSchema,
    ) -> Result<()> {
        // Collect names of columns that are present (non-NULL writes + deletes)
        let present_columns: std::collections::HashSet<&str> = mutation
            .operations
            .iter()
            .filter_map(|op| match op {
                crate::storage::write_engine::mutation::CellOperation::Write { column, value }
                | crate::storage::write_engine::mutation::CellOperation::WriteWithTtl {
                    column,
                    value,
                    ..
                } if !matches!(value, Value::Null) => Some(column.as_str()),
                crate::storage::write_engine::mutation::CellOperation::Delete { column } => {
                    Some(column.as_str())
                }
                _ => None,
            })
            .collect();

        let static_columns = self.static_columns(schema);
        self.write_column_subset(buf, &static_columns, &present_columns)
    }

    /// Write cells for static columns only
    fn write_static_cells(
        &self,
        buf: &mut Vec<u8>,
        mutation: &Mutation,
        schema: &TableSchema,
    ) -> Result<()> {
        // Get set of static column names for validation
        let static_column_names: std::collections::HashSet<_> = schema
            .columns
            .iter()
            .filter(|c| c.is_static)
            .map(|c| &c.name)
            .collect();

        for op in self.sorted_operations(mutation, &self.static_columns(schema)) {
            match op {
                crate::storage::write_engine::mutation::CellOperation::Write { column, value } => {
                    // Only write if it's a static column
                    if static_column_names.contains(column) && !matches!(value, Value::Null) {
                        self.write_cell(buf, column, value, mutation.timestamp_micros)?;
                    }
                }
                crate::storage::write_engine::mutation::CellOperation::WriteWithTtl {
                    column,
                    value,
                    ttl_seconds,
                } => {
                    // Only write if it's a static column
                    if static_column_names.contains(column) && !matches!(value, Value::Null) {
                        self.write_cell_with_ttl(
                            buf,
                            column,
                            value,
                            mutation.timestamp_micros,
                            *ttl_seconds,
                        )?;
                    }
                }
                crate::storage::write_engine::mutation::CellOperation::Delete { column } => {
                    // Only process if it's a static column
                    if static_column_names.contains(column) {
                        let local_deletion_time = (mutation.timestamp_micros / 1_000_000) as i32;
                        self.write_tombstone_cell(
                            buf,
                            column,
                            mutation.timestamp_micros,
                            local_deletion_time,
                        )?;
                    }
                }
                crate::storage::write_engine::mutation::CellOperation::DeleteRow => {
                    // Row deletion handled at row level with HAS_DELETION flag
                }
            }
        }

        Ok(())
    }

    /// Build row body (everything after row_size VInt)
    ///
    /// Returns the bytes for: timestamp, TTL, deletion, column bitmap, and cells.
    /// Build a row body from a single mutation (legacy/test entry point).
    /// Routes through the merged-row body builder.
    #[cfg(test)]
    fn build_row_body(
        &self,
        mutation: &Mutation,
        schema: &TableSchema,
        flags: u8,
    ) -> Result<Vec<u8>> {
        let row = Self::merge_row_group(&[mutation], schema, false, None).unwrap_or(RowWrite {
            clustering_key: mutation.clustering_key.as_ref(),
            liveness_ts: Some(mutation.timestamp_micros),
            ttl_seconds: mutation.ttl_seconds,
            row_deletion: None,
            ops: Vec::new(),
        });
        self.build_merged_row_body(&row, schema, flags)
    }

    /// Build a merged row body (everything after the row_size VInt, excluding
    /// the prev_unfiltered_size VInt written by the caller).
    ///
    /// Field order per Cassandra's `UnfilteredSerializer.serializeRowBody`:
    /// liveness timestamp, TTL + expiration LDT, row deletion, columns
    /// subset, then cells. Issue #717: the columns subset is written for
    /// EVERY row lacking HAS_ALL_COLUMNS — including row tombstones.
    fn build_merged_row_body(
        &self,
        row: &RowWrite<'_>,
        schema: &TableSchema,
        flags: u8,
    ) -> Result<Vec<u8>> {
        let mut body = Vec::new();

        // Write timestamp delta (if HAS_TIMESTAMP)
        //
        // Fix #644 (S6): Cassandra writes UNSIGNED VInt for all temporal deltas.
        // SerializationHeader.java:167: out.writeUnsignedVInt(timestamp - stats.minTimestamp)
        if (flags & ROW_HAS_TIMESTAMP) != 0 {
            let liveness_ts = row.liveness_ts.ok_or_else(|| {
                Error::InvalidInput(
                    "ROW_HAS_TIMESTAMP set but row has no liveness timestamp".to_string(),
                )
            })?;
            let timestamp_delta = (liveness_ts - self.stats.min_timestamp) as u64;
            encode_unsigned(timestamp_delta, &mut body);
        }

        // Write TTL delta (if HAS_TTL)
        //
        // Fix #644 (S6): Both TTL and LDT deltas are UNSIGNED VInt.
        // SerializationHeader.java:177: out.writeUnsignedVInt32(ttl - stats.minTTL)
        // SerializationHeader.java:172: out.writeUnsignedVInt32(ldt - stats.minLocalDeletionTime)
        if (flags & ROW_HAS_TTL) != 0 {
            if let Some(ttl) = row.ttl_seconds {
                let ttl_delta = ttl as i64 - self.stats.min_ttl as i64;
                if ttl_delta < 0 {
                    return Err(Error::InvalidInput(format!(
                        "TTL {} is less than min_ttl {}",
                        ttl, self.stats.min_ttl
                    )));
                }
                encode_unsigned(ttl_delta as u64, &mut body);

                let local_deletion_time = self.expiring_local_deletion_time(ttl)?;
                let ldt_delta =
                    (local_deletion_time as i64) - (self.stats.min_local_deletion_time as i64);
                if ldt_delta < 0 {
                    return Err(Error::InvalidInput(format!(
                        "Local deletion time {} is less than min_local_deletion_time {}",
                        local_deletion_time, self.stats.min_local_deletion_time
                    )));
                }
                encode_unsigned(ldt_delta as u64, &mut body);
            }
        }

        // Write deletion (if HAS_DELETION)
        if (flags & ROW_HAS_DELETION) != 0 {
            // Row tombstone: Cassandra canonical order (markedForDeleteAt first, then localDeletionTime)
            // Per SerializationHeader.writeDeletionTime(): writeTimestamp() then writeLocalDeletionTime()
            // Fix #644 (S6): both are UNSIGNED VInt.
            let (deletion_ts, local_deletion_time) = row.row_deletion.ok_or_else(|| {
                Error::InvalidInput("ROW_HAS_DELETION set but row has no deletion time".to_string())
            })?;
            let ts_delta = (deletion_ts - self.stats.min_timestamp) as u64;
            encode_unsigned(ts_delta, &mut body);

            let ldt_delta =
                local_deletion_time.wrapping_sub(self.stats.min_local_deletion_time) as u32;
            encode_unsigned(ldt_delta as u64, &mut body);
        }

        // Write column bitmap (if NOT HAS_ALL_COLUMNS).
        // Issue #717: this is written even for row tombstones — Cassandra's
        // deserializer reads the subset right after the deletion times.
        if (flags & ROW_HAS_ALL_COLUMNS) == 0 {
            self.write_merged_column_bitmap(&mut body, &row.ops, schema)?;
        }

        // Write cell data (none survive for pure row tombstones)
        self.write_merged_cells(&mut body, row, schema)?;

        Ok(body)
    }

    /// Write clustering prefix
    ///
    /// Format:
    /// ```text
    /// [header: VInt]              ← 2 bits per clustering column (state)
    /// [value_1: type-specific]    ← Only if state is PRESENT (00)
    /// [value_2: type-specific]
    /// ...
    /// ```
    fn write_clustering_prefix(
        &mut self,
        clustering_key: &crate::storage::write_engine::mutation::ClusteringKey,
        schema: &TableSchema,
    ) -> Result<()> {
        // Build header: 2 bits per column
        // 00 = PRESENT, 01 = EMPTY, 10 = NULL, 11 = reserved
        let mut header = 0u64;
        for (i, (_, value)) in clustering_key.columns.iter().enumerate() {
            let state = match value {
                Value::Null => 2, // NULL
                _ => 0,           // PRESENT
            };
            header |= (state as u64) << (i * 2);
        }

        // Write header as VUInt
        encode_unsigned(header, &mut self.buffer);

        // Write values for PRESENT columns
        for (i, (_, value)) in clustering_key.columns.iter().enumerate() {
            if !matches!(value, Value::Null) {
                // Get clustering column definition
                if i >= schema.clustering_keys.len() {
                    return Err(Error::Schema(format!(
                        "Clustering key has more columns than schema: {} > {}",
                        i + 1,
                        schema.clustering_keys.len()
                    )));
                }
                let cluster_col = &schema.clustering_keys[i];
                let comparator = ComparatorType::from_data_type(&cluster_col.data_type)?;

                // Write value bytes (type-specific encoding)
                let value_bytes = serialize_value_for_clustering(value, &comparator)?;
                self.buffer.extend_from_slice(&value_bytes);
            }
        }

        Ok(())
    }

    /// Write column bitmap
    ///
    /// Cassandra `Columns.Serializer.serializeSubset()` format.
    ///
    /// For <64 regular columns (the common case), this writes a single
    /// unsigned VInt whose bits indicate **missing** columns:
    ///   - bit = 1 → column is MISSING (NULL / not written)
    ///   - bit = 0 → column is PRESENT
    ///   - bitmap = 0 means all columns present (this case is prevented by
    ///     the caller which sets `HAS_ALL_COLUMNS` instead).
    ///
    /// Only regular columns participate in the bitmap — partition key and
    /// clustering key columns are serialized elsewhere.
    #[cfg(test)]
    fn write_column_bitmap(
        &self,
        buf: &mut Vec<u8>,
        mutation: &Mutation,
        schema: &TableSchema,
    ) -> Result<()> {
        // Collect names of columns that are present (non-NULL writes + deletes).
        // Delete operations must be marked as present so the reader parses
        // the tombstone/complex-deletion bytes that write_cells() emits.
        let present_columns: std::collections::HashSet<&str> = mutation
            .operations
            .iter()
            .filter_map(|op| match op {
                crate::storage::write_engine::mutation::CellOperation::Write { column, value }
                | crate::storage::write_engine::mutation::CellOperation::WriteWithTtl {
                    column,
                    value,
                    ..
                } if !matches!(value, Value::Null) => Some(column.as_str()),
                crate::storage::write_engine::mutation::CellOperation::Delete { column } => {
                    Some(column.as_str())
                }
                _ => None,
            })
            .collect();

        let regular_columns = self.regular_columns(schema);
        self.write_column_subset(buf, &regular_columns, &present_columns)
    }

    /// Write the columns subset for a merged row's surviving operations.
    ///
    /// Same encoding as [`Self::write_column_bitmap`]; for a pure row
    /// tombstone the ops list is empty, producing the all-missing bitmask.
    fn write_merged_column_bitmap(
        &self,
        buf: &mut Vec<u8>,
        ops: &[MergedOp<'_>],
        schema: &TableSchema,
    ) -> Result<()> {
        use crate::storage::write_engine::mutation::CellOperation;

        let present_columns: std::collections::HashSet<&str> = ops
            .iter()
            .filter_map(|mop| match mop.op {
                CellOperation::Write { column, value }
                | CellOperation::WriteWithTtl { column, value, .. }
                    if !matches!(value, Value::Null) =>
                {
                    Some(column.as_str())
                }
                CellOperation::Delete { column } => Some(column.as_str()),
                _ => None,
            })
            .collect();

        let regular_columns = self.regular_columns(schema);
        self.write_column_subset(buf, &regular_columns, &present_columns)
    }

    /// Get regular (non-PK, non-CK, non-static) columns from schema.
    ///
    /// Cassandra's column bitmap only covers regular columns — partition key
    /// and clustering key columns are serialized separately in the partition
    /// header and clustering prefix. Within the regular set, simple columns
    /// sort before complex columns, then by name.
    fn regular_columns<'a>(&self, schema: &'a TableSchema) -> Vec<&'a Column> {
        self.ordered_columns(schema, |column| {
            !column.is_static
                && !schema.is_partition_key(&column.name)
                && !schema.is_clustering_key(&column.name)
        })
    }

    /// Get static columns from schema in Cassandra serialization-header order.
    fn static_columns<'a>(&self, schema: &'a TableSchema) -> Vec<&'a Column> {
        self.ordered_columns(schema, |column| column.is_static)
    }

    /// Write cells for this row
    ///
    /// Cells are written in alphabetical column name order to match Cassandra's
    /// `Columns` sorting (regular columns are sorted by name).
    /// Write the surviving cells of a merged row, in regular-column order.
    ///
    /// Cells whose timestamp matches the row liveness timestamp use
    /// USE_ROW_TIMESTAMP; cells merged in from other mutations (e.g. a later
    /// single-cell DELETE) carry an explicit timestamp delta.
    fn write_merged_cells(
        &self,
        buf: &mut Vec<u8>,
        row: &RowWrite<'_>,
        schema: &TableSchema,
    ) -> Result<()> {
        use crate::storage::write_engine::mutation::CellOperation;

        for mop in self.sorted_merged_ops(&row.ops, schema) {
            match mop.op {
                CellOperation::Write { column, value } => {
                    // Skip NULL values - they are represented by absence in the bitmap
                    if matches!(value, Value::Null) {
                        continue;
                    }
                    // Check if this column is a complex column (non-frozen collection)
                    let is_complex = schema
                        .columns
                        .iter()
                        .find(|c| c.name == *column)
                        .map(|c| is_complex_column(&c.data_type))
                        .unwrap_or(false);

                    if is_complex {
                        let col = schema
                            .columns
                            .iter()
                            .find(|c| c.name == *column)
                            .ok_or_else(|| {
                                Error::Schema(format!(
                                    "Complex column '{}' not found in schema",
                                    column
                                ))
                            })?;
                        self.write_complex_column(buf, col, value, mop.timestamp_micros, None)?;
                    } else if let Some(ttl_seconds) = mop.row_ttl_seconds {
                        if row.ttl_seconds == Some(ttl_seconds)
                            && row.liveness_ts == Some(mop.timestamp_micros)
                        {
                            self.write_cell_with_row_ttl(
                                buf,
                                column,
                                value,
                                mop.timestamp_micros,
                                ttl_seconds,
                            )?;
                        } else {
                            self.write_cell_with_ttl(
                                buf,
                                column,
                                value,
                                mop.timestamp_micros,
                                ttl_seconds,
                            )?;
                        }
                    } else if row.liveness_ts == Some(mop.timestamp_micros) {
                        self.write_cell(buf, column, value, mop.timestamp_micros)?;
                    } else {
                        self.write_cell_explicit_ts(buf, column, value, mop.timestamp_micros)?;
                    }
                }
                CellOperation::WriteWithTtl {
                    column,
                    value,
                    ttl_seconds,
                } => {
                    // Skip NULL values - they are represented by absence in the bitmap
                    if matches!(value, Value::Null) {
                        continue;
                    }
                    let is_complex = schema
                        .columns
                        .iter()
                        .find(|c| c.name == *column)
                        .map(|c| is_complex_column(&c.data_type))
                        .unwrap_or(false);

                    if is_complex {
                        let col = schema
                            .columns
                            .iter()
                            .find(|c| c.name == *column)
                            .ok_or_else(|| {
                                Error::Schema(format!(
                                    "Complex column '{}' not found in schema",
                                    column
                                ))
                            })?;
                        self.write_complex_column(
                            buf,
                            col,
                            value,
                            mop.timestamp_micros,
                            Some(*ttl_seconds),
                        )?;
                    } else {
                        self.write_cell_with_ttl(
                            buf,
                            column,
                            value,
                            mop.timestamp_micros,
                            *ttl_seconds,
                        )?;
                    }
                }
                CellOperation::Delete { column } => {
                    let is_complex = schema
                        .columns
                        .iter()
                        .find(|c| c.name == *column)
                        .map(|c| is_complex_column(&c.data_type))
                        .unwrap_or(false);

                    if is_complex {
                        // Complex column deletion: write empty complex column
                        // with active deletion time (not LIVE)
                        self.write_complex_column_deletion(buf, mop.timestamp_micros)?;
                    } else {
                        let local_deletion_time = (mop.timestamp_micros / 1_000_000) as i32;
                        self.write_tombstone_cell(
                            buf,
                            column,
                            mop.timestamp_micros,
                            local_deletion_time,
                        )?;
                    }
                }
                CellOperation::DeleteRow => {
                    // Row deletion handled at row level with HAS_DELETION flag
                }
            }
        }

        Ok(())
    }

    /// Write a complex column (non-frozen collection stored as multiple cells).
    ///
    /// Complex columns use the following wire format:
    /// ```text
    /// [complex_deletion: marked_for_delete_at (signed VInt) + local_deletion_time (unsigned VInt)]
    /// [cell_count: unsigned VInt]
    /// For each cell:
    ///   [flags: u8]
    ///   [cell_path_length: unsigned VInt]
    ///   [cell_path_bytes]
    ///   [value_length: unsigned VInt]  (if not HAS_EMPTY_VALUE)
    ///   [value_bytes]
    /// ```
    ///
    /// Per collection type:
    /// - SET<T>: cell_path = serialized element, value = empty (HAS_EMPTY_VALUE)
    /// - MAP<K,V>: cell_path = serialized key, value = serialized value
    /// - LIST<T>: cell_path = 16-byte TimeUUID, value = serialized element
    fn write_complex_column(
        &self,
        buf: &mut Vec<u8>,
        column: &Column,
        value: &Value,
        timestamp_micros: i64,
        ttl_seconds: Option<u32>,
    ) -> Result<()> {
        // Write complex deletion time: DeletionTime.LIVE
        // Cassandra canonical order: markedForDeleteAt first, then localDeletionTime
        // Per SerializationHeader.writeDeletionTime(): writeTimestamp() then writeLocalDeletionTime()
        // Fix #644 (S6): markedForDeleteAt delta is UNSIGNED VInt.
        // DeletionTime.LIVE.markedForDeleteAt = Long.MIN_VALUE; delta wraps to large positive u64.
        let ts_delta = i64::MIN.wrapping_sub(self.stats.min_timestamp) as u64;
        encode_unsigned(ts_delta, buf);
        // localDeletionTime delta = Integer.MAX_VALUE - stats.min_local_deletion_time (unsigned VInt)
        let ldt_delta = i32::MAX.wrapping_sub(self.stats.min_local_deletion_time) as u32;
        encode_unsigned(ldt_delta as u64, buf);

        let dt = column.data_type.to_lowercase();

        if dt.starts_with("set<") || dt.starts_with("org.apache.cassandra.db.marshal.settype(") {
            self.write_set_complex_cells(buf, value, timestamp_micros, ttl_seconds)?;
        } else if dt.starts_with("map<")
            || dt.starts_with("org.apache.cassandra.db.marshal.maptype(")
        {
            self.write_map_complex_cells(buf, value, timestamp_micros, ttl_seconds)?;
        } else if dt.starts_with("list<")
            || dt.starts_with("org.apache.cassandra.db.marshal.listtype(")
        {
            self.write_list_complex_cells(buf, value, timestamp_micros, ttl_seconds)?;
        } else {
            return Err(Error::InvalidInput(format!(
                "Column '{}' has type '{}' which is not a recognized complex column type",
                column.name, column.data_type
            )));
        }

        Ok(())
    }

    /// Write a complex column deletion (delete all elements of a collection).
    ///
    /// Wire format: active deletion time + zero cells.
    /// Per SerializationHeader.writeDeletionTime(): timestamp first, LDT second.
    /// ```text
    /// [marked_for_delete_at: unsigned VInt]  ← mutation timestamp (delta from min)
    /// [local_deletion_time: unsigned VInt]   ← seconds since epoch (delta from min)
    /// [cell_count: unsigned VInt]            ← 0 (no cells)
    /// ```
    fn write_complex_column_deletion(
        &self,
        buf: &mut Vec<u8>,
        timestamp_micros: i64,
    ) -> Result<()> {
        // Active deletion: Cassandra canonical order (markedForDeleteAt first, then localDeletionTime)
        // Per SerializationHeader.writeDeletionTime(): writeTimestamp() then writeLocalDeletionTime()
        // Fix #644 (S6): marked_for_delete_at delta is UNSIGNED VInt.
        let ts_delta = (timestamp_micros - self.stats.min_timestamp) as u64;
        encode_unsigned(ts_delta, buf);

        // local_deletion_time = mutation timestamp as seconds (unsigned VInt delta)
        let local_deletion_time = (timestamp_micros / 1_000_000) as i32;
        let ldt_delta = local_deletion_time.wrapping_sub(self.stats.min_local_deletion_time) as u32;
        encode_unsigned(ldt_delta as u64, buf);

        // Zero cells
        encode_unsigned(0u64, buf);

        Ok(())
    }

    /// Write per-cell TTL fields for a complex cell.
    ///
    /// When TTL is present, writes:
    /// - flags: CELL_IS_EXPIRING (0x02), NO USE_ROW_TIMESTAMP
    /// - timestamp delta (unsigned VInt; fix #644: all temporal deltas are unsigned)
    /// - local_deletion_time delta (unsigned VInt)
    /// - TTL delta (unsigned VInt)
    ///
    /// When TTL is absent, writes:
    /// - flags: base_flags | CELL_USE_ROW_TIMESTAMP (0x08)
    ///
    /// Returns the flags byte written (for caller to check HAS_EMPTY_VALUE etc.).
    fn write_complex_cell_header(
        &self,
        buf: &mut Vec<u8>,
        base_flags: u8,
        timestamp_micros: i64,
        ttl_seconds: Option<u32>,
    ) -> Result<()> {
        match ttl_seconds {
            Some(ttl) => {
                // Expiring cell: IS_EXPIRING flag, explicit timestamp + LDT + TTL
                let flags = base_flags | CELL_IS_EXPIRING;
                buf.push(flags);

                // Timestamp delta (UNSIGNED VInt, NOT USE_ROW_TIMESTAMP)
                // Fix #644 (S6): SerializationHeader.java:167 uses writeUnsignedVInt.
                let timestamp_delta = (timestamp_micros - self.stats.min_timestamp) as u64;
                encode_unsigned(timestamp_delta, buf);

                // local_deletion_time = now + ttl
                let now_seconds = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map_err(|e| Error::Storage(format!("System time error: {}", e)))?
                    .as_secs() as i32;
                let local_deletion_time = now_seconds.saturating_add(ttl as i32);
                let ldt_delta =
                    (local_deletion_time as i64) - (self.stats.min_local_deletion_time as i64);
                if ldt_delta < 0 {
                    return Err(Error::InvalidInput(format!(
                        "Complex cell: local deletion time {} is less than min_local_deletion_time {}",
                        local_deletion_time, self.stats.min_local_deletion_time
                    )));
                }
                encode_unsigned(ldt_delta as u64, buf);

                // TTL delta
                let ttl_delta = (ttl as i64) - (self.stats.min_ttl as i64);
                if ttl_delta < 0 {
                    return Err(Error::InvalidInput(format!(
                        "Complex cell: TTL {} is less than min_ttl {}",
                        ttl, self.stats.min_ttl
                    )));
                }
                encode_unsigned(ttl_delta as u64, buf);
            }
            None => {
                // Non-expiring cell: use row timestamp
                buf.push(base_flags | CELL_USE_ROW_TIMESTAMP);
            }
        }
        Ok(())
    }

    /// Write SET complex cells.
    ///
    /// SET elements: cell_path = serialized element value, cell value = empty (HAS_EMPTY_VALUE).
    /// Elements are sorted by their serialized byte representation for Cassandra compatibility.
    fn write_set_complex_cells(
        &self,
        buf: &mut Vec<u8>,
        value: &Value,
        timestamp_micros: i64,
        ttl_seconds: Option<u32>,
    ) -> Result<()> {
        let elements = match value {
            Value::Set(elements) => elements,
            _ => {
                return Err(Error::InvalidInput(format!(
                    "Expected Set value for complex SET column, got {:?}",
                    value
                )))
            }
        };

        // Serialize all elements first, then sort by byte representation.
        // serialize_value rejects Value::Null, enforcing CQL semantics.
        let mut serialized: Vec<Vec<u8>> = elements
            .iter()
            .map(|e| serialize_collection_element(e, "SET"))
            .collect::<Result<Vec<_>>>()?;
        serialized.sort();

        // Cell count
        encode_unsigned(serialized.len() as u64, buf);

        for path_bytes in &serialized {
            // Cell header: flags + optional TTL fields
            self.write_complex_cell_header(
                buf,
                CELL_HAS_EMPTY_VALUE,
                timestamp_micros,
                ttl_seconds,
            )?;

            // Cell path: serialized element value
            encode_unsigned(path_bytes.len() as u64, buf);
            buf.extend_from_slice(path_bytes);

            // No value bytes (HAS_EMPTY_VALUE flag set)
        }

        Ok(())
    }

    /// Write MAP complex cells.
    ///
    /// MAP entries: cell_path = serialized key, cell value = serialized value.
    /// Entries are sorted by their serialized key byte representation for Cassandra compatibility.
    fn write_map_complex_cells(
        &self,
        buf: &mut Vec<u8>,
        value: &Value,
        timestamp_micros: i64,
        ttl_seconds: Option<u32>,
    ) -> Result<()> {
        let entries = match value {
            Value::Map(entries) => entries,
            _ => {
                return Err(Error::InvalidInput(format!(
                    "Expected Map value for complex MAP column, got {:?}",
                    value
                )))
            }
        };

        // Serialize all keys and values, then sort by serialized key bytes.
        // Null keys are rejected inline; null values are allowed for MAP.
        let mut serialized: Vec<(Vec<u8>, Vec<u8>)> = entries
            .iter()
            .map(|(key, val)| {
                if matches!(key, Value::Null) {
                    return Err(Error::InvalidInput(
                        "MAP keys cannot be null (CQL semantics)".to_string(),
                    ));
                }
                Ok((serialize_value(key)?, serialize_value(val)?))
            })
            .collect::<Result<Vec<_>>>()?;
        serialized.sort_by(|a, b| a.0.cmp(&b.0));

        // Cell count
        encode_unsigned(serialized.len() as u64, buf);

        for (path_bytes, value_bytes) in &serialized {
            // Cell header: flags + optional TTL fields
            self.write_complex_cell_header(buf, 0, timestamp_micros, ttl_seconds)?;

            // Cell path: serialized key
            encode_unsigned(path_bytes.len() as u64, buf);
            buf.extend_from_slice(path_bytes);

            // Cell value: serialized value
            encode_unsigned(value_bytes.len() as u64, buf);
            buf.extend_from_slice(value_bytes);
        }

        Ok(())
    }

    /// Write LIST complex cells.
    ///
    /// LIST elements: cell_path = 16-byte TimeUUID, cell value = serialized element.
    /// Lists preserve insertion order (no sorting) — TimeUUIDs provide ordering.
    fn write_list_complex_cells(
        &self,
        buf: &mut Vec<u8>,
        value: &Value,
        timestamp_micros: i64,
        ttl_seconds: Option<u32>,
    ) -> Result<()> {
        let elements = match value {
            Value::List(elements) => elements,
            _ => {
                return Err(Error::InvalidInput(format!(
                    "Expected List value for complex LIST column, got {:?}",
                    value
                )))
            }
        };

        // Cell count
        encode_unsigned(elements.len() as u64, buf);

        for (i, elem) in elements.iter().enumerate() {
            // Reject null elements inline (CQL semantics)
            if matches!(elem, Value::Null) {
                return Err(Error::InvalidInput(
                    "LIST elements cannot be null (CQL semantics)".to_string(),
                ));
            }

            // Cell header: flags + optional TTL fields
            self.write_complex_cell_header(buf, 0, timestamp_micros, ttl_seconds)?;

            // Cell path: 16-byte TimeUUID
            let timeuuid = generate_list_cell_path_timeuuid(timestamp_micros, i as u64);
            encode_unsigned(16u64, buf);
            buf.extend_from_slice(&timeuuid);

            // Cell value: serialized element
            let value_bytes = serialize_value(elem)?;
            encode_unsigned(value_bytes.len() as u64, buf);
            buf.extend_from_slice(&value_bytes);
        }

        Ok(())
    }

    /// Write a single cell
    ///
    /// Format:
    /// ```text
    /// [flags: u8]
    /// [timestamp_delta: VInt if NOT USE_ROW_TIMESTAMP]
    /// [value_length: VInt]
    /// [value_bytes]
    /// ```
    ///
    /// NOTE: NULL values should NOT be written - they are represented by absence in the bitmap.
    /// This function will return an error if called with Value::Null.
    fn write_cell(
        &self,
        buf: &mut Vec<u8>,
        column: &str,
        value: &Value,
        timestamp: i64,
    ) -> Result<()> {
        // NULL values should not be written as cells - they are represented by absence
        if matches!(value, Value::Null) {
            return Err(Error::InvalidInput(format!(
                "NULL values should not be written as cells (column: {}). They are represented by absence in the bitmap.",
                column
            )));
        }

        // Cell flags
        let mut flags = CELL_USE_ROW_TIMESTAMP; // Use row timestamp by default

        // Empty string: set HAS_EMPTY_VALUE flag
        // This is for actual empty strings (''), not NULLs
        let is_empty_string = matches!(value, Value::Text(s) if s.is_empty());
        if is_empty_string {
            flags |= CELL_HAS_EMPTY_VALUE;
        }

        buf.push(flags);

        // Timestamp (skip if USE_ROW_TIMESTAMP)
        // Fix #644 (S6): Cell timestamp delta is UNSIGNED VInt per Cassandra
        // SerializationHeader.java:167: out.writeUnsignedVInt(timestamp - stats.minTimestamp).
        if (flags & CELL_USE_ROW_TIMESTAMP) == 0 {
            let timestamp_delta = (timestamp - self.stats.min_timestamp) as u64;
            encode_unsigned(timestamp_delta, buf);
        }

        if (flags & CELL_HAS_EMPTY_VALUE) != 0 {
            return Ok(());
        }

        // Value
        let value_bytes = serialize_value(value)?;

        // Bounds check: value length must fit in i64
        if value_bytes.len() > i64::MAX as usize {
            return Err(Error::InvalidInput(format!(
                "Value too large for column '{}': {} bytes (max {})",
                column,
                value_bytes.len(),
                i64::MAX
            )));
        }

        if cell_value_uses_length_prefix(value) {
            encode_unsigned(value_bytes.len() as u64, buf);
        }

        // Write value bytes
        buf.extend_from_slice(&value_bytes);

        Ok(())
    }

    /// Write a live cell that carries its own timestamp (no USE_ROW_TIMESTAMP).
    ///
    /// Used for cells merged into a row from a different mutation than the
    /// one providing the row's liveness timestamp.
    ///
    /// Format:
    /// ```text
    /// [flags: u8]                ← 0x00 (or HAS_EMPTY_VALUE for empty text)
    /// [timestamp_delta: VUInt]   ← delta from min_timestamp
    /// [value_length: VInt]       ← variable-length types only
    /// [value_bytes]
    /// ```
    fn write_cell_explicit_ts(
        &self,
        buf: &mut Vec<u8>,
        column: &str,
        value: &Value,
        timestamp: i64,
    ) -> Result<()> {
        if matches!(value, Value::Null) {
            return Err(Error::InvalidInput(format!(
                "NULL values should not be written as cells (column: {}). They are represented by absence in the bitmap.",
                column
            )));
        }

        let mut flags = 0u8;
        if matches!(value, Value::Text(s) if s.is_empty()) {
            flags |= CELL_HAS_EMPTY_VALUE;
        }
        buf.push(flags);

        // Timestamp delta (UNSIGNED VInt)
        let timestamp_delta = (timestamp - self.stats.min_timestamp) as u64;
        encode_unsigned(timestamp_delta, buf);

        if (flags & CELL_HAS_EMPTY_VALUE) != 0 {
            return Ok(());
        }

        let value_bytes = serialize_value(value)?;
        if value_bytes.len() > i64::MAX as usize {
            return Err(Error::InvalidInput(format!(
                "Value too large for column '{}': {} bytes (max {})",
                column,
                value_bytes.len(),
                i64::MAX
            )));
        }

        if cell_value_uses_length_prefix(value) {
            encode_unsigned(value_bytes.len() as u64, buf);
        }

        buf.extend_from_slice(&value_bytes);
        Ok(())
    }

    /// Write a cell with TTL (expiring cell)
    ///
    /// Format:
    /// ```text
    /// [flags: u8]                    ← CELL_IS_EXPIRING (0x02) set
    /// [timestamp_delta: VInt]        ← Delta from min_timestamp (NOT USE_ROW_TIMESTAMP for TTL cells)
    /// [local_deletion_time_delta: VUInt]  ← When the cell expires (relative to min_local_deletion_time)
    /// [ttl_delta: VUInt]            ← TTL value (relative to min_ttl)
    /// [value_length: VInt]
    /// [value_bytes]
    /// ```
    ///
    /// CRITICAL: TTL cells MUST NOT use USE_ROW_TIMESTAMP or USE_ROW_TTL flags.
    /// They need explicit timestamp and TTL deltas.
    fn write_cell_with_ttl(
        &self,
        buf: &mut Vec<u8>,
        column: &str,
        value: &Value,
        timestamp: i64,
        ttl_seconds: u32,
    ) -> Result<()> {
        // NULL values should not be written as cells
        if matches!(value, Value::Null) {
            return Err(Error::InvalidInput(format!(
                "NULL values should not be written as cells (column: {}). They are represented by absence in the bitmap.",
                column
            )));
        }

        let local_deletion_time = self.expiring_local_deletion_time(ttl_seconds)?;

        // Cell flags - CELL_IS_EXPIRING, NO USE_ROW_TIMESTAMP or USE_ROW_TTL
        let mut flags = CELL_IS_EXPIRING;
        if matches!(value, Value::Text(s) if s.is_empty()) {
            flags |= CELL_HAS_EMPTY_VALUE;
        }
        buf.push(flags);

        // Timestamp delta (required for expiring cells)
        // Fix #644 (S6): Cell timestamp delta is UNSIGNED VInt.
        // SerializationHeader.java:167: out.writeUnsignedVInt(timestamp - stats.minTimestamp)
        let timestamp_delta = (timestamp - self.stats.min_timestamp) as u64;
        encode_unsigned(timestamp_delta, buf);

        // Local deletion time delta
        let ldt_delta = (local_deletion_time as i64) - (self.stats.min_local_deletion_time as i64);
        if ldt_delta < 0 {
            return Err(Error::InvalidInput(format!(
                "Local deletion time {} is less than min_local_deletion_time {}",
                local_deletion_time, self.stats.min_local_deletion_time
            )));
        }
        encode_unsigned(ldt_delta as u64, buf);

        // TTL delta
        let ttl_delta = (ttl_seconds as i64) - (self.stats.min_ttl as i64);
        if ttl_delta < 0 {
            return Err(Error::InvalidInput(format!(
                "TTL {} is less than min_ttl {}",
                ttl_seconds, self.stats.min_ttl
            )));
        }
        encode_unsigned(ttl_delta as u64, buf);

        if (flags & CELL_HAS_EMPTY_VALUE) != 0 {
            return Ok(());
        }

        // Value
        let value_bytes = serialize_value(value)?;

        // Bounds check: value length must fit in i64
        if value_bytes.len() > i64::MAX as usize {
            return Err(Error::InvalidInput(format!(
                "Value too large for column '{}': {} bytes (max {})",
                column,
                value_bytes.len(),
                i64::MAX
            )));
        }

        if cell_value_uses_length_prefix(value) {
            encode_unsigned(value_bytes.len() as u64, buf);
        }

        // Write value bytes
        buf.extend_from_slice(&value_bytes);

        Ok(())
    }

    fn write_cell_with_row_ttl(
        &self,
        buf: &mut Vec<u8>,
        column: &str,
        value: &Value,
        _timestamp: i64,
        _ttl_seconds: u32,
    ) -> Result<()> {
        if matches!(value, Value::Null) {
            return Err(Error::InvalidInput(format!(
                "NULL values should not be written as cells (column: {}). They are represented by absence in the bitmap.",
                column
            )));
        }

        let mut flags = CELL_IS_EXPIRING | CELL_USE_ROW_TIMESTAMP | CELL_USE_ROW_TTL;
        if matches!(value, Value::Text(s) if s.is_empty()) {
            flags |= CELL_HAS_EMPTY_VALUE;
        }
        buf.push(flags);

        if (flags & CELL_HAS_EMPTY_VALUE) != 0 {
            return Ok(());
        }

        let value_bytes = serialize_value(value)?;
        if value_bytes.len() > i64::MAX as usize {
            return Err(Error::InvalidInput(format!(
                "Value too large for column '{}': {} bytes (max {})",
                column,
                value_bytes.len(),
                i64::MAX
            )));
        }

        if cell_value_uses_length_prefix(value) {
            encode_unsigned(value_bytes.len() as u64, buf);
        }

        buf.extend_from_slice(&value_bytes);
        Ok(())
    }

    fn expiring_local_deletion_time(&self, ttl_seconds: u32) -> Result<i32> {
        let now_seconds = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_err(|e| Error::Storage(format!("System time error: {}", e)))?
            .as_secs() as i32;
        Ok(now_seconds.saturating_add(ttl_seconds as i32))
    }

    /// Write a tombstone cell
    ///
    /// Tombstones require:
    /// - IS_DELETED flag set
    /// - Own timestamp (NOT USE_ROW_TIMESTAMP - tombstones need explicit timestamps)
    /// - local_deletion_time field
    /// - No value data
    fn write_tombstone_cell(
        &self,
        buf: &mut Vec<u8>,
        _column: &str,
        timestamp: i64,
        local_deletion_time: i32,
    ) -> Result<()> {
        // Cell flags for tombstone
        // CRITICAL: Do NOT set USE_ROW_TIMESTAMP - tombstones need their own timestamp
        //
        // Issue #716: HAS_EMPTY_VALUE MUST be set. Cassandra's Cell.Serializer
        // derives `hasValue = (flags & HAS_EMPTY_VALUE_MASK) == 0`, so a deleted
        // cell without this flag makes Cassandra read a value that was never
        // written, desyncing the row stream (EOFException on readback).
        let flags = CELL_IS_DELETED | CELL_HAS_EMPTY_VALUE;
        buf.push(flags);

        // Timestamp delta (VInt) - required for tombstones
        // Fix #644 (S6): tombstone timestamp delta is UNSIGNED VInt per Cassandra.
        // SerializationHeader.java:167: out.writeUnsignedVInt(timestamp - stats.minTimestamp)
        let timestamp_delta = (timestamp - self.stats.min_timestamp) as u64;
        encode_unsigned(timestamp_delta, buf);

        // Local deletion time delta (VUInt) - required for tombstones
        let deletion_time_delta =
            (local_deletion_time as i64) - (self.stats.min_local_deletion_time as i64);
        if deletion_time_delta < 0 {
            return Err(Error::InvalidInput(format!(
                "Local deletion time {} is less than min_local_deletion_time {}",
                local_deletion_time, self.stats.min_local_deletion_time
            )));
        }
        encode_unsigned(deletion_time_delta as u64, buf);

        // No value length or value bytes for tombstones
        // Parser returns immediately after reading local_deletion_time
        Ok(())
    }

    /// Write a single range tombstone bound marker.
    ///
    /// On-disk layout (must mirror the reader's `skip_range_tombstone_marker`
    /// and Cassandra's `UnfilteredSerializer.serialize(RangeTombstoneMarker)`):
    /// ```text
    /// [flags: u8]                      ← IS_MARKER (0x02)
    /// [bound_kind: u8]                 ← ClusteringPrefix.Kind ordinal
    /// [cluster_count: u16 BE]          ← bound.size()
    /// [cluster_header: VUInt]          ← only when cluster_count > 0
    /// [cluster_values: ...]
    /// [marker_body_size: VUInt]        ← size of (prev_size + deletion times)
    /// [prev_unfiltered_size: VUInt]
    /// [marked_for_delete_at: VUInt]    ← delta from min_timestamp (µs)
    /// [local_deletion_time: VUInt]     ← delta from min_local_deletion_time (s)
    /// ```
    ///
    /// Issue #717: the previous writer emitted private bound-kind ordinals,
    /// no u16 cluster count, and no marker_body_size/prev_size VInts — bytes
    /// no Cassandra (or CQLite) reader could parse.
    ///
    /// Returns the total serialized marker size (for prev_unfiltered_size
    /// threading).
    fn write_range_bound(
        &mut self,
        bound: &ClusteringBound,
        is_open: bool,
        deletion_time: i64,
        local_deletion_time: i32,
        schema: &TableSchema,
        prev_size: u64,
    ) -> Result<usize> {
        let start_len = self.buffer.len();

        // Marker flag
        self.buffer.push(IS_MARKER);

        // Bound kind (ClusteringPrefix.Kind ordinal) + clustering values.
        // Bottom/Top are the full-partition bounds: an inclusive bound with
        // zero clustering values.
        let (bound_kind, clustering) = match (is_open, bound) {
            (true, ClusteringBound::Inclusive(ck)) => (INCL_START_BOUND, Some(ck)),
            (true, ClusteringBound::Exclusive(ck)) => (EXCL_START_BOUND, Some(ck)),
            (false, ClusteringBound::Inclusive(ck)) => (INCL_END_BOUND, Some(ck)),
            (false, ClusteringBound::Exclusive(ck)) => (EXCL_END_BOUND, Some(ck)),
            (true, ClusteringBound::Bottom | ClusteringBound::Top) => (INCL_START_BOUND, None),
            (false, ClusteringBound::Bottom | ClusteringBound::Top) => (INCL_END_BOUND, None),
        };
        self.buffer.push(bound_kind);

        // Cluster count (u16 BE) — ClusteringBoundOrBoundary.Serializer
        // writes `out.writeShort(bound.size())` before the values.
        let cluster_count = clustering.map_or(0, |ck| ck.columns.len());
        if cluster_count > u16::MAX as usize {
            return Err(Error::InvalidInput(format!(
                "Range tombstone bound has too many clustering values: {}",
                cluster_count
            )));
        }
        self.buffer
            .write_all(&(cluster_count as u16).to_be_bytes())?;

        // Clustering header + values (only when the bound carries values).
        if let Some(ck) = clustering {
            self.write_clustering_prefix(ck, schema)?;
        }

        // Deletion time: Cassandra canonical order (markedForDeleteAt first,
        // then localDeletionTime), both UNSIGNED VInt deltas.
        let mut deletion = Vec::new();
        let ts_delta = (deletion_time - self.stats.min_timestamp) as u64;
        encode_unsigned(ts_delta, &mut deletion);
        let ldt_delta =
            (local_deletion_time as i64 - self.stats.min_local_deletion_time as i64) as u64;
        encode_unsigned(ldt_delta, &mut deletion);

        // marker_body_size covers the prev_size VInt + deletion times (same
        // convention as row_size for rows).
        let body_size = unsigned_len(prev_size) as u64 + deletion.len() as u64;
        encode_unsigned(body_size, &mut self.buffer);
        encode_unsigned(prev_size, &mut self.buffer);
        self.buffer.extend_from_slice(&deletion);

        Ok(self.buffer.len() - start_len)
    }

    /// Get current file position (for Index.db offset tracking).
    ///
    /// This is the total number of Data.db bytes produced so far: bytes already
    /// flushed to the sink (`position`) plus bytes currently buffered. Identical
    /// in both streaming and in-memory modes.
    pub fn position(&self) -> u64 {
        self.position + self.buffer.len() as u64
    }

    /// Length of the per-partition scratch buffer.
    ///
    /// In streaming mode this reflects only the most recently written partition
    /// (the scratch is cleared after each flush), which is the basis of the
    /// bounded-memory guarantee. Test-only accessor.
    #[cfg(test)]
    pub(crate) fn scratch_len(&self) -> usize {
        self.buffer.len()
    }

    /// Number of bytes already flushed to the streaming sink. Test-only accessor.
    #[cfg(test)]
    pub(crate) fn flushed_position(&self) -> u64 {
        self.position
    }

    fn ordered_columns<'a, F>(&self, schema: &'a TableSchema, predicate: F) -> Vec<&'a Column>
    where
        F: Fn(&Column) -> bool,
    {
        let mut columns: Vec<&'a Column> = schema
            .columns
            .iter()
            .filter(|column| predicate(column))
            .collect();
        columns.sort_by_key(|column| column_order_key(column));
        columns
    }

    fn sorted_operations<'a>(
        &self,
        mutation: &'a Mutation,
        columns: &[&Column],
    ) -> Vec<&'a crate::storage::write_engine::mutation::CellOperation> {
        let column_order: std::collections::HashMap<&str, usize> = columns
            .iter()
            .enumerate()
            .map(|(idx, column)| (column.name.as_str(), idx))
            .collect();

        let mut operations: Vec<_> = mutation.operations.iter().collect();
        operations.sort_by_key(|operation| match operation {
            crate::storage::write_engine::mutation::CellOperation::Write { column, .. }
            | crate::storage::write_engine::mutation::CellOperation::WriteWithTtl {
                column, ..
            }
            | crate::storage::write_engine::mutation::CellOperation::Delete { column } => {
                column_order
                    .get(column.as_str())
                    .copied()
                    .unwrap_or(usize::MAX - 1)
            }
            crate::storage::write_engine::mutation::CellOperation::DeleteRow => usize::MAX,
        });
        operations
    }

    /// Sort merged ops into regular-column serialization order
    /// (simple columns before complex, then by name).
    fn sorted_merged_ops<'a, 'b>(
        &self,
        ops: &'b [MergedOp<'a>],
        schema: &TableSchema,
    ) -> Vec<&'b MergedOp<'a>> {
        let columns = self.regular_columns(schema);
        let column_order: std::collections::HashMap<&str, usize> = columns
            .iter()
            .enumerate()
            .map(|(idx, column)| (column.name.as_str(), idx))
            .collect();

        let mut sorted: Vec<&'b MergedOp<'a>> = ops.iter().collect();
        sorted.sort_by_key(|mop| match mop.op {
            crate::storage::write_engine::mutation::CellOperation::Write { column, .. }
            | crate::storage::write_engine::mutation::CellOperation::WriteWithTtl {
                column, ..
            }
            | crate::storage::write_engine::mutation::CellOperation::Delete { column } => {
                column_order
                    .get(column.as_str())
                    .copied()
                    .unwrap_or(usize::MAX - 1)
            }
            crate::storage::write_engine::mutation::CellOperation::DeleteRow => usize::MAX,
        });
        sorted
    }

    fn write_column_subset(
        &self,
        buf: &mut Vec<u8>,
        columns: &[&Column],
        present_columns: &std::collections::HashSet<&str>,
    ) -> Result<()> {
        let mut present_indices = Vec::new();
        let mut missing_indices = Vec::new();

        for (idx, column) in columns.iter().enumerate() {
            if present_columns.contains(column.name.as_str()) {
                present_indices.push(idx);
            } else {
                missing_indices.push(idx);
            }
        }

        if missing_indices.is_empty() {
            encode_unsigned(0, buf);
            return Ok(());
        }

        if columns.len() < 64 {
            let mut bitmap = 0u64;
            for idx in missing_indices {
                bitmap |= 1u64 << idx;
            }
            encode_unsigned(bitmap, buf);
            return Ok(());
        }

        encode_unsigned((columns.len() - present_indices.len()) as u64, buf);

        if present_indices.len() < columns.len() / 2 {
            for idx in present_indices {
                encode_unsigned(idx as u64, buf);
            }
        } else {
            for idx in missing_indices {
                encode_unsigned(idx as u64, buf);
            }
        }

        Ok(())
    }
}

/// Returns true if the column type is a non-frozen collection (complex column).
///
/// Complex columns are stored as multiple cells with cell paths, unlike
/// frozen collections which are stored as a single cell with blob value.
/// Matches the reader logic in `v5_compressed_legacy.rs`.
fn is_complex_column(data_type: &str) -> bool {
    let dt = data_type.to_lowercase();

    // Frozen collections are NOT complex (they're single-cell frozen types)
    if dt.starts_with("frozen<") || dt.starts_with("org.apache.cassandra.db.marshal.frozentype(") {
        return false;
    }

    // CQL-style collection types
    if dt.starts_with("list<") || dt.starts_with("set<") || dt.starts_with("map<") {
        return true;
    }

    // Cassandra internal collection types
    if dt.starts_with("org.apache.cassandra.db.marshal.listtype(")
        || dt.starts_with("org.apache.cassandra.db.marshal.settype(")
        || dt.starts_with("org.apache.cassandra.db.marshal.maptype(")
    {
        return true;
    }

    false
}

/// A surviving cell operation in a merged row, tagged with the timestamp and
/// row-level TTL of the mutation it came from.
struct MergedOp<'a> {
    op: &'a crate::storage::write_engine::mutation::CellOperation,
    timestamp_micros: i64,
    /// Row-level TTL (`Mutation::ttl_seconds`) of the originating mutation.
    /// Per-cell TTL lives inside `CellOperation::WriteWithTtl` itself.
    row_ttl_seconds: Option<u32>,
}

/// One Data.db row assembled by merging every mutation of a partition that
/// shares the same clustering key (Issues #716/#717: a partition must never
/// contain two rows with equal clustering).
struct RowWrite<'a> {
    clustering_key: Option<&'a crate::storage::write_engine::mutation::ClusteringKey>,
    /// Primary-key liveness timestamp. `None` for pure row tombstones —
    /// Cassandra serializes those without HAS_TIMESTAMP.
    liveness_ts: Option<i64>,
    /// Row-level TTL from the liveness-providing mutation.
    ttl_seconds: Option<u32>,
    /// Row deletion as (marked_for_delete_at µs, local_deletion_time s).
    row_deletion: Option<(i64, i32)>,
    /// Surviving cell operations (already reconciled, unsorted).
    ops: Vec<MergedOp<'a>>,
}

fn column_order_key(column: &Column) -> (bool, &str) {
    (is_complex_column(&column.data_type), column.name.as_str())
}

/// Generate a version-1 TimeUUID for use as a list cell path.
///
/// List elements in Cassandra use TimeUUIDs as cell paths to maintain insertion order.
/// Each call with a different `element_index` produces a monotonically increasing UUID.
///
/// # Arguments
/// * `timestamp_micros` - Mutation timestamp in microseconds since Unix epoch
/// * `element_index` - Index of the element within the list (for monotonic ordering)
fn generate_list_cell_path_timeuuid(timestamp_micros: i64, element_index: u64) -> [u8; 16] {
    // UUID v1 timestamp: 100-nanosecond intervals since UUID epoch (Oct 15, 1582)
    // Offset from Unix epoch to UUID epoch in 100-ns units
    const UUID_EPOCH_OFFSET: u64 = 0x01B2_1DD2_1381_4000;

    let ts_100ns = (timestamp_micros as u64) * 10 + element_index;
    let uuid_ts = ts_100ns + UUID_EPOCH_OFFSET;

    // Extract time fields per RFC 4122
    let time_low = (uuid_ts & 0xFFFF_FFFF) as u32;
    let time_mid = ((uuid_ts >> 32) & 0xFFFF) as u16;
    let time_hi = ((uuid_ts >> 48) & 0x0FFF) as u16 | 0x1000; // version 1

    // Fixed clock_seq and node for deterministic output
    let clock_seq: u16 = 0x80; // variant bits (10xx) + seq=0
    let node: [u8; 6] = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00];

    let mut uuid = [0u8; 16];
    uuid[0..4].copy_from_slice(&time_low.to_be_bytes());
    uuid[4..6].copy_from_slice(&time_mid.to_be_bytes());
    uuid[6..8].copy_from_slice(&time_hi.to_be_bytes());
    uuid[8] = (clock_seq >> 8) as u8;
    uuid[9] = (clock_seq & 0xFF) as u8;
    uuid[10..16].copy_from_slice(&node);

    uuid
}

/// Convert a usize length to i32 for Cassandra's collection wire format.
/// Returns an error if the length exceeds i32::MAX.
fn len_as_i32(len: usize) -> Result<i32> {
    i32::try_from(len).map_err(|_| {
        Error::InvalidInput(format!(
            "Length {} exceeds maximum i32 for collection encoding",
            len
        ))
    })
}

/// Serialize a collection element, rejecting null (CQL semantics: lists/sets cannot contain null).
fn serialize_collection_element(value: &Value, collection_kind: &str) -> Result<Vec<u8>> {
    if matches!(value, Value::Null) {
        return Err(Error::InvalidInput(format!(
            "{} elements cannot be null (CQL semantics)",
            collection_kind
        )));
    }
    serialize_value(value)
}

/// Serialize a Value to bytes for cell storage
///
/// This follows Cassandra's type-specific serialization rules.
fn serialize_value(value: &Value) -> Result<Vec<u8>> {
    match value {
        Value::Null => Ok(Vec::new()),
        Value::Boolean(b) => Ok(vec![if *b { 1 } else { 0 }]),
        Value::TinyInt(n) => Ok(vec![*n as u8]),
        Value::SmallInt(n) => Ok(n.to_be_bytes().to_vec()),
        Value::Integer(n) => Ok(n.to_be_bytes().to_vec()),
        Value::BigInt(n) => Ok(n.to_be_bytes().to_vec()),
        Value::Counter(n) => Ok(n.to_be_bytes().to_vec()),
        Value::Float32(f) => Ok(f.to_bits().to_be_bytes().to_vec()),
        Value::Float(f) => Ok(f.to_bits().to_be_bytes().to_vec()),
        Value::Text(s) => Ok(s.as_bytes().to_vec()),
        Value::Blob(bytes) => Ok(bytes.clone()),
        Value::Timestamp(millis) => Ok(millis.to_be_bytes().to_vec()),
        Value::Date(days) => {
            // Cassandra DATE: stored as unsigned int with Integer.MIN_VALUE offset
            let stored = days.wrapping_sub(i32::MIN) as u32;
            Ok(stored.to_be_bytes().to_vec())
        }
        Value::Time(nanos) => Ok(nanos.to_be_bytes().to_vec()),
        Value::Uuid(bytes) => Ok(bytes.to_vec()),
        Value::Inet(bytes) => Ok(bytes.clone()),
        Value::Varint(bytes) => Ok(bytes.clone()),
        Value::Decimal { scale, unscaled } => {
            let mut result = Vec::new();
            result.extend_from_slice(&scale.to_be_bytes());
            result.extend_from_slice(unscaled);
            Ok(result)
        }
        Value::Duration {
            months,
            days,
            nanos,
        } => {
            let mut result = Vec::new();
            // Cassandra DurationType stores three signed VInts, not fixed-width ints.
            encode_signed(*months as i64, &mut result);
            encode_signed(*days as i64, &mut result);
            encode_signed(*nanos, &mut result);
            Ok(result)
        }
        Value::Udt(udt_value) => {
            // Construct UdtTypeDef from UdtValue fields by inferring types
            let mut schema =
                UdtTypeDef::new(udt_value.keyspace.clone(), udt_value.type_name.clone());

            // Infer field types from values
            for field in &udt_value.fields {
                let field_type = infer_cql_type_from_value(field.value.as_ref());
                schema = schema.with_field(field.name.clone(), field_type, true);
            }

            let serializer = TypeSerializer::new();
            serializer.serialize_udt(value, &schema)
        }
        Value::List(elements) | Value::Set(elements) => {
            let mut buf = Vec::new();
            buf.extend_from_slice(&len_as_i32(elements.len())?.to_be_bytes());
            for elem in elements {
                let elem_bytes = serialize_collection_element(elem, "Collection")?;
                buf.extend_from_slice(&len_as_i32(elem_bytes.len())?.to_be_bytes());
                buf.extend_from_slice(&elem_bytes);
            }
            Ok(buf)
        }
        Value::Map(entries) => {
            let mut buf = Vec::new();
            buf.extend_from_slice(&len_as_i32(entries.len())?.to_be_bytes());
            for (key, val) in entries {
                if matches!(key, Value::Null) {
                    return Err(Error::InvalidInput(
                        "MAP keys cannot be null (CQL semantics)".to_string(),
                    ));
                }
                let key_bytes = serialize_value(key)?;
                buf.extend_from_slice(&len_as_i32(key_bytes.len())?.to_be_bytes());
                buf.extend_from_slice(&key_bytes);
                let val_bytes = serialize_value(val)?;
                buf.extend_from_slice(&len_as_i32(val_bytes.len())?.to_be_bytes());
                buf.extend_from_slice(&val_bytes);
            }
            Ok(buf)
        }
        Value::Tuple(fields) => {
            let mut buf = Vec::new();
            for field in fields {
                match field {
                    Value::Null => buf.extend_from_slice(&(-1i32).to_be_bytes()),
                    other => {
                        let field_bytes = serialize_value(other)?;
                        buf.extend_from_slice(&len_as_i32(field_bytes.len())?.to_be_bytes());
                        buf.extend_from_slice(&field_bytes);
                    }
                }
            }
            Ok(buf)
        }
        Value::Frozen(inner) => serialize_value(inner),
        _ => Err(Error::InvalidInput(format!(
            "Unsupported value type for serialization: {:?}",
            value
        ))),
    }
}

/// Infer CQL type from a Value instance
///
/// Used for UDT serialization when schema context is not available.
/// Empty collections still fall back to `text` because there is no element
/// value available to inspect.
fn infer_cql_type_from_value(value: Option<&Value>) -> CqlType {
    match value {
        None | Some(Value::Null) => CqlType::Text, // Default for NULL
        Some(Value::Boolean(_)) => CqlType::Boolean,
        Some(Value::TinyInt(_)) => CqlType::TinyInt,
        Some(Value::SmallInt(_)) => CqlType::SmallInt,
        Some(Value::Integer(_)) => CqlType::Int,
        Some(Value::BigInt(_)) => CqlType::BigInt,
        Some(Value::Float32(_)) => CqlType::Float,
        Some(Value::Float(_)) => CqlType::Double,
        Some(Value::Text(_)) => CqlType::Text,
        Some(Value::Blob(_)) => CqlType::Blob,
        Some(Value::Timestamp(_)) => CqlType::Timestamp,
        Some(Value::Date(_)) => CqlType::Date,
        Some(Value::Time(_)) => CqlType::Time,
        Some(Value::Uuid(_)) => CqlType::Uuid,
        Some(Value::Inet(_)) => CqlType::Inet,
        Some(Value::Varint(_)) => CqlType::Varint,
        Some(Value::Decimal { .. }) => CqlType::Decimal,
        Some(Value::Duration { .. }) => CqlType::Duration,
        Some(Value::Counter(_)) => CqlType::Counter,
        Some(Value::List(elements)) => CqlType::List(Box::new(
            elements
                .first()
                .map(|elem| infer_cql_type_from_value(Some(elem)))
                .unwrap_or(CqlType::Text),
        )),
        Some(Value::Set(elements)) => CqlType::Set(Box::new(
            elements
                .first()
                .map(|elem| infer_cql_type_from_value(Some(elem)))
                .unwrap_or(CqlType::Text),
        )),
        Some(Value::Map(entries)) => {
            let (key_type, value_type) = entries
                .first()
                .map(|(key, value)| {
                    (
                        infer_cql_type_from_value(Some(key)),
                        infer_cql_type_from_value(Some(value)),
                    )
                })
                .unwrap_or((CqlType::Text, CqlType::Text));
            CqlType::Map(Box::new(key_type), Box::new(value_type))
        }
        Some(Value::Tuple(fields)) => CqlType::Tuple(
            fields
                .iter()
                .map(|field| infer_cql_type_from_value(Some(field)))
                .collect(),
        ),
        Some(Value::Udt(udt)) => CqlType::Udt(
            udt.type_name.clone(),
            udt.fields
                .iter()
                .map(|field| {
                    (
                        field.name.clone(),
                        infer_cql_type_from_value(field.value.as_ref()),
                    )
                })
                .collect(),
        ),
        Some(Value::Frozen(inner)) => {
            CqlType::Frozen(Box::new(infer_cql_type_from_value(Some(inner))))
        }
        Some(Value::Tombstone(_)) => CqlType::Text, // Tombstones shouldn't appear in UDT fields
        Some(Value::Json(_)) => CqlType::Text,      // JSON is stored as text
    }
}

fn cell_value_uses_length_prefix(value: &Value) -> bool {
    !matches!(
        value,
        Value::Boolean(_)
            | Value::Integer(_)
            | Value::BigInt(_)
            | Value::Float32(_)
            | Value::Float(_)
            | Value::Timestamp(_)
            | Value::Uuid(_)
    )
}

fn is_static_row_mutation(mutation: &Mutation, schema: &TableSchema) -> bool {
    if mutation.clustering_key.is_some() || !schema.columns.iter().any(|column| column.is_static) {
        return false;
    }

    mutation.operations.iter().all(|operation| match operation {
        crate::storage::write_engine::mutation::CellOperation::Write { column, .. }
        | crate::storage::write_engine::mutation::CellOperation::WriteWithTtl { column, .. }
        | crate::storage::write_engine::mutation::CellOperation::Delete { column } => schema
            .columns
            .iter()
            .find(|candidate| candidate.name == *column)
            .map(|candidate| candidate.is_static)
            .unwrap_or(false),
        crate::storage::write_engine::mutation::CellOperation::DeleteRow => true,
    })
}

/// Returns true if this single operation targets a static column.
fn is_static_operation(
    op: &crate::storage::write_engine::mutation::CellOperation,
    schema: &TableSchema,
) -> bool {
    match op {
        crate::storage::write_engine::mutation::CellOperation::Write { column, .. }
        | crate::storage::write_engine::mutation::CellOperation::WriteWithTtl { column, .. }
        | crate::storage::write_engine::mutation::CellOperation::Delete { column } => schema
            .columns
            .iter()
            .find(|c| c.name == *column)
            .map(|c| c.is_static)
            .unwrap_or(false),
        crate::storage::write_engine::mutation::CellOperation::DeleteRow => false,
    }
}

/// Returns true if this mutation contributes at least one static-column operation.
fn has_static_operation(mutation: &Mutation, schema: &TableSchema) -> bool {
    mutation
        .operations
        .iter()
        .any(|op| is_static_operation(op, schema))
}

/// Collect and merge static-column operations from all mutations in a partition.
///
/// Scans every mutation (regardless of whether it has a clustering key) and
/// collects operations that target static columns.  Last-write-wins by
/// `timestamp_micros` when the same column is written more than once.
///
/// Mutations at or before `shadow_floor` (the partition tombstone's deletion
/// timestamp) are skipped: their static cells are shadowed and an sstable
/// must be internally reconciled (see `DataWriter::write_partition`).
///
/// Returns the merged operations in an unspecified order (the writer will
/// sort them by schema column order when building the row body).
fn collect_static_operations(
    mutations: &[Mutation],
    schema: &TableSchema,
    shadow_floor: Option<i64>,
) -> Vec<crate::storage::write_engine::mutation::CellOperation> {
    use std::collections::HashMap;

    // Map: column_name → (timestamp, operation)
    let mut best: HashMap<String, (i64, crate::storage::write_engine::mutation::CellOperation)> =
        HashMap::new();

    for mutation in mutations {
        if shadow_floor.is_some_and(|floor| mutation.timestamp_micros <= floor) {
            continue;
        }
        for op in &mutation.operations {
            if !is_static_operation(op, schema) {
                continue;
            }
            let col_name = match op {
                crate::storage::write_engine::mutation::CellOperation::Write { column, .. }
                | crate::storage::write_engine::mutation::CellOperation::WriteWithTtl {
                    column,
                    ..
                }
                | crate::storage::write_engine::mutation::CellOperation::Delete { column } => {
                    column.clone()
                }
                crate::storage::write_engine::mutation::CellOperation::DeleteRow => continue,
            };
            let entry = best.entry(col_name).or_insert((i64::MIN, op.clone()));
            if mutation.timestamp_micros >= entry.0 {
                *entry = (mutation.timestamp_micros, op.clone());
            }
        }
    }

    best.into_values().map(|(_, op)| op).collect()
}

/// Whether a range tombstone's clustering range covers the given clustering key.
fn range_tombstone_covers(
    rt: &RangeTombstone,
    clustering_key: Option<&ClusteringKey>,
    schema: &TableSchema,
) -> bool {
    use std::cmp::Ordering;

    let Some(ck) = clustering_key else {
        return false;
    };
    let cmp = |bound: &ClusteringKey| ck.compare(bound, schema).unwrap_or_else(|_| ck.cmp(bound));

    let after_start = match &rt.start {
        ClusteringBound::Inclusive(b) => cmp(b) != Ordering::Less,
        ClusteringBound::Exclusive(b) => cmp(b) == Ordering::Greater,
        ClusteringBound::Bottom => true,
        ClusteringBound::Top => false,
    };
    let before_end = match &rt.end {
        ClusteringBound::Inclusive(b) => cmp(b) != Ordering::Greater,
        ClusteringBound::Exclusive(b) => cmp(b) == Ordering::Less,
        ClusteringBound::Top => true,
        ClusteringBound::Bottom => false,
    };
    after_start && before_end
}

/// Serialize value for clustering key (type-specific encoding)
///
/// Fixed-width types: raw bytes (no length prefix)
/// Variable-width types: VInt length + bytes
fn serialize_value_for_clustering(value: &Value, comparator: &ComparatorType) -> Result<Vec<u8>> {
    match (value, comparator) {
        // Fixed-width types (no length prefix)
        (Value::Boolean(b), ComparatorType::Boolean) => Ok(vec![if *b { 1 } else { 0 }]),
        (Value::TinyInt(n), ComparatorType::TinyInt) => Ok(n.to_be_bytes().to_vec()),
        (Value::SmallInt(n), ComparatorType::SmallInt) => Ok(n.to_be_bytes().to_vec()),
        (Value::Integer(n), ComparatorType::Int) => Ok(n.to_be_bytes().to_vec()),
        (Value::BigInt(n), ComparatorType::BigInt) => Ok(n.to_be_bytes().to_vec()),
        (Value::Float32(f), ComparatorType::Float32) => Ok(f.to_bits().to_be_bytes().to_vec()),
        (Value::Float(f), ComparatorType::Float) => Ok(f.to_bits().to_be_bytes().to_vec()),
        (Value::Timestamp(millis), ComparatorType::Timestamp) => Ok(millis.to_be_bytes().to_vec()),
        (Value::Date(days), ComparatorType::Date) => {
            // Cassandra DATE in clustering keys: stored as unsigned int with Integer.MIN_VALUE offset
            let stored = days.wrapping_sub(i32::MIN) as u32;
            let mut result = Vec::new();
            encode_unsigned(4, &mut result);
            result.extend_from_slice(&stored.to_be_bytes());
            Ok(result)
        }
        (Value::Uuid(bytes), ComparatorType::Uuid) => Ok(bytes.to_vec()),

        // Variable-width types (VInt length + bytes)
        (Value::Text(s), ComparatorType::Text) => {
            let bytes = s.as_bytes();
            let mut result = Vec::new();
            encode_unsigned(bytes.len() as u64, &mut result);
            result.extend_from_slice(bytes);
            Ok(result)
        }
        (Value::Blob(bytes), ComparatorType::Blob) => {
            let mut result = Vec::new();
            encode_unsigned(bytes.len() as u64, &mut result);
            result.extend_from_slice(bytes);
            Ok(result)
        }

        // Frozen collections as clustering keys: serialize the full collection bytes with VInt length prefix
        (Value::Frozen(inner), _) => {
            let bytes = serialize_value(inner)?;
            let mut result = Vec::new();
            encode_unsigned(bytes.len() as u64, &mut result);
            result.extend_from_slice(&bytes);
            Ok(result)
        }

        _ => Err(Error::InvalidInput(format!(
            "Type mismatch or unsupported clustering type: value={:?}, comparator={:?}",
            value, comparator
        ))),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schema::{
        ClusteringColumn, ClusteringOrder, Column, CqlType, KeyColumn, TableSchema,
    };
    use crate::storage::serialization::types::TypeSerializer;
    use crate::storage::write_engine::mutation::{
        CellOperation, ClusteringKey, PartitionKey, TableId,
    };
    use crate::types::UdtValue;
    use std::collections::HashMap;

    fn create_test_schema() -> TableSchema {
        TableSchema {
            keyspace: "test_ks".to_string(),
            table: "test_table".to_string(),
            partition_keys: vec![KeyColumn {
                name: "id".to_string(),
                data_type: "int".to_string(),
                position: 0,
            }],
            clustering_keys: vec![],
            columns: vec![
                Column {
                    name: "name".to_string(),
                    data_type: "text".to_string(),
                    nullable: true,
                    default: None,
                    is_static: false,
                },
                Column {
                    name: "age".to_string(),
                    data_type: "int".to_string(),
                    nullable: true,
                    default: None,
                    is_static: false,
                },
            ],
            comments: HashMap::new(),
        }
    }

    fn create_test_stats() -> StatisticsMetadata {
        let mut stats = StatisticsMetadata::new();
        stats.min_timestamp = 1000000;
        stats.min_ttl = 0;
        stats.min_local_deletion_time = 0;
        stats
    }

    fn phase3_address_schema() -> UdtTypeDef {
        UdtTypeDef::new("test_ks".to_string(), "address".to_string())
            .with_field("street".to_string(), CqlType::Text, true)
            .with_field("city".to_string(), CqlType::Text, true)
    }

    fn phase3_person_schema() -> UdtTypeDef {
        UdtTypeDef::new("test_ks".to_string(), "person".to_string())
            .with_field("name".to_string(), CqlType::Text, true)
            .with_field(
                "phone_numbers".to_string(),
                CqlType::List(Box::new(CqlType::Frozen(Box::new(CqlType::Udt(
                    "phone_number".to_string(),
                    vec![],
                ))))),
                true,
            )
            .with_field(
                "home_address".to_string(),
                CqlType::Frozen(Box::new(CqlType::Udt("address".to_string(), vec![]))),
                true,
            )
    }

    fn phase3_company_schema() -> UdtTypeDef {
        UdtTypeDef::new("test_ks".to_string(), "company".to_string())
            .with_field("name".to_string(), CqlType::Text, true)
            .with_field(
                "employees".to_string(),
                CqlType::List(Box::new(CqlType::Frozen(Box::new(CqlType::Udt(
                    "person".to_string(),
                    vec![],
                ))))),
                true,
            )
            .with_field(
                "departments".to_string(),
                CqlType::Map(
                    Box::new(CqlType::Text),
                    Box::new(CqlType::Frozen(Box::new(CqlType::List(Box::new(
                        CqlType::Frozen(Box::new(CqlType::Udt("person".to_string(), vec![]))),
                    ))))),
                ),
                true,
            )
    }

    fn phase3_address_value() -> UdtValue {
        UdtValue::new("address".to_string(), "test_ks".to_string())
            .with_field(
                "street".to_string(),
                Some(Value::Text("Main St".to_string())),
            )
            .with_field("city".to_string(), Some(Value::Text("Seattle".to_string())))
    }

    fn phase3_phone_value() -> UdtValue {
        UdtValue::new("phone_number".to_string(), "test_ks".to_string())
            .with_field("label".to_string(), Some(Value::Text("mobile".to_string())))
            .with_field(
                "number".to_string(),
                Some(Value::Text("+1-555-0101".to_string())),
            )
    }

    fn phase3_person_value(name: &str) -> UdtValue {
        UdtValue::new("person".to_string(), "test_ks".to_string())
            .with_field("name".to_string(), Some(Value::Text(name.to_string())))
            .with_field(
                "phone_numbers".to_string(),
                Some(Value::List(vec![Value::Frozen(Box::new(Value::Udt(
                    phase3_phone_value(),
                )))])),
            )
            .with_field(
                "home_address".to_string(),
                Some(Value::Frozen(Box::new(Value::Udt(phase3_address_value())))),
            )
    }

    fn phase3_company_value() -> UdtValue {
        let person = phase3_person_value("Alice");
        UdtValue::new("company".to_string(), "test_ks".to_string())
            .with_field("name".to_string(), Some(Value::Text("Acme".to_string())))
            .with_field(
                "employees".to_string(),
                Some(Value::List(vec![Value::Frozen(Box::new(Value::Udt(
                    person.clone(),
                )))])),
            )
            .with_field(
                "departments".to_string(),
                Some(Value::Map(vec![(
                    Value::Text("platform".to_string()),
                    Value::Frozen(Box::new(Value::List(vec![Value::Frozen(Box::new(
                        Value::Udt(person),
                    ))]))),
                )])),
            )
    }

    fn create_static_test_schema() -> TableSchema {
        TableSchema {
            keyspace: "test_ks".to_string(),
            table: "test_table".to_string(),
            partition_keys: vec![KeyColumn {
                name: "id".to_string(),
                data_type: "int".to_string(),
                position: 0,
            }],
            clustering_keys: vec![ClusteringColumn {
                name: "ck".to_string(),
                data_type: "int".to_string(),
                position: 0,
                order: ClusteringOrder::Asc,
            }],
            columns: vec![
                Column {
                    name: "static_val".to_string(),
                    data_type: "text".to_string(),
                    nullable: true,
                    default: None,
                    is_static: true,
                },
                Column {
                    name: "regular_val".to_string(),
                    data_type: "text".to_string(),
                    nullable: true,
                    default: None,
                    is_static: false,
                },
            ],
            comments: HashMap::new(),
        }
    }

    #[test]
    fn test_data_writer_new() {
        let stats = create_test_stats();
        let writer = DataWriter::new(stats);
        assert_eq!(writer.position(), 0);
    }

    #[test]
    fn test_write_partition_header() {
        let stats = create_test_stats();
        let mut writer = DataWriter::new(stats);

        let key = DecoratedKey::new(12345, vec![0x00, 0x00, 0x00, 0x2A]); // int = 42
        writer.write_partition_header(&key, None).unwrap();

        let bytes = writer.finish().unwrap();

        // Verify structure (Cassandra BigFormat):
        // [0x00, 0x04] key length (u16 BE = 4 bytes)
        // [0x00, 0x00, 0x00, 0x2A] key bytes
        // [0x7F, 0xFF, 0xFF, 0xFF] DeletionTime.LIVE local_deletion_time (i32::MAX)
        // [0x80, 0x00...] DeletionTime.LIVE deletion_timestamp (i64::MIN)
        assert_eq!(&bytes[0..2], &[0x00, 0x04]); // key length (u16 BE)
        assert_eq!(&bytes[2..6], &[0x00, 0x00, 0x00, 0x2A]); // key bytes
        assert_eq!(&bytes[6..10], &i32::MAX.to_be_bytes()); // DeletionTime.LIVE ldt
        assert_eq!(&bytes[10..18], &i64::MIN.to_be_bytes()); // DeletionTime.LIVE ts
    }

    #[test]
    fn test_write_simple_row() {
        let stats = create_test_stats();
        let mut writer = DataWriter::new(stats);
        let schema = create_test_schema();

        let table_id = TableId::new("test_ks", "test_table");
        let pk = PartitionKey::single("id", Value::Integer(1));
        let mutation = Mutation::new(
            table_id,
            pk,
            None,
            vec![
                CellOperation::Write {
                    column: "name".to_string(),
                    value: Value::Text("Alice".to_string()),
                },
                CellOperation::Write {
                    column: "age".to_string(),
                    value: Value::Integer(30),
                },
            ],
            1001000, // timestamp (delta = 1000)
            None,
        );

        writer.write_row(&mutation, &schema).unwrap();

        let bytes = writer.finish().unwrap();
        assert!(!bytes.is_empty());

        // Verify row flags
        let flags = bytes[0];
        assert_eq!(
            flags & ROW_HAS_TIMESTAMP,
            ROW_HAS_TIMESTAMP,
            "Should have timestamp"
        );
        assert_eq!(
            flags & ROW_HAS_ALL_COLUMNS,
            ROW_HAS_ALL_COLUMNS,
            "Should have all columns"
        );
    }

    #[test]
    fn test_write_row_with_clustering() {
        let mut schema = create_test_schema();
        schema.clustering_keys = vec![ClusteringColumn {
            name: "ts".to_string(),
            data_type: "timestamp".to_string(),
            position: 0,
            order: ClusteringOrder::Asc,
        }];

        let stats = create_test_stats();
        let mut writer = DataWriter::new(stats);

        let table_id = TableId::new("test_ks", "test_table");
        let pk = PartitionKey::single("id", Value::Integer(1));
        let ck = ClusteringKey::single("ts", Value::Timestamp(1234567890));
        let mutation = Mutation::new(
            table_id,
            pk,
            Some(ck),
            vec![CellOperation::Write {
                column: "name".to_string(),
                value: Value::Text("Bob".to_string()),
            }],
            1001000,
            None,
        );

        writer.write_row(&mutation, &schema).unwrap();

        let bytes = writer.finish().unwrap();
        assert!(!bytes.is_empty());

        // Verify row has flags and clustering prefix
        let flags = bytes[0];
        assert_eq!(flags & ROW_HAS_TIMESTAMP, ROW_HAS_TIMESTAMP);
    }

    #[test]
    fn test_write_partition_complete() {
        let stats = create_test_stats();
        let mut writer = DataWriter::new(stats);
        let schema = create_test_schema();

        let key = DecoratedKey::new(12345, vec![0x00, 0x00, 0x00, 0x01]);
        let table_id = TableId::new("test_ks", "test_table");
        let pk = PartitionKey::single("id", Value::Integer(1));

        let mutations = vec![
            Mutation::new(
                table_id.clone(),
                pk.clone(),
                None,
                vec![CellOperation::Write {
                    column: "name".to_string(),
                    value: Value::Text("Alice".to_string()),
                }],
                1001000,
                None,
            ),
            Mutation::new(
                table_id,
                pk,
                None,
                vec![CellOperation::Write {
                    column: "name".to_string(),
                    value: Value::Text("Bob".to_string()),
                }],
                1002000,
                None,
            ),
        ];

        let offset = writer
            .write_partition(&key, &mutations, &schema, None, &[])
            .unwrap();
        assert_eq!(offset, 0); // First partition starts at offset 0

        let bytes = writer.finish().unwrap();
        assert!(!bytes.is_empty());

        // Verify end-of-partition marker is present
        assert_eq!(bytes[bytes.len() - 1], END_OF_PARTITION);
    }

    /// Regression test for bug #644 (S6): temporal deltas MUST use unsigned VInt.
    ///
    /// The writer previously used ZigZag-encoded signed VInt (`encode_signed`) for
    /// all row-header temporal deltas (timestamp, TTL, LDT).  ZigZag maps positive
    /// integer n → 2n, so a delta of 5000 would be encoded as 10000, which the
    /// reader (fixed in S1, using `parse_vuint` = unsigned VInt) would decode as
    /// 10000 — doubling every timestamp on readback.
    ///
    /// Per Cassandra `SerializationHeader.java:167`:
    ///   `out.writeUnsignedVInt(timestamp - stats.minTimestamp)`
    ///   `out.writeUnsignedVInt(ttl - stats.minTTL)`
    ///   `out.writeUnsignedVInt(localDeletionTime - stats.minLocalDeletionTime)`
    ///
    /// Expected encodings (2-byte unsigned VInt, Cassandra format: leading 1-bits + data):
    ///   unsigned VInt(5000 = 0x1388):
    ///     extra_bytes=1, first=(0x80 | (0x1388>>8)&0x3F)=0x93, second=0x88  → [0x93, 0x88]
    ///     ZigZag(5000)=10000 would give [0xA7, 0x10]  ← WRONG (pre-fix value)
    ///
    ///   unsigned VInt(3600 = 0x0E10):
    ///     extra_bytes=1, first=(0x80 | (0x0E10>>8)&0x3F)=0x8E, second=0x10  → [0x8E, 0x10]
    ///     ZigZag(3600)=7200 would give [0x9C, 0x20]  ← WRONG (pre-fix value)
    #[test]
    fn test_delta_encoding_unsigned_vint_fix_644() {
        let mut stats = create_test_stats();
        stats.min_timestamp = 1_000_000;
        stats.min_ttl = 3_600;
        stats.min_local_deletion_time = 0;

        let writer = DataWriter::new(stats.clone());
        let schema = create_test_schema();

        let table_id = TableId::new("test_ks", "test_table");
        let pk = PartitionKey::single("id", Value::Integer(1));
        let mutation = Mutation::new(
            table_id,
            pk,
            None,
            vec![CellOperation::Write {
                column: "name".to_string(),
                value: Value::Text("Test".to_string()),
            }],
            1_005_000,  // timestamp_micros; delta from min_timestamp(1_000_000) = 5_000
            Some(7200), // ttl; delta from min_ttl(3_600) = 3_600
        );

        let row_body = writer
            .build_row_body(&mutation, &schema, ROW_HAS_TIMESTAMP | ROW_HAS_TTL)
            .unwrap();
        assert!(!row_body.is_empty(), "row body must be non-empty");

        // The row body for HAS_TIMESTAMP | HAS_TTL starts with:
        //   [0..2] timestamp delta as unsigned VInt
        //   [2..4] ttl delta as unsigned VInt
        //   [4..]  ldt delta as unsigned VInt (time-dependent, not asserted)
        //   ...    column bitmap, cells
        //
        // timestamp_delta = 5000 → unsigned VInt = [0x93, 0x88]
        // ZigZag(5000) = 10000 → would give [0xA7, 0x10]  ← OLD/WRONG pre-fix encoding
        assert_eq!(
            &row_body[0..2],
            &[0x93u8, 0x88u8],
            "Fix #644: timestamp delta=5000 must encode as unsigned VInt [0x93, 0x88], \
             not ZigZag [0xA7, 0x10]. Reader uses parse_vuint (unsigned), so ZigZag would \
             double the delta on readback (5000 → decoded as 10000)."
        );

        // ttl_delta = 7200 - 3600 = 3600 → unsigned VInt = [0x8E, 0x10]
        // ZigZag(3600) = 7200 → would give [0x9C, 0x20]  ← OLD/WRONG pre-fix encoding
        assert_eq!(
            &row_body[2..4],
            &[0x8Eu8, 0x10u8],
            "Fix #644: TTL delta=3600 must encode as unsigned VInt [0x8E, 0x10], \
             not ZigZag [0x9C, 0x20]. This is the first of two HAS_TTL fields."
        );
    }

    #[test]
    fn test_delta_encoding() {
        let mut stats = create_test_stats();
        stats.min_timestamp = 1000000;
        stats.min_ttl = 3600;

        let writer = DataWriter::new(stats.clone());
        let schema = create_test_schema();

        let table_id = TableId::new("test_ks", "test_table");
        let pk = PartitionKey::single("id", Value::Integer(1));
        let mutation = Mutation::new(
            table_id,
            pk,
            None,
            vec![CellOperation::Write {
                column: "name".to_string(),
                value: Value::Text("Test".to_string()),
            }],
            1005000,    // timestamp (delta = 5000)
            Some(7200), // TTL (delta = 3600)
        );

        let row_body = writer
            .build_row_body(&mutation, &schema, ROW_HAS_TIMESTAMP | ROW_HAS_TTL)
            .unwrap();
        assert!(!row_body.is_empty());
    }

    #[test]
    fn test_serialize_value_types() {
        // Boolean
        let bytes = serialize_value(&Value::Boolean(true)).unwrap();
        assert_eq!(bytes, vec![1]);

        // Integer
        let bytes = serialize_value(&Value::Integer(42)).unwrap();
        assert_eq!(bytes, vec![0x00, 0x00, 0x00, 0x2A]);

        // Text
        let bytes = serialize_value(&Value::Text("hello".to_string())).unwrap();
        assert_eq!(bytes, b"hello");

        // BigInt
        let bytes = serialize_value(&Value::BigInt(9223372036854775807)).unwrap();
        assert_eq!(bytes, vec![0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]);

        // Null
        let bytes = serialize_value(&Value::Null).unwrap();
        assert_eq!(bytes, Vec::<u8>::new());
    }

    #[test]
    fn test_column_bitmap() {
        let stats = create_test_stats();
        let writer = DataWriter::new(stats);
        let schema = create_test_schema();

        let table_id = TableId::new("test_ks", "test_table");
        let pk = PartitionKey::single("id", Value::Integer(1));

        // Only write "name" column (not "age")
        // Schema has 2 regular columns sorted alphabetically: [age(0), name(1)]
        // "age" is MISSING → bitmap bit 0 set → bitmap = 0b01 = 1
        let mutation = Mutation::new(
            table_id,
            pk,
            None,
            vec![CellOperation::Write {
                column: "name".to_string(),
                value: Value::Text("Alice".to_string()),
            }],
            1001000,
            None,
        );

        let mut buf = Vec::new();
        writer
            .write_column_bitmap(&mut buf, &mutation, &schema)
            .unwrap();

        // Cassandra format: single VUInt of missing columns bitmask
        // "age" (index 0) is missing → bitmap = 0x01
        assert_eq!(buf, vec![0x01]);
    }

    #[test]
    fn test_partition_key_size_limit() {
        let stats = create_test_stats();
        let mut writer = DataWriter::new(stats);

        // 256 bytes should succeed (u16 allows up to 65535)
        let key_256 = vec![0xFF; 256];
        let key = DecoratedKey::new(12345, key_256);
        let result = writer.write_partition_header(&key, None);
        assert!(result.is_ok());

        // Create a partition key larger than 65535 bytes
        let mut writer2 = DataWriter::new(create_test_stats());
        let large_key = vec![0xFF; 65536];
        let key = DecoratedKey::new(12345, large_key);

        let result = writer2.write_partition_header(&key, None);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("too large"));
    }

    #[test]
    fn test_write_tombstone_cell() {
        let mut stats = create_test_stats();
        stats.min_timestamp = 1000000;
        stats.min_local_deletion_time = 1700000000; // Jan 2023
        let writer = DataWriter::new(stats);

        let mut buf = Vec::new();
        let timestamp = 1001000; // delta = 1000
        let local_deletion_time = 1700000010; // delta = 10
        writer
            .write_tombstone_cell(&mut buf, "deleted_col", timestamp, local_deletion_time)
            .unwrap();

        assert!(!buf.is_empty());
        // First byte should be tombstone flags (only IS_DELETED, no USE_ROW_TIMESTAMP)
        let flags = buf[0];
        assert_eq!(
            flags & CELL_IS_DELETED,
            CELL_IS_DELETED,
            "Should have IS_DELETED flag"
        );
        assert_eq!(
            flags & CELL_USE_ROW_TIMESTAMP,
            0,
            "Should NOT have USE_ROW_TIMESTAMP flag"
        );

        // Should have timestamp delta and local_deletion_time delta encoded as VInts
        assert!(
            buf.len() > 1,
            "Should have timestamp and deletion_time deltas"
        );
    }

    #[test]
    fn test_serialize_clustering_value_fixed_width() {
        // Integer (fixed-width, no length prefix)
        let bytes =
            serialize_value_for_clustering(&Value::Integer(42), &ComparatorType::Int).unwrap();
        assert_eq!(bytes, vec![0x00, 0x00, 0x00, 0x2A]);

        // BigInt (fixed-width)
        let bytes =
            serialize_value_for_clustering(&Value::BigInt(1000), &ComparatorType::BigInt).unwrap();
        assert_eq!(bytes, vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xE8]);
    }

    #[test]
    fn test_serialize_clustering_value_variable_width() {
        // Text (variable-width, VInt length prefix)
        let bytes =
            serialize_value_for_clustering(&Value::Text("test".to_string()), &ComparatorType::Text)
                .unwrap();
        assert!(!bytes.is_empty());
        // First byte(s) should be VInt length (4), followed by "test"
        // VInt(4) = 0x04, then "test"
        assert_eq!(bytes[0], 0x04); // VInt length = 4
        assert_eq!(&bytes[1..], b"test");
    }

    #[test]
    fn test_serialize_clustering_date_includes_length_prefix() {
        let bytes = serialize_value_for_clustering(&Value::Date(0), &ComparatorType::Date).unwrap();
        assert_eq!(
            bytes[0], 0x04,
            "date clustering values should be length-prefixed"
        );
        assert_eq!(
            bytes.len(),
            5,
            "date clustering value should be 1-byte length + 4-byte payload"
        );
    }

    #[test]
    fn test_serialize_clustering_frozen_list_text() {
        let value = Value::Frozen(Box::new(Value::List(vec![Value::Text("solo".to_string())])));
        let comparator = ComparatorType::Frozen(Box::new(ComparatorType::List(Box::new(
            ComparatorType::Text,
        ))));

        let bytes = serialize_value_for_clustering(&value, &comparator).unwrap();
        let expected_inner =
            serialize_value(&Value::List(vec![Value::Text("solo".to_string())])).unwrap();

        let mut expected = vec![expected_inner.len() as u8];
        expected.extend_from_slice(&expected_inner);

        assert_eq!(bytes, expected);
    }

    #[test]
    fn test_null_vs_empty_string() {
        let stats = create_test_stats();
        let writer = DataWriter::new(stats);

        // Test NULL - should not be written as a cell
        let result = writer.write_cell(&mut Vec::new(), "test_col", &Value::Null, 1001000);
        assert!(result.is_err(), "NULL values should return error");
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("NULL values should not be written"));

        // Test empty string - should have HAS_EMPTY_VALUE flag
        let mut buf = Vec::new();
        writer
            .write_cell(&mut buf, "test_col", &Value::Text(String::new()), 1001000)
            .unwrap();

        assert!(!buf.is_empty());
        let flags = buf[0];
        assert_eq!(
            flags & CELL_HAS_EMPTY_VALUE,
            CELL_HAS_EMPTY_VALUE,
            "Empty string should have HAS_EMPTY_VALUE flag"
        );

        // Test non-empty string - should NOT have HAS_EMPTY_VALUE flag
        let mut buf2 = Vec::new();
        writer
            .write_cell(
                &mut buf2,
                "test_col",
                &Value::Text("test".to_string()),
                1001000,
            )
            .unwrap();

        let flags2 = buf2[0];
        assert_eq!(
            flags2 & CELL_HAS_EMPTY_VALUE,
            0,
            "Non-empty string should NOT have HAS_EMPTY_VALUE flag"
        );

        assert_eq!(buf, vec![CELL_USE_ROW_TIMESTAMP | CELL_HAS_EMPTY_VALUE]);
    }

    #[test]
    fn test_fixed_width_cell_omits_length_prefix() {
        let stats = create_test_stats();
        let writer = DataWriter::new(stats);
        let mut buf = Vec::new();

        writer
            .write_cell(&mut buf, "value", &Value::Integer(42), 1001000)
            .unwrap();

        assert_eq!(buf, vec![CELL_USE_ROW_TIMESTAMP, 0x00, 0x00, 0x00, 0x2A]);
    }

    #[test]
    fn test_variable_width_cell_keeps_length_prefix() {
        let stats = create_test_stats();
        let writer = DataWriter::new(stats);
        let mut buf = Vec::new();

        writer
            .write_cell(&mut buf, "value", &Value::Text("abc".to_string()), 1001000)
            .unwrap();

        assert_eq!(buf, vec![CELL_USE_ROW_TIMESTAMP, 0x03, b'a', b'b', b'c']);
    }

    #[test]
    fn test_value_length_bounds_check() {
        let stats = create_test_stats();
        let writer = DataWriter::new(stats);

        // Create a value that exceeds i64::MAX (simulated via the check)
        // Since we can't actually allocate > i64::MAX bytes, we test the logic path
        // by checking that reasonable values pass
        let mut buf = Vec::new();
        let large_text = "x".repeat(1000);
        let result = writer.write_cell(&mut buf, "test_col", &Value::Text(large_text), 1001000);
        assert!(result.is_ok(), "Reasonable-sized values should succeed");
    }

    #[test]
    fn test_tombstone_requires_deletion_time() {
        let mut stats = create_test_stats();
        stats.min_timestamp = 1000000;
        stats.min_local_deletion_time = 1700000000;
        let writer = DataWriter::new(stats);

        let mut buf = Vec::new();

        // Test with valid deletion_time > min_local_deletion_time
        let result = writer.write_tombstone_cell(
            &mut buf,
            "deleted_col",
            1001000,
            1700000010, // Greater than min
        );
        assert!(result.is_ok(), "Valid deletion_time should succeed");

        // Test with deletion_time < min_local_deletion_time (should error)
        let mut buf2 = Vec::new();
        let result2 = writer.write_tombstone_cell(
            &mut buf2,
            "deleted_col",
            1001000,
            1600000000, // Less than min
        );
        assert!(result2.is_err(), "deletion_time < min should fail");
        assert!(result2
            .unwrap_err()
            .to_string()
            .contains("less than min_local_deletion_time"));
    }

    #[test]
    fn test_column_bitmap_skips_nulls() {
        let stats = create_test_stats();
        let writer = DataWriter::new(stats);
        let schema = create_test_schema();

        let table_id = TableId::new("test_ks", "test_table");
        let pk = PartitionKey::single("id", Value::Integer(1));

        // Write "name" with value, "age" with NULL
        // Schema has 2 regular columns sorted alphabetically: [age(0), name(1)]
        // "age" is NULL (missing) → bit 0 = 1
        // "name" is present → bit 1 = 0
        // bitmap = 0b01 = 0x01
        let mutation = Mutation::new(
            table_id,
            pk,
            None,
            vec![
                CellOperation::Write {
                    column: "name".to_string(),
                    value: Value::Text("Alice".to_string()),
                },
                CellOperation::Write {
                    column: "age".to_string(),
                    value: Value::Null,
                },
            ],
            1001000,
            None,
        );

        let mut buf = Vec::new();
        writer
            .write_column_bitmap(&mut buf, &mutation, &schema)
            .unwrap();

        // Cassandra format: single VUInt bitmask where bit=1 means MISSING
        // Only "age" (index 0) is missing → bitmap = 0x01
        assert_eq!(
            buf,
            vec![0x01],
            "Bitmap should encode age as missing (bit 0)"
        );
    }

    #[test]
    fn test_row_with_null_values() {
        let stats = create_test_stats();
        let mut writer = DataWriter::new(stats);
        let schema = create_test_schema();

        let table_id = TableId::new("test_ks", "test_table");
        let pk = PartitionKey::single("id", Value::Integer(1));
        let mutation = Mutation::new(
            table_id,
            pk,
            None,
            vec![
                CellOperation::Write {
                    column: "name".to_string(),
                    value: Value::Text("Alice".to_string()),
                },
                CellOperation::Write {
                    column: "age".to_string(),
                    value: Value::Null, // NULL value
                },
            ],
            1001000,
            None,
        );

        writer.write_row(&mutation, &schema).unwrap();

        let bytes = writer.finish().unwrap();
        assert!(!bytes.is_empty());

        // Verify row flags do NOT have HAS_ALL_COLUMNS (because of NULL)
        let flags = bytes[0];
        assert_eq!(
            flags & ROW_HAS_ALL_COLUMNS,
            0,
            "Row with NULL should NOT have HAS_ALL_COLUMNS flag"
        );
    }

    #[test]
    fn test_multiple_partitions() {
        let stats = create_test_stats();
        let mut writer = DataWriter::new(stats);
        let schema = create_test_schema();

        // Write first partition
        let key1 = DecoratedKey::new(100, vec![0x00, 0x00, 0x00, 0x01]);
        let table_id = TableId::new("test_ks", "test_table");
        let pk1 = PartitionKey::single("id", Value::Integer(1));
        let mutations1 = vec![Mutation::new(
            table_id.clone(),
            pk1,
            None,
            vec![CellOperation::Write {
                column: "name".to_string(),
                value: Value::Text("Alice".to_string()),
            }],
            1001000,
            None,
        )];

        let offset1 = writer
            .write_partition(&key1, &mutations1, &schema, None, &[])
            .unwrap();
        assert_eq!(offset1, 0);

        // Write second partition
        let key2 = DecoratedKey::new(200, vec![0x00, 0x00, 0x00, 0x02]);
        let pk2 = PartitionKey::single("id", Value::Integer(2));
        let mutations2 = vec![Mutation::new(
            table_id,
            pk2,
            None,
            vec![CellOperation::Write {
                column: "name".to_string(),
                value: Value::Text("Bob".to_string()),
            }],
            1002000,
            None,
        )];

        let offset2 = writer
            .write_partition(&key2, &mutations2, &schema, None, &[])
            .unwrap();
        assert!(offset2 > offset1); // Second partition starts after first

        let bytes = writer.finish().unwrap();
        assert!(!bytes.is_empty());

        // Both partitions should have end-of-partition markers
        // Note: END_OF_PARTITION (0x01) may appear elsewhere (e.g., in cell flags)
        // For this test, we verify the file structure is valid and both partitions were written
        assert!(
            offset2 > offset1,
            "Second partition should start after first"
        );

        // The last byte should be an END_OF_PARTITION marker
        assert_eq!(
            bytes[bytes.len() - 1],
            END_OF_PARTITION,
            "File should end with END_OF_PARTITION"
        );
    }

    // ========== M5.2 Tombstone Tests ==========

    #[test]
    fn test_row_tombstone() {
        let stats = create_test_stats();
        let mut writer = DataWriter::new(stats);
        let schema = create_test_schema();

        let table_id = TableId::new("test_ks", "test_table");
        let pk = PartitionKey::single("id", Value::Integer(1));
        let mutation = Mutation::new(
            table_id,
            pk,
            None,
            vec![CellOperation::DeleteRow],
            1001000,
            None,
        );

        writer.write_row(&mutation, &schema).unwrap();

        let bytes = writer.finish().unwrap();
        assert!(!bytes.is_empty());

        // Verify row flags have HAS_DELETION
        let flags = bytes[0];
        assert_eq!(
            flags & ROW_HAS_DELETION,
            ROW_HAS_DELETION,
            "Should have HAS_DELETION flag"
        );
        // Issue #717: a pure row tombstone carries no primary-key liveness —
        // Cassandra serializes DELETE-d rows without HAS_TIMESTAMP.
        assert_eq!(
            flags & ROW_HAS_TIMESTAMP,
            0,
            "Pure row tombstone must not have HAS_TIMESTAMP"
        );
        assert_eq!(
            flags & ROW_HAS_ALL_COLUMNS,
            0,
            "Row tombstone must not claim all columns"
        );

        // Issue #717: the columns subset must follow the deletion times.
        // Layout: [flags][row_size][prev_size=0][deletion mfda][deletion ldt][subset]
        // With create_test_stats baselines both deletion deltas and the
        // all-missing subset are single-byte VInts.
        let row_size = bytes[1] as usize;
        // Body = prev_size(1) + mfda(vint) + ldt(vint) + subset(vint ≥ 1 byte)
        assert!(
            row_size >= 4,
            "Row tombstone body must include the columns subset (got row_size={})",
            row_size
        );
        // The final body byte is the all-missing subset bitmask: 2 regular
        // columns (name, value) in create_test_schema → 0b11.
        let body_end = 2 + row_size; // flags + row_size byte + body
        assert_eq!(
            bytes[body_end - 1],
            0b11,
            "Columns subset must mark every regular column missing"
        );
    }

    #[test]
    fn test_partition_tombstone() {
        use crate::storage::write_engine::mutation::PartitionTombstone;

        let stats = create_test_stats();
        let mut writer = DataWriter::new(stats);

        let key = DecoratedKey::new(12345, vec![0x00, 0x00, 0x00, 0x2A]);
        let tombstone = PartitionTombstone {
            deletion_time: 1001000,          // microseconds
            local_deletion_time: 1700000010, // seconds
        };

        writer
            .write_partition_header(&key, Some(&tombstone))
            .unwrap();

        let bytes = writer.finish().unwrap();

        // Verify structure (Cassandra BigFormat):
        // [0x00, 0x04] key length (u16 BE)
        // [key bytes]
        // [local_deletion_time: i32 BE]
        // [deletion_timestamp: i64 BE]
        assert_eq!(&bytes[0..2], &[0x00, 0x04], "Key length (u16 BE)");

        // Check local_deletion_time (i32 BE at offset 6)
        let ldt_bytes = &bytes[6..10];
        let ldt = i32::from_be_bytes([ldt_bytes[0], ldt_bytes[1], ldt_bytes[2], ldt_bytes[3]]);
        assert_eq!(ldt, 1700000010, "Local deletion time should match");

        // Check deletion_timestamp (i64 BE at offset 10)
        let ts_bytes = &bytes[10..18];
        let ts = i64::from_be_bytes([
            ts_bytes[0],
            ts_bytes[1],
            ts_bytes[2],
            ts_bytes[3],
            ts_bytes[4],
            ts_bytes[5],
            ts_bytes[6],
            ts_bytes[7],
        ]);
        assert_eq!(ts, 1001000, "Deletion timestamp should match");
    }

    #[test]
    fn test_range_tombstone_inclusive_bounds() {
        use crate::storage::write_engine::mutation::{ClusteringBound, RangeTombstone};

        let mut schema = create_test_schema();
        schema.clustering_keys = vec![ClusteringColumn {
            name: "ts".to_string(),
            data_type: "timestamp".to_string(),
            position: 0,
            order: ClusteringOrder::Asc,
        }];

        let stats = create_test_stats();
        let mut writer = DataWriter::new(stats);

        let range = RangeTombstone {
            start: ClusteringBound::Inclusive(ClusteringKey::single("ts", Value::Timestamp(1000))),
            end: ClusteringBound::Inclusive(ClusteringKey::single("ts", Value::Timestamp(2000))),
            deletion_time: 1001000,
            local_deletion_time: 1700000010,
        };

        let open_size = writer
            .write_range_bound(
                &range.start,
                true,
                range.deletion_time,
                range.local_deletion_time,
                &schema,
                0,
            )
            .unwrap();
        writer
            .write_range_bound(
                &range.end,
                false,
                range.deletion_time,
                range.local_deletion_time,
                &schema,
                open_size as u64,
            )
            .unwrap();

        let bytes = writer.finish().unwrap();
        assert!(!bytes.is_empty());

        // Verify opening bound: Cassandra ClusteringPrefix.Kind ordinals
        assert_eq!(bytes[0], IS_MARKER, "Should have IS_MARKER flag");
        assert_eq!(
            bytes[1], INCL_START_BOUND,
            "Should have INCL_START_BOUND kind (ordinal 1)"
        );
        // u16 BE cluster count follows the kind byte
        assert_eq!(
            u16::from_be_bytes([bytes[2], bytes[3]]),
            1,
            "Bound carries one clustering value"
        );

        // Closing bound starts right after the opening marker
        assert_eq!(bytes[open_size], IS_MARKER);
        assert_eq!(
            bytes[open_size + 1],
            INCL_END_BOUND,
            "Should have INCL_END_BOUND kind (ordinal 6)"
        );
    }

    #[test]
    fn test_range_tombstone_exclusive_bounds() {
        use crate::storage::write_engine::mutation::{ClusteringBound, RangeTombstone};

        let mut schema = create_test_schema();
        schema.clustering_keys = vec![ClusteringColumn {
            name: "ts".to_string(),
            data_type: "timestamp".to_string(),
            position: 0,
            order: ClusteringOrder::Asc,
        }];

        let stats = create_test_stats();
        let mut writer = DataWriter::new(stats);

        let range = RangeTombstone {
            start: ClusteringBound::Exclusive(ClusteringKey::single("ts", Value::Timestamp(1000))),
            end: ClusteringBound::Exclusive(ClusteringKey::single("ts", Value::Timestamp(2000))),
            deletion_time: 1001000,
            local_deletion_time: 1700000010,
        };

        let open_size = writer
            .write_range_bound(
                &range.start,
                true,
                range.deletion_time,
                range.local_deletion_time,
                &schema,
                0,
            )
            .unwrap();
        writer
            .write_range_bound(
                &range.end,
                false,
                range.deletion_time,
                range.local_deletion_time,
                &schema,
                open_size as u64,
            )
            .unwrap();

        let bytes = writer.finish().unwrap();
        assert!(!bytes.is_empty());

        // Verify opening bound: Cassandra ClusteringPrefix.Kind ordinals
        assert_eq!(bytes[0], IS_MARKER, "Should have IS_MARKER flag");
        assert_eq!(
            bytes[1], EXCL_START_BOUND,
            "Should have EXCL_START_BOUND kind (ordinal 7)"
        );
        assert_eq!(
            bytes[open_size + 1],
            EXCL_END_BOUND,
            "Should have EXCL_END_BOUND kind (ordinal 0)"
        );
    }

    #[test]
    fn test_range_tombstone_bottom_top_bounds() {
        use crate::storage::write_engine::mutation::{ClusteringBound, RangeTombstone};

        let mut schema = create_test_schema();
        schema.clustering_keys = vec![ClusteringColumn {
            name: "ts".to_string(),
            data_type: "timestamp".to_string(),
            position: 0,
            order: ClusteringOrder::Asc,
        }];

        let stats = create_test_stats();
        let mut writer = DataWriter::new(stats);

        // Delete everything from start to end of partition
        let range = RangeTombstone {
            start: ClusteringBound::Bottom,
            end: ClusteringBound::Top,
            deletion_time: 1001000,
            local_deletion_time: 1700000010,
        };

        let open_size = writer
            .write_range_bound(
                &range.start,
                true,
                range.deletion_time,
                range.local_deletion_time,
                &schema,
                0,
            )
            .unwrap();
        writer
            .write_range_bound(
                &range.end,
                false,
                range.deletion_time,
                range.local_deletion_time,
                &schema,
                open_size as u64,
            )
            .unwrap();

        let bytes = writer.finish().unwrap();
        assert!(!bytes.is_empty());

        // Bottom serializes as an inclusive start bound with zero clustering
        // values (u16 count = 0, no clustering header byte).
        assert_eq!(bytes[0], IS_MARKER, "Should have IS_MARKER flag");
        assert_eq!(
            bytes[1], INCL_START_BOUND,
            "Bottom should serialize as INCL_START_BOUND"
        );
        assert_eq!(
            u16::from_be_bytes([bytes[2], bytes[3]]),
            0,
            "Bottom carries no clustering values"
        );
        // Top serializes as an inclusive end bound with zero values
        assert_eq!(bytes[open_size + 1], INCL_END_BOUND);
    }

    #[test]
    fn test_complete_partition_with_range_tombstone() {
        use crate::storage::write_engine::mutation::{ClusteringBound, RangeTombstone};

        let mut schema = create_test_schema();
        schema.clustering_keys = vec![ClusteringColumn {
            name: "ts".to_string(),
            data_type: "timestamp".to_string(),
            position: 0,
            order: ClusteringOrder::Asc,
        }];

        let stats = create_test_stats();
        let mut writer = DataWriter::new(stats);

        let key = DecoratedKey::new(12345, vec![0x00, 0x00, 0x00, 0x01]);
        let table_id = TableId::new("test_ks", "test_table");
        let pk = PartitionKey::single("id", Value::Integer(1));

        // Create mutations
        let mutations = vec![Mutation::new(
            table_id,
            pk,
            Some(ClusteringKey::single("ts", Value::Timestamp(1000))),
            vec![CellOperation::Write {
                column: "name".to_string(),
                value: Value::Text("Alice".to_string()),
            }],
            1001000,
            None,
        )];

        // Create range tombstone
        let range_tombstones = vec![RangeTombstone {
            start: ClusteringBound::Inclusive(ClusteringKey::single("ts", Value::Timestamp(500))),
            end: ClusteringBound::Inclusive(ClusteringKey::single("ts", Value::Timestamp(1500))),
            deletion_time: 1002000, // Later than row timestamp - will shadow it
            local_deletion_time: 1700000020,
        }];

        let offset = writer
            .write_partition(&key, &mutations, &schema, None, &range_tombstones)
            .unwrap();
        assert_eq!(offset, 0);

        let bytes = writer.finish().unwrap();
        assert!(!bytes.is_empty());

        // Verify partition header is present (u16 BE key length)
        assert_eq!(&bytes[0..2], &[0x00, 0x04], "Key length (u16 BE)");

        // Range tombstone markers should appear before rows
        // This is validated by the structure of the output
    }

    #[test]
    fn test_write_cell_with_ttl() {
        let mut stats = create_test_stats();
        stats.min_timestamp = 1000000;
        stats.min_local_deletion_time = 1700000000;
        stats.min_ttl = 3600;
        let writer = DataWriter::new(stats);

        let mut buf = Vec::new();
        let timestamp = 1001000;
        let ttl_seconds = 7200;

        writer
            .write_cell_with_ttl(
                &mut buf,
                "test_col",
                &Value::Text("test".to_string()),
                timestamp,
                ttl_seconds,
            )
            .unwrap();

        assert!(!buf.is_empty());

        // First byte should be CELL_IS_EXPIRING flag (0x02)
        let flags = buf[0];
        assert_eq!(
            flags & CELL_IS_EXPIRING,
            CELL_IS_EXPIRING,
            "Should have IS_EXPIRING flag"
        );
        assert_eq!(
            flags & CELL_USE_ROW_TIMESTAMP,
            0,
            "Should NOT have USE_ROW_TIMESTAMP flag"
        );
        assert_eq!(
            flags & CELL_USE_ROW_TTL,
            0,
            "Should NOT have USE_ROW_TTL flag"
        );

        // Should contain timestamp delta, local_deletion_time delta, TTL delta, and value
        assert!(buf.len() > 10, "Should have all TTL cell fields");
    }

    #[test]
    fn test_row_with_ttl_cells() {
        let mut stats = create_test_stats();
        stats.min_timestamp = 1000000;
        stats.min_local_deletion_time = 1700000000;
        stats.min_ttl = 3600;
        let mut writer = DataWriter::new(stats);
        let schema = create_test_schema();

        let table_id = TableId::new("test_ks", "test_table");
        let pk = PartitionKey::single("id", Value::Integer(1));
        let mutation = Mutation::new(
            table_id,
            pk,
            None,
            vec![
                CellOperation::WriteWithTtl {
                    column: "name".to_string(),
                    value: Value::Text("Alice".to_string()),
                    ttl_seconds: 7200,
                },
                CellOperation::Write {
                    column: "age".to_string(),
                    value: Value::Integer(30),
                },
            ],
            1001000,
            None,
        );

        writer.write_row(&mutation, &schema).unwrap();

        let bytes = writer.finish().unwrap();
        assert!(!bytes.is_empty());

        // Verify row flags
        let flags = bytes[0];
        assert_eq!(
            flags & ROW_HAS_TIMESTAMP,
            ROW_HAS_TIMESTAMP,
            "Should have timestamp"
        );
        assert_eq!(
            flags & ROW_HAS_ALL_COLUMNS,
            ROW_HAS_ALL_COLUMNS,
            "Should have all columns"
        );
    }

    #[test]
    fn test_row_with_multiple_ttl_cells() {
        let mut stats = create_test_stats();
        stats.min_timestamp = 1000000;
        stats.min_local_deletion_time = 1700000000;
        stats.min_ttl = 1800;
        let mut writer = DataWriter::new(stats);
        let schema = create_test_schema();

        let table_id = TableId::new("test_ks", "test_table");
        let pk = PartitionKey::single("id", Value::Integer(1));
        let mutation = Mutation::new(
            table_id,
            pk,
            None,
            vec![
                CellOperation::WriteWithTtl {
                    column: "name".to_string(),
                    value: Value::Text("Alice".to_string()),
                    ttl_seconds: 3600, // 1 hour
                },
                CellOperation::WriteWithTtl {
                    column: "age".to_string(),
                    value: Value::Integer(30),
                    ttl_seconds: 7200, // 2 hours (different TTL)
                },
            ],
            1001000,
            None,
        );

        writer.write_row(&mutation, &schema).unwrap();

        let bytes = writer.finish().unwrap();
        assert!(!bytes.is_empty());

        // Verify both cells were written with their own TTLs
        // The exact validation would require parsing the binary format
    }

    #[test]
    fn test_mixed_ttl_and_regular_cells() {
        let mut stats = create_test_stats();
        stats.min_timestamp = 1000000;
        stats.min_local_deletion_time = 1700000000;
        stats.min_ttl = 3600;
        let mut writer = DataWriter::new(stats);
        let schema = create_test_schema();

        let table_id = TableId::new("test_ks", "test_table");
        let pk = PartitionKey::single("id", Value::Integer(1));
        let mutation = Mutation::new(
            table_id,
            pk,
            None,
            vec![
                CellOperation::Write {
                    column: "name".to_string(),
                    value: Value::Text("Alice".to_string()),
                },
                CellOperation::WriteWithTtl {
                    column: "age".to_string(),
                    value: Value::Integer(30),
                    ttl_seconds: 7200,
                },
            ],
            1001000,
            None,
        );

        writer.write_row(&mutation, &schema).unwrap();

        let bytes = writer.finish().unwrap();
        assert!(!bytes.is_empty());

        // Row should contain both regular and TTL cells
        let flags = bytes[0];
        assert_eq!(flags & ROW_HAS_TIMESTAMP, ROW_HAS_TIMESTAMP);
    }

    #[test]
    fn test_ttl_zero_special_case() {
        let mut stats = create_test_stats();
        stats.min_timestamp = 1000000;
        stats.min_local_deletion_time = 1700000000;
        stats.min_ttl = 0;
        let writer = DataWriter::new(stats);

        let mut buf = Vec::new();
        let timestamp = 1001000;
        let ttl_seconds = 0; // Immediate expiration

        writer
            .write_cell_with_ttl(
                &mut buf,
                "test_col",
                &Value::Text("test".to_string()),
                timestamp,
                ttl_seconds,
            )
            .unwrap();

        assert!(!buf.is_empty());

        // Should have IS_EXPIRING flag even with TTL=0
        let flags = buf[0];
        assert_eq!(flags & CELL_IS_EXPIRING, CELL_IS_EXPIRING);
    }

    #[test]
    fn test_ttl_statistics_tracking() {
        let mut stats = StatisticsMetadata::new();

        // Update with various TTL values
        stats.update_ttl(3600);
        stats.update_ttl(7200);
        stats.update_ttl(1800);
        stats.update_ttl(0); // TTL=0 should be ignored

        assert_eq!(stats.min_ttl, 1800, "min_ttl should be 1800");
        assert_eq!(stats.max_ttl, 7200, "max_ttl should be 7200");
    }

    #[test]
    fn test_ttl_cell_with_null_value() {
        let stats = create_test_stats();
        let writer = DataWriter::new(stats);

        let mut buf = Vec::new();
        let result = writer.write_cell_with_ttl(&mut buf, "test_col", &Value::Null, 1001000, 3600);

        assert!(result.is_err(), "NULL values should return error");
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("NULL values should not be written"));
    }

    #[test]
    fn test_ttl_cell_local_deletion_time_calculation() {
        let mut stats = create_test_stats();
        stats.min_timestamp = 1000000;
        stats.min_local_deletion_time = 1700000000;
        stats.min_ttl = 3600;
        let writer = DataWriter::new(stats);

        let mut buf = Vec::new();
        let timestamp = 1001000;
        let ttl_seconds = 7200; // 2 hours

        // The local_deletion_time should be computed as current_time + ttl_seconds
        writer
            .write_cell_with_ttl(
                &mut buf,
                "test_col",
                &Value::Text("test".to_string()),
                timestamp,
                ttl_seconds,
            )
            .unwrap();

        assert!(!buf.is_empty());
        // Detailed validation would require parsing the encoded deltas
    }

    #[test]
    fn test_row_ttl_uses_row_ttl_cell_flags() {
        let mut stats = create_test_stats();
        stats.min_timestamp = 1001000;
        stats.min_ttl = 7200;
        stats.min_local_deletion_time = 1;
        let mut writer = DataWriter::new(stats);
        let schema = create_test_schema();

        let mutation = Mutation::new(
            TableId::new("test_ks", "test_table"),
            PartitionKey::single("id", Value::Integer(1)),
            None,
            vec![
                CellOperation::Write {
                    column: "name".to_string(),
                    value: Value::Text("Alice".to_string()),
                },
                CellOperation::Write {
                    column: "age".to_string(),
                    value: Value::Integer(30),
                },
            ],
            1001000,
            Some(7200),
        );

        writer.write_row(&mutation, &schema).unwrap();
        let bytes = writer.finish().unwrap();

        assert_eq!(bytes[0] & ROW_HAS_TTL, ROW_HAS_TTL);
        let expiring_row_ttl_flags = CELL_IS_EXPIRING | CELL_USE_ROW_TIMESTAMP | CELL_USE_ROW_TTL;
        let flag_count = bytes
            .iter()
            .filter(|&&byte| byte == expiring_row_ttl_flags)
            .count();
        assert_eq!(flag_count, 2, "expected both cells to inherit row TTL");
    }

    #[test]
    fn test_write_partition_emits_static_row_before_regular_rows() {
        let stats = create_test_stats();
        let mut writer = DataWriter::new(stats);
        let schema = create_static_test_schema();
        let key = DecoratedKey::new(1, vec![0, 0, 0, 1]);

        let static_mutation = Mutation::new(
            TableId::new("test_ks", "test_table"),
            PartitionKey::single("id", Value::Integer(1)),
            None,
            vec![CellOperation::Write {
                column: "static_val".to_string(),
                value: Value::Text("static".to_string()),
            }],
            1001000,
            None,
        );
        let regular_mutation = Mutation::new(
            TableId::new("test_ks", "test_table"),
            PartitionKey::single("id", Value::Integer(1)),
            Some(ClusteringKey::single("ck", Value::Integer(1))),
            vec![CellOperation::Write {
                column: "regular_val".to_string(),
                value: Value::Text("regular".to_string()),
            }],
            1002000,
            None,
        );

        writer
            .write_partition(
                &key,
                &[static_mutation, regular_mutation],
                &schema,
                None,
                &[],
            )
            .unwrap();
        let bytes = writer.finish().unwrap();

        let partition_header_len = 2 + key.key.len() + 4 + 8;
        assert_eq!(
            bytes[partition_header_len] & ROW_HAS_EXTENDED_FLAGS,
            ROW_HAS_EXTENDED_FLAGS
        );
        assert_eq!(bytes[partition_header_len + 1], EXTENDED_IS_STATIC);
    }

    /// Cassandra switches to large-subset encoding when the superset reaches 64 columns.
    #[test]
    fn test_column_subset_exactly_64_regular_columns_uses_large_subset_encoding() {
        let stats = create_test_stats();
        let writer = DataWriter::new(stats);

        // Create schema with exactly 64 regular columns
        let columns: Vec<Column> = (0..64)
            .map(|i| Column {
                name: format!("col_{:03}", i),
                data_type: "text".to_string(),
                nullable: true,
                default: None,
                is_static: false,
            })
            .collect();

        let schema = TableSchema {
            keyspace: "test_ks".to_string(),
            table: "test_table".to_string(),
            partition_keys: vec![KeyColumn {
                name: "id".to_string(),
                data_type: "int".to_string(),
                position: 0,
            }],
            clustering_keys: vec![],
            columns,
            comments: HashMap::new(),
        };

        let table_id = TableId::new("test_ks", "test_table");
        let pk = PartitionKey::single("id", Value::Integer(1));

        // Only write col_0 and col_63, forcing the large-subset path.
        let mutation = Mutation::new(
            table_id,
            pk,
            None,
            vec![
                CellOperation::Write {
                    column: "col_000".to_string(),
                    value: Value::Text("first".to_string()),
                },
                CellOperation::Write {
                    column: "col_063".to_string(),
                    value: Value::Text("last".to_string()),
                },
            ],
            1001000,
            None,
        );

        let mut buf = Vec::new();
        writer
            .write_column_bitmap(&mut buf, &mutation, &schema)
            .unwrap();

        // missing_count=62, then present indexes [0, 63]
        assert_eq!(buf, vec![62, 0, 63]);
    }

    /// Large static-column subsets use the same delta encoding as regular columns.
    #[test]
    fn test_column_subset_65_static_columns_uses_missing_indexes_when_present_majority() {
        let stats = create_test_stats();
        let writer = DataWriter::new(stats);

        // Create schema with 65 static columns
        let columns: Vec<Column> = (0..65)
            .map(|i| Column {
                name: format!("scol_{:03}", i),
                data_type: "text".to_string(),
                nullable: true,
                default: None,
                is_static: true,
            })
            .collect();

        let schema = TableSchema {
            keyspace: "test_ks".to_string(),
            table: "test_table".to_string(),
            partition_keys: vec![KeyColumn {
                name: "id".to_string(),
                data_type: "int".to_string(),
                position: 0,
            }],
            clustering_keys: vec![ClusteringColumn {
                name: "ck".to_string(),
                data_type: "int".to_string(),
                position: 0,
                order: ClusteringOrder::Asc,
            }],
            columns,
            comments: HashMap::new(),
        };

        let table_id = TableId::new("test_ks", "test_table");
        let pk = PartitionKey::single("id", Value::Integer(1));

        // Write all but one static column so the encoding emits missing indexes.
        let mut operations = Vec::new();
        for i in 0..65 {
            if i == 17 {
                continue;
            }
            operations.push(CellOperation::Write {
                column: format!("scol_{:03}", i),
                value: Value::Text(format!("value-{}", i)),
            });
        }

        let mutation = Mutation::new(table_id, pk, None, operations, 1001000, None);

        let mut buf = Vec::new();
        writer
            .write_static_column_bitmap(&mut buf, &mutation, &schema)
            .unwrap();

        // missing_count=1, followed by the missing column index.
        assert_eq!(buf, vec![1, 17]);
    }

    /// Smaller subsets still use the missing-column bitmap.
    #[test]
    fn test_column_subset_under_64_regular_columns_uses_bitmap() {
        let stats = create_test_stats();
        let writer = DataWriter::new(stats);

        let columns: Vec<Column> = (0..4)
            .map(|i| Column {
                name: format!("col_{i}"),
                data_type: "text".to_string(),
                nullable: true,
                default: None,
                is_static: false,
            })
            .collect();

        let schema = TableSchema {
            keyspace: "test_ks".to_string(),
            table: "test_table".to_string(),
            partition_keys: vec![KeyColumn {
                name: "id".to_string(),
                data_type: "int".to_string(),
                position: 0,
            }],
            clustering_keys: vec![],
            columns,
            comments: HashMap::new(),
        };

        let table_id = TableId::new("test_ks", "test_table");
        let pk = PartitionKey::single("id", Value::Integer(1));

        // Only col_1 is present, so bits 0, 2, and 3 are set.
        let mutation = Mutation::new(
            table_id,
            pk,
            None,
            vec![CellOperation::Write {
                column: "col_1".to_string(),
                value: Value::Text("present".to_string()),
            }],
            1001000,
            None,
        );

        let mut buf = Vec::new();
        writer
            .write_column_bitmap(&mut buf, &mutation, &schema)
            .unwrap();

        assert_eq!(buf, vec![0b1101]);
    }

    #[test]
    fn test_regular_columns_sort_simple_before_complex() {
        let stats = create_test_stats();
        let writer = DataWriter::new(stats);

        let schema = TableSchema {
            keyspace: "test_ks".to_string(),
            table: "test_table".to_string(),
            partition_keys: vec![KeyColumn {
                name: "id".to_string(),
                data_type: "int".to_string(),
                position: 0,
            }],
            clustering_keys: vec![],
            columns: vec![
                Column {
                    name: "z_simple".to_string(),
                    data_type: "text".to_string(),
                    nullable: true,
                    default: None,
                    is_static: false,
                },
                Column {
                    name: "a_complex".to_string(),
                    data_type: "set<text>".to_string(),
                    nullable: true,
                    default: None,
                    is_static: false,
                },
                Column {
                    name: "m_simple".to_string(),
                    data_type: "int".to_string(),
                    nullable: true,
                    default: None,
                    is_static: false,
                },
            ],
            comments: HashMap::new(),
        };

        let ordered = writer.regular_columns(&schema);
        let names: Vec<_> = ordered.iter().map(|column| column.name.as_str()).collect();

        assert_eq!(names, vec!["m_simple", "z_simple", "a_complex"]);
    }

    #[test]
    fn test_static_columns_sort_simple_before_complex() {
        let stats = create_test_stats();
        let writer = DataWriter::new(stats);

        let schema = TableSchema {
            keyspace: "test_ks".to_string(),
            table: "test_table".to_string(),
            partition_keys: vec![KeyColumn {
                name: "id".to_string(),
                data_type: "int".to_string(),
                position: 0,
            }],
            clustering_keys: vec![ClusteringColumn {
                name: "ck".to_string(),
                data_type: "int".to_string(),
                position: 0,
                order: ClusteringOrder::Asc,
            }],
            columns: vec![
                Column {
                    name: "z_static_simple".to_string(),
                    data_type: "text".to_string(),
                    nullable: true,
                    default: None,
                    is_static: true,
                },
                Column {
                    name: "a_static_complex".to_string(),
                    data_type: "set<text>".to_string(),
                    nullable: true,
                    default: None,
                    is_static: true,
                },
                Column {
                    name: "m_static_simple".to_string(),
                    data_type: "int".to_string(),
                    nullable: true,
                    default: None,
                    is_static: true,
                },
            ],
            comments: HashMap::new(),
        };

        let ordered = writer.static_columns(&schema);
        let names: Vec<_> = ordered.iter().map(|column| column.name.as_str()).collect();

        assert_eq!(
            names,
            vec!["m_static_simple", "z_static_simple", "a_static_complex"]
        );
    }

    #[test]
    fn test_write_column_bitmap_zero_when_all_columns_present() {
        let stats = create_test_stats();
        let writer = DataWriter::new(stats);

        let columns: Vec<Column> = (0..65)
            .map(|i| Column {
                name: format!("col_{:03}", i),
                data_type: "text".to_string(),
                nullable: true,
                default: None,
                is_static: false,
            })
            .collect();

        let schema = TableSchema {
            keyspace: "test_ks".to_string(),
            table: "test_table".to_string(),
            partition_keys: vec![KeyColumn {
                name: "id".to_string(),
                data_type: "int".to_string(),
                position: 0,
            }],
            clustering_keys: vec![],
            columns,
            comments: HashMap::new(),
        };

        let table_id = TableId::new("test_ks", "test_table");
        let pk = PartitionKey::single("id", Value::Integer(1));

        let operations: Vec<_> = (0..65)
            .map(|i| CellOperation::Write {
                column: format!("col_{:03}", i),
                value: Value::Text(format!("value-{}", i)),
            })
            .collect();

        let mutation = Mutation::new(table_id, pk, None, operations, 1001000, None);

        let mut buf = Vec::new();
        writer
            .write_column_bitmap(&mut buf, &mutation, &schema)
            .unwrap();

        assert_eq!(buf, vec![0]);
    }

    #[test]
    fn test_serialize_list() {
        let list = Value::List(vec![
            Value::Integer(1),
            Value::Integer(2),
            Value::Integer(3),
        ]);
        let bytes = serialize_value(&list).unwrap();
        // 4 bytes count + 3 * (4 bytes len + 4 bytes i32)
        assert_eq!(bytes.len(), 4 + 3 * 8);
        // Count = 3
        assert_eq!(&bytes[0..4], &3i32.to_be_bytes());
        // First element length = 4
        assert_eq!(&bytes[4..8], &4i32.to_be_bytes());
        // First element value = 1
        assert_eq!(&bytes[8..12], &1i32.to_be_bytes());
    }

    #[test]
    fn test_serialize_empty_list() {
        let list = Value::List(vec![]);
        let bytes = serialize_value(&list).unwrap();
        assert_eq!(bytes.len(), 4);
        assert_eq!(&bytes[0..4], &0i32.to_be_bytes());
    }

    #[test]
    fn test_serialize_single_element_list() {
        let list = Value::List(vec![Value::Integer(42)]);
        let bytes = serialize_value(&list).unwrap();
        assert_eq!(
            bytes,
            vec![
                0x00, 0x00, 0x00, 0x01, // count = 1
                0x00, 0x00, 0x00, 0x04, // len = 4
                0x00, 0x00, 0x00, 0x2A, // value = 42
            ]
        );
    }

    #[test]
    fn test_serialize_set() {
        let set = Value::Set(vec![
            Value::Text("alpha".to_string()),
            Value::Text("beta".to_string()),
        ]);
        let bytes = serialize_value(&set).unwrap();
        // Count = 2
        assert_eq!(&bytes[0..4], &2i32.to_be_bytes());
        // First element length = 5 ("alpha")
        assert_eq!(&bytes[4..8], &5i32.to_be_bytes());
        assert_eq!(&bytes[8..13], b"alpha");
    }

    #[test]
    fn test_serialize_single_element_set() {
        let set = Value::Set(vec![Value::Text("alpha".to_string())]);
        let bytes = serialize_value(&set).unwrap();
        assert_eq!(
            bytes,
            vec![
                0x00, 0x00, 0x00, 0x01, // count = 1
                0x00, 0x00, 0x00, 0x05, // len = 5
                b'a', b'l', b'p', b'h', b'a', // value = "alpha"
            ]
        );
    }

    #[test]
    fn test_serialize_empty_set() {
        let set = Value::Set(vec![]);
        let bytes = serialize_value(&set).unwrap();
        assert_eq!(bytes, 0i32.to_be_bytes().to_vec());
    }

    #[test]
    fn test_serialize_map() {
        let map = Value::Map(vec![(Value::Text("key1".to_string()), Value::Integer(100))]);
        let bytes = serialize_value(&map).unwrap();
        // Count = 1
        assert_eq!(&bytes[0..4], &1i32.to_be_bytes());
        // Key length = 4 ("key1")
        assert_eq!(&bytes[4..8], &4i32.to_be_bytes());
        assert_eq!(&bytes[8..12], b"key1");
        // Value length = 4 (i32)
        assert_eq!(&bytes[12..16], &4i32.to_be_bytes());
        // Value = 100
        assert_eq!(&bytes[16..20], &100i32.to_be_bytes());
    }

    #[test]
    fn test_serialize_empty_map() {
        let map = Value::Map(vec![]);
        let bytes = serialize_value(&map).unwrap();
        assert_eq!(bytes.len(), 4);
        assert_eq!(&bytes[0..4], &0i32.to_be_bytes());
    }

    #[test]
    fn test_serialize_tuple() {
        let tuple = Value::Tuple(vec![
            Value::Integer(42),
            Value::Text("hello".to_string()),
            Value::Null,
        ]);
        let bytes = serialize_value(&tuple).unwrap();
        // Field 1: 4 bytes len + 4 bytes i32 = 8
        assert_eq!(&bytes[0..4], &4i32.to_be_bytes());
        assert_eq!(&bytes[4..8], &42i32.to_be_bytes());
        // Field 2: 4 bytes len + 5 bytes text = 9
        assert_eq!(&bytes[8..12], &5i32.to_be_bytes());
        assert_eq!(&bytes[12..17], b"hello");
        // Field 3: NULL = -1 as i32
        assert_eq!(&bytes[17..21], &(-1i32).to_be_bytes());
    }

    #[test]
    fn test_serialize_single_element_tuple() {
        let tuple = Value::Tuple(vec![Value::Text("solo".to_string())]);
        let bytes = serialize_value(&tuple).unwrap();
        assert_eq!(
            bytes,
            vec![
                0x00, 0x00, 0x00, 0x04, // len = 4
                b's', b'o', b'l', b'o', // value = "solo"
            ]
        );
    }

    #[test]
    fn test_serialize_frozen() {
        let frozen = Value::Frozen(Box::new(Value::List(vec![
            Value::Integer(10),
            Value::Integer(20),
        ])));
        let frozen_bytes = serialize_value(&frozen).unwrap();
        let list_bytes =
            serialize_value(&Value::List(vec![Value::Integer(10), Value::Integer(20)])).unwrap();
        // Frozen should produce identical bytes to inner value
        assert_eq!(frozen_bytes, list_bytes);
    }

    #[test]
    fn test_serialize_single_element_frozen() {
        let frozen = Value::Frozen(Box::new(Value::List(vec![Value::Text("solo".to_string())])));
        let frozen_bytes = serialize_value(&frozen).unwrap();
        let list_bytes =
            serialize_value(&Value::List(vec![Value::Text("solo".to_string())])).unwrap();
        assert_eq!(frozen_bytes, list_bytes);
    }

    #[test]
    fn test_serialize_nested_collection() {
        // MAP<TEXT, FROZEN<LIST<INT>>>
        let nested = Value::Map(vec![(
            Value::Text("nums".to_string()),
            Value::Frozen(Box::new(Value::List(vec![
                Value::Integer(1),
                Value::Integer(2),
            ]))),
        )]);
        let bytes = serialize_value(&nested).unwrap();
        // Should not error - validates nested serialization works
        assert!(!bytes.is_empty());
        // Count = 1
        assert_eq!(&bytes[0..4], &1i32.to_be_bytes());
    }

    #[test]
    fn test_serialize_udt_with_nested_collections_matches_schema_aware_bytes() {
        let serializer = TypeSerializer::new();
        let company = phase3_company_value();

        let bytes = serialize_value(&Value::Udt(company.clone())).unwrap();
        let expected = serializer
            .serialize_udt(&Value::Udt(company), &phase3_company_schema())
            .unwrap();

        assert_eq!(bytes, expected);
    }

    #[test]
    fn test_serialize_collection_containing_nested_udts() {
        let serializer = TypeSerializer::new();
        let company = phase3_company_value();
        let company_bytes = serializer
            .serialize_udt(&Value::Udt(company.clone()), &phase3_company_schema())
            .unwrap();

        let value = Value::Map(vec![(
            Value::Text("empresa_日本".to_string()),
            Value::Frozen(Box::new(Value::Udt(company))),
        )]);
        let bytes = serialize_value(&value).unwrap();

        let key = "empresa_日本".as_bytes();
        let mut expected = Vec::new();
        expected.extend_from_slice(&1i32.to_be_bytes());
        expected.extend_from_slice(&(key.len() as i32).to_be_bytes());
        expected.extend_from_slice(key);
        expected.extend_from_slice(&(company_bytes.len() as i32).to_be_bytes());
        expected.extend_from_slice(&company_bytes);

        assert_eq!(bytes, expected);
    }

    #[test]
    fn test_serialize_tuple_with_collection_fields_and_udt() {
        let serializer = TypeSerializer::new();
        let address = phase3_address_value();
        let person = phase3_person_value("Tuple User");
        let address_bytes = serializer
            .serialize_udt(&Value::Udt(address.clone()), &phase3_address_schema())
            .unwrap();
        let person_bytes = serializer
            .serialize_udt(&Value::Udt(person.clone()), &phase3_person_schema())
            .unwrap();

        let tuple = Value::Tuple(vec![
            Value::Text("phase3".to_string()),
            Value::Frozen(Box::new(Value::List(vec![
                Value::Integer(3),
                Value::Integer(5),
                Value::Integer(8),
            ]))),
            Value::Frozen(Box::new(Value::Map(vec![(
                Value::Text("home".to_string()),
                Value::Frozen(Box::new(Value::Udt(address))),
            )]))),
            Value::Frozen(Box::new(Value::Udt(person))),
        ]);
        let bytes = serialize_value(&tuple).unwrap();

        let list_bytes = serialize_value(&Value::List(vec![
            Value::Integer(3),
            Value::Integer(5),
            Value::Integer(8),
        ]))
        .unwrap();
        let map_bytes = {
            let key = b"home";
            let mut encoded = Vec::new();
            encoded.extend_from_slice(&1i32.to_be_bytes());
            encoded.extend_from_slice(&(key.len() as i32).to_be_bytes());
            encoded.extend_from_slice(key);
            encoded.extend_from_slice(&(address_bytes.len() as i32).to_be_bytes());
            encoded.extend_from_slice(&address_bytes);
            encoded
        };

        let mut expected = Vec::new();
        expected.extend_from_slice(&6i32.to_be_bytes());
        expected.extend_from_slice(b"phase3");
        expected.extend_from_slice(&(list_bytes.len() as i32).to_be_bytes());
        expected.extend_from_slice(&list_bytes);
        expected.extend_from_slice(&(map_bytes.len() as i32).to_be_bytes());
        expected.extend_from_slice(&map_bytes);
        expected.extend_from_slice(&(person_bytes.len() as i32).to_be_bytes());
        expected.extend_from_slice(&person_bytes);

        assert_eq!(bytes, expected);
    }

    #[test]
    fn test_serialize_high_complexity_nested_collection() {
        let nested = Value::Map(vec![(
            Value::Text("outer".to_string()),
            Value::Frozen(Box::new(Value::List(vec![Value::Frozen(Box::new(
                Value::Map(vec![(
                    Value::Text("inner".to_string()),
                    Value::Frozen(Box::new(Value::List(vec![
                        Value::Integer(1),
                        Value::Integer(2),
                    ]))),
                )]),
            ))]))),
        )]);

        let bytes = serialize_value(&nested).unwrap();

        assert!(!bytes.is_empty());
        assert_eq!(&bytes[0..4], &1i32.to_be_bytes());
    }

    // ========== Complex Column (Multi-Cell) Tests ==========

    #[test]
    fn test_is_complex_column() {
        // Non-frozen collections ARE complex (CQL syntax)
        assert!(is_complex_column("set<int>"));
        assert!(is_complex_column("list<text>"));
        assert!(is_complex_column("map<text, int>"));
        assert!(is_complex_column("SET<INT>"));
        assert!(is_complex_column("List<Text>"));
        assert!(is_complex_column("Map<Text, Int>"));

        // Non-frozen collections ARE complex (Cassandra internal syntax)
        assert!(is_complex_column(
            "org.apache.cassandra.db.marshal.SetType(org.apache.cassandra.db.marshal.Int32Type)"
        ));
        assert!(is_complex_column(
            "org.apache.cassandra.db.marshal.ListType(org.apache.cassandra.db.marshal.UTF8Type)"
        ));
        assert!(is_complex_column(
            "org.apache.cassandra.db.marshal.MapType(org.apache.cassandra.db.marshal.UTF8Type,org.apache.cassandra.db.marshal.Int32Type)"
        ));

        // Frozen collections are NOT complex (CQL syntax)
        assert!(!is_complex_column("frozen<set<int>>"));
        assert!(!is_complex_column("frozen<list<text>>"));
        assert!(!is_complex_column("frozen<map<text, int>>"));
        assert!(!is_complex_column("FROZEN<SET<INT>>"));

        // Frozen collections are NOT complex (Cassandra internal syntax)
        assert!(!is_complex_column(
            "org.apache.cassandra.db.marshal.FrozenType(org.apache.cassandra.db.marshal.SetType(org.apache.cassandra.db.marshal.Int32Type))"
        ));

        // Primitives are NOT complex
        assert!(!is_complex_column("int"));
        assert!(!is_complex_column("text"));
        assert!(!is_complex_column("uuid"));
        assert!(!is_complex_column("timestamp"));
    }

    #[test]
    fn test_generate_list_cell_path_timeuuid() {
        let ts = 1_704_067_200_000_000i64; // 2024-01-01 00:00:00 UTC

        let uuid0 = generate_list_cell_path_timeuuid(ts, 0);
        let uuid1 = generate_list_cell_path_timeuuid(ts, 1);
        let uuid2 = generate_list_cell_path_timeuuid(ts, 2);

        // All should be 16 bytes
        assert_eq!(uuid0.len(), 16);
        assert_eq!(uuid1.len(), 16);

        // Version bits should be 1 (0x1X in byte 6)
        assert_eq!(uuid0[6] & 0xF0, 0x10, "Should be UUID version 1");
        assert_eq!(uuid1[6] & 0xF0, 0x10, "Should be UUID version 1");

        // UUIDs should be monotonically increasing (as byte arrays)
        assert!(uuid0 < uuid1, "UUID0 should be less than UUID1");
        assert!(uuid1 < uuid2, "UUID1 should be less than UUID2");
    }

    #[test]
    fn test_write_set_complex_column() {
        let stats = create_test_stats();
        let writer = DataWriter::new(stats);

        let column = Column {
            name: "tags".to_string(),
            data_type: "set<text>".to_string(),
            nullable: true,
            default: None,
            is_static: false,
        };

        let value = Value::Set(vec![
            Value::Text("alpha".to_string()),
            Value::Text("beta".to_string()),
        ]);

        let mut buf = Vec::new();
        writer
            .write_complex_column(&mut buf, &column, &value, 1001000, None)
            .unwrap();

        assert!(!buf.is_empty());

        // Parse: complex_deletion (2 signed VInts) + cell_count + cells
        // The first bytes are DeletionTime.LIVE encoded as signed VInts
        // Then cell_count = 2 (unsigned VInt)
        // Then for each cell: flags(1) + path_len(VInt) + path_bytes + (no value for SET)

        // Verify we can find 2 cell flag bytes with USE_ROW_TIMESTAMP | HAS_EMPTY_VALUE = 0x0C
        let expected_cell_flags = CELL_USE_ROW_TIMESTAMP | CELL_HAS_EMPTY_VALUE;
        let cell_flag_count = buf.iter().filter(|&&b| b == expected_cell_flags).count();
        assert_eq!(
            cell_flag_count, 2,
            "Should have 2 SET cells with USE_ROW_TIMESTAMP | HAS_EMPTY_VALUE flags"
        );
    }

    #[test]
    fn test_write_map_complex_column() {
        let stats = create_test_stats();
        let writer = DataWriter::new(stats);

        let column = Column {
            name: "props".to_string(),
            data_type: "map<text, int>".to_string(),
            nullable: true,
            default: None,
            is_static: false,
        };

        let value = Value::Map(vec![
            (Value::Text("key1".to_string()), Value::Integer(100)),
            (Value::Text("key2".to_string()), Value::Integer(200)),
        ]);

        let mut buf = Vec::new();
        writer
            .write_complex_column(&mut buf, &column, &value, 1001000, None)
            .unwrap();

        assert!(!buf.is_empty());

        // MAP cells have USE_ROW_TIMESTAMP (0x08) but NOT HAS_EMPTY_VALUE
        let cell_flag_count = buf.iter().filter(|&&b| b == CELL_USE_ROW_TIMESTAMP).count();
        assert_eq!(
            cell_flag_count, 2,
            "Should have 2 MAP cells with USE_ROW_TIMESTAMP flags"
        );
    }

    #[test]
    fn test_write_list_complex_column() {
        let stats = create_test_stats();
        let writer = DataWriter::new(stats);

        let column = Column {
            name: "items".to_string(),
            data_type: "list<int>".to_string(),
            nullable: true,
            default: None,
            is_static: false,
        };

        let value = Value::List(vec![Value::Integer(10), Value::Integer(20)]);

        let mut buf = Vec::new();
        writer
            .write_complex_column(&mut buf, &column, &value, 1001000, None)
            .unwrap();

        assert!(!buf.is_empty());

        // LIST cells have USE_ROW_TIMESTAMP (0x08) and 16-byte TimeUUID paths
        let cell_flag_count = buf.iter().filter(|&&b| b == CELL_USE_ROW_TIMESTAMP).count();
        assert_eq!(
            cell_flag_count, 2,
            "Should have 2 LIST cells with USE_ROW_TIMESTAMP flags"
        );

        // Verify TimeUUID path length (16) appears in the output
        // Each cell has: flags(1) + path_len_vint(1, value=16=0x10) + path(16) + val_len + val
        // The VInt encoding of 16 is 0x10
        let timeuuid_len_count = buf.iter().filter(|&&b| b == 0x10).count();
        assert!(
            timeuuid_len_count >= 2,
            "Should have TimeUUID path length (16) for each list cell"
        );
    }

    #[test]
    fn test_frozen_collection_not_complex() {
        // Frozen collections should still use simple cell (serialize_value), not complex column
        let schema = TableSchema {
            keyspace: "test_ks".to_string(),
            table: "test_table".to_string(),
            partition_keys: vec![KeyColumn {
                name: "id".to_string(),
                data_type: "int".to_string(),
                position: 0,
            }],
            clustering_keys: vec![],
            columns: vec![Column {
                name: "frozen_tags".to_string(),
                data_type: "frozen<set<text>>".to_string(),
                nullable: true,
                default: None,
                is_static: false,
            }],
            comments: HashMap::new(),
        };

        let stats = create_test_stats();
        let mut writer = DataWriter::new(stats);

        let table_id = TableId::new("test_ks", "test_table");
        let pk = PartitionKey::single("id", Value::Integer(1));
        let mutation = Mutation::new(
            table_id,
            pk,
            None,
            vec![CellOperation::Write {
                column: "frozen_tags".to_string(),
                value: Value::Frozen(Box::new(Value::Set(vec![
                    Value::Text("a".to_string()),
                    Value::Text("b".to_string()),
                ]))),
            }],
            1001000,
            None,
        );

        writer.write_row(&mutation, &schema).unwrap();

        let bytes = writer.finish().unwrap();
        assert!(!bytes.is_empty());

        // Frozen collection should NOT have HAS_COMPLEX_DELETION flag
        let flags = bytes[0];
        assert_eq!(
            flags & ROW_HAS_COMPLEX_DELETION,
            0,
            "Frozen collection should NOT have HAS_COMPLEX_DELETION flag"
        );
    }

    #[test]
    fn test_mixed_simple_and_complex_columns() {
        let schema = TableSchema {
            keyspace: "test_ks".to_string(),
            table: "test_table".to_string(),
            partition_keys: vec![KeyColumn {
                name: "id".to_string(),
                data_type: "int".to_string(),
                position: 0,
            }],
            clustering_keys: vec![],
            columns: vec![
                Column {
                    name: "name".to_string(),
                    data_type: "text".to_string(),
                    nullable: true,
                    default: None,
                    is_static: false,
                },
                Column {
                    name: "tags".to_string(),
                    data_type: "set<text>".to_string(),
                    nullable: true,
                    default: None,
                    is_static: false,
                },
            ],
            comments: HashMap::new(),
        };

        let stats = create_test_stats();
        let mut writer = DataWriter::new(stats);

        let table_id = TableId::new("test_ks", "test_table");
        let pk = PartitionKey::single("id", Value::Integer(1));
        let mutation = Mutation::new(
            table_id,
            pk,
            None,
            vec![
                CellOperation::Write {
                    column: "name".to_string(),
                    value: Value::Text("Alice".to_string()),
                },
                CellOperation::Write {
                    column: "tags".to_string(),
                    value: Value::Set(vec![
                        Value::Text("admin".to_string()),
                        Value::Text("user".to_string()),
                    ]),
                },
            ],
            1001000,
            None,
        );

        writer.write_row(&mutation, &schema).unwrap();

        let bytes = writer.finish().unwrap();
        assert!(!bytes.is_empty());

        // Row should have HAS_COMPLEX_DELETION flag because of the SET column
        let flags = bytes[0];
        assert_eq!(
            flags & ROW_HAS_COMPLEX_DELETION,
            ROW_HAS_COMPLEX_DELETION,
            "Row with non-frozen SET should have HAS_COMPLEX_DELETION flag"
        );
        assert_eq!(
            flags & ROW_HAS_TIMESTAMP,
            ROW_HAS_TIMESTAMP,
            "Should have timestamp"
        );
        assert_eq!(
            flags & ROW_HAS_ALL_COLUMNS,
            ROW_HAS_ALL_COLUMNS,
            "Should have all columns"
        );
    }

    #[test]
    fn test_set_canonical_ordering() {
        // Elements provided out of order should be sorted by serialized bytes
        let stats = create_test_stats();
        let writer = DataWriter::new(stats);

        let column = Column {
            name: "tags".to_string(),
            data_type: "set<text>".to_string(),
            nullable: true,
            default: None,
            is_static: false,
        };

        // Input: zebra, alpha, mango (unsorted)
        let value = Value::Set(vec![
            Value::Text("zebra".to_string()),
            Value::Text("alpha".to_string()),
            Value::Text("mango".to_string()),
        ]);

        let mut buf = Vec::new();
        writer
            .write_complex_column(&mut buf, &column, &value, 1001000, None)
            .unwrap();

        // Extract cell paths from the binary output.
        // After complex deletion (2 VInts) and cell count (1 VInt), each cell is:
        //   flags(1) + path_len(VInt) + path_bytes
        // Find the text values in order by scanning for ASCII strings.
        let buf_str = String::from_utf8_lossy(&buf);
        let alpha_pos = buf_str.find("alpha").expect("alpha should be in output");
        let mango_pos = buf_str.find("mango").expect("mango should be in output");
        let zebra_pos = buf_str.find("zebra").expect("zebra should be in output");

        assert!(
            alpha_pos < mango_pos && mango_pos < zebra_pos,
            "SET elements should be in sorted order: alpha({}) < mango({}) < zebra({})",
            alpha_pos,
            mango_pos,
            zebra_pos
        );
    }

    #[test]
    fn test_map_canonical_ordering() {
        let stats = create_test_stats();
        let writer = DataWriter::new(stats);

        let column = Column {
            name: "props".to_string(),
            data_type: "map<text, int>".to_string(),
            nullable: true,
            default: None,
            is_static: false,
        };

        // Input: keys out of order (z_key, a_key)
        let value = Value::Map(vec![
            (Value::Text("z_key".to_string()), Value::Integer(1)),
            (Value::Text("a_key".to_string()), Value::Integer(2)),
        ]);

        let mut buf = Vec::new();
        writer
            .write_complex_column(&mut buf, &column, &value, 1001000, None)
            .unwrap();

        let buf_str = String::from_utf8_lossy(&buf);
        let a_pos = buf_str.find("a_key").expect("a_key should be in output");
        let z_pos = buf_str.find("z_key").expect("z_key should be in output");

        assert!(
            a_pos < z_pos,
            "MAP entries should be sorted by key: a_key({}) < z_key({})",
            a_pos,
            z_pos
        );
    }

    #[test]
    fn test_set_rejects_list_value() {
        let stats = create_test_stats();
        let writer = DataWriter::new(stats);

        let column = Column {
            name: "tags".to_string(),
            data_type: "set<text>".to_string(),
            nullable: true,
            default: None,
            is_static: false,
        };

        // Pass a List value to a SET column — should be rejected
        let value = Value::List(vec![Value::Text("x".to_string())]);
        let mut buf = Vec::new();
        let result = writer.write_complex_column(&mut buf, &column, &value, 1001000, None);
        assert!(result.is_err(), "SET column should reject Value::List");
    }

    #[test]
    fn test_list_rejects_set_value() {
        let stats = create_test_stats();
        let writer = DataWriter::new(stats);

        let column = Column {
            name: "items".to_string(),
            data_type: "list<text>".to_string(),
            nullable: true,
            default: None,
            is_static: false,
        };

        // Pass a Set value to a LIST column — should be rejected
        let value = Value::Set(vec![Value::Text("x".to_string())]);
        let mut buf = Vec::new();
        let result = writer.write_complex_column(&mut buf, &column, &value, 1001000, None);
        assert!(result.is_err(), "LIST column should reject Value::Set");
    }

    #[test]
    fn test_complex_column_deletion() {
        let stats = create_test_stats();
        let writer = DataWriter::new(stats);

        let mut buf = Vec::new();
        writer
            .write_complex_column_deletion(&mut buf, 1001000)
            .unwrap();

        assert!(!buf.is_empty());

        // Should contain: marked_for_delete_at delta + local_deletion_time delta + cell_count(0)
        // The last byte should be 0x00 (cell_count = 0 encoded as unsigned VInt)
        assert_eq!(
            buf[buf.len() - 1],
            0x00,
            "Last byte should be cell_count = 0"
        );
    }

    #[test]
    fn test_write_with_ttl_complex_column() {
        // WriteWithTtl on a complex column should use complex format, not simple cell
        let schema = TableSchema {
            keyspace: "test_ks".to_string(),
            table: "test_table".to_string(),
            partition_keys: vec![KeyColumn {
                name: "id".to_string(),
                data_type: "int".to_string(),
                position: 0,
            }],
            clustering_keys: vec![],
            columns: vec![Column {
                name: "tags".to_string(),
                data_type: "set<text>".to_string(),
                nullable: true,
                default: None,
                is_static: false,
            }],
            comments: HashMap::new(),
        };

        let stats = create_test_stats();
        let mut writer = DataWriter::new(stats);

        let table_id = TableId::new("test_ks", "test_table");
        let pk = PartitionKey::single("id", Value::Integer(1));
        let mutation = Mutation::new(
            table_id,
            pk,
            None,
            vec![CellOperation::WriteWithTtl {
                column: "tags".to_string(),
                value: Value::Set(vec![
                    Value::Text("a".to_string()),
                    Value::Text("b".to_string()),
                ]),
                ttl_seconds: 3600,
            }],
            1001000,
            None,
        );

        // Should succeed without error — complex format should be used
        writer.write_row(&mutation, &schema).unwrap();

        let bytes = writer.finish().unwrap();
        assert!(!bytes.is_empty());

        // Should have HAS_COMPLEX_DELETION flag
        let flags = bytes[0];
        assert_eq!(
            flags & ROW_HAS_COMPLEX_DELETION,
            ROW_HAS_COMPLEX_DELETION,
            "WriteWithTtl on SET should set HAS_COMPLEX_DELETION"
        );
    }

    #[test]
    fn test_delete_complex_column() {
        // Delete on a complex column should write complex deletion, not simple tombstone
        let schema = TableSchema {
            keyspace: "test_ks".to_string(),
            table: "test_table".to_string(),
            partition_keys: vec![KeyColumn {
                name: "id".to_string(),
                data_type: "int".to_string(),
                position: 0,
            }],
            clustering_keys: vec![],
            columns: vec![Column {
                name: "tags".to_string(),
                data_type: "set<text>".to_string(),
                nullable: true,
                default: None,
                is_static: false,
            }],
            comments: HashMap::new(),
        };

        let stats = create_test_stats();
        let mut writer = DataWriter::new(stats);

        let table_id = TableId::new("test_ks", "test_table");
        let pk = PartitionKey::single("id", Value::Integer(1));
        let mutation = Mutation::new(
            table_id,
            pk,
            None,
            vec![CellOperation::Delete {
                column: "tags".to_string(),
            }],
            1001000,
            None,
        );

        // Should succeed — uses complex deletion format
        writer.write_row(&mutation, &schema).unwrap();

        let bytes = writer.finish().unwrap();
        assert!(!bytes.is_empty());

        // Should have HAS_COMPLEX_DELETION flag
        let flags = bytes[0];
        assert_eq!(
            flags & ROW_HAS_COMPLEX_DELETION,
            ROW_HAS_COMPLEX_DELETION,
            "Delete on SET should set HAS_COMPLEX_DELETION"
        );
    }

    #[test]
    fn test_internal_type_string_complex_column() {
        // Cassandra internal type strings should be recognized as complex
        let schema = TableSchema {
            keyspace: "test_ks".to_string(),
            table: "test_table".to_string(),
            partition_keys: vec![KeyColumn {
                name: "id".to_string(),
                data_type: "int".to_string(),
                position: 0,
            }],
            clustering_keys: vec![],
            columns: vec![Column {
                name: "tags".to_string(),
                data_type: "org.apache.cassandra.db.marshal.SetType(org.apache.cassandra.db.marshal.UTF8Type)".to_string(),
                nullable: true,
                default: None,
                is_static: false,
            }],
            comments: HashMap::new(),
        };

        let stats = create_test_stats();
        let mut writer = DataWriter::new(stats);

        let table_id = TableId::new("test_ks", "test_table");
        let pk = PartitionKey::single("id", Value::Integer(1));
        let mutation = Mutation::new(
            table_id,
            pk,
            None,
            vec![CellOperation::Write {
                column: "tags".to_string(),
                value: Value::Set(vec![Value::Text("test".to_string())]),
            }],
            1001000,
            None,
        );

        writer.write_row(&mutation, &schema).unwrap();

        let bytes = writer.finish().unwrap();
        let flags = bytes[0];
        assert_eq!(
            flags & ROW_HAS_COMPLEX_DELETION,
            ROW_HAS_COMPLEX_DELETION,
            "Internal type string should be recognized as complex column"
        );
    }

    /// Parse a `write_complex_column` output buffer and return the flag byte for every cell.
    ///
    /// The buffer has this deterministic structure:
    /// ```text
    /// [complex_deletion_ts_delta:  unsigned VInt]  ← 2 VInts, time-derived but fixed per stats
    /// [complex_deletion_ldt_delta: unsigned VInt]
    /// [cell_count: unsigned VInt]
    /// per cell:
    ///   [flags: u8]
    ///   if IS_EXPIRING (0x02 set):
    ///     [ts_delta:  unsigned VInt]
    ///     [ldt_delta: unsigned VInt]   ← wall-clock-derived
    ///     [ttl_delta: unsigned VInt]
    ///   [path_len:  unsigned VInt]
    ///   [path_bytes: path_len]
    ///   if !HAS_EMPTY_VALUE (0x04 NOT set):
    ///     [value_len: unsigned VInt]
    ///     [value_bytes: value_len]
    /// ```
    ///
    /// Scanning the raw buffer for a flag byte value is fragile because
    /// wall-clock-derived LDT bytes can coincidentally equal the flag byte (~1-2% of CI runs).
    /// This helper walks the structure deterministically so each flag byte is read at
    /// its exact position.
    fn parse_complex_cell_flags(buf: &[u8]) -> Vec<u8> {
        /// Read one unsigned VInt from `buf` starting at `*pos`; advance `*pos`.
        fn read_uvint(buf: &[u8], pos: &mut usize) -> u64 {
            let first = buf[*pos];
            *pos += 1;
            if first == 0xFF {
                // 9-byte form: 0xFF + 8 big-endian bytes
                let mut v = 0u64;
                for _ in 0..8 {
                    v = (v << 8) | buf[*pos] as u64;
                    *pos += 1;
                }
                return v;
            }
            // Count leading 1-bits in `first` to determine extra bytes
            let extra = first.leading_ones() as usize;
            // Data bits in first byte: mask off the leading 1s and the 0 separator
            let mask = 0xFF_u8.wrapping_shr((extra + 1) as u32);
            let mut v = (first & mask) as u64;
            for _ in 0..extra {
                v = (v << 8) | buf[*pos] as u64;
                *pos += 1;
            }
            v
        }

        let mut pos = 0usize;
        // Skip complex deletion header: 2 unsigned VInts
        read_uvint(buf, &mut pos);
        read_uvint(buf, &mut pos);

        // Cell count
        let cell_count = read_uvint(buf, &mut pos) as usize;

        let mut flags_out = Vec::with_capacity(cell_count);
        for _ in 0..cell_count {
            let flags = buf[pos];
            pos += 1;
            flags_out.push(flags);

            if (flags & CELL_IS_EXPIRING) != 0 {
                // IS_EXPIRING: ts_delta + ldt_delta + ttl_delta (3 unsigned VInts)
                read_uvint(buf, &mut pos);
                read_uvint(buf, &mut pos);
                read_uvint(buf, &mut pos);
            }
            // USE_ROW_TIMESTAMP / non-expiring cells: no extra fields before path

            // Cell path: path_len VInt + path_len bytes
            let path_len = read_uvint(buf, &mut pos) as usize;
            pos += path_len;

            // Cell value: only present when HAS_EMPTY_VALUE is NOT set
            if (flags & CELL_HAS_EMPTY_VALUE) == 0 {
                let value_len = read_uvint(buf, &mut pos) as usize;
                pos += value_len;
            }
        }

        flags_out
    }

    #[test]
    fn test_set_complex_column_with_ttl() {
        // SET with TTL should write IS_EXPIRING flag per cell, not USE_ROW_TIMESTAMP.
        // Uses structural parsing to read cell flags at their exact byte positions,
        // avoiding false positives from time-derived LDT bytes that can equal 0x02.
        let stats = create_test_stats();
        let writer = DataWriter::new(stats);

        let column = Column {
            name: "tags".to_string(),
            data_type: "set<text>".to_string(),
            nullable: true,
            default: None,
            is_static: false,
        };

        let value = Value::Set(vec![
            Value::Text("alpha".to_string()),
            Value::Text("beta".to_string()),
        ]);

        let mut buf = Vec::new();
        writer
            .write_complex_column(&mut buf, &column, &value, 1001000, Some(3600))
            .unwrap();

        // Parse cell flags structurally so wall-clock LDT bytes in the header and
        // per-cell TTL fields cannot be misidentified as flag bytes.
        let cell_flags = parse_complex_cell_flags(&buf);
        let expected_flags = CELL_IS_EXPIRING | CELL_HAS_EMPTY_VALUE; // 0x06

        assert_eq!(
            cell_flags.len(),
            2,
            "SET with 2 elements should produce 2 cells"
        );
        assert!(
            cell_flags.iter().all(|&f| f == expected_flags),
            "SET with TTL: all cells should have IS_EXPIRING | HAS_EMPTY_VALUE (0x06), got: {:?}",
            cell_flags
        );

        // Confirm absence of USE_ROW_TIMESTAMP on all cells
        assert!(
            cell_flags
                .iter()
                .all(|&f| (f & CELL_USE_ROW_TIMESTAMP) == 0),
            "SET with TTL should NOT have USE_ROW_TIMESTAMP on any cell, got: {:?}",
            cell_flags
        );
    }

    #[test]
    fn test_map_complex_column_with_ttl() {
        // MAP with TTL should write IS_EXPIRING flag per cell.
        // Uses structural parsing to read cell flags at their exact byte positions,
        // avoiding false positives from time-derived LDT bytes that can equal 0x02.
        let stats = create_test_stats();
        let writer = DataWriter::new(stats);

        let column = Column {
            name: "props".to_string(),
            data_type: "map<text, int>".to_string(),
            nullable: true,
            default: None,
            is_static: false,
        };

        let value = Value::Map(vec![(Value::Text("key1".to_string()), Value::Integer(100))]);

        let mut buf = Vec::new();
        writer
            .write_complex_column(&mut buf, &column, &value, 1001000, Some(7200))
            .unwrap();

        // Parse cell flags structurally so wall-clock LDT bytes cannot be
        // misidentified as IS_EXPIRING (0x02) flag bytes.
        let cell_flags = parse_complex_cell_flags(&buf);

        assert_eq!(
            cell_flags.len(),
            1,
            "MAP with 1 entry should produce 1 cell"
        );
        assert_eq!(
            cell_flags[0] & CELL_IS_EXPIRING,
            CELL_IS_EXPIRING,
            "MAP with TTL: cell should have IS_EXPIRING flag set, got flags byte: 0x{:02X}",
            cell_flags[0]
        );
        assert_eq!(
            cell_flags[0] & CELL_HAS_EMPTY_VALUE,
            0,
            "MAP with TTL: cell should NOT have HAS_EMPTY_VALUE, got flags byte: 0x{:02X}",
            cell_flags[0]
        );
    }

    #[test]
    fn test_list_complex_column_with_ttl() {
        // LIST with TTL should write IS_EXPIRING per cell, producing a larger
        // output than without TTL (extra timestamp/LDT/TTL delta fields).
        // Uses structural parsing to read cell flags at their exact byte positions,
        // avoiding false positives from time-derived LDT bytes.
        let stats = create_test_stats();
        let writer_ttl = DataWriter::new(stats.clone());
        let writer_no_ttl = DataWriter::new(stats);

        let column = Column {
            name: "items".to_string(),
            data_type: "list<int>".to_string(),
            nullable: true,
            default: None,
            is_static: false,
        };

        let value = Value::List(vec![
            Value::Integer(1),
            Value::Integer(2),
            Value::Integer(3),
        ]);

        let mut buf_ttl = Vec::new();
        writer_ttl
            .write_complex_column(&mut buf_ttl, &column, &value, 1001000, Some(1800))
            .unwrap();

        let mut buf_no_ttl = Vec::new();
        writer_no_ttl
            .write_complex_column(&mut buf_no_ttl, &column, &value, 1001000, None)
            .unwrap();

        // TTL version must be larger: each cell gets timestamp + LDT + TTL deltas
        // instead of just USE_ROW_TIMESTAMP flag.
        assert!(
            buf_ttl.len() > buf_no_ttl.len(),
            "LIST with TTL ({} bytes) should be larger than without TTL ({} bytes)",
            buf_ttl.len(),
            buf_no_ttl.len()
        );

        // Structurally verify IS_EXPIRING is set on every cell in the TTL version.
        let cell_flags_ttl = parse_complex_cell_flags(&buf_ttl);
        assert_eq!(
            cell_flags_ttl.len(),
            3,
            "LIST with 3 elements should produce 3 cells"
        );
        assert!(
            cell_flags_ttl.iter().all(|&f| (f & CELL_IS_EXPIRING) != 0),
            "LIST with TTL: all cells should have IS_EXPIRING flag set, got: {:?}",
            cell_flags_ttl
        );

        // Verify the no-TTL version uses USE_ROW_TIMESTAMP instead.
        let cell_flags_no_ttl = parse_complex_cell_flags(&buf_no_ttl);
        assert_eq!(cell_flags_no_ttl.len(), 3);
        assert!(
            cell_flags_no_ttl
                .iter()
                .all(|&f| (f & CELL_IS_EXPIRING) == 0),
            "LIST without TTL: no cells should have IS_EXPIRING flag, got: {:?}",
            cell_flags_no_ttl
        );
    }

    #[test]
    fn test_complex_column_no_ttl_uses_row_timestamp() {
        // Regression: without TTL, cells should still use USE_ROW_TIMESTAMP
        let stats = create_test_stats();
        let writer = DataWriter::new(stats);

        let column = Column {
            name: "tags".to_string(),
            data_type: "set<text>".to_string(),
            nullable: true,
            default: None,
            is_static: false,
        };

        let value = Value::Set(vec![Value::Text("x".to_string())]);

        let mut buf = Vec::new();
        writer
            .write_complex_column(&mut buf, &column, &value, 1001000, None)
            .unwrap();

        // Without TTL: USE_ROW_TIMESTAMP | HAS_EMPTY_VALUE = 0x0C
        let expected_flags = CELL_USE_ROW_TIMESTAMP | CELL_HAS_EMPTY_VALUE;
        let count = buf.iter().filter(|&&b| b == expected_flags).count();
        assert_eq!(
            count, 1,
            "Without TTL, SET cells should use USE_ROW_TIMESTAMP"
        );
    }

    #[test]
    fn test_bitmap_includes_deleted_columns() {
        // Delete operations should mark columns as present in the bitmap
        let schema = TableSchema {
            keyspace: "test_ks".to_string(),
            table: "test_table".to_string(),
            partition_keys: vec![KeyColumn {
                name: "id".to_string(),
                data_type: "int".to_string(),
                position: 0,
            }],
            clustering_keys: vec![],
            columns: vec![
                Column {
                    name: "age".to_string(),
                    data_type: "int".to_string(),
                    nullable: true,
                    default: None,
                    is_static: false,
                },
                Column {
                    name: "name".to_string(),
                    data_type: "text".to_string(),
                    nullable: true,
                    default: None,
                    is_static: false,
                },
            ],
            comments: HashMap::new(),
        };

        let stats = create_test_stats();
        let writer = DataWriter::new(stats);

        // Write "name" and delete "age"
        let table_id = TableId::new("test_ks", "test_table");
        let pk = PartitionKey::single("id", Value::Integer(1));
        let mutation = Mutation::new(
            table_id,
            pk,
            None,
            vec![
                CellOperation::Delete {
                    column: "age".to_string(),
                },
                CellOperation::Write {
                    column: "name".to_string(),
                    value: Value::Text("Alice".to_string()),
                },
            ],
            1001000,
            None,
        );

        // Write bitmap — both columns should be present (bitmap = 0)
        let mut buf = Vec::new();
        writer
            .write_column_bitmap(&mut buf, &mutation, &schema)
            .unwrap();

        // bitmap = 0 means all columns present (no MISSING bits set)
        // Since we have 2 regular columns and both are in operations,
        // all should be marked present
        assert_eq!(buf.len(), 1, "Bitmap should be a single byte");
        assert_eq!(
            buf[0], 0,
            "Bitmap should be 0 (all columns present) when both write and delete cover all columns"
        );
    }

    #[test]
    fn test_bitmap_delete_only_column_is_present() {
        // A column that ONLY has a Delete should still be marked present
        let schema = TableSchema {
            keyspace: "test_ks".to_string(),
            table: "test_table".to_string(),
            partition_keys: vec![KeyColumn {
                name: "id".to_string(),
                data_type: "int".to_string(),
                position: 0,
            }],
            clustering_keys: vec![],
            columns: vec![
                Column {
                    name: "age".to_string(),
                    data_type: "int".to_string(),
                    nullable: true,
                    default: None,
                    is_static: false,
                },
                Column {
                    name: "name".to_string(),
                    data_type: "text".to_string(),
                    nullable: true,
                    default: None,
                    is_static: false,
                },
            ],
            comments: HashMap::new(),
        };

        let stats = create_test_stats();
        let writer = DataWriter::new(stats);

        // Only delete "age", don't write "name"
        let table_id = TableId::new("test_ks", "test_table");
        let pk = PartitionKey::single("id", Value::Integer(1));
        let mutation = Mutation::new(
            table_id,
            pk,
            None,
            vec![CellOperation::Delete {
                column: "age".to_string(),
            }],
            1001000,
            None,
        );

        let mut buf = Vec::new();
        writer
            .write_column_bitmap(&mut buf, &mutation, &schema)
            .unwrap();

        // Regular columns sorted alphabetically: [age, name]
        // age (idx 0) = present (Delete), name (idx 1) = missing
        // bitmap bit 1 = 1, bit 0 = 0 → bitmap = 0b10 = 2
        assert_eq!(buf.len(), 1);
        assert_eq!(
            buf[0], 2,
            "Bitmap should mark 'name' as missing (bit 1) but 'age' as present (bit 0)"
        );
    }

    // ========== Issue #492: streaming DataWriter tests ==========

    /// Build a deterministic set of partitions used by the streaming tests.
    fn streaming_test_partitions() -> Vec<(DecoratedKey, Vec<Mutation>)> {
        let table_id = TableId::new("test_ks", "test_table");
        (0..16u32)
            .map(|i| {
                let key = DecoratedKey::new(i as i64, i.to_be_bytes().to_vec());
                let pk = PartitionKey::single("id", Value::Integer(i as i32));
                let mutation = Mutation::new(
                    table_id.clone(),
                    pk,
                    None,
                    vec![CellOperation::Write {
                        column: "name".to_string(),
                        value: Value::Text(format!("partition-{i}")),
                    }],
                    1_001_000 + i as i64,
                    None,
                );
                (key, vec![mutation])
            })
            .collect()
    }

    /// Byte-identical guard (Issue #492): the streaming writer (flushing each
    /// partition to a file) must produce a Data.db byte sequence that is
    /// identical to the legacy in-memory writer, and the returned partition
    /// offsets must match exactly. Anything else breaks Index.db offsets.
    #[test]
    fn test_streaming_writer_byte_identical_to_in_memory() {
        let schema = create_test_schema();
        let partitions = streaming_test_partitions();

        // In-memory reference: accumulate every partition in `buffer`.
        let mut mem_writer = DataWriter::new(create_test_stats());
        let mut mem_offsets = Vec::new();
        for (key, mutations) in &partitions {
            mem_offsets.push(
                mem_writer
                    .write_partition(key, mutations, &schema, None, &[])
                    .unwrap(),
            );
        }
        let expected_bytes = mem_writer.finish().unwrap();

        // Streaming: flush each partition to a temp Data.db file.
        let dir = tempfile::tempdir().unwrap();
        let data_path = dir.path().join("nb-1-big-Data.db");
        let mut stream_writer = DataWriter::with_sink(create_test_stats(), data_path.clone());
        let mut stream_offsets = Vec::new();
        for (key, mutations) in &partitions {
            stream_offsets.push(
                stream_writer
                    .write_partition(key, mutations, &schema, None, &[])
                    .unwrap(),
            );
        }
        let data_size = stream_writer.finish_streaming().unwrap();

        // Offsets returned to the caller (fed to Index.db) must be identical.
        assert_eq!(
            stream_offsets, mem_offsets,
            "streaming partition offsets must equal in-memory offsets"
        );

        // The on-disk Data.db must be byte-for-byte identical to the in-memory
        // bytes, and the reported data_size must match the file length.
        let on_disk = std::fs::read(&data_path).unwrap();
        assert_eq!(
            on_disk, expected_bytes,
            "streamed Data.db must be byte-identical to in-memory Data.db"
        );
        assert_eq!(
            data_size as usize,
            expected_bytes.len(),
            "finish_streaming() data_size must equal file length"
        );

        // Every returned offset must point at the actual start byte in the file:
        // a partition starts with its 2-byte key length, here always 0x0004.
        for &off in &stream_offsets {
            assert_eq!(
                &on_disk[off as usize..off as usize + 2],
                &[0x00, 0x04],
                "offset {off} must land on a partition's key-length prefix"
            );
        }
    }

    /// Bounded-memory evidence (Issue #492): after each `write_partition` the
    /// scratch buffer must hold only the most recent partition, while the
    /// flushed `position` grows monotonically. This is the proof that peak heap
    /// is O(largest partition) rather than O(file).
    #[test]
    fn test_streaming_writer_bounds_memory_to_one_partition() {
        let schema = create_test_schema();
        let partitions = streaming_test_partitions();

        let dir = tempfile::tempdir().unwrap();
        let data_path = dir.path().join("nb-1-big-Data.db");
        let mut writer = DataWriter::with_sink(create_test_stats(), data_path);

        let mut prev_flushed = 0u64;
        // Tracks the largest single-partition flushed size. Because the scratch is
        // cleared after every partition (asserted below), peak resident Data.db
        // bytes are bounded by this value, not the whole file.
        let mut max_partition_size = 0usize;
        for (i, (key, mutations)) in partitions.iter().enumerate() {
            let flushed_before = writer.flushed_position();
            writer
                .write_partition(key, mutations, &schema, None, &[])
                .unwrap();

            // After a partition is written it has been flushed and the scratch
            // cleared: the scratch must be empty, never accumulating prior
            // partitions.
            assert_eq!(
                writer.scratch_len(),
                0,
                "scratch must be cleared after partition {i} (bounded memory)"
            );

            // Flushed bytes must strictly increase by this partition's size.
            let flushed_after = writer.flushed_position();
            assert!(
                flushed_after > flushed_before,
                "flushed position must grow after writing partition {i}"
            );
            let this_partition_size = (flushed_after - flushed_before) as usize;
            max_partition_size = max_partition_size.max(this_partition_size);
            assert!(flushed_after > prev_flushed);
            prev_flushed = flushed_after;
        }

        let total = writer.finish_streaming().unwrap();
        assert_eq!(
            total, prev_flushed,
            "total size must equal last flushed pos"
        );

        // Peak resident bytes were bounded by the largest single partition,
        // which is far smaller than the whole file for many partitions.
        assert!(
            (max_partition_size as u64) < total,
            "largest single partition ({max_partition_size}) must be smaller than the full file ({total})"
        );
    }
}