Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
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
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
/*--------------------------------------------------------------------------
 * test_cfs.c
 *      Test module for the Compressed File Store (CFS) codec and
 *      page-level compression/decompression API.
 *
 * CFS exposes no SQL surface of its own; this extension provides
 * a SQL-callable entry point so that the codec dispatch table and the
 * CfsCompressPage/CfsDecompressPage helpers can be exercised through the
 * regression-test infrastructure.
 *
 * The tests are deterministic so that the expected output is stable.
 *
 * Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group
 *
 * IDENTIFICATION
 *      src/test/modules/test_cfs/test_cfs.c
 *
 * -------------------------------------------------------------------------
 */
#include "postgres.h"
 
#include <errno.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
 
#ifdef USE_LZ4
#include <lz4.h>
#include <lz4hc.h>
#endif
 
#ifdef USE_ZSTD
#include <zstd.h>
#endif
 
#include "catalog/pg_tablespace_d.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "access/relation.h"
#include "access/htup_details.h"
#include "access/xact.h"
#include "access/xlog.h"
#include "port/pg_crc32c.h"
#include "postmaster/bgwriter.h"
#include "storage/block.h"
#include "storage/cfs/cfs.h"
#include "storage/cfs/cfs_cfp.h"
#include "storage/cfs/cfs_codec.h"
#include "storage/cfs/cfs_compact.h"
#include "storage/cfs/cfs_compress.h"
#include "storage/cfs/cfs_format.h"
#include "storage/cfs/cfs_fsck.h"
#include "storage/cfs/cfs_guc.h"
#include "storage/cfs/cfs_journal.h"
#include "storage/cfs/cfs_path.h"
#include "storage/cfs/cfs_recovery.h"
#include "storage/cfs/cfs_rel.h"
#include "storage/cfs/cfs_shmem.h"
#include "storage/cfs/cfs_smgr.h"
#include "storage/cfs/cfs_storage.h"
#include "storage/fd.h"
#include "storage/lmgr.h"
#include "storage/smgr.h"
#include "utils/builtins.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/resowner.h"
#include "utils/timestamp.h"
#include "utils/tuplestore.h"
#include "varatt.h"
 
PG_MODULE_MAGIC;
 
/* Page size used throughout the tests (matches CFS_BLCKSZ). */
#define TEST_BLCKSZ         8192
 
/*
 * Result of a single test case, accumulated in a fixed array and emitted as
 * a result set at the end of cfs_run_tests().
 */
typedef struct CfsTestResult
{
    const char *test_name;
    const char *result;         /* "ok", "skip", or "fail"      */
    char        detail[128];    /* human-readable detail        */
}           CfsTestResult;
 
#define MAX_RESULTS         64
static CfsTestResult test_results[MAX_RESULTS];
static int  test_result_count = 0;
 
/*
 * Test-side journal reset: the production API asks the caller for the
 * generation watermark it stamped.  Full test handles can compute it from
 * their map; lazy ones (map == NULL) carry no rows and use the handle's
 * current watermark.
 */
static void
test_journal_reset(CfsRelation *cfs, int elevel)
{
    uint32      max_generation = cfs->map_hdr.max_generation;
 
    if (cfs->map != NULL)
        max_generation = cfs_map_live_summary(cfs);
    cfs_journal_reset_point(cfs, max_generation, elevel);
}
 
static CfsAlgorithm
parse_algorithm_text(text *algorithm)
{
    char       *name;
    CfsAlgorithm result;
 
    name = text_to_cstring(algorithm);
    result = CfsAlgorithmFromName(name);
 
    if (!CFS_ALGORITHM_VALID(result))
    {
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("invalid CFS algorithm name: %s", name)));
    }
    pfree(name);
 
    return result;
}
 
static void
fill_page_from_payload(unsigned char *page, bytea *payload)
{
    Size        payload_size = VARSIZE_ANY_EXHDR(payload);
    char       *payload_data = VARDATA_ANY(payload);
    Size        offset;
 
    if (payload_size == 0)
    {
        MemSet(page, 0, TEST_BLCKSZ);
        return;
    }
 
    for (offset = 0; offset < TEST_BLCKSZ; offset += payload_size)
    {
        Size        chunk_size = Min(payload_size, TEST_BLCKSZ - offset);
 
        memcpy(page + offset, payload_data, chunk_size);
    }
}
 
static void
add_result(const char *name, const char *result, const char *detail)
{
    CfsTestResult *r;
 
    if (test_result_count >= MAX_RESULTS)
        elog(ERROR, "test_cfs: test result table overflow (MAX_RESULTS=%d)",
             MAX_RESULTS);
    r = &test_results[test_result_count++];
    r->test_name = name;
    r->result = result;
    if (detail != NULL)
        strlcpy(r->detail, detail, sizeof(r->detail));
    else
        r->detail[0] = '\0';
}
 
/* ----------------------------------------------------------------
 * Deterministic test-data fillers
 * ---------------------------------------------------------------- */
 
/* Monotonic pattern; highly compressible by every algorithm. */
static void
fill_sequential(unsigned char *buf, size_t len)
{
    size_t      i;
 
    for (i = 0; i < len; i++)
        buf[i] = (unsigned char) (i & 0xFF);
}
 
/* Constant pattern; compresses to almost nothing. */
static void
fill_constant(unsigned char *buf, size_t len, unsigned char val)
{
    memset(buf, val, len);
}
 
/*
 * Deterministic pseudo-random pattern (LCG). Resembles incompressible data
 * well enough to defeat LZ4/Zstd within an 8 kB page.
 */
static void
fill_pseudo_random(unsigned char *buf, size_t len)
{
    size_t      i;
    uint32      state = 0x12345678;
 
    for (i = 0; i < len; i++)
    {
        state = state * 1103515245u + 12345u;
        buf[i] = (unsigned char) ((state >> 16) & 0xFF);
    }
}
 
/* ----------------------------------------------------------------
 * Codec-level round-trip helper
 *
 * Compresses src, decompresses it back, and checks the data matches.
 * Returns true on success.
 * ---------------------------------------------------------------- */
static bool
codec_roundtrip(CfsAlgorithm algo, const unsigned char *src, size_t src_size,
                int level, char *detail, size_t detail_len)
{
    const CfsCodec *codec = CfsCodecLookup(algo);
    CfsCodecState *state;
    CfsCodecResult rc;
    void       *cbuf;
    void       *dbuf;
    size_t      bound;
    size_t      csize = 0;
    size_t      dsize = 0;
    bool        ok = false;
 
    if (codec == NULL || !codec->available())
    {
        snprintf(detail, detail_len, "codec %d not available", (int) algo);
        return false;
    }
 
    bound = codec->compress_bound(src_size);
    cbuf = palloc(bound);
    dbuf = palloc(src_size);
 
    state = CfsCodecStateCreate(algo);
    if (state == NULL)
    {
        snprintf(detail, detail_len, "could not create codec state");
        goto done;
    }
 
    rc = codec->compress(state, src, src_size, cbuf, bound, level, &csize);
 
    /*
     * CFS_CODEC_OK means the data was compressed (or, for RAW, copied
     * verbatim); CFS_CODEC_NOOP is still accepted for any codec that may
     * report it.  In both cases the output buffer holds valid data and the
     * round-trip can proceed.
     */
    if (rc != CFS_CODEC_OK && rc != CFS_CODEC_NOOP)
    {
        snprintf(detail, detail_len, "compress rc=%d", (int) rc);
        goto done;
    }
 
    rc = codec->decompress(state, cbuf, csize, dbuf, src_size, src_size, &dsize);
    if (rc != CFS_CODEC_OK)
    {
        snprintf(detail, detail_len, "decompress rc=%d", (int) rc);
        goto done;
    }
 
    if (dsize != src_size || memcmp(src, dbuf, src_size) != 0)
    {
        snprintf(detail, detail_len, "round-trip mismatch");
        goto done;
    }
 
    snprintf(detail, detail_len, "compressed %zu -> %zu bytes", src_size, csize);
    ok = true;
 
done:
    if (state != NULL)
        CfsCodecStateDestroy(algo);
    pfree(cbuf);
    pfree(dbuf);
    return ok;
}
 
/* ----------------------------------------------------------------
 * Individual test cases
 * ---------------------------------------------------------------- */
 
static void
test_raw_codec(void)
{
    unsigned char page[TEST_BLCKSZ];
    char        detail[128];
 
    fill_sequential(page, sizeof(page));
    if (codec_roundtrip(CFS_ALGORITHM_RAW, page, sizeof(page), 0,
                        detail, sizeof(detail)))
        add_result("raw_codec_roundtrip", "ok", detail);
    else
        add_result("raw_codec_roundtrip", "fail", detail);
}
 
static void
test_lz4_codec(void)
{
    unsigned char page[TEST_BLCKSZ];
    char        detail[128];
 
    if (!CfsCodecAvailable(CFS_ALGORITHM_LZ4))
    {
        add_result("lz4_codec_roundtrip", "skip", "LZ4 not compiled in");
        return;
    }
 
    fill_constant(page, sizeof(page), 0x41);
    if (codec_roundtrip(CFS_ALGORITHM_LZ4, page, sizeof(page), 1,
                        detail, sizeof(detail)))
        add_result("lz4_codec_roundtrip", "ok", detail);
    else
        add_result("lz4_codec_roundtrip", "fail", detail);
}
 
static void
test_zstd_codec(void)
{
    unsigned char page[TEST_BLCKSZ];
    char        detail[128];
 
    if (!CfsCodecAvailable(CFS_ALGORITHM_ZSTD))
    {
        add_result("zstd_codec_roundtrip", "skip", "Zstd not compiled in");
        return;
    }
 
    fill_constant(page, sizeof(page), 0x00);
    if (codec_roundtrip(CFS_ALGORITHM_ZSTD, page, sizeof(page), 3,
                        detail, sizeof(detail)))
        add_result("zstd_codec_roundtrip", "ok", detail);
    else
        add_result("zstd_codec_roundtrip", "fail", detail);
}
 
/* Direct codec tests: no RAW fallback can hide a codec failure here. */
static const char *const pglz_extended_names[6] = {
    "pglz_sizes", "pglz_incompressible", "pglz_corrupt_stream",
    "pglz_truncated_stream", "pglz_buffer_bounds", "pglz_state_reuse"
};
static const char *const zlib_extended_names[6] = {
    "zlib_sizes", "zlib_incompressible", "zlib_corrupt_stream",
    "zlib_truncated_stream", "zlib_buffer_bounds", "zlib_state_reuse"
};
 
static void
test_extended_codec(CfsAlgorithm algo, const char *const names[6])
{
    static const size_t sizes[] = {64, 256, 1024, 4096, TEST_BLCKSZ};
    const CfsCodec *codec = CfsCodecLookup(algo);
    CfsCodecState *state = NULL;
    unsigned char *src = NULL, *compressed = NULL, *decoded = NULL;
    unsigned char *scratch = NULL;
    size_t bound = 0, csize = 0, dsize = 0;
    CfsCodecResult rc;
    CfsCompressOptions opts = CFS_COMPRESS_OPTIONS_INIT;
    CfsCompressResult cres;
    CfsDecompressResult dres;
    bool ok, base_ok;
    int i;
 
    /* names point to static storage: add_result retains these pointers. */
    if (codec == NULL || !codec->available())
    {
        for (i = 0; i < 6; i++)
            add_result(names[i], "skip", "codec unavailable");
        return;
    }
    state = CfsCodecStateCreate(algo);
    bound = codec->compress_bound(TEST_BLCKSZ);
    if (state == NULL || bound == 0)
    {
        for (i = 0; i < 6; i++)
            add_result(names[i], "fail", "state/bound initialization failed");
        goto done;
    }
    src = palloc(TEST_BLCKSZ);
    compressed = palloc(bound + 16);
    decoded = palloc(TEST_BLCKSZ + 16);
    scratch = palloc(CfsCompressScratchSize(TEST_BLCKSZ));
 
    ok = true;
    for (i = 0; i < lengthof(sizes); i++)
    {
        fill_constant(src, sizes[i], (unsigned char) (0x41 + i));
        csize = dsize = 0;
        rc = codec->compress(state, src, sizes[i], compressed, bound, 1, &csize);
        if (rc != CFS_CODEC_OK || csize == 0 || csize > bound)
        {
            ok = false;
            break;
        }
        rc = codec->decompress(state, compressed, csize, decoded,
                               sizes[i], sizes[i], &dsize);
        if (rc != CFS_CODEC_OK || dsize != sizes[i] ||
            memcmp(src, decoded, sizes[i]) != 0)
        {
            ok = false;
            break;
        }
    }
    add_result(names[0], ok ? "ok" : "fail",
               ok ? "64/256/1024/4096/8192 exact" : "size matrix mismatch");
 
    /* Direct OVERFLOW on incompressible data is valid; page RAW fallback
     * must still be byte-exact. */
    fill_pseudo_random(src, TEST_BLCKSZ);
    csize = 0;
    rc = codec->compress(state, src, TEST_BLCKSZ, compressed, bound, 1, &csize);
    ok = rc == CFS_CODEC_OVERFLOW;
    if (rc == CFS_CODEC_OK)
    {
        dsize = 0;
        ok = csize > 0 && csize <= bound &&
            codec->decompress(state, compressed, csize, decoded,
                              TEST_BLCKSZ, TEST_BLCKSZ, &dsize) == CFS_CODEC_OK &&
            dsize == TEST_BLCKSZ &&
            memcmp(src, decoded, TEST_BLCKSZ) == 0;
    }
    opts.algorithm = algo;
    opts.level = 1;
    opts.min_gain_bytes = 1;
    opts.explicit_algorithm = true;
    opts.allow_raw_fallback = true;
    CfsCompressPage(src, TEST_BLCKSZ, &opts, scratch,
                    CfsCompressScratchSize(TEST_BLCKSZ), &cres);
    ok = ok && cres.is_raw && cres.algorithm_used == CFS_ALGORITHM_RAW &&
        CfsDecompressPage(cres.result_data, cres.total_size,
                          decoded, TEST_BLCKSZ, &dres) == CFS_DECOMPRESS_OK &&
        dres.decompressed_size == TEST_BLCKSZ &&
        memcmp(src, decoded, TEST_BLCKSZ) == 0;
    add_result(names[1], ok ? "ok" : "fail",
               ok ? "incompressible/RAW fallback exact" :
                    "incompressible/RAW fallback mismatch");
 
    fill_constant(src, TEST_BLCKSZ, 0x5A);
    csize = 0;
    rc = codec->compress(state, src, TEST_BLCKSZ, compressed, bound, 1, &csize);
    base_ok = rc == CFS_CODEC_OK && csize > 2 && csize <= bound;
 
    ok = false;
    if (base_ok)
    {
        unsigned char old = compressed[0];
        compressed[0] = 0xFF;
        dsize = 0;
        rc = codec->decompress(state, compressed, csize, decoded,
                               TEST_BLCKSZ, TEST_BLCKSZ, &dsize);
        /* The codec alone has no CRC obligation; a changed byte result
         * is detectable by the outer page's CRC. */
        ok = rc != CFS_CODEC_OK || dsize != TEST_BLCKSZ ||
            memcmp(src, decoded, TEST_BLCKSZ) != 0;
        compressed[0] = old;
    }
    add_result(names[2], ok ? "ok" : "fail",
               ok ? "damaged stream rejected/mismatched" :
                    "damaged stream undetected");
 
    ok = base_ok;
    if (ok)
    {
        dsize = 0;
        rc = codec->decompress(state, compressed, csize - 1, decoded,
                               TEST_BLCKSZ, TEST_BLCKSZ, &dsize);
        ok = rc != CFS_CODEC_OK;
    }
    add_result(names[3], ok ? "ok" : "fail",
               ok ? "truncated stream rejected" : "truncation accepted");
 
    ok = base_ok;
    if (ok)
    {
        memset(decoded + TEST_BLCKSZ - 1, 0xA5, 17);
        dsize = 0;
        rc = codec->decompress(state, compressed, csize, decoded,
                               TEST_BLCKSZ - 1, TEST_BLCKSZ, &dsize);
        ok = rc != CFS_CODEC_OK;
        for (i = TEST_BLCKSZ - 1; i < TEST_BLCKSZ + 16; i++)
            ok = ok && decoded[i] == 0xA5;
        memset(compressed, 0xCC, 16);
        rc = codec->compress(state, src, TEST_BLCKSZ, compressed, 0, 1, &csize);
        ok = ok && rc != CFS_CODEC_OK;
        for (i = 0; i < 16; i++)
            ok = ok && compressed[i] == 0xCC;
    }
    add_result(names[4], ok ? "ok" : "fail",
               ok ? "short buffers rejected; canaries intact" :
                    "short buffer/guard failure");
 
    /* Reuse a single codec state after the negative cases. */
    ok = true;
    for (i = 0; i < 32; i++)
    {
        int j;
 
        if (i & 1)
            fill_sequential(src, TEST_BLCKSZ);
        else
            fill_constant(src, TEST_BLCKSZ, (unsigned char) i);
        csize = dsize = 0;
        memset(compressed + bound, 0xA5, 16);
        memset(decoded + TEST_BLCKSZ, 0xA5, 16);
        rc = codec->compress(state, src, TEST_BLCKSZ, compressed, bound,
                             1, &csize);
        if (rc != CFS_CODEC_OK || csize == 0 || csize > bound ||
            codec->decompress(state, compressed, csize, decoded,
                              TEST_BLCKSZ, TEST_BLCKSZ, &dsize) != CFS_CODEC_OK ||
            dsize != TEST_BLCKSZ ||
            memcmp(src, decoded, TEST_BLCKSZ) != 0)
        {
            ok = false;
            break;
        }
        for (j = 0; j < 16; j++)
            if (compressed[bound + j] != 0xA5 ||
                decoded[TEST_BLCKSZ + j] != 0xA5)
                ok = false;
        if (!ok)
            break;
    }
    add_result(names[5], ok ? "ok" : "fail",
               ok ? "32 reused cycles; canaries intact" :
                    "state reuse/guard mismatch");
 
done:
    if (state != NULL)
        CfsCodecStateDestroy(algo);
    if (scratch != NULL)
        pfree(scratch);
    if (decoded != NULL)
        pfree(decoded);
    if (compressed != NULL)
        pfree(compressed);
    if (src != NULL)
        pfree(src);
}
 
/*
 * LZ4 level range: every user level 1..12 must round-trip.  Levels
 * 1..2 use the fast encoder (two accelerations), levels 3..12 use LZ4 HC.
 */
static void
test_lz4_level_roundtrip(void)
{
    char        detail[128];
    int         level;
 
    if (!CfsCodecAvailable(CFS_ALGORITHM_LZ4))
    {
        add_result("lz4_level_roundtrip", "skip", "LZ4 not compiled in");
        return;
    }
 
    for (level = 1; level <= CFS_LZ4_LEVEL_MAX; level++)
    {
        unsigned char page[TEST_BLCKSZ];
 
        fill_sequential(page, sizeof(page));
        if (!codec_roundtrip(CFS_ALGORITHM_LZ4, page, sizeof(page), level,
                             detail, sizeof(detail)))
        {
            snprintf(detail, sizeof(detail), "round-trip failed at level %d",
                     level);
            add_result("lz4_level_roundtrip", "fail", detail);
            return;
        }
    }
 
    add_result("lz4_level_roundtrip", "ok", "round-trip levels 1..12");
}
 
/*
 * Per-algorithm level ceiling (NB1): CfsCodecMaxLevel must report each
 * codec's native maximum — LZ4 caps at 12 while Zstd reaches the global 22.
 * For Zstd the ceiling is the runtime library maximum clamped to the format
 * bound (ZSTD_maxCLevel() may be lower than CFS_ZSTD_LEVEL_MAX).
 */
static void
test_codec_max_level(void)
{
    bool        ok = true;
 
    ok &= (CfsCodecMaxLevel(CFS_ALGORITHM_LZ4) == CFS_LZ4_LEVEL_MAX);
#ifdef USE_ZSTD
    ok &= (CfsCodecMaxLevel(CFS_ALGORITHM_ZSTD) ==
           Min(CFS_ZSTD_LEVEL_MAX, ZSTD_maxCLevel()));
#else
    ok &= (CfsCodecMaxLevel(CFS_ALGORITHM_ZSTD) == CFS_ZSTD_LEVEL_MAX);
#endif
    ok &= (CfsCodecMaxLevel(CFS_ALGORITHM_RAW) == CFS_COMPRESS_LEVEL_MAX);
 
    if (ok)
        add_result("codec_max_level", "ok", "per-algorithm level ceiling");
    else
        add_result("codec_max_level", "fail", "unexpected level ceiling");
}
 
/*
 * Fallback write policy (NB1): cfs_default_write_opts picks the first
 * available codec and leaves every tunable field unset.  The fallback is
 * not an explicit user choice, so level and minimum gain must keep the 0
 * sentinel with their set-flags cleared: consumers re-resolve them from
 * their own GUCs at write time, and a published fallback (shared memory /
 * WAL) must carry nothing computed from the writer's session GUC.
 */
static void
test_default_write_opts_level(void)
{
    CfsEffectiveOptions opts;
    char        detail[128];
    bool        ok = true;
 
    cfs_default_write_opts(&opts);
 
    ok &= (opts.level == 0 && opts.min_gain_bytes == 0);
    ok &= !opts.level_set && !opts.min_gain_bytes_set;
    ok &= (opts.algorithm == CFS_ALGORITHM_RAW ||
           CfsCodecAvailable(opts.algorithm));
 
    if (ok)
        add_result("default_write_opts_level", "ok",
                   "tunables unset, set-flags cleared");
    else
    {
        snprintf(detail, sizeof(detail),
                 "level %d, min_gain %d, flags %d/%d, algo %d",
                 opts.level, opts.min_gain_bytes,
                 (int) opts.level_set, (int) opts.min_gain_bytes_set,
                 (int) opts.algorithm);
        add_result("default_write_opts_level", "fail", detail);
    }
}
 
/*
 * Per-algorithm default level lookup: cfs_default_level_for must return
 * each algorithm's own GUC, read fresh at call time — the runtime-resolve
 * contract (nothing is cached between calls, a GUC change affects the very
 * next call).
 */
static void
test_default_level_for(void)
{
    int         saved_lz4 = cfs_default_lz4_level;
    int         saved_zstd = cfs_default_zstd_level;
    bool        ok = true;
 
    cfs_default_lz4_level = 7;
    cfs_default_zstd_level = 17;
 
    ok &= (cfs_default_level_for(CFS_ALGORITHM_LZ4) == 7);
    ok &= (cfs_default_level_for(CFS_ALGORITHM_ZSTD) == 17);
 
    /* Re-read after a change: no caching between calls. */
    cfs_default_lz4_level = 2;
    ok &= (cfs_default_level_for(CFS_ALGORITHM_LZ4) == 2);
 
    cfs_default_lz4_level = saved_lz4;
    cfs_default_zstd_level = saved_zstd;
 
    if (ok)
        add_result("default_level_for", "ok", "per-algorithm GUC lookup");
    else
        add_result("default_level_for", "fail", "wrong per-algorithm level");
}
 
/*
 * Explicit-only policy with set-flags survives a publish/read roundtrip
 * through the shared-memory slot, and a flag-only change (unset level
 * becoming explicit) is a policy change: the generation must be bumped.
 */
static void
test_policy_flags_roundtrip(void)
{
    RelFileLocatorBackend rlb;
    CfsEffectiveOptions in;
    CfsEffectiveOptions out;
    uint64      gen1;
    uint64      gen2;
    bool        ok = true;
 
    rlb.locator.spcOid = InvalidOid;
    rlb.locator.dbOid = InvalidOid;
    rlb.locator.relNumber = 99998;
    rlb.backend = INVALID_PROC_NUMBER;
 
    memset(&in, 0, sizeof(in));
    in.is_cfs = true;
    in.algorithm = CFS_ALGORITHM_ZSTD;
    in.level_set = false;
    in.min_gain_bytes_set = false;
 
    gen1 = cfs_publish_options(rlb, MAIN_FORKNUM, &in);
    ok &= cfs_get_options(rlb, MAIN_FORKNUM, &out);
    ok &= (out.algorithm == CFS_ALGORITHM_ZSTD);
    ok &= (!out.level_set && out.level == 0);
    ok &= (!out.min_gain_bytes_set && out.min_gain_bytes == 0);
 
    /* An unset level becoming explicit is a policy change. */
    in.level = 5;
    in.level_set = true;
    gen2 = cfs_publish_options(rlb, MAIN_FORKNUM, &in);
    ok &= (gen2 != gen1);
    ok &= cfs_get_options(rlb, MAIN_FORKNUM, &out);
    ok &= (out.level_set && out.level == 5);
 
    cfs_forget_options(rlb, MAIN_FORKNUM);
 
    if (ok)
        add_result("policy_flags_roundtrip", "ok",
                   "set-flags roundtrip and generation bump");
    else
        add_result("policy_flags_roundtrip", "fail",
                   "set-flags lost or generation not bumped");
}
 
/*
 * Explicit RAW through the page functions: algorithm = RAW must
 * round-trip via the codec table, producing a RAW record (is_raw set).
 */
static void
test_raw_page_roundtrip(void)
{
    unsigned char page[TEST_BLCKSZ];
    unsigned char decompressed[TEST_BLCKSZ];
    unsigned char *scratch;
    size_t      scratch_sz;
    CfsCompressOptions opts;
    CfsCompressResult cres;
    CfsDecompressResult dres;
    CfsDecompressStatus dstatus;
    char        detail[128];
 
    scratch_sz = CfsCompressScratchSize(sizeof(page));
    scratch = palloc(scratch_sz);
 
    fill_pseudo_random(page, sizeof(page));
    memset(&opts, 0, sizeof(opts));
    opts.algorithm = CFS_ALGORITHM_RAW;
    opts.level = CFS_COMPRESS_LEVEL_DEFAULT;
    opts.min_gain_bytes = 1;
    opts.explicit_algorithm = true;
    opts.allow_raw_fallback = false;
 
    CfsCompressPage(page, sizeof(page), &opts,
                    scratch, scratch_sz, &cres);
 
    if (!cres.is_raw || cres.algorithm_used != CFS_ALGORITHM_RAW)
    {
        add_result("raw_page_roundtrip", "fail",
                   "explicit RAW not stored as RAW");
        pfree(scratch);
        return;
    }
 
    dstatus = CfsDecompressPage(cres.result_data, cres.total_size,
                                decompressed, sizeof(decompressed), &dres);
 
    if (dstatus != CFS_DECOMPRESS_OK ||
        dres.decompressed_size != sizeof(page) ||
        memcmp(page, decompressed, sizeof(page)) != 0)
    {
        snprintf(detail, sizeof(detail), "RAW decompress status=%d",
                 (int) dstatus);
        add_result("raw_page_roundtrip", "fail", detail);
        pfree(scratch);
        return;
    }
 
    add_result("raw_page_roundtrip", "ok", "explicit RAW round-trip ok");
    pfree(scratch);
}
 
static void
test_compress_page_lz4(void)
{
    unsigned char page[TEST_BLCKSZ];
    unsigned char decompressed[TEST_BLCKSZ];
    unsigned char *scratch;
    size_t      scratch_sz;
    CfsCompressOptions opts;
    CfsCompressResult cres;
    CfsDecompressStatus dstatus;
    char        detail[128];
 
    if (!CfsCodecAvailable(CFS_ALGORITHM_LZ4))
    {
        add_result("compress_page_lz4", "skip", "LZ4 not compiled in");
        return;
    }
 
    scratch_sz = CfsCompressScratchSize(sizeof(page));
    scratch = palloc(scratch_sz);
 
    /* Highly compressible page. */
    fill_constant(page, sizeof(page), 0xBB);
    memset(&opts, 0, sizeof(opts));
    opts.algorithm = CFS_ALGORITHM_LZ4;
    opts.level = CFS_COMPRESS_LEVEL_DEFAULT;
    opts.min_gain_bytes = 1;
 
    CfsCompressPage(page, sizeof(page), &opts,
                    scratch, scratch_sz, &cres);
 
    if (cres.is_raw ||
        cres.algorithm_used != CFS_ALGORITHM_LZ4 ||
        cres.compressed_size >= sizeof(page))
    {
        snprintf(detail, sizeof(detail),
                 "expected LZ4, got algo=%d raw=%d",
                 (int) cres.algorithm_used, cres.is_raw);
        add_result("compress_page_lz4", "fail", detail);
        pfree(scratch);
        return;
    }
 
    dstatus = CfsDecompressPage(cres.result_data, cres.total_size,
                                decompressed, sizeof(decompressed), NULL);
    if (dstatus != CFS_DECOMPRESS_OK)
    {
        snprintf(detail, sizeof(detail), "decompress status=%d", (int) dstatus);
        add_result("compress_page_lz4", "fail", detail);
        pfree(scratch);
        return;
    }
 
    if (memcmp(page, decompressed, sizeof(page)) != 0)
    {
        add_result("compress_page_lz4", "fail", "decompressed page mismatch");
        pfree(scratch);
        return;
    }
 
    snprintf(detail, sizeof(detail),
             "payload %u bytes (raw=%d)",
             cres.compressed_size, cres.is_raw);
    add_result("compress_page_lz4", "ok", detail);
    pfree(scratch);
}
 
static void
test_incompressible_raw_fallback(void)
{
    unsigned char page[TEST_BLCKSZ];
    unsigned char decompressed[TEST_BLCKSZ];
    unsigned char *scratch;
    size_t      scratch_sz;
    CfsCompressOptions opts;
    CfsCompressResult cres;
    CfsDecompressStatus dstatus;
    char        detail[128];
 
    scratch_sz = CfsCompressScratchSize(sizeof(page));
    scratch = palloc(scratch_sz);
 
    /* Incompressible data + a high min-gain requirement -> must be RAW. */
    fill_pseudo_random(page, sizeof(page));
    memset(&opts, 0, sizeof(opts));
    opts.algorithm = CfsCodecAvailable(CFS_ALGORITHM_LZ4) ?
        CFS_ALGORITHM_LZ4 : CFS_ALGORITHM_RAW;
    opts.level = CFS_COMPRESS_LEVEL_DEFAULT;
    opts.min_gain_bytes = CFS_MIN_GAIN_BYTES_DEFAULT;
 
    CfsCompressPage(page, sizeof(page), &opts,
                    scratch, scratch_sz, &cres);
 
    if (!cres.is_raw || cres.algorithm_used != CFS_ALGORITHM_RAW)
    {
        snprintf(detail, sizeof(detail),
                 "expected RAW fallback, got algo=%d raw=%d",
                 (int) cres.algorithm_used, cres.is_raw);
        add_result("incompressible_raw_fallback", "fail", detail);
        pfree(scratch);
        return;
    }
 
    dstatus = CfsDecompressPage(cres.result_data, cres.total_size,
                                decompressed, sizeof(decompressed), NULL);
    if (dstatus != CFS_DECOMPRESS_OK || memcmp(page, decompressed, sizeof(page)) != 0)
    {
        snprintf(detail, sizeof(detail), "RAW decompress status=%d", (int) dstatus);
        add_result("incompressible_raw_fallback", "fail", detail);
        pfree(scratch);
        return;
    }
 
    snprintf(detail, sizeof(detail), "stored as RAW (%u bytes)", cres.compressed_size);
    add_result("incompressible_raw_fallback", "ok", detail);
    pfree(scratch);
}
 
static void
test_crc_corruption_detection(void)
{
    unsigned char page[TEST_BLCKSZ];
    unsigned char decompressed[TEST_BLCKSZ];
    unsigned char *scratch;
    size_t      scratch_sz;
    CfsCompressOptions opts;
    CfsCompressResult cres;
    CfsDecompressStatus dstatus;
    CfsCompressedBlockHeader *hdr;
    uint32      saved_crc;
    char        detail[128];
 
    scratch_sz = CfsCompressScratchSize(sizeof(page));
    scratch = palloc(scratch_sz);
 
    fill_constant(page, sizeof(page), 0x5A);
    memset(&opts, 0, sizeof(opts));
    opts.algorithm = CFS_ALGORITHM_RAW;
    opts.level = CFS_COMPRESS_LEVEL_DEFAULT;
    opts.min_gain_bytes = 1;
 
    CfsCompressPage(page, sizeof(page), &opts,
                    scratch, scratch_sz, &cres);
 
    /* Corrupt the header CRC and expect BAD_HDR on decompression. */
    hdr = (CfsCompressedBlockHeader *) cres.result_data;
    saved_crc = hdr->hdr_crc;
    hdr->hdr_crc = 0xDEADBEEFu;
 
    dstatus = CfsDecompressPage(cres.result_data, cres.total_size,
                                decompressed, sizeof(decompressed), NULL);
 
    hdr->hdr_crc = saved_crc;
 
    if (dstatus == CFS_DECOMPRESS_BAD_HDR)
    {
        snprintf(detail, sizeof(detail), "detected header CRC mismatch");
        add_result("crc_corruption_detection", "ok", detail);
    }
    else
    {
        snprintf(detail, sizeof(detail), "expected BAD_HDR, got %d", (int) dstatus);
        add_result("crc_corruption_detection", "fail", detail);
    }
    pfree(scratch);
}
 
/*
 * original_size contract: a header whose original_size differs from
 * CFS_BLCKSZ must be rejected even when its hdr_crc is recomputed to match.
 * Otherwise a CRC-consistent sub-8 kB header would decompress only part of
 * the page and leave the tail of out_page holding stale bytes.
 */
static void
test_decompress_original_size_rejected(void)
{
    unsigned char page[TEST_BLCKSZ];
    unsigned char decompressed[TEST_BLCKSZ];
    unsigned char *scratch;
    size_t      scratch_sz;
    CfsCompressOptions opts;
    CfsCompressResult cres;
    CfsDecompressStatus dstatus;
    CfsCompressedBlockHeader *hdr;
    uint32      saved_original_size;
    char        detail[128];
 
    scratch_sz = CfsCompressScratchSize(sizeof(page));
    scratch = palloc(scratch_sz);
 
    fill_constant(page, sizeof(page), 0x6C);
    memset(&opts, 0, sizeof(opts));
    opts.algorithm = CFS_ALGORITHM_RAW;
    opts.level = CFS_COMPRESS_LEVEL_DEFAULT;
    opts.min_gain_bytes = 1;
 
    CfsCompressPage(page, sizeof(page), &opts,
                    scratch, scratch_sz, &cres);
 
    hdr = (CfsCompressedBlockHeader *) cres.result_data;
    saved_original_size = hdr->original_size;
    hdr->original_size = CFS_BLCKSZ - 1;
    hdr->hdr_crc = CfsCrc32cHeader(hdr);
 
    dstatus = CfsDecompressPage(cres.result_data, cres.total_size,
                                decompressed, sizeof(decompressed), NULL);
 
    hdr->original_size = saved_original_size;
 
    if (dstatus == CFS_DECOMPRESS_BAD_HDR)
    {
        snprintf(detail, sizeof(detail), "sub-8kB original_size rejected");
        add_result("decompress_original_size_rejected", "ok", detail);
    }
    else
    {
        snprintf(detail, sizeof(detail), "expected BAD_HDR, got %d", (int) dstatus);
        add_result("decompress_original_size_rejected", "fail", detail);
    }
    pfree(scratch);
}
 
/*
 * Unavailable codec on the read path: a block compressed with a
 * codec this build lacks must surface as a status (CFS_DECOMPRESS_ERROR),
 * not as a hard ERROR, so the caller's corruption policy can apply.  We
 * simulate a codec-less build via the cfs_debug_disable_codecs fault
 * injection instead of actually rebuilding.
 */
static void
test_decompress_codec_unavailable(void)
{
    unsigned char page[TEST_BLCKSZ];
    unsigned char decompressed[TEST_BLCKSZ];
    unsigned char *scratch;
    size_t      scratch_sz;
    CfsCompressOptions opts;
    CfsCompressResult cres;
    CfsDecompressStatus dstatus;
    char        detail[128];
 
    if (!CfsCodecAvailable(CFS_ALGORITHM_LZ4))
    {
        add_result("decompress_codec_unavailable", "skip",
                   "LZ4 not compiled in");
        return;
    }
 
    scratch_sz = CfsCompressScratchSize(sizeof(page));
    scratch = palloc(scratch_sz);
 
    /* Highly compressible page -> a genuinely LZ4-compressed record. */
    fill_constant(page, sizeof(page), 0x42);
    memset(&opts, 0, sizeof(opts));
    opts.algorithm = CFS_ALGORITHM_LZ4;
    opts.level = CFS_COMPRESS_LEVEL_DEFAULT;
    opts.min_gain_bytes = 1;
    opts.explicit_algorithm = true;
    opts.allow_raw_fallback = false;
 
    CfsCompressPage(page, sizeof(page), &opts,
                    scratch, scratch_sz, &cres);
 
    if (cres.is_raw || cres.algorithm_used != CFS_ALGORITHM_LZ4)
    {
        add_result("decompress_codec_unavailable", "fail",
                   "page unexpectedly stored as RAW");
        pfree(scratch);
        return;
    }
 
    /* Pretend LZ4 was not compiled in, then try to read it back. */
    cfs_debug_disable_codecs |= (1 << CFS_ALGORITHM_LZ4);
    dstatus = CfsDecompressPage(cres.result_data, cres.total_size,
                                decompressed, sizeof(decompressed), NULL);
    cfs_debug_disable_codecs &= ~(1 << CFS_ALGORITHM_LZ4);
 
    if (dstatus == CFS_DECOMPRESS_ERROR)
    {
        snprintf(detail, sizeof(detail), "unavailable codec returned status");
        add_result("decompress_codec_unavailable", "ok", detail);
    }
    else
    {
        snprintf(detail, sizeof(detail), "expected DECOMPRESS_ERROR, got %d",
                 (int) dstatus);
        add_result("decompress_codec_unavailable", "fail", detail);
    }
    pfree(scratch);
}
 
/*
 * test_record_padding_zeroed
 *      Reproduce the .cfp padding leak: the per-relation compress scratch is
 *      allocated with palloc() (not palloc0) and reused across writes, so any
 *      record byte that is neither explicitly assigned nor covered by a CRC
 *      would carry stale backend memory unless CfsCompressPage() zeroes it
 *      before the record is appended to .cfp.  Two regions are checked:
 *
 *        (a) CfsCompressedBlockHeader trailing struct padding -- the header
 *            is 40 bytes but hdr_crc ends at offset 36, so bytes [36,40)
 *            are written to disk, never assigned, and not covered by any CRC.
 *
 *        (b) the 0..7 alignment bytes after the compressed payload, also
 *            outside the CRC-covered payload range.
 *
 * We mirror the leak by garbage-filling the scratch before each compress and
 * then requiring (1) both padding regions to be all-zero, and (2) two
 * independent compressions -- into scratch buffers filled with *different*
 * garbage -- to produce byte-identical full records, which rules out any
 * non-determinism across the whole record, not just the payload padding.  A
 * RAW record is exactly page-sized and therefore has zero payload padding, so
 * it cannot exercise (b); a real compression codec is required.  (a) still
 * applies to RAW records, but we only assert it here when a codec produced a
 * genuinely compressed record, matching the rest of the test's scope.
 */
static void
test_record_padding_zeroed(void)
{
    unsigned char page[TEST_BLCKSZ];
    unsigned char *scratch1;
    unsigned char *scratch2;
    size_t      scratch_sz;
    CfsCompressOptions opts;
    CfsCompressResult cres1;
    CfsCompressResult cres2;
    CfsAlgorithm algo;
    char        detail[128];
    size_t      pad_off;
    size_t      pad_len;
    size_t      i;
    bool        padding_clean = true;
 
    if (CfsCodecAvailable(CFS_ALGORITHM_LZ4))
        algo = CFS_ALGORITHM_LZ4;
    else if (CfsCodecAvailable(CFS_ALGORITHM_ZSTD))
        algo = CFS_ALGORITHM_ZSTD;
    else
    {
        add_result("record_padding_zeroed", "skip",
                   "no compression codec available");
        return;
    }
 
    scratch_sz = CfsCompressScratchSize(sizeof(page));
 
    /* Highly compressible page -> small, non-aligned compressed payload. */
    fill_constant(page, sizeof(page), 0xBB);
    memset(&opts, 0, sizeof(opts));
    opts.algorithm = algo;
    opts.level = CFS_COMPRESS_LEVEL_DEFAULT;
    opts.min_gain_bytes = 1;
 
    /*
     * Garbage-fill both scratch buffers with *different* patterns, mimicking
     * a reused buffer that still holds a previous, unrelated record.  Using
     * distinct fill bytes (0xA5 vs 0x5A) makes the final full-record memcmp
     * catch any byte that was left untouched -- in the payload padding, in
     * the header trailing padding, or anywhere else -- rather than passing
     * just because both buffers happened to hold identical garbage.
     */
    scratch1 = palloc(scratch_sz);
    scratch2 = palloc(scratch_sz);
    memset(scratch1, 0xA5, scratch_sz);
    memset(scratch2, 0x5A, scratch_sz);
 
    CfsCompressPage(page, sizeof(page), &opts,
                    scratch1, scratch_sz, &cres1);
 
    /* Only a genuinely compressed record carries padding worth checking. */
    if (cres1.is_raw)
    {
        add_result("record_padding_zeroed", "skip",
                   "page stored as RAW (no padding)");
        pfree(scratch1);
        pfree(scratch2);
        return;
    }
 
    /*
     * Header trailing struct padding: CfsCompressedBlockHeader is 40 bytes
     * but hdr_crc (the last field) ends at offset 36, so bytes [36,40) are
     * written to disk yet neither assigned by CfsFillBlockHeader() nor
     * covered by any CRC.  Require them to be zero.  Computed via offsetof so
     * the range tracks the layout automatically.
     */
    {
        size_t      hdr_pad_off = offsetof(CfsCompressedBlockHeader, hdr_crc) +
            sizeof(uint32);
        size_t      hdr_pad_len = sizeof(CfsCompressedBlockHeader) - hdr_pad_off;
 
        for (i = 0; i < hdr_pad_len; i++)
        {
            if (scratch1[hdr_pad_off + i] != 0)
            {
                snprintf(detail, sizeof(detail),
                         "header trailing padding not zeroed "
                         "(off %zu, %zu bytes leaked)",
                         hdr_pad_off, hdr_pad_len);
                add_result("record_padding_zeroed", "fail", detail);
                pfree(scratch1);
                pfree(scratch2);
                return;
            }
        }
    }
 
    /* Payload padding spans [payload end, aligned record end). */
    pad_off = CFS_BLOCK_HEADER_SIZE + cres1.compressed_size;
    pad_len = cres1.total_size - pad_off;
 
    if (pad_len == 0)
    {
        snprintf(detail, sizeof(detail),
                 "payload %u already aligned (no padding)",
                 cres1.compressed_size);
        add_result("record_padding_zeroed", "skip", detail);
        pfree(scratch1);
        pfree(scratch2);
        return;
    }
 
    for (i = 0; i < pad_len; i++)
    {
        if (scratch1[pad_off + i] != 0)
        {
            padding_clean = false;
            break;
        }
    }
 
    if (!padding_clean)
    {
        snprintf(detail, sizeof(detail),
                 "padding not zeroed (payload %u, pad %zu bytes leaked)",
                 cres1.compressed_size, pad_len);
        add_result("record_padding_zeroed", "fail", detail);
        pfree(scratch1);
        pfree(scratch2);
        return;
    }
 
    /*
     * Determinism: compress the same page into the second scratch (filled
     * with a *different* garbage pattern) and require the two full records --
     * header, payload and all padding -- to be byte-identical.  Distinct fill
     * bytes make any left-over untouched byte fail this memcmp.
     */
    CfsCompressPage(page, sizeof(page), &opts,
                    scratch2, scratch_sz, &cres2);
    if (cres2.total_size != cres1.total_size ||
        memcmp(scratch1, scratch2, cres1.total_size) != 0)
    {
        snprintf(detail, sizeof(detail),
                 "non-deterministic record (payload %u, pad %zu)",
                 cres1.compressed_size, pad_len);
        add_result("record_padding_zeroed", "fail", detail);
        pfree(scratch1);
        pfree(scratch2);
        return;
    }
 
    snprintf(detail, sizeof(detail),
             "payload %u bytes, header + payload padding all zero",
             cres1.compressed_size);
    add_result("record_padding_zeroed", "ok", detail);
    pfree(scratch1);
    pfree(scratch2);
}
 
/*
 * Padding verification on read: the header trailing struct padding
 * and the payload alignment padding are written as zero and must stay zero.
 * A nonzero byte in either region (covered by no CRC) must be flagged as
 * BAD_HDR / BAD_DATA respectively.
 */
static void
test_record_padding_checked(void)
{
    unsigned char page[TEST_BLCKSZ];
    unsigned char decompressed[TEST_BLCKSZ];
    unsigned char *scratch;
    size_t      scratch_sz;
    CfsCompressOptions opts;
    CfsCompressResult cres;
    CfsCompressedBlockHeader *hdr;
    CfsDecompressStatus dstatus;
    size_t      hdr_pad_off;
    size_t      payload_pad_off;
    size_t      payload_pad_len;
    char        detail[128];
 
    if (!CfsCodecAvailable(CFS_ALGORITHM_LZ4))
    {
        add_result("record_padding_checked", "skip",
                   "LZ4 not compiled in");
        return;
    }
 
    scratch_sz = CfsCompressScratchSize(sizeof(page));
    scratch = palloc(scratch_sz);
 
    /* Highly compressible page -> a compressed record with payload padding. */
    fill_constant(page, sizeof(page), 0xBB);
    memset(&opts, 0, sizeof(opts));
    opts.algorithm = CFS_ALGORITHM_LZ4;
    opts.level = CFS_COMPRESS_LEVEL_DEFAULT;
    opts.min_gain_bytes = 1;
    opts.explicit_algorithm = true;
    opts.allow_raw_fallback = false;
 
    CfsCompressPage(page, sizeof(page), &opts,
                    scratch, scratch_sz, &cres);
 
    if (cres.is_raw)
    {
        add_result("record_padding_checked", "fail",
                   "page unexpectedly stored as RAW");
        pfree(scratch);
        return;
    }
 
    hdr = (CfsCompressedBlockHeader *) cres.result_data;
 
    /*
     * The whole 28-byte header is covered by hdr_crc, so there is no header
     * padding left to corrupt: flipping any header byte must trip the header
     * CRC check.  Use the byte just past the header (the first payload byte)
     * as the stand-in: the payload CRC must reject it as BAD_DATA.
     */
    hdr_pad_off = offsetof(CfsCompressedBlockHeader, hdr_crc);
    ((unsigned char *) hdr)[hdr_pad_off] ^= 0xFF;
 
    dstatus = CfsDecompressPage(cres.result_data, cres.total_size,
                                decompressed, sizeof(decompressed), NULL);
 
    ((unsigned char *) hdr)[hdr_pad_off] ^= 0xFF;
 
    if (dstatus != CFS_DECOMPRESS_BAD_HDR)
    {
        snprintf(detail, sizeof(detail),
                 "header byte corruption: expected BAD_HDR, got %d",
                 (int) dstatus);
        add_result("record_padding_checked", "fail", detail);
        pfree(scratch);
        return;
    }
 
    /* Corrupt one byte of the record tail padding. */
    payload_pad_off = CFS_BLOCK_HEADER_SIZE + cres.compressed_size;
    payload_pad_len = cres.total_size - payload_pad_off;
 
    if (payload_pad_len == 0)
    {
        add_result("record_padding_checked", "fail",
                   "compressed payload unexpectedly aligned (no padding)");
        pfree(scratch);
        return;
    }
 
    ((unsigned char *) cres.result_data)[payload_pad_off] ^= 0xFF;
 
    dstatus = CfsDecompressPage(cres.result_data, cres.total_size,
                                decompressed, sizeof(decompressed), NULL);
 
    if (dstatus == CFS_DECOMPRESS_BAD_DATA)
    {
        add_result("record_padding_checked", "ok",
                   "header and record tail padding rejected");
    }
    else
    {
        snprintf(detail, sizeof(detail),
                 "record tail padding corruption: expected BAD_DATA, got %d",
                 (int) dstatus);
        add_result("record_padding_checked", "fail", detail);
    }
    pfree(scratch);
}
 
static void
test_scratch_and_alignment(void)
{
    char        detail[128];
    size_t      sz = CfsCompressScratchSize(TEST_BLCKSZ);
    bool        ok = true;
 
    if (sz <= CFS_BLOCK_HEADER_SIZE)
        ok = false;
    if (sz > CFS_BLOCK_HEADER_SIZE + TEST_BLCKSZ + CFS_BLOCK_ALIGN + 1024)
        ok = false;
 
    if (!(CFS_ALIGN_UP(1) == 8 &&
          CFS_ALIGN_UP(8) == 8 &&
          CFS_ALIGN_UP(9) == 16 &&
          CFS_RECORD_SIZE(10) == CFS_ALIGN_UP(CFS_BLOCK_HEADER_SIZE + 10)))
        ok = false;
 
    if (ok)
    {
        snprintf(detail, sizeof(detail), "scratch=%zu align ok", sz);
        add_result("scratch_and_alignment", "ok", detail);
    }
    else
    {
        snprintf(detail, sizeof(detail), "scratch=%zu align check failed", sz);
        add_result("scratch_and_alignment", "fail", detail);
    }
}
 
/*
 * page_size contract: CfsCompressPage() must reject any page size
 * other than CFS_BLCKSZ, not merely sizes larger than it.  A smaller size
 * used to be accepted and written into the header as a sub-8 kB
 * original_size that the format validator would later reject.
 */
static void
test_compress_page_size_rejected(void)
{
    unsigned char page[TEST_BLCKSZ];
    unsigned char *scratch;
    size_t      scratch_sz;
    CfsCompressOptions opts;
    CfsCompressResult cres;
    bool        raised = false;
 
    scratch_sz = CfsCompressScratchSize(sizeof(page));
    scratch = palloc(scratch_sz);
 
    fill_constant(page, sizeof(page), 0x42);
    memset(&opts, 0, sizeof(opts));
    opts.algorithm = CFS_ALGORITHM_RAW;
    opts.min_gain_bytes = 1;
 
    PG_TRY();
    {
        CfsCompressPage(page, CFS_BLCKSZ / 2, &opts,
                        scratch, scratch_sz, &cres);
    }
    PG_CATCH();
    {
        ErrorData  *edata;
        MemoryContext oldcontext = MemoryContextSwitchTo(TopMemoryContext);
 
        edata = CopyErrorData();
        raised = (edata->sqlerrcode == ERRCODE_INTERNAL_ERROR);
        MemoryContextSwitchTo(oldcontext);
        FlushErrorState();
    }
    PG_END_TRY();
 
    if (!raised)
    {
        add_result("compress_page_size_rejected", "fail",
                   "sub-8kB page_size accepted by CfsCompressPage");
        pfree(scratch);
        return;
    }
 
    add_result("compress_page_size_rejected", "ok",
               "page_size != CFS_BLCKSZ rejected");
    pfree(scratch);
}
 
/* ================================================================
 * On-disk format serialisation/validation,
 * sidecar path helpers and structural fsck.
 * ================================================================ */
 
/* ------------------------------------------------------------------
 * Format layer tests
 * ------------------------------------------------------------------ */
static void
test_format_map_header(void)
{
    CfsMapPrologue prologue;
    char        detail[128];
 
    cfs_map_prologue_init(&prologue);
    if (cfs_map_prologue_validate(&prologue) != CFS_FORMAT_OK)
    {
        add_result("format_map_header", "fail", "valid prologue rejected");
        return;
    }
 
    prologue.magic ^= 0x1;
    if (cfs_map_prologue_validate(&prologue) != CFS_FORMAT_BAD_MAGIC)
    {
        add_result("format_map_header", "fail", "bad magic not detected");
        return;
    }
    prologue.magic ^= 0x1;
 
    prologue.version = (uint16) (CFS_MAP_VERSION + 1);
    if (cfs_map_prologue_validate(&prologue) != CFS_FORMAT_BAD_VERSION)
    {
        add_result("format_map_header", "fail", "bad version not detected");
        return;
    }
    prologue.version = CFS_MAP_VERSION;
 
    /* nonzero _reserved is a field error. */
    prologue._reserved = 1;
    if (cfs_map_prologue_validate(&prologue) != CFS_FORMAT_BAD_FIELD)
    {
        add_result("format_map_header", "fail",
                   "nonzero reserved not detected");
        return;
    }
    prologue._reserved = 0;
 
    snprintf(detail, sizeof(detail), "magic/version/reserved checks pass");
    add_result("format_map_header", "ok", detail);
}
 
static void
test_format_map_entry(void)
{
    CfsMapEntry e;
    char        detail[128];
 
    cfs_map_entry_init(&e);
    if (cfs_map_entry_validate(&e, true) != CFS_FORMAT_OK)
    {
        add_result("format_map_entry", "fail", "empty entry rejected");
        return;
    }
 
    e.physical_offset = 4096;
    e.compressed_size = 2048;
    e.generation = 3;
    cfs_map_entry_crc_set(&e);
    if (cfs_map_entry_validate(&e, true) != CFS_FORMAT_OK)
    {
        add_result("format_map_entry", "fail", "live entry rejected");
        return;
    }
 
    e.entry_crc ^= 0x1;
    if (cfs_map_entry_validate(&e, true) != CFS_FORMAT_BAD_CRC)
    {
        add_result("format_map_entry", "fail", "bad CRC not detected");
        return;
    }
    e.entry_crc ^= 0x1;
 
    /* compressed_size beyond the page size is a field error. */
    e.compressed_size = CFS_BLCKSZ + 1;
    cfs_map_entry_crc_set(&e);
    if (cfs_map_entry_validate(&e, true) != CFS_FORMAT_BAD_FIELD)
    {
        add_result("format_map_entry", "fail",
                   "oversized compressed_size not detected");
        return;
    }
 
    snprintf(detail, sizeof(detail), "entry CRC round-trip ok");
    add_result("format_map_entry", "ok", detail);
}
 
static void
test_format_journal_header(void)
{
    CfsJournalFileHeader hdr;
    char        detail[128];
 
    cfs_journal_header_init(&hdr);
    if (cfs_journal_header_validate(&hdr) != CFS_FORMAT_OK)
    {
        add_result("format_journal_header", "fail", "valid header rejected");
        return;
    }
 
    hdr.magic ^= 0x1;
    if (cfs_journal_header_validate(&hdr) != CFS_FORMAT_BAD_MAGIC)
    {
        add_result("format_journal_header", "fail", "bad magic not detected");
        return;
    }
    hdr.magic ^= 0x1;
 
    hdr.hdr_crc ^= 0x1;
    if (cfs_journal_header_validate(&hdr) != CFS_FORMAT_BAD_CRC)
    {
        add_result("format_journal_header", "fail", "bad CRC not detected");
        return;
    }
 
    snprintf(detail, sizeof(detail), "journal header checks pass");
    add_result("format_journal_header", "ok", detail);
}
 
static void
test_format_journal_entry(void)
{
    CfsMapEntry e;
    CfsJournalEntry upd;
    CfsJournalEntry del;
    char        detail[128];
 
    cfs_map_entry_init(&e);
    e.physical_offset = 8192;
    e.compressed_size = 4096;
    cfs_map_entry_crc_set(&e);
 
    cfs_journal_entry_init_update(&upd, 42, &e);
    if (cfs_journal_entry_validate(&upd) != CFS_FORMAT_OK)
    {
        add_result("format_journal_entry", "fail", "UPDATE record rejected");
        return;
    }
 
    cfs_journal_entry_init_delete(&del, 42);
    if (cfs_journal_entry_validate(&del) != CFS_FORMAT_OK)
    {
        add_result("format_journal_entry", "fail", "DELETE record rejected");
        return;
    }
 
    /* nonzero _reserved is a field error even with a valid CRC. */
    upd._reserved[0] = 1;
    cfs_journal_entry_crc_set(&upd);
    if (cfs_journal_entry_validate(&upd) != CFS_FORMAT_BAD_FIELD)
    {
        add_result("format_journal_entry", "fail",
                   "nonzero reserved not detected");
        return;
    }
    upd._reserved[0] = 0;
    cfs_journal_entry_crc_set(&upd);
 
    upd.entry_crc ^= 0x1;
    if (cfs_journal_entry_validate(&upd) != CFS_FORMAT_BAD_CRC)
    {
        add_result("format_journal_entry", "fail", "bad CRC not detected");
        return;
    }
 
    snprintf(detail, sizeof(detail), "UPDATE/DELETE records ok");
    add_result("format_journal_entry", "ok", detail);
}
 
static void
test_format_block_header(void)
{
    unsigned char page[TEST_BLCKSZ];
    unsigned char *scratch;
    size_t      scratch_sz;
    CfsCompressOptions opts = CFS_COMPRESS_OPTIONS_INIT;
    CfsCompressResult cres;
    CfsCompressedBlockHeader *bh;
    char        detail[128];
 
    scratch_sz = CfsCompressScratchSize(sizeof(page));
    scratch = palloc(scratch_sz);
 
    fill_constant(page, sizeof(page), 0x33);
    opts.algorithm = CFS_ALGORITHM_RAW;
    opts.min_gain_bytes = 1;
 
    CfsCompressPage(page, sizeof(page), &opts,
                    scratch, scratch_sz, &cres);
 
    bh = (CfsCompressedBlockHeader *) cres.result_data;
    if (cfs_block_header_validate(bh) != CFS_FORMAT_OK)
    {
        add_result("format_block_header", "fail", "valid block rejected");
        pfree(scratch);
        return;
    }
 
    bh->magic ^= 0x1;
    if (cfs_block_header_validate(bh) != CFS_FORMAT_BAD_MAGIC)
    {
        add_result("format_block_header", "fail", "bad magic not detected");
        pfree(scratch);
        return;
    }
    bh->magic ^= 0x1;
 
    /* Oversized fields must be rejected before the CRC is computed. */
    bh->compressed_size = CFS_BLCKSZ + 1;
    if (cfs_block_header_validate(bh) != CFS_FORMAT_BAD_FIELD)
    {
        add_result("format_block_header", "fail",
                   "oversized compressed_size not detected");
        pfree(scratch);
        return;
    }
    bh->compressed_size = CFS_BLCKSZ;
 
    bh->original_size = CFS_BLCKSZ + 1;
    if (cfs_block_header_validate(bh) != CFS_FORMAT_BAD_FIELD)
    {
        add_result("format_block_header", "fail",
                   "non-page original_size not detected");
        pfree(scratch);
        return;
    }
    bh->original_size = CFS_BLCKSZ;
 
    bh->hdr_crc ^= 0x1;
    if (cfs_block_header_validate(bh) != CFS_FORMAT_BAD_CRC)
    {
        add_result("format_block_header", "fail", "bad CRC not detected");
        pfree(scratch);
        return;
    }
 
    snprintf(detail, sizeof(detail), "block header magic/version/CRC ok");
    add_result("format_block_header", "ok", detail);
    pfree(scratch);
}
 
/* ------------------------------------------------------------------
 * Path helper tests
 * ------------------------------------------------------------------ */
static bool
cfs_test_ends_with(const char *s, const char *suffix)
{
    size_t      ls = strlen(s);
    size_t      lf = strlen(suffix);
 
    return ls >= lf && strcmp(s + ls - lf, suffix) == 0;
}
 
static void
test_path_helpers(void)
{
    RelFileLocatorBackend rl;
    char       *p;
    CfsFileKind kind;
    bool        ok = true;
    char        detail[160];
 
    /* Default tablespace, permanent relation. */
    rl.locator.spcOid = DEFAULTTABLESPACE_OID;
    rl.locator.dbOid = 16384;
    rl.locator.relNumber = 12345;
    rl.backend = INVALID_PROC_NUMBER;
 
    p = cfs_make_filename(rl, MAIN_FORKNUM, CFS_FILE_DATA);
    if (p == NULL || !cfs_test_ends_with(p, "/12345.cfp") || strstr(p, "base/") == NULL)
        ok = false;
    if (p)
        pfree(p);
 
    p = cfs_make_filename(rl, MAIN_FORKNUM, CFS_FILE_MAP);
    if (p == NULL || !cfs_test_ends_with(p, "/12345.cfsmap"))
        ok = false;
    if (p)
        pfree(p);
 
    p = cfs_make_filename(rl, MAIN_FORKNUM, CFS_FILE_JOURNAL);
    if (p == NULL || !cfs_test_ends_with(p, "/12345.cfsjrn"))
        ok = false;
    if (p)
        pfree(p);
 
    p = cfs_make_segment_filename(rl, MAIN_FORKNUM, CFS_FILE_DATA, 2);
    if (p == NULL || !cfs_test_ends_with(p, "/12345.cfp.2"))
        ok = false;
    if (p)
        pfree(p);
 
    /* Non-default tablespace. */
    rl.locator.spcOid = 99999;
    p = cfs_make_filename(rl, MAIN_FORKNUM, CFS_FILE_DATA);
    if (p == NULL || strstr(p, "pg_tblspc/") == NULL || !cfs_test_ends_with(p, "/12345.cfp"))
        ok = false;
    if (p)
        pfree(p);
 
    /* Temporary (backend-local) locator must be unsupported. */
    rl.locator.spcOid = DEFAULTTABLESPACE_OID;
    rl.backend = 1;             /* any non-INVALID_PROC_NUMBER value */
    p = cfs_make_filename(rl, MAIN_FORKNUM, CFS_FILE_DATA);
    if (p != NULL)
    {
        ok = false;
        pfree(p);
    }
    rl.backend = INVALID_PROC_NUMBER;
 
    /* Suffix parsing. */
    if (!cfs_sidecar_kind_from_suffix("12345.cfp", &kind) || kind != CFS_FILE_DATA)
        ok = false;
    if (!cfs_sidecar_kind_from_suffix("12345.cfsmap", &kind) || kind != CFS_FILE_MAP)
        ok = false;
    if (!cfs_sidecar_kind_from_suffix("12345.cfsjrn", &kind) || kind != CFS_FILE_JOURNAL)
        ok = false;
    if (!cfs_sidecar_kind_from_suffix("base/16384/12345.cfp.7", &kind) ||
        kind != CFS_FILE_DATA)
        ok = false;
    if (cfs_sidecar_kind_from_suffix("12345", &kind))
        ok = false;
    if (cfs_sidecar_kind_from_suffix("12345.dat", &kind))
        ok = false;
    if (!cfs_is_sidecar_filename("12345.cfp"))
        ok = false;
 
    snprintf(detail, sizeof(detail), "default/non-default/temp/suffix cases");
    add_result("path_helpers", ok ? "ok" : "fail", detail);
}
 
/* ------------------------------------------------------------------
 * fsck tests
 * ------------------------------------------------------------------ */
typedef enum CfsFsckTestMode
{
    FSCK_MODE_CLEAN,
    FSCK_MODE_BAD_MAP_CRC,
    FSCK_MODE_TRUNC_JOURNAL,
    FSCK_MODE_OFFSET_OOB
}           CfsFsckTestMode;
 
typedef struct CfsFsckFixture
{
    char       *dir;
    char       *cfp_path;
    char       *map_path;
    char       *jrn_path;
}           CfsFsckFixture;
 
static bool
cfs_test_write_file(const char *path, const void *data, size_t len)
{
    int         fd = BasicOpenFile(path, O_CREAT | O_WRONLY | O_TRUNC | PG_BINARY);
    const char *p = (const char *) data;
    size_t      off = 0;
 
    if (fd < 0)
        return false;
    while (off < len)
    {
        ssize_t     n = write(fd, p + off, len - off);
 
        if (n < 0)
        {
            if (errno == EINTR)
                continue;
            close(fd);
            return false;
        }
        off += n;
    }
    close(fd);
    return true;
}
 
static bool
cfs_fsck_setup(CfsFsckFixture * fx, const char *casename, CfsFsckTestMode mode)
{
    unsigned char page[TEST_BLCKSZ];
    unsigned char *scratch;
    size_t      scratch_sz;
    CfsCompressOptions opts = CFS_COMPRESS_OPTIONS_INIT;
    CfsCompressResult cres;
    CfsMapEntry e;
    CfsMapPrologue mhdr;
    CfsJournalFileHeader jhdr;
    CfsJournalEntry je;
    char        mapbuf[CFS_MAP_HEADER_SIZE + CFS_MAP_ENTRY_SIZE];
    char        jrnbuf[CFS_JOURNAL_HEADER_SIZE + CFS_JOURNAL_ENTRY_SIZE];
 
    memset(fx, 0, sizeof(CfsFsckFixture));
 
    fx->dir = psprintf("%s/cfs_fsck_test_%d_%s", DataDir, (int) MyProcPid, casename);
    if (mkdir(fx->dir, 0700) != 0 && errno != EEXIST)
    {
        pfree(fx->dir);
        fx->dir = NULL;
        return false;
    }
 
    fx->cfp_path = psprintf("%s/%s.cfp", fx->dir, casename);
    fx->map_path = psprintf("%s/%s.cfsmap", fx->dir, casename);
    fx->jrn_path = psprintf("%s/%s.cfsjrn", fx->dir, casename);
 
    scratch_sz = CfsCompressScratchSize(sizeof(page));
    scratch = palloc(scratch_sz);
 
    fill_constant(page, sizeof(page), 0x77);
    opts.algorithm = CFS_ALGORITHM_RAW;
    opts.min_gain_bytes = 1;
 
    CfsCompressPage(page, sizeof(page), &opts,
                    scratch, scratch_sz, &cres);
 
    /*
     * Build a single live map entry pointing at the compressed block.  Real
     * records start at CFS_CFP_BASE_OFFSET, so offset 0 stays reserved as the
     * "absent" sentinel.
     */
    cfs_map_entry_init(&e);
    e.physical_offset = (mode == FSCK_MODE_OFFSET_OOB) ? 999999 : CFS_CFP_BASE_OFFSET;
    e.compressed_size = cres.compressed_size;
    e.generation = 1;
    cfs_map_entry_crc_set(&e);
 
    if (mode == FSCK_MODE_BAD_MAP_CRC)
        e.entry_crc ^= 0x1;
 
    cfs_map_prologue_init(&mhdr);
    memcpy(mapbuf, &mhdr, sizeof(mhdr));
    memcpy(mapbuf + sizeof(mhdr), &e, sizeof(e));
 
    cfs_journal_header_init(&jhdr);
    cfs_journal_entry_init_update(&je, 0, &e);
    memcpy(jrnbuf, &jhdr, sizeof(jhdr));
    memcpy(jrnbuf + sizeof(jhdr), &je, sizeof(je));
 
    /*
     * .cfp = reserved lead-in (zero) followed by the compressed record at
     * CFS_CFP_BASE_OFFSET.
     */
    {
        size_t      tlen = CFS_CFP_BASE_OFFSET + cres.total_size;
        char       *cfpbuf = palloc(tlen);
        bool        ok;
 
        MemSet(cfpbuf, 0, CFS_CFP_BASE_OFFSET);
        memcpy(cfpbuf + CFS_CFP_BASE_OFFSET, cres.result_data, cres.total_size);
        ok = cfs_test_write_file(fx->cfp_path, cfpbuf, tlen);
        pfree(cfpbuf);
        if (!ok)
        {
            pfree(scratch);
            return false;
        }
    }
 
    if (!cfs_test_write_file(fx->map_path, mapbuf, sizeof(mapbuf)))
    {
        pfree(scratch);
        return false;
    }
 
    if (mode == FSCK_MODE_TRUNC_JOURNAL)
    {
        /* Write a torn final record: header + only the first 8 bytes. */
        if (!cfs_test_write_file(fx->jrn_path, jrnbuf, sizeof(jhdr) + 8))
        {
            pfree(scratch);
            return false;
        }
    }
    else
    {
        if (!cfs_test_write_file(fx->jrn_path, jrnbuf, sizeof(jrnbuf)))
        {
            pfree(scratch);
            return false;
        }
    }
 
    pfree(scratch);
    return true;
}
 
static void
cfs_fsck_teardown(CfsFsckFixture * fx)
{
    if (fx->cfp_path)
    {
        unlink(fx->cfp_path);
        pfree(fx->cfp_path);
    }
    if (fx->map_path)
    {
        unlink(fx->map_path);
        pfree(fx->map_path);
    }
    if (fx->jrn_path)
    {
        unlink(fx->jrn_path);
        pfree(fx->jrn_path);
    }
    if (fx->dir)
    {
        rmdir(fx->dir);
        pfree(fx->dir);
    }
}
 
static void
test_fsck_clean_relation(void)
{
    CfsFsckFixture fx;
    CfsFsckResult res;
    CfsFsckOptions opts = CFS_FSCK_OPTIONS_DEFAULT;
    char        detail[128];
 
    if (!cfs_fsck_setup(&fx, "clean", FSCK_MODE_CLEAN))
    {
        add_result("fsck_clean_relation", "fail", "setup failed");
        return;
    }
 
    cfs_fsck_result_init(&res);
    cfs_fsck_map_file(fx.map_path, fx.cfp_path, &opts, &res, NULL);
    cfs_fsck_journal_file(fx.jrn_path, &opts, &res, NULL);
    cfs_fsck_cfp_file(fx.cfp_path, &opts, &res);
 
    if (res.errors == 0 && res.live_entries == 1 && res.journal_records == 1 &&
        res.cfp_records == 1)
        snprintf(detail, sizeof(detail), "live=%llu jrn=%llu cfp=%llu",
                 (unsigned long long) res.live_entries,
                 (unsigned long long) res.journal_records,
                 (unsigned long long) res.cfp_records);
    else
        snprintf(detail, sizeof(detail),
                 "errors=%llu live=%llu jrn=%llu cfp=%llu",
                 (unsigned long long) res.errors,
                 (unsigned long long) res.live_entries,
                 (unsigned long long) res.journal_records,
                 (unsigned long long) res.cfp_records);
 
    add_result("fsck_clean_relation",
               (res.errors == 0) ? "ok" : "fail", detail);
    cfs_fsck_teardown(&fx);
}
 
static void
test_fsck_corrupt_map(void)
{
    CfsFsckFixture fx;
    CfsFsckResult res;
    CfsFsckOptions opts = CFS_FSCK_OPTIONS_DEFAULT;
    char        detail[128];
 
    if (!cfs_fsck_setup(&fx, "badmap", FSCK_MODE_BAD_MAP_CRC))
    {
        add_result("fsck_corrupt_map", "fail", "setup failed");
        return;
    }
 
    cfs_fsck_result_init(&res);
    cfs_fsck_map_file(fx.map_path, fx.cfp_path, &opts, &res, NULL);
 
    snprintf(detail, sizeof(detail), "crc_failures=%llu",
             (unsigned long long) res.crc_failures);
    add_result("fsck_corrupt_map",
               (res.crc_failures > 0) ? "ok" : "fail", detail);
    cfs_fsck_teardown(&fx);
}
 
static void
test_fsck_torn_journal(void)
{
    CfsFsckFixture fx;
    CfsFsckResult res;
    CfsFsckOptions opts = CFS_FSCK_OPTIONS_DEFAULT;
    char        detail[128];
 
    if (!cfs_fsck_setup(&fx, "truncjrn", FSCK_MODE_TRUNC_JOURNAL))
    {
        add_result("fsck_torn_journal", "fail", "setup failed");
        return;
    }
 
    cfs_fsck_result_init(&res);
    cfs_fsck_journal_file(fx.jrn_path, &opts, &res, NULL);
 
    snprintf(detail, sizeof(detail), "torn_tails=%llu errors=%llu",
             (unsigned long long) res.torn_tails,
             (unsigned long long) res.errors);
    add_result("fsck_torn_journal",
               (res.torn_tails == 1 && res.errors == 0) ? "ok" : "fail",
               detail);
    cfs_fsck_teardown(&fx);
}
 
/*
 * A .cfp file whose last (short) segment ends with a partial block header is
 * a torn write after a crash, not corruption: it must be reported as a soft
 * torn_tails status, not as an error.
 */
static void
test_fsck_torn_cfp_header(void)
{
    CfsFsckFixture fx;
    CfsFsckResult res;
    CfsFsckOptions opts = CFS_FSCK_OPTIONS_DEFAULT;
    char        detail[128];
    char        buf[CFS_CFP_BASE_OFFSET + 20];
    bool        ok = true;
 
    if (!cfs_fsck_setup(&fx, "torncfp", FSCK_MODE_CLEAN))
    {
        add_result("fsck_torn_cfp_header", "fail", "setup failed");
        return;
    }
 
    /* Lead-in + a partial (20-byte) block header. */
    memset(buf, 0, CFS_CFP_BASE_OFFSET);
    memset(buf + CFS_CFP_BASE_OFFSET, 0xAB, sizeof(buf) - CFS_CFP_BASE_OFFSET);
    if (!cfs_test_write_file(fx.cfp_path, buf, sizeof(buf)))
        ok = false;
 
    if (ok)
    {
        cfs_fsck_result_init(&res);
        cfs_fsck_cfp_file(fx.cfp_path, &opts, &res);
        if (res.torn_tails != 1 || res.errors != 0)
            ok = false;
    }
 
    snprintf(detail, sizeof(detail), "torn_tails=%llu errors=%llu",
             (unsigned long long) res.torn_tails,
             (unsigned long long) res.errors);
    add_result("fsck_torn_cfp_header", ok ? "ok" : "fail", detail);
    cfs_fsck_teardown(&fx);
}
 
/*
 * A .cfp file whose last (short) segment ends with a valid record header
 * whose payload was cut off by a crash is a torn tail, not corruption: the
 * engine never reads the bytes past the last record, and compaction will
 * reclaim the space.  Once a next segment exists, the same layout means real
 * truncation and must stay a hard error.
 */
static void
test_fsck_torn_cfp_record(void)
{
    CfsFsckFixture fx;
    CfsFsckResult res;
    CfsFsckOptions opts = CFS_FSCK_OPTIONS_DEFAULT;
    char        detail[128];
    CfsCompressedBlockHeader bh;
    char        buf[CFS_CFP_BASE_OFFSET + sizeof(bh)];
    pg_crc32c   crc;
    char       *seg1_path;
    bool        ok = true;
 
    if (!cfs_fsck_setup(&fx, "torncfprec", FSCK_MODE_CLEAN))
    {
        add_result("fsck_torn_cfp_record", "fail", "setup failed");
        return;
    }
 
    /* Lead-in + a valid RAW record header with the payload missing. */
    MemSet(&bh, 0, sizeof(bh));
    bh.magic = CFS_BLOCK_MAGIC;
    bh.version = CFS_FORMAT_VERSION;
    bh.algorithm = CFS_ALGORITHM_RAW;
    bh.compressed_size = CFS_BLCKSZ;
    bh.original_size = CFS_BLCKSZ;
    INIT_CRC32C(crc);
    COMP_CRC32C(crc, &bh, offsetof(CfsCompressedBlockHeader, hdr_crc));
    FIN_CRC32C(crc);
    bh.hdr_crc = crc;
 
    memset(buf, 0, CFS_CFP_BASE_OFFSET);
    memcpy(buf + CFS_CFP_BASE_OFFSET, &bh, sizeof(bh));
    if (!cfs_test_write_file(fx.cfp_path, buf, sizeof(buf)))
        ok = false;
 
    /* Case 1: single-segment chain — the torn record must be soft. */
    if (ok)
    {
        cfs_fsck_result_init(&res);
        cfs_fsck_cfp_file(fx.cfp_path, &opts, &res);
        if (res.torn_tails != 1 || res.errors != 0 ||
            res.truncated_records != 0)
            ok = false;
    }
 
    /*
     * Case 2: a ".cfp.1" makes segment 0 non-final — the same layout is a
     * hard truncated record.
     */
    seg1_path = psprintf("%s.1", fx.cfp_path);
    if (ok)
    {
        int         fd = BasicOpenFile(seg1_path, O_CREAT | O_WRONLY | PG_BINARY);
 
        if (fd < 0)
            ok = false;
        else
            close(fd);
    }
    if (ok)
    {
        cfs_fsck_result_init(&res);
        cfs_fsck_cfp_file(fx.cfp_path, &opts, &res);
        if (res.errors < 1 || res.truncated_records < 1)
            ok = false;
 
        /*
         * Case 3: with ".cfp.1" gone the chain is single-segment again —
         * the classification must return to a soft torn tail.
         */
        if (unlink(seg1_path) != 0)
            ok = false;
        else
        {
            cfs_fsck_result_init(&res);
            cfs_fsck_cfp_file(fx.cfp_path, &opts, &res);
            if (res.torn_tails != 1 || res.errors != 0 ||
                res.truncated_records != 0)
                ok = false;
        }
    }
 
    snprintf(detail, sizeof(detail), "torn_tails=%llu errors=%llu truncated=%llu",
             (unsigned long long) res.torn_tails,
             (unsigned long long) res.errors,
             (unsigned long long) res.truncated_records);
    add_result("fsck_torn_cfp_record", ok ? "ok" : "fail", detail);
    unlink(seg1_path);
    pfree(seg1_path);
    cfs_fsck_teardown(&fx);
}
 
/*
 * An invalid *full* record in the middle of the .cfp stream is still a hard
 * error; only a torn tail at the very end is soft.
 */
static void
test_fsck_corrupt_cfp_record(void)
{
    CfsFsckFixture fx;
    CfsFsckResult res;
    CfsFsckOptions opts = CFS_FSCK_OPTIONS_DEFAULT;
    char        detail[128];
    int         fd;
    unsigned char b;
    bool        ok = true;
 
    if (!cfs_fsck_setup(&fx, "corruptcfp", FSCK_MODE_CLEAN))
    {
        add_result("fsck_corrupt_cfp_record", "fail", "setup failed");
        return;
    }
 
    /* Corrupt the magic byte of the single full record in the .cfp. */
    fd = BasicOpenFile(fx.cfp_path, O_RDWR | PG_BINARY);
    if (fd < 0)
        ok = false;
    if (ok)
    {
        if (pread(fd, &b, 1, CFS_CFP_BASE_OFFSET) != 1)
            ok = false;
        else
        {
            b ^= 0xFF;
            if (pwrite(fd, &b, 1, CFS_CFP_BASE_OFFSET) != 1)
                ok = false;
        }
        close(fd);
    }
 
    if (ok)
    {
        cfs_fsck_result_init(&res);
        cfs_fsck_cfp_file(fx.cfp_path, &opts, &res);
 
        /*
         * The corrupted byte is part of the header magic, not of the
         * CRC-covered content: the failure must land in field_failures.
         */
        if (res.field_failures < 1 || res.crc_failures != 0 || res.errors < 1)
            ok = false;
    }
 
    snprintf(detail, sizeof(detail), "field_failures=%llu errors=%llu",
             (unsigned long long) res.field_failures,
             (unsigned long long) res.errors);
    add_result("fsck_corrupt_cfp_record", ok ? "ok" : "fail", detail);
    cfs_fsck_teardown(&fx);
}
 
/*
 * Synthetic relation locators in these tests bypass smgr's relation-drop
 * cleanup.  Drain their pending sync requests before unlinking sidecars:
 * otherwise a later real CHECKPOINT can PANIC attempting to fsync an already
 * removed test file (e.g. 999090.cfsjrn).
 */
static void
cfs_test_unlink_synthetic(RelFileLocatorBackend rlocator)
{
    cfs_forget_sync_requests(rlocator, MAIN_FORKNUM);
    cfs_unlink(rlocator, MAIN_FORKNUM);
}
 
/*
 * Deep fsck cross-checks every live map entry against the .cfp record header
 * it points at: an entry whose offset lands in the middle of a record, or
 * whose fields disagree with the header, is corruption that the independent
 * map and .cfp scans cannot see.
 *
 * The relation is created through the real storage engine so the files live
 * at their locator-derived paths, then its .cfsmap is corrupted on disk (with
 * a recomputed entry_crc, so the map scan itself sees nothing wrong).
 */
static void
test_fsck_cross_check(void)
{
    RelFileLocatorBackend rl;
    CfsRelation *cfs;
    CfsWriteOptions wopts = CFS_WRITE_OPTIONS_INIT;
    unsigned char page[TEST_BLCKSZ];
    char       *map_path;
    CfsMapEntry e;
    CfsFsckResult res;
    CfsFsckOptions fopts = CFS_FSCK_OPTIONS_DEFAULT;
    uint64      orig_off;
    int         fd;
    bool        ok = true;
 
    /* RAW records: deterministic 8232-byte records, no codec involved. */
    wopts.algorithm = CFS_ALGORITHM_RAW;
    wopts.explicit_algorithm = true;
    wopts.allow_raw_fallback = true;
    wopts.min_gain_bytes = 1;
 
    rl.locator.spcOid = DEFAULTTABLESPACE_OID;
    rl.locator.dbOid = MyDatabaseId;
    rl.locator.relNumber = 999091;
    rl.backend = INVALID_PROC_NUMBER;
 
    cfs_test_unlink_synthetic(rl);
    cfs = cfs_create(rl, MAIN_FORKNUM);
    if (cfs == NULL)
    {
        add_result("fsck_cross_check", "fail", "create failed");
        return;
    }
 
    /* Two blocks -> two real records in .cfp. */
    memset(page, 0x30, sizeof(page));
    if (cfs_write_page(cfs, 0, (const char *) page, &wopts) != CFS_STORAGE_OK ||
        cfs_write_page(cfs, 1, (const char *) page, &wopts) != CFS_STORAGE_OK)
        ok = false;
 
    if (ok)
    {
        cfs_map_save_snapshot(cfs);
        test_journal_reset(cfs, ERROR);
    }
    cfs_close(cfs);
 
    map_path = cfs_make_filename(rl, MAIN_FORKNUM, CFS_FILE_MAP);
 
    /* Baseline: deep fsck on the clean relation must be green. */
    if (ok)
    {
        cfs_fsck_result_init(&res);
        cfs_fsck_relation(rl, MAIN_FORKNUM, &fopts, &res);
        if (res.errors != 0 || res.cross_check_failures != 0)
            ok = false;
    }
 
    /*
     * Corrupt block 0's entry: shift the offset 8 bytes into its own record,
     * so the "header" there is garbage.  The CRC is recomputed, so only the
     * cross-check can see the problem.
     */
    if (ok)
    {
        fd = BasicOpenFile(map_path, O_RDWR | PG_BINARY);
        if (fd < 0)
            ok = false;
        if (ok)
        {
            if (pread(fd, &e, sizeof(e), CFS_MAP_HEADER_SIZE) != sizeof(e))
                ok = false;
            else
            {
                orig_off = e.physical_offset;
                e.physical_offset = orig_off + CFS_BLOCK_ALIGN;
                cfs_map_entry_crc_set(&e);
                if (pwrite(fd, &e, sizeof(e), CFS_MAP_HEADER_SIZE) != sizeof(e))
                    ok = false;
            }
            close(fd);
        }
    }
 
    /* Deep fsck: the bogus offset must surface as a cross-check failure. */
    if (ok)
    {
        cfs_fsck_result_init(&res);
        cfs_fsck_relation(rl, MAIN_FORKNUM, &fopts, &res);
        if (res.cross_check_failures < 1 || res.errors < 1)
            ok = false;
    }
 
    /*
     * Restore the offset, then corrupt the compressed_size instead: the
     * record header is the single source of truth for the payload size, so
     * the map/header disagreement must surface in the cross-check.
     */
    if (ok)
    {
        fd = BasicOpenFile(map_path, O_RDWR | PG_BINARY);
        if (fd < 0)
            ok = false;
        if (ok)
        {
            if (pread(fd, &e, sizeof(e), CFS_MAP_HEADER_SIZE) != sizeof(e))
                ok = false;
            else
            {
                e.physical_offset = orig_off;
                e.compressed_size -= 1; /* disagrees with the record header */
                cfs_map_entry_crc_set(&e);
                if (pwrite(fd, &e, sizeof(e), CFS_MAP_HEADER_SIZE) != sizeof(e))
                    ok = false;
            }
            close(fd);
        }
    }
 
    /* Deep fsck: the compressed_size mismatch must surface too. */
    if (ok)
    {
        cfs_fsck_result_init(&res);
        cfs_fsck_relation(rl, MAIN_FORKNUM, &fopts, &res);
        if (res.cross_check_failures < 1 || res.errors < 1)
            ok = false;
    }
 
    /* Non-deep fsck: no .cfp pass, no cross-check — nothing is detected. */
    if (ok)
    {
        fopts.verify_block_headers = false;
        cfs_fsck_result_init(&res);
        cfs_fsck_relation(rl, MAIN_FORKNUM, &fopts, &res);
        if (res.cross_check_failures != 0 || res.errors != 0)
            ok = false;
    }
 
    pfree(map_path);
    cfs_test_unlink_synthetic(rl);
 
    add_result("fsck_cross_check", ok ? "ok" : "fail",
               ok ? "cross-check flags bogus offsets, deep mode only"
               : "cross-check failed");
}
 
/*
 * A shrink RESIZE followed by a grow must stay healable in the dropped
 * interval: replay applies RESIZE records in order, so the shrink zeroes the
 * slots it drops and the later grow leaves them sparse.  A corrupt map row in
 * [target, old_nblocks) is therefore healed by the journal even though the
 * relation grew back over the slot; fsck must not look at the last RESIZE
 * target alone.
 *
 * With an empty journal the same row is real damage, so the fixture also runs
 * that control to prove the corruption itself is detected.
 */
static void
test_fsck_resize_shrink_grow(void)
{
    RelFileLocatorBackend rl;
    CfsRelation *cfs;
    CfsWriteOptions wopts = CFS_WRITE_OPTIONS_INIT;
    unsigned char page[TEST_BLCKSZ];
    char       *map_path;
    char       *jrn_path;
    CfsMapEntry e;
    CfsFsckResult res;
    CfsFsckOptions fopts = CFS_FSCK_OPTIONS_DEFAULT;
    CfsJournalFileHeader jhdr;
    int         fd;
    int         blk;
    bool        ok = true;
 
    /* RAW records: deterministic 8232-byte records, no codec involved. */
    wopts.algorithm = CFS_ALGORITHM_RAW;
    wopts.explicit_algorithm = true;
    wopts.allow_raw_fallback = true;
    wopts.min_gain_bytes = 1;
 
    rl.locator.spcOid = DEFAULTTABLESPACE_OID;
    rl.locator.dbOid = MyDatabaseId;
    rl.locator.relNumber = 999094;
    rl.backend = INVALID_PROC_NUMBER;
 
    cfs_test_unlink_synthetic(rl);
    cfs = cfs_create(rl, MAIN_FORKNUM);
    if (cfs == NULL)
    {
        add_result("fsck_resize_shrink_grow", "fail", "create failed");
        return;
    }
 
    /* Four blocks -> four rows in the map snapshot. */
    memset(page, 0x50, sizeof(page));
    for (blk = 0; blk < 4; blk++)
    {
        if (cfs_write_page(cfs, blk, (const char *) page, &wopts) !=
            CFS_STORAGE_OK)
            ok = false;
    }
    if (ok)
    {
        cfs_map_save_snapshot(cfs);
        test_journal_reset(cfs, ERROR);
    }
    cfs_close(cfs);
 
    map_path = cfs_make_filename(rl, MAIN_FORKNUM, CFS_FILE_MAP);
    jrn_path = cfs_make_filename(rl, MAIN_FORKNUM, CFS_FILE_JOURNAL);
 
    /*
     * Journal: shrink to 2 (drops blocks 2 and 3), then grow back to 4.  The
     * replay clears the dropped slots on the shrink and leaves them sparse on
     * the grow, so block 2's row is healed by the journal, not by its bytes.
     */
    if (ok)
    {
        char        jrnbuf[CFS_JOURNAL_HEADER_SIZE +
                           2 * CFS_JOURNAL_ENTRY_SIZE];
        CfsJournalEntry resize;
 
        cfs_journal_header_init(&jhdr);
        memcpy(jrnbuf, &jhdr, sizeof(jhdr));
        cfs_journal_entry_init_resize(&resize, 2);
        memcpy(jrnbuf + sizeof(jhdr), &resize, sizeof(resize));
        cfs_journal_entry_init_resize(&resize, 4);
        memcpy(jrnbuf + sizeof(jhdr) + sizeof(resize), &resize,
               sizeof(resize));
        if (!cfs_test_write_file(jrn_path, jrnbuf, sizeof(jrnbuf)))
            ok = false;
    }
 
    /* Corrupt block 2's entry_crc; every role field stays intact. */
    if (ok)
    {
        fd = BasicOpenFile(map_path, O_RDWR | PG_BINARY);
        if (fd < 0)
            ok = false;
        if (ok)
        {
            off_t       row_off = cfs_map_row_off(2);
 
            if (pread(fd, &e, sizeof(e), row_off) != sizeof(e))
                ok = false;
            else
            {
                e.entry_crc ^= 0x1;
                if (pwrite(fd, &e, sizeof(e), row_off) != sizeof(e))
                    ok = false;
            }
            close(fd);
        }
    }
 
    /* The shrink-then-grow journal heals the row: no damage, one heal. */
    if (ok)
    {
        cfs_fsck_result_init(&res);
        cfs_fsck_relation(rl, MAIN_FORKNUM, &fopts, &res);
        if (res.healed_entries != 1 || res.errors != 0 ||
            res.cross_check_failures != 0)
            ok = false;
    }
 
    /* Control: with an empty journal the same row is real damage. */
    if (ok)
    {
        cfs_journal_header_init(&jhdr);
        if (!cfs_test_write_file(jrn_path, &jhdr, sizeof(jhdr)))
            ok = false;
    }
    if (ok)
    {
        cfs_fsck_result_init(&res);
        cfs_fsck_relation(rl, MAIN_FORKNUM, &fopts, &res);
        if (res.errors < 1 || res.healed_entries != 0)
            ok = false;
    }
 
    pfree(map_path);
    pfree(jrn_path);
    cfs_test_unlink_synthetic(rl);
 
    add_result("fsck_resize_shrink_grow", ok ? "ok" : "fail",
               ok ? "shrink then grow keeps the dropped slot healable"
               : "shrink-then-grow coverage failed");
}
 
/*
 * The recovery scan must use the strict sidecar-name parser: a journal
 * renamed to a leading-zero name ("0999092.cfsjrn") is ignored — the engine
 * never creates such names — while the valid name is replayed as usual.
 *
 * The relation lives at its locator-derived paths in the real database
 * directory, so the public CfsReplayAllJournals() scan finds it.  A lenient
 * parser would map the decoy onto the relation and open it, recreating the
 * journal file; the strict parser must leave both files untouched.
 */
static void
test_recovery_scan_strict_names(void)
{
    RelFileLocatorBackend rl;
    CfsRelation *cfs;
    CfsWriteOptions wopts = CFS_WRITE_OPTIONS_INIT;
    unsigned char page[TEST_BLCKSZ];
    char       *jrn_path;
    char       *decoy_path;
    struct stat st;
    bool        ok = true;
 
    wopts.algorithm = CFS_ALGORITHM_RAW;
    wopts.explicit_algorithm = true;
    wopts.allow_raw_fallback = true;
    wopts.min_gain_bytes = 1;
 
    rl.locator.spcOid = DEFAULTTABLESPACE_OID;
    rl.locator.dbOid = MyDatabaseId;
    rl.locator.relNumber = 999092;
    rl.backend = INVALID_PROC_NUMBER;
 
    cfs_test_unlink_synthetic(rl);
    cfs = cfs_create(rl, MAIN_FORKNUM);
    if (cfs == NULL)
    {
        add_result("recovery_scan_strict_names", "fail", "create failed");
        return;
    }
 
    /* One write leaves an UPDATE record pending in the journal. */
    memset(page, 0x40, sizeof(page));
    if (cfs_write_page(cfs, 0, (const char *) page, &wopts) != CFS_STORAGE_OK)
        ok = false;
    cfs_close(cfs);
 
    jrn_path = cfs_make_filename(rl, MAIN_FORKNUM, CFS_FILE_JOURNAL);
    {
        const char *slash = strrchr(jrn_path, '/');
 
        decoy_path = psprintf("%.*s/0999092.cfsjrn",
                              (int) (slash - jrn_path), jrn_path);
    }
 
    /* Hide the journal under a leading-zero name the engine never creates. */
    if (ok && rename(jrn_path, decoy_path) != 0)
        ok = false;
 
    if (ok)
    {
        CfsReplayAllJournals();
 
        /*
         * The decoy must be ignored entirely: its content untouched, and the
         * relation never opened (a recreated journal file would prove the
         * lenient name mapping).
         */
        if (stat(decoy_path, &st) != 0 ||
            st.st_size <= (off_t) CFS_JOURNAL_HEADER_SIZE)
            ok = false;
        if (stat(jrn_path, &st) == 0)
            ok = false;         /* must not have been recreated */
    }
 
    /* Restore the valid name. */
    if (ok && rename(decoy_path, jrn_path) != 0)
        ok = false;
 
    if (ok)
    {
        CfsReplayAllJournals();
 
        /* Valid name: replayed, journal truncated back to the bare header. */
        if (stat(jrn_path, &st) != 0 ||
            st.st_size != (off_t) CFS_JOURNAL_HEADER_SIZE)
            ok = false;
    }
 
    unlink(decoy_path);
    pfree(jrn_path);
    pfree(decoy_path);
    cfs_test_unlink_synthetic(rl);
 
    add_result("recovery_scan_strict_names", ok ? "ok" : "fail",
               ok ? "leading-zero journal ignored, valid name replayed"
               : "recovery scan name handling broken");
}
 
static void
test_fsck_offset_out_of_range(void)
{
    CfsFsckFixture fx;
    CfsFsckResult res;
    CfsFsckOptions opts = CFS_FSCK_OPTIONS_DEFAULT;
    char        detail[128];
 
    if (!cfs_fsck_setup(&fx, "oob", FSCK_MODE_OFFSET_OOB))
    {
        add_result("fsck_offset_out_of_range", "fail", "setup failed");
        return;
    }
 
    cfs_fsck_result_init(&res);
    cfs_fsck_map_file(fx.map_path, fx.cfp_path, &opts, &res, NULL);
 
    snprintf(detail, sizeof(detail), "offset_oob=%llu",
             (unsigned long long) res.offset_out_of_range);
    add_result("fsck_offset_out_of_range",
               (res.offset_out_of_range > 0) ? "ok" : "fail", detail);
    cfs_fsck_teardown(&fx);
}
 
/*
 * A map with live entries but a missing/empty .cfp chain must be flagged in
 * both deep and non-deep modes; the per-entry EOF check only runs when
 * cfp_size > 0, so this case is caught by a dedicated end-of-scan check.
 */
static void
test_fsck_live_entries_missing_cfp(void)
{
    CfsFsckFixture fx;
    CfsFsckResult res;
    CfsFsckOptions opts = CFS_FSCK_OPTIONS_DEFAULT;
    bool        ok = true;
 
    if (!cfs_fsck_setup(&fx, "live_nocfp", FSCK_MODE_CLEAN))
    {
        add_result("fsck_live_entries_missing_cfp", "fail", "setup failed");
        return;
    }
 
    /* Remove the .cfp data file: the live map entry now points nowhere. */
    if (unlink(fx.cfp_path) != 0)
        ok = false;
    pfree(fx.cfp_path);
    fx.cfp_path = NULL;
 
    /* Non-deep mode. */
    cfs_fsck_result_init(&res);
    opts.verify_block_headers = false;
    cfs_fsck_map_file(fx.map_path, fx.cfp_path, &opts, &res, NULL);
    if (res.live_entries < 1 || res.missing_files < 1 || res.errors < 1)
        ok = false;
 
    /* Deep mode. */
    cfs_fsck_result_init(&res);
    opts.verify_block_headers = true;
    cfs_fsck_map_file(fx.map_path, fx.cfp_path, &opts, &res, NULL);
    if (res.live_entries < 1 || res.missing_files < 1 || res.errors < 1)
        ok = false;
 
    add_result("fsck_live_entries_missing_cfp", ok ? "ok" : "fail",
               ok ? "live map + missing .cfp is an error in both modes"
               : "live map + missing .cfp not detected");
    cfs_fsck_teardown(&fx);
}
 
/*
 * A fully empty map (no entries) without a .cfp file is a clean relation,
 * not an error.
 */
static void
test_fsck_empty_map_no_cfp(void)
{
    char       *dir;
    char       *map_path;
    CfsMapPrologue mhdr;
    char        mapbuf[CFS_MAP_HEADER_SIZE];
    CfsFsckResult res;
    CfsFsckOptions opts = CFS_FSCK_OPTIONS_DEFAULT;
    bool        ok = true;
 
    dir = psprintf("%s/cfs_fsck_empty_%d", DataDir, (int) MyProcPid);
    if (mkdir(dir, 0700) != 0 && errno != EEXIST)
    {
        pfree(dir);
        add_result("fsck_empty_map_no_cfp", "fail", "setup failed");
        return;
    }
    map_path = psprintf("%s/empty.cfsmap", dir);
 
    cfs_map_prologue_init(&mhdr);
    memcpy(mapbuf, &mhdr, sizeof(mhdr));
    if (!cfs_test_write_file(map_path, mapbuf, sizeof(mapbuf)))
        ok = false;
 
    cfs_fsck_result_init(&res);
    opts.verify_block_headers = false;
    cfs_fsck_map_file(map_path, NULL, &opts, &res, NULL);
    if (res.errors != 0 || res.live_entries != 0)
        ok = false;
 
    unlink(map_path);
    pfree(map_path);
    rmdir(dir);
    pfree(dir);
 
    add_result("fsck_empty_map_no_cfp", ok ? "ok" : "fail",
               ok ? "empty map without .cfp is clean"
               : "empty map without .cfp misreported");
}
 
/* ================================================================
 * autonomous storage layer
 * ================================================================ */
 
typedef struct CfsStorageFixture
{
    char       *dir;
    char       *cfp_path;
    char       *map_path;
    char       *jrn_path;
    RelFileLocatorBackend rl;   /* synthetic, for diagnostics only */
}           CfsStorageFixture;
 
static void
cfs_storage_setup(CfsStorageFixture * fx, const char *casename)
{
    MemoryContext oldcontext;
 
    memset(fx, 0, sizeof(*fx));
 
    /*
     * A test may catch an expected ERROR and keep using the fixture.  An
     * ERROR resets the query context, so keep the paths in the same durable
     * context the backend uses for CFS handles; teardown pfrees them.
     */
    oldcontext = MemoryContextSwitchTo(TopMemoryContext);
    fx->dir = psprintf("%s/cfs_storage_test_%d_%s", DataDir,
                       (int) MyProcPid, casename);
    if (mkdir(fx->dir, 0700) != 0 && errno != EEXIST)
    {
        pfree(fx->dir);
        fx->dir = NULL;
        MemoryContextSwitchTo(oldcontext);
        return;
    }
    fx->cfp_path = psprintf("%s/%s.cfp", fx->dir, casename);
    fx->map_path = psprintf("%s/%s.cfsmap", fx->dir, casename);
    fx->jrn_path = psprintf("%s/%s.cfsjrn", fx->dir, casename);
    MemoryContextSwitchTo(oldcontext);
 
    fx->rl.locator.spcOid = DEFAULTTABLESPACE_OID;
    fx->rl.locator.dbOid = 16384;
    fx->rl.locator.relNumber = 99990;
    fx->rl.backend = INVALID_PROC_NUMBER;
}
 
static void
cfs_storage_teardown(CfsStorageFixture * fx)
{
    /*
     * Drop every shared cache trace of the fixture's relation before its
     * files go away: an unpinned leftover slot would carry an IDLE .cfp
     * tail that describes the unlinked files, and the next fixture that
     * reuses this relNumber must not inherit it (the cfs_write_page()
     * contract requires no slot without a pin, cfs_storage.h).
     */
    cfs_map_cache_invalidate(fx->rl, MAIN_FORKNUM);
    cfs_shared_map_invalidate_relation(fx->rl, MAIN_FORKNUM);
 
    /*
     * The fixture uses a synthetic relfilenumber with sidecar files outside
     * the normal relation path.  Writes can enqueue fsync requests using the
     * synthetic locator; if left pending, a later CHECKPOINT would attempt
     * to fsync base/<dboid>/99990.cfp instead of these fixture paths and
     * PANIC after the files have been removed.  Cancel only this fixture's
     * registered requests before unlinking its files.
     */
    if (fx->rl.locator.relNumber != 0)
        cfs_forget_sync_requests(fx->rl, MAIN_FORKNUM);
 
    if (fx->cfp_path)
    {
        /* Remove the whole segment chain (".cfp", ".cfp.1", ...). */
        uint32      segno;
 
        for (segno = 0;; segno++)
        {
            char       *seg = (segno == 0) ? pstrdup(fx->cfp_path) :
                psprintf("%s.%u", fx->cfp_path, segno);
 
            if (unlink(seg) != 0)
            {
                pfree(seg);
                break;
            }
            pfree(seg);
        }
        pfree(fx->cfp_path);
    }
    if (fx->map_path)
    {
        unlink(fx->map_path);
        pfree(fx->map_path);
    }
    if (fx->jrn_path)
    {
        unlink(fx->jrn_path);
        pfree(fx->jrn_path);
    }
    if (fx->dir)
    {
        rmdir(fx->dir);
        pfree(fx->dir);
    }
}
 
/*
 * Open (creating) a fresh CfsRelation from a fixture.  The handle lives in
 * TopMemoryContext like a backend smgr handle, so a test that catches an
 * expected ERROR can still close it (and its paths) afterwards.
 */
static CfsRelation *
cfs_storage_open_new(const CfsStorageFixture * fx)
{
    CfsRelation *cfs;
    MemoryContext oldcontext;
 
    oldcontext = MemoryContextSwitchTo(TopMemoryContext);
    cfs = cfs_open_paths(fx->rl, MAIN_FORKNUM,
                         fx->cfp_path, fx->map_path, fx->jrn_path,
                         CFS_OPEN_RDWR | CFS_OPEN_CREATE);
    MemoryContextSwitchTo(oldcontext);
 
    return cfs;
}
 
/*
 * Open a lazy handle in TopMemoryContext, the way the smgr bridge does.
 * These tests catch an expected ERROR from the read path and keep using the
 * handle; a handle allocated in the query context is already freed by then.
 */
static CfsRelation *
cfs_test_open_lazy(RelFileLocatorBackend rl,
                   const char *cfp_path, const char *map_path,
                   const char *jrn_path)
{
    CfsRelation *cfs;
    MemoryContext oldcontext;
 
    oldcontext = MemoryContextSwitchTo(TopMemoryContext);
    cfs = cfs_open_paths(rl, MAIN_FORKNUM, cfp_path, map_path, jrn_path,
                         CFS_OPEN_RDWR | CFS_OPEN_LAZY_MAP);
    MemoryContextSwitchTo(oldcontext);
 
    return cfs;
}
 
/* Fill a page with a deterministic, compressible pattern tagged by 'tag'. */
static void
cfs_test_fill_page(unsigned char *page, unsigned char tag)
{
    size_t      i;
 
    for (i = 0; i < TEST_BLCKSZ; i++)
        page[i] = (unsigned char) ((tag + i) & 0x7F);
}
 
static CfsWriteOptions
cfs_test_write_opts(void)
{
    CfsWriteOptions opts = CFS_WRITE_OPTIONS_INIT;
 
    opts.algorithm = CfsCodecAvailable(CFS_ALGORITHM_LZ4) ?
        CFS_ALGORITHM_LZ4 : CFS_ALGORITHM_RAW;
    opts.level = CFS_COMPRESS_LEVEL_DEFAULT;
    opts.min_gain_bytes = 1;
    return opts;
}
 
static void
test_storage_create_open(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    char        detail[128];
 
    cfs_storage_setup(&fx, "create");
    if (fx.dir == NULL)
    {
        add_result("storage_create_open", "fail", "setup failed");
        return;
    }
 
    cfs = cfs_storage_open_new(&fx);
    if (cfs == NULL || cfs_map_nblocks(cfs) != 0)
    {
        snprintf(detail, sizeof(detail), "nblocks=%u", cfs ? cfs_map_nblocks(cfs) : 0);
        add_result("storage_create_open", "fail", detail);
        if (cfs)
            cfs_close(cfs);
        cfs_storage_teardown(&fx);
        return;
    }
    cfs_close(cfs);
 
    /* Reopen without CREATE and verify headers validate. */
    cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM,
                         fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR);
    if (cfs == NULL || cfs_map_nblocks(cfs) != 0)
    {
        snprintf(detail, sizeof(detail), "reopen nblocks=%u",
                 cfs ? cfs_map_nblocks(cfs) : 0);
        add_result("storage_create_open", "fail", detail);
        if (cfs)
            cfs_close(cfs);
        cfs_storage_teardown(&fx);
        return;
    }
    cfs_close(cfs);
 
    snprintf(detail, sizeof(detail), "create+reopen, nblocks=0");
    add_result("storage_create_open", "ok", detail);
    cfs_storage_teardown(&fx);
}
 
static void
test_storage_write_read(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    unsigned char page[TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    char        detail[128];
 
    cfs_storage_setup(&fx, "rw");
    if (fx.dir == NULL)
    {
        add_result("storage_write_read", "fail", "setup failed");
        return;
    }
    cfs = cfs_storage_open_new(&fx);
    cfs_test_fill_page(page, 0x10);
    if (cfs_write_page(cfs, 0, (const char *) page, &opts) != CFS_STORAGE_OK)
    {
        add_result("storage_write_read", "fail", "write_page failed");
        cfs_close(cfs);
        cfs_storage_teardown(&fx);
        return;
    }
    /* After an append the in-memory entry must be CRC-consistent. */
    if (cfs_map_entry_validate(&cfs->map[0], true) != CFS_FORMAT_OK ||
        !CFS_MAP_ENTRY_VALID(&cfs->map[0]))
    {
        add_result("storage_write_read", "fail", "map header CRC inconsistent after append");
        cfs_close(cfs);
        cfs_storage_teardown(&fx);
        return;
    }
    if (cfs_read_page(cfs, 0, (char *) back) != CFS_STORAGE_OK ||
        memcmp(page, back, TEST_BLCKSZ) != 0)
    {
        add_result("storage_write_read", "fail", "read mismatch");
        cfs_close(cfs);
        cfs_storage_teardown(&fx);
        return;
    }
    snprintf(detail, sizeof(detail), "write+read block 0 ok, nblocks=%u",
             cfs_map_nblocks(cfs));
    add_result("storage_write_read", "ok", detail);
    cfs_close(cfs);
    cfs_storage_teardown(&fx);
}
 
static void
test_storage_update_generation(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    unsigned char pageA[TEST_BLCKSZ];
    unsigned char pageB[TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    char        detail[128];
    bool        ok = true;
 
    cfs_storage_setup(&fx, "gen");
    if (fx.dir == NULL)
    {
        add_result("storage_update_generation", "fail", "setup failed");
        return;
    }
    cfs = cfs_storage_open_new(&fx);
 
    cfs_test_fill_page(pageA, 0x20);
    cfs_test_fill_page(pageB, 0x30);
    cfs_write_page(cfs, 0, (const char *) pageA, &opts);
    cfs_write_page(cfs, 0, (const char *) pageB, &opts);
 
    /* Latest generation must be read back. */
    if (cfs_read_page(cfs, 0, (char *) back) != CFS_STORAGE_OK ||
        memcmp(pageB, back, TEST_BLCKSZ) != 0)
        ok = false;
 
    /* The header watermark must cover every entry it will persist. */
    if (cfs->map == NULL || cfs_map_nblocks(cfs) < 1 ||
        cfs->map_hdr.max_generation < cfs->map[0].generation)
        ok = false;
 
    /* Close and reopen: the journal must replay to the latest version. */
    cfs_close(cfs);
    cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM,
                         fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR);
    if (cfs_read_page(cfs, 0, (char *) back) != CFS_STORAGE_OK ||
        memcmp(pageB, back, TEST_BLCKSZ) != 0)
        ok = false;
    if (cfs->map == NULL || cfs_map_nblocks(cfs) < 1 ||
        cfs->map_hdr.max_generation < cfs->map[0].generation)
        ok = false;
 
    /* An old on-disk version must be rejected, never silently upgraded. */
    {
        CfsMapPrologue prologue;
 
        cfs_map_prologue_init(&prologue);
        prologue.version = CFS_MAP_VERSION - 1;
        if (cfs_map_prologue_validate(&prologue) != CFS_FORMAT_BAD_VERSION)
            ok = false;
    }
    cfs_close(cfs);
 
    snprintf(detail, sizeof(detail), "generation=%s", ok ? "latest" : "stale");
    add_result("storage_update_generation", ok ? "ok" : "fail", detail);
    cfs_storage_teardown(&fx);
}
 
/*
 * The checkpoint fold must apply the replay's durability policy: an UPDATE
 * record whose referenced .cfp record is missing is skipped, not frozen
 * into the map right before the journal reset erases the evidence.
 */
static void
test_storage_fold_skips_missing_cfp(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    unsigned char page[TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    CfsMapEntry bogus;
    CfsJournalFoldResult res;
    off_t       jrn_size;
    int64       folded;
    bool        ok = true;
 
    cfs_storage_setup(&fx, "foldskip");
    if (fx.dir == NULL)
    {
        add_result("storage_fold_skips_missing_cfp", "fail", "setup failed");
        return;
    }
    cfs = cfs_storage_open_new(&fx);
 
    cfs_test_fill_page(page, 0x42);
    if (cfs_write_page(cfs, 0, (const char *) page, &opts) != CFS_STORAGE_OK ||
        cfs_map_save_snapshot(cfs) != CFS_STORAGE_OK)
        ok = false;
    test_journal_reset(cfs, ERROR);
 
    /*
     * A structurally valid UPDATE that points at a .cfp offset which was
     * never written: the record itself is durable, its data is not.
     */
    cfs_map_entry_init(&bogus);
    bogus.physical_offset = CFS_CFP_BASE_OFFSET + 1024 * 1024;
    bogus.compressed_size = 8;
    bogus.generation = cfs->map_hdr.max_generation + 1;
    cfs_map_entry_crc_set(&bogus);
    cfs_journal_append_update(cfs, 0, &bogus);
 
    jrn_size = cfs_fd_size(cfs->jrn_fd);
    if (jrn_size < (off_t) CFS_JOURNAL_HEADER_SIZE)
        ok = false;
    folded = ok ? cfs_journal_fold(cfs, CFS_JOURNAL_HEADER_SIZE, jrn_size,
                                   1, &res) : -1;
    if (folded != 0 || res.superseded_pages != 0)
        ok = false;
 
    /* The persisted row must still point at the original page. */
    if (ok)
    {
        cfs_close(cfs);
        cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path,
                             fx.map_path, fx.jrn_path, CFS_OPEN_RDWR);
        if (cfs_read_page(cfs, 0, (char *) back) != CFS_STORAGE_OK ||
            memcmp(page, back, TEST_BLCKSZ) != 0)
            ok = false;
    }
    cfs_close(cfs);
 
    add_result("storage_fold_skips_missing_cfp", ok ? "ok" : "fail",
               ok ? "row preserved" : "record was folded");
    cfs_storage_teardown(&fx);
}
 
/*
 * The apply engine's sink contract: an UPDATE whose update_usable hook
 * rejects it is not written but still occupies its generation, and a
 * RESIZE records its target.  One policy drives every replay path.
 */
static void
test_apply_write_row(void *arg, BlockNumber block, const CfsMapEntry *row)
{
    uint64     *n = (uint64 *) arg;
 
    (*n)++;
    (void) block;
    (void) row;
}
 
static void
test_apply_resize(void *arg, BlockNumber target)
{
    (void) arg;
    (void) target;
}
 
static bool
test_apply_never_usable(void *arg, const CfsJournalEntry *je)
{
    (void) arg;
    (void) je;
    return false;
}
 
static void
test_cfs_journal_apply_sink(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    CfsMapEntry entry;
    CfsJournalEntry je;
    CfsJournalSink sink;
    uint64      written = 0;
    bool        ok = true;
 
    cfs_storage_setup(&fx, "applysink");
    if (fx.dir == NULL)
    {
        add_result("journal_apply_policy", "fail", "setup failed");
        return;
    }
    cfs = cfs_storage_open_new(&fx);
 
    memset(&sink, 0, sizeof(sink));
    sink.write_row = test_apply_write_row;
    sink.resize = test_apply_resize;
    sink.update_usable = test_apply_never_usable;
    sink.arg = &written;
 
    memset(&je, 0, sizeof(je));
    je.op = CFS_JRN_OP_UPDATE;
    je.blocknum = 7;
    cfs_map_entry_init(&entry);
    entry.generation = 41;
    cfs_map_entry_crc_set(&entry);
    je.new_entry = entry;
 
    cfs_journal_apply_record(cfs, &je, &sink);
    if (written != 0 || sink.max_generation != 41)
        ok = false;             /* skipped, but the generation counts */
 
    je.op = CFS_JRN_OP_RESIZE;
    je.blocknum = 3;
    cfs_journal_apply_record(cfs, &je, &sink);
    if (!sink.have_resize || sink.resize_target != 3)
        ok = false;
 
    cfs_close(cfs);
    add_result("journal_apply_policy", ok ? "ok" : "fail",
               ok ? "one policy" : "sink contract broken");
    cfs_storage_teardown(&fx);
}
 
static void
cfs_test_seg_cb(BlockNumber blocknum, const CfsMapEntry *entry, void *arg)
{
    uint64     *applied = (uint64 *) arg;
 
    (void) blocknum;
    (void) entry;
    (*applied)++;
}
 
/*
 * The segment replay is where the pool sync and the scratch fallback reach the
 * journal, so it must reject a journal whose header does not validate before
 * it interprets any bytes as records.  After a reset the header is always
 * present, so a failure here is corruption, not a legitimate empty journal.
 * The error must be the corrupt-journal one and no record may reach the
 * callback.
 */
static void
test_storage_segment_replay_header(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    CfsJournalFileHeader hdr;
    unsigned char page[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    MemoryContext oldcontext = CurrentMemoryContext;
    uint64      applied = 0;
    char        detail[128];
    bool        rejected = false;
    bool        ok = true;
 
    cfs_storage_setup(&fx, "jreplayhdr");
    if (fx.dir == NULL)
    {
        add_result("storage_replay_bad_header", "fail", "setup failed");
        return;
    }
    cfs = cfs_storage_open_new(&fx);
 
    cfs_test_fill_page(page, 0x5a);
    if (cfs_write_page(cfs, 0, (const char *) page, &opts) != CFS_STORAGE_OK)
        ok = false;
 
    /* A real journal now exists; corrupt its magic in place. */
    if (ok && cfs_pread_all(cfs->jrn_fd, &hdr, sizeof(hdr), 0) != CFS_STORAGE_OK)
        ok = false;
    if (ok)
    {
        hdr.magic ^= 0xFF;
        if (cfs_pwrite_all(cfs->jrn_fd, &hdr, sizeof(hdr), 0) != CFS_STORAGE_OK)
            ok = false;
    }
 
    if (ok)
    {
        PG_TRY();
        {
            (void) cfs_journal_replay_segment(cfs, CFS_JOURNAL_HEADER_SIZE,
                                              0, cfs_test_seg_cb, &applied);
        }
        PG_CATCH();
        {
            ErrorData  *edata;
 
            /*
             * An ERROR leaves CurrentMemoryContext on ErrorContext; switch
             * back before copying, or the CopyErrorData assert trips.
             *
             * Outside recovery the header rejection is routed through
             * cfs_report_corruption() (QDB-1507 U8), so accept both the
             * historical direct message and the centralised one.
             */
            MemoryContextSwitchTo(oldcontext);
            edata = CopyErrorData();
            rejected = (edata->sqlerrcode == ERRCODE_DATA_CORRUPTED &&
                        edata->message != NULL &&
                        (strstr(edata->message,
                                "corrupt page map journal") != NULL ||
                         strstr(edata->message,
                                "checksum or format corruption") != NULL));
            FreeErrorData(edata);
            FlushErrorState();
        }
        PG_END_TRY();
    }
 
    if (!rejected || applied != 0)
        ok = false;
 
    cfs_close(cfs);
    if (ok)
        strlcpy(detail, "header rejected before any record", sizeof(detail));
    else
        snprintf(detail, sizeof(detail),
                 "rejected=%d records=%llu", rejected ? 1 : 0,
                 (unsigned long long) applied);
    add_result("storage_replay_bad_header", ok ? "ok" : "fail", detail);
    cfs_storage_teardown(&fx);
}
 
/*
 * Journal an UPDATE for blocknum carrying the given generation.  The
 * production write path journals every generation it allocates under the
 * same append lock; the counter test has to do the same, otherwise an
 * allocated-but-never-journaled value has no on-disk trace to be monotonic
 * against.
 */
static void
cfs_test_journal_generation(CfsRelation *cfs, BlockNumber blocknum,
                            uint32 generation)
{
    CfsMapEntry entry;
 
    cfs_map_entry_init(&entry);
    entry.physical_offset = CFS_CFP_BASE_OFFSET;
    entry.compressed_size = 8;
    entry.generation = generation;
    cfs_map_entry_crc_set(&entry);
    cfs_journal_append_update(cfs, blocknum, &entry);
}
 
/*
 * Relation-wide generation allocator (E1): the first value handed out must be
 * strictly above every generation the snapshot header or the journal still
 * holds, and values must never repeat, including after the metadata slot is
 * dropped and the counter re-seeds.  The test exercises the allocator
 * directly: cfs_write_page() is a single-threaded test/compaction helper that
 * keeps deriving the generation from the local map, the shared counter is
 * consumed by cfs_write_page_cached().
 */
static void
test_storage_next_generation(void)
{
    CfsStorageFixture fx;
    CfsRelation *h;
    CfsRelation *lazy;
    unsigned char page[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    char        detail[160];
    uint32      g1 = 0;
    uint32      g2 = 0;
    uint32      g3 = 0;
    uint32      g4 = 0;
    bool        ok = true;
 
    cfs_storage_setup(&fx, "nextgen");
    if (fx.dir == NULL)
    {
        add_result("storage_next_generation", "fail", "setup failed");
        return;
    }
    fx.rl.locator.relNumber = 800760;
    cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
    cfs_map_cache_pin(fx.rl, MAIN_FORKNUM);
 
    h = cfs_storage_open_new(&fx);
    cfs_test_fill_page(page, 0x51);
    cfs_write_page(h, 0, (const char *) page, &opts);   /* generation 1 */
    cfs_write_page(h, 0, (const char *) page, &opts);   /* generation 2 */
    if (cfs_map_save_snapshot(h) != CFS_STORAGE_OK) /* header watermark 2 */
        ok = false;
    /* Generation 3 stays journal-only: the on-disk header keeps 2. */
    cfs_write_page(h, 0, (const char *) page, &opts);
    cfs_close(h);
 
    /*
     * Drop the metadata slot.  The on-disk header still says 2 while the
     * journal tail holds 3: seeding from the header alone would return 3 and
     * reuse a generation the journal already carries.
     */
    cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM);
    cfs_map_cache_pin(fx.rl, MAIN_FORKNUM);
    lazy = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path, fx.map_path,
                          fx.jrn_path, CFS_OPEN_RDWR | CFS_OPEN_LAZY_MAP);
    if (lazy == NULL)
        ok = false;
    else
    {
        cfs_append_lock_acquire(fx.rl, MAIN_FORKNUM, LW_EXCLUSIVE);
        g1 = cfs_map_cache_next_generation(lazy);
        cfs_test_journal_generation(lazy, 0, g1);
        g2 = cfs_map_cache_next_generation(lazy);
        cfs_test_journal_generation(lazy, 0, g2);
        cfs_append_lock_release(fx.rl, MAIN_FORKNUM);
 
        /* Losing the slot must not recycle the generations just journaled. */
        cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM);
        cfs_map_cache_pin(fx.rl, MAIN_FORKNUM);
        cfs_append_lock_acquire(fx.rl, MAIN_FORKNUM, LW_EXCLUSIVE);
        g3 = cfs_map_cache_next_generation(lazy);
        cfs_test_journal_generation(lazy, 0, g3);
        g4 = cfs_map_cache_next_generation(lazy);
        cfs_append_lock_release(fx.rl, MAIN_FORKNUM);
 
        cfs_close(lazy);
    }
 
    if (g1 <= 3 || g2 <= g1 || g3 <= g2 || g4 <= g3)
        ok = false;
 
    cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM);
    cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
    cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM);
 
    snprintf(detail, sizeof(detail), "generations %u/%u/%u/%u %s",
             g1, g2, g3, g4,
             ok ? "monotonic above journal" : "reused or below journal");
    add_result("storage_next_generation", ok ? "ok" : "fail", detail);
    cfs_storage_teardown(&fx);
}
 
/*
 * Crash-recovery simulation: write several pages, close WITHOUT checkpoint
 * (so the .cfsmap snapshot stays empty and only the journal has the data),
 * then reopen and verify that journal replay reconstructs every page.
 */
static void
test_storage_journal_replay(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    unsigned char pages[5][TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    char        detail[128];
    int         i;
    bool        ok = true;
 
    cfs_storage_setup(&fx, "replay");
    if (fx.dir == NULL)
    {
        add_result("storage_journal_replay", "fail", "setup failed");
        return;
    }
    cfs = cfs_storage_open_new(&fx);
 
    for (i = 0; i < 5; i++)
    {
        cfs_test_fill_page(pages[i], (unsigned char) (0x40 + i));
        if (cfs_write_page(cfs, i, (const char *) pages[i], &opts) != CFS_STORAGE_OK)
        {
            ok = false;
            break;
        }
    }
    cfs_close(cfs);
 
    /* Reopen: snapshot is empty, journal must be replayed. */
    cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM,
                         fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR);
    if (cfs_map_nblocks(cfs) != 5)
        ok = false;
    for (i = 0; ok && i < 5; i++)
    {
        if (cfs_read_page(cfs, i, (char *) back) != CFS_STORAGE_OK ||
            memcmp(pages[i], back, TEST_BLCKSZ) != 0)
            ok = false;
    }
 
    /* Idempotency: replay again must not change anything. */
    {
        off_t       stop_off;
        bool        mid_file_stop = false;
 
        (void) cfs_journal_replay(cfs, &stop_off, &mid_file_stop, NULL, 0,
                                  CFS_LOAD_NORMAL);
        /* A fully valid journal must never be classified as mid-file torn. */
        if (mid_file_stop)
            ok = false;
    }
    for (i = 0; ok && i < 5; i++)
    {
        if (cfs_read_page(cfs, i, (char *) back) != CFS_STORAGE_OK ||
            memcmp(pages[i], back, TEST_BLCKSZ) != 0)
            ok = false;
    }
    cfs_close(cfs);
 
    snprintf(detail, sizeof(detail), "5 pages replayed %s",
             ok ? "ok" : "failed");
    add_result("storage_journal_replay", ok ? "ok" : "fail", detail);
    cfs_storage_teardown(&fx);
}
 
/*
 * Checkpoint: after writing, save a snapshot and truncate the journal, then
 * reopen and confirm the snapshot alone reproduces the data (0 replays).
 */
static void
test_storage_checkpoint(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    unsigned char page[TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    char        detail[128];
    bool        ok = true;
 
    cfs_storage_setup(&fx, "ckpt");
    if (fx.dir == NULL)
    {
        add_result("storage_checkpoint", "fail", "setup failed");
        return;
    }
    cfs = cfs_storage_open_new(&fx);
 
    cfs_test_fill_page(page, 0x50);
    cfs_write_page(cfs, 0, (const char *) page, &opts);
    cfs_write_page(cfs, 1, (const char *) page, &opts);
 
    /* Checkpoint: snapshot + journal reset. */
    cfs_map_save_snapshot(cfs);
    test_journal_reset(cfs, ERROR);
    cfs_close(cfs);
 
    /* Reopen: snapshot holds the data, journal is empty. */
    cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM,
                         fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR);
    if (cfs_map_nblocks(cfs) != 2)
        ok = false;
    if (cfs_read_page(cfs, 0, (char *) back) != CFS_STORAGE_OK ||
        memcmp(page, back, TEST_BLCKSZ) != 0)
        ok = false;
    if (cfs_read_page(cfs, 1, (char *) back) != CFS_STORAGE_OK ||
        memcmp(page, back, TEST_BLCKSZ) != 0)
        ok = false;
    cfs_close(cfs);
 
    snprintf(detail, sizeof(detail), "checkpoint+reopen %s",
             ok ? "ok" : "failed");
    add_result("storage_checkpoint", ok ? "ok" : "fail", detail);
    cfs_storage_teardown(&fx);
}
 
/*
 * A map entry whose compressed_size exceeds the page size (with a valid,
 * recomputed entry_crc — a "malicious" corruption) must be rejected at read
 * time as corruption instead of driving a palloc sized off the bogus field.
 */
static void
test_read_record_size_guard(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    unsigned char page[TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    CfsMapEntry e;
    int         fd;
    bool        ok = true;
 
    cfs_storage_setup(&fx, "sizeguard");
    if (fx.dir == NULL)
    {
        add_result("read_record_size_guard", "fail", "setup failed");
        return;
    }
    cfs = cfs_storage_open_new(&fx);
 
    cfs_test_fill_page(page, 0x11);
    if (cfs_write_page(cfs, 0, (const char *) page, &opts) != CFS_STORAGE_OK)
        ok = false;
 
    /* Persist a snapshot and drop the journal so the entry survives reopen. */
    if (ok)
    {
        cfs_map_save_snapshot(cfs);
        test_journal_reset(cfs, ERROR);
    }
    cfs_close(cfs);
 
    /* Inflate the on-disk entry's compressed_size and fix up its CRC. */
    fd = BasicOpenFile(fx.map_path, O_RDWR | PG_BINARY);
    if (fd < 0)
        ok = false;
    if (ok)
    {
        if (pread(fd, &e, sizeof(e), CFS_MAP_HEADER_SIZE) != sizeof(e))
            ok = false;
        else
        {
            e.compressed_size = CFS_BLCKSZ + 1;
            cfs_map_entry_crc_set(&e);
            if (pwrite(fd, &e, sizeof(e), CFS_MAP_HEADER_SIZE) != sizeof(e))
                ok = false;
        }
        close(fd);
    }
 
    /* The corrupted entry must come back as corruption, without OOM. */
    if (ok)
    {
        cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM,
                             fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR);
        if (cfs_read_page(cfs, 0, (char *) back) != CFS_STORAGE_CORRUPT)
            ok = false;
        cfs_close(cfs);
    }
 
    add_result("read_record_size_guard", ok ? "ok" : "fail",
               ok ? "inflated compressed_size rejected as CORRUPT"
               : "oversized record was not rejected");
    cfs_storage_teardown(&fx);
}
 
 
 
/*
 * A sparse hole (an all-zero row) is a legal
 * never-written block and reads as a zero page, not as corruption.
 */
static void
test_map_sparse_hole_zero_page(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    unsigned char page[TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    unsigned char zero[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    CfsMapEntry hole;
    int         fd;
    bool        ok = true;
 
    cfs_storage_setup(&fx, "sparsehole");
    if (fx.dir == NULL)
    {
        add_result("map_sparse_hole_zero_page", "fail", "setup failed");
        return;
    }
    cfs = cfs_storage_open_new(&fx);
 
    cfs_test_fill_page(page, 0x31);
    MemSet(zero, 0, sizeof(zero));
    if (cfs_write_page(cfs, 0, (const char *) page, &opts) != CFS_STORAGE_OK)
        ok = false;
    if (ok && cfs_map_save_snapshot(cfs) != CFS_STORAGE_OK)
        ok = false;
    if (ok)
        test_journal_reset(cfs, ERROR);
    cfs_close(cfs);
 
    /* Append an all-zero row for block 1, extending the file by one row. */
    if (ok)
    {
        fd = BasicOpenFile(fx.map_path, O_RDWR | PG_BINARY);
        if (fd < 0)
            ok = false;
        else
        {
            MemSet(&hole, 0, sizeof(hole));
            if (pwrite(fd, &hole, sizeof(hole),
                       CFS_MAP_HEADER_SIZE + CFS_MAP_ENTRY_SIZE)
                != sizeof(hole))
                ok = false;
            close(fd);
        }
    }
 
    /* The hole reads as a zero page; the written block keeps its data. */
    if (ok)
    {
        cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM,
                             fx.cfp_path, fx.map_path, fx.jrn_path,
                             CFS_OPEN_RDWR);
        if (cfs_map_nblocks(cfs) != 2 ||
            cfs_read_page(cfs, 1, (char *) back) != CFS_STORAGE_OK ||
            memcmp(zero, back, TEST_BLCKSZ) != 0 ||
            cfs_read_page(cfs, 0, (char *) back) != CFS_STORAGE_OK ||
            memcmp(page, back, TEST_BLCKSZ) != 0)
            ok = false;
        cfs_close(cfs);
    }
 
    add_result("map_sparse_hole_zero_page", ok ? "ok" : "fail",
               ok ? "sparse hole reads as a zero page"
               : "sparse hole mishandled");
    cfs_storage_teardown(&fx);
}
 
/*
 * A corrupt row whose block the journal still covers is
 * healed by the replay - the map reads back the correct data.
 */
static void
test_map_corrupt_row_healed(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    unsigned char page[TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    CfsMapEntry e;
    int         fd;
    bool        ok = true;
 
    cfs_storage_setup(&fx, "maphealed");
    if (fx.dir == NULL)
    {
        add_result("map_corrupt_row_healed", "fail", "setup failed");
        return;
    }
    cfs = cfs_storage_open_new(&fx);
 
    cfs_test_fill_page(page, 0x52);
    if (cfs_write_page(cfs, 0, (const char *) page, &opts) != CFS_STORAGE_OK)
        ok = false;
    /* Snapshot only: the journal record for block 0 stays in place. */
    if (ok && cfs_map_save_snapshot(cfs) != CFS_STORAGE_OK)
        ok = false;
    cfs_close(cfs);
 
    /* Break the on-disk row CRC; the journal record still covers block 0. */
    if (ok)
    {
        fd = BasicOpenFile(fx.map_path, O_RDWR | PG_BINARY);
        if (fd < 0)
            ok = false;
        else
        {
            if (pread(fd, &e, sizeof(e), CFS_MAP_HEADER_SIZE) != sizeof(e))
                ok = false;
            else
            {
                e.physical_offset ^= UINT64_C(1);
                if (pwrite(fd, &e, sizeof(e), CFS_MAP_HEADER_SIZE)
                    != sizeof(e))
                    ok = false;
            }
            close(fd);
        }
    }
 
    /* The replay must heal the row: the read returns the written data. */
    if (ok)
    {
        cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM,
                             fx.cfp_path, fx.map_path, fx.jrn_path,
                             CFS_OPEN_RDWR);
        if (cfs_read_page(cfs, 0, (char *) back) != CFS_STORAGE_OK ||
            memcmp(page, back, TEST_BLCKSZ) != 0)
            ok = false;
        cfs_close(cfs);
    }
 
    add_result("map_corrupt_row_healed", ok ? "ok" : "fail",
               ok ? "covering journal record healed the corrupt row"
               : "healing failed");
    cfs_storage_teardown(&fx);
}
 
/*
 * Crash-after-cfp simulation: write two blocks, then physically truncate the
 * last journal record (as if the process died after the .cfp append but
 * before the journal was durable).  After reopen the lost block must be
 * absent while the earlier block survives.
 */
static void
test_storage_crash_after_cfp(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    unsigned char page0[TEST_BLCKSZ];
    unsigned char page1[TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    char        detail[128];
    bool        ok = true;
 
    cfs_storage_setup(&fx, "crash");
    if (fx.dir == NULL)
    {
        add_result("storage_crash_after_cfp", "fail", "setup failed");
        return;
    }
    cfs = cfs_storage_open_new(&fx);
 
    cfs_test_fill_page(page0, 0x60);
    cfs_test_fill_page(page1, 0x70);
    cfs_write_page(cfs, 0, (const char *) page0, &opts);
    cfs_write_page(cfs, 1, (const char *) page1, &opts);
    cfs_close(cfs);
 
    /*
     * Remove block 1's journal records (its RESIZE + UPDATE), simulating a
     * crash that left block 1's journal entry torn.  Each extend-write now
     * appends a RESIZE followed by an UPDATE, so block 0 occupies the first
     * two records of the journal.
     */
    {
        off_t       keep = CFS_JOURNAL_HEADER_SIZE + 2 * CFS_JOURNAL_ENTRY_SIZE;
 
        if (pg_truncate(fx.jrn_path, keep) != 0)
            ok = false;
    }
 
    /* Reopen: only block 0 should be recoverable. */
    cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM,
                         fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR);
    if (cfs_map_nblocks(cfs) != 1)
        ok = false;
    if (cfs_read_page(cfs, 0, (char *) back) != CFS_STORAGE_OK ||
        memcmp(page0, back, TEST_BLCKSZ) != 0)
        ok = false;
    cfs_close(cfs);
 
    snprintf(detail, sizeof(detail), "nblocks=%u after trunc",
             ok ? 1u : 0u);
    add_result("storage_crash_after_cfp", ok ? "ok" : "fail", detail);
    cfs_storage_teardown(&fx);
}
 
 
static void
test_storage_zero_extend_truncate(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    unsigned char back[TEST_BLCKSZ];
    unsigned char zero[TEST_BLCKSZ];
    off_t       jrn_after_extend;
    char        detail[160];
    bool        ok = true;
 
    cfs_storage_setup(&fx, "ext");
    if (fx.dir == NULL)
    {
        add_result("storage_zero_extend_truncate", "fail", "setup failed");
        return;
    }
    cfs = cfs_storage_open_new(&fx);
 
    MemSet(zero, 0, TEST_BLCKSZ);
 
    /* Extend by 4 zero blocks. */
    if (cfs_zero_extend(cfs, 0, 4) != CFS_STORAGE_OK ||
        cfs_map_nblocks(cfs) != 4)
        ok = false;
 
    /*
     * zero_extend must journal only a single RESIZE record (header + one
     * entry), not one UPDATE per extended block.  A larger journal would mean
     * the per-block UPDATE loop is back.
     */
    jrn_after_extend = cfs->jrn_write_off;
    if (jrn_after_extend !=
        (off_t) (CFS_JOURNAL_HEADER_SIZE + CFS_JOURNAL_ENTRY_SIZE))
        ok = false;
 
    /* Zero blocks must read back as all-zero pages. */
    if (ok && (cfs_read_page(cfs, 2, (char *) back) != CFS_STORAGE_OK ||
               memcmp(back, zero, TEST_BLCKSZ) != 0))
        ok = false;
 
    /* Truncate to 1 block. */
    if (ok && cfs_truncate(cfs, 1) != CFS_STORAGE_OK)
        ok = false;
    if (ok && cfs_map_nblocks(cfs) != 1)
        ok = false;
    cfs_close(cfs);
 
    snprintf(detail, sizeof(detail),
             "extend+truncate %s (journal after extend=%lld, expect=%lld)",
             ok ? "ok" : "failed",
             (long long) jrn_after_extend,
             (long long) (CFS_JOURNAL_HEADER_SIZE + CFS_JOURNAL_ENTRY_SIZE));
    add_result("storage_zero_extend_truncate", ok ? "ok" : "fail", detail);
    cfs_storage_teardown(&fx);
}
 
/*
 * cfs_zero_extend must reject a start/count pair whose sum overflows
 * BlockNumber (and would otherwise wrap to a tiny nblocks), instead of
 * silently extending to a wrong size.
 */
static void
test_storage_zero_extend_overflow(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    MemoryContext oldcontext = CurrentMemoryContext;
    bool        raised = false;
    bool        ok = true;
 
    cfs_storage_setup(&fx, "ext_ovf");
    if (fx.dir == NULL)
    {
        add_result("storage_zero_extend_overflow", "fail", "setup failed");
        return;
    }
    cfs = cfs_storage_open_new(&fx);
 
    /*
     * MaxBlockNumber - 2 + 4 exceeds MaxBlockNumber: this must raise an ERROR
     * (ERRCODE_PROGRAM_LIMIT_EXCEEDED) rather than wrap around.
     */
    PG_TRY();
    {
        cfs_zero_extend(cfs, (BlockNumber) (MaxBlockNumber - 2), 4);
        raised = false;
    }
    PG_CATCH();
    {
        ErrorData  *edata;
 
        MemoryContextSwitchTo(oldcontext);
        edata = CopyErrorData();
        raised = (edata->sqlerrcode == ERRCODE_PROGRAM_LIMIT_EXCEEDED);
        FlushErrorState();
    }
    PG_END_TRY();
 
    if (!raised)
        ok = false;
 
    /*
     * A start beyond MaxBlockNumber must also be rejected.  With only "count
     * > MaxBlockNumber - start" the subtraction wraps when start is
     * InvalidBlockNumber, the guard passes, and end = start + count silently
     * wraps to a tiny nblocks.  start=InvalidBlockNumber, count=2 -> end=1.
     */
    PG_TRY();
    {
        cfs_zero_extend(cfs, InvalidBlockNumber, 2);
        raised = false;
    }
    PG_CATCH();
    {
        ErrorData  *edata;
 
        MemoryContextSwitchTo(oldcontext);
        edata = CopyErrorData();
        raised = (edata->sqlerrcode == ERRCODE_PROGRAM_LIMIT_EXCEEDED);
        FlushErrorState();
    }
    PG_END_TRY();
 
    if (!raised)
        ok = false;
 
    /* The overflow must be rejected before any state change: nblocks == 0. */
    if (ok && cfs_map_nblocks(cfs) != 0)
        ok = false;
 
    cfs_close(cfs);
    cfs_storage_teardown(&fx);
 
    add_result("storage_zero_extend_overflow", ok ? "ok" : "fail",
               ok ? "overflow rejected with ERRCODE_PROGRAM_LIMIT_EXCEEDED"
               : "overflow not rejected");
}
 
/*
 * TRUNCATE must journal a single RESIZE (whose replay invalidates the
 * dropped slots), not one DELETE per removed block.  Verify the journal has
 * no DELETE records, replay restores nblocks and invalidates the dropped
 * slots, and re-extending does not resurrect the truncated entries.
 */
static void
test_storage_truncate_journal_resize_only(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    unsigned char page[TEST_BLCKSZ];
    unsigned char zero[TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    off_t       off;
    int         n_resizes = 0;
    int         n_deletes = 0;
    char        detail[160];
    int         i;
    bool        ok = true;
 
    cfs_storage_setup(&fx, "trjrn");
    if (fx.dir == NULL)
    {
        add_result("storage_truncate_journal_resize_only", "fail", "setup failed");
        return;
    }
    cfs = cfs_storage_open_new(&fx);
    cfs_test_fill_page(page, 0x71);
    MemSet(zero, 0, TEST_BLCKSZ);
 
    /* Write 6 live blocks so the old code path would have journaled DELETEs. */
    for (i = 0; i < 6 && ok; i++)
    {
        if (cfs_write_page(cfs, i, (const char *) page, &opts) !=
            CFS_STORAGE_OK)
            ok = false;
    }
 
    /* Truncate to 2 blocks. */
    if (ok && cfs_truncate(cfs, 2) != CFS_STORAGE_OK)
        ok = false;
    if (ok && cfs_map_nblocks(cfs) != 2)
        ok = false;
 
    /* The journal must contain no DELETE records. */
    for (off = CFS_JOURNAL_HEADER_SIZE; ok; off += sizeof(CfsJournalEntry))
    {
        CfsJournalEntry je;
        ssize_t     n;
 
        n = pread(cfs->jrn_fd, &je, sizeof(je), off);
        if (n != (ssize_t) sizeof(je))
            break;
        if (cfs_journal_entry_validate(&je) != CFS_FORMAT_OK)
            break;
        if (je.op == CFS_JRN_OP_RESIZE)
            n_resizes++;
        else if (je.op == CFS_JRN_OP_DELETE)
            n_deletes++;
    }
    if (ok && (n_resizes < 1 || n_deletes != 0))
        ok = false;
 
    /* Reopen: replay must restore nblocks=2 and invalidate dropped slots. */
    cfs_close(cfs);
    cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM,
                         fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR);
    if (ok && cfs_map_nblocks(cfs) != 2)
        ok = false;
    if (ok && cfs->map[4].physical_offset != CFS_ENTRY_INVALID_OFFSET)
        ok = false;             /* dropped slot must be invalid */
 
    /* Re-extending must not resurrect the truncated block. */
    if (ok && cfs_zero_extend(cfs, 2, 4) != CFS_STORAGE_OK)
        ok = false;
    if (ok && (cfs_read_page(cfs, 4, (char *) back) != CFS_STORAGE_OK ||
               memcmp(back, zero, TEST_BLCKSZ) != 0))
        ok = false;             /* pre-truncate content resurrected */
 
    cfs_close(cfs);
 
    snprintf(detail, sizeof(detail), "resizes=%d deletes=%d %s",
             n_resizes, n_deletes, ok ? "replay+reextend ok" : "failed");
    add_result("storage_truncate_journal_resize_only", ok ? "ok" : "fail", detail);
    cfs_storage_teardown(&fx);
}
 
/*
 * A failure inside cfs_reopen() must close every descriptor it has
 * opened so far and reset it to -1, so a later cfs_close() never closes a
 * recycled fd number.  The handle itself stays owned by the caller.
 */
static void
test_storage_reopen_closes_fds_on_error(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    MemoryContext oldcontext = CurrentMemoryContext;
    bool        raised = false;
    bool        ok = true;
 
    cfs_storage_setup(&fx, "reopen");
    if (fx.dir == NULL)
    {
        add_result("storage_reopen_closes_fds_on_error", "fail", "setup failed");
        return;
    }
    cfs = cfs_storage_open_new(&fx);
 
    /* Drop the .cfsmap so the reopen fails after opening .cfp/.cfsjrn. */
    if (unlink(fx.map_path) != 0)
        ok = false;
 
    PG_TRY();
    {
        cfs_reopen(cfs);
    }
    PG_CATCH();
    {
        MemoryContextSwitchTo(oldcontext);
        FlushErrorState();
        raised = true;
    }
    PG_END_TRY();
 
    if (!raised)
        ok = false;
 
    /* After the ERROR every descriptor must be reset to -1. */
    if (ok && (cfs->cfp_fd != -1 || cfs->cfp_read_fd != -1 ||
               cfs->map_fd != -1 || cfs->jrn_fd != -1))
        ok = false;
 
    cfs_close(cfs);
    cfs_storage_teardown(&fx);
 
    add_result("storage_reopen_closes_fds_on_error", ok ? "ok" : "fail",
               raised ? "fds reset after reopen error" : "reopen error not raised");
}
 
/*
 * cfs_unlink must also remove the artifacts of an interrupted
 * compaction swap (the .cfsswap commit marker plus the .new / .tmp
 * candidates of the map and of every .cfp segment), so a dropped relation
 * leaves a clean directory even after a failed compaction.
 */
static void
test_storage_unlink_swap_artifacts(void)
{
    RelFileLocatorBackend rl;
    CfsRelation *cfs;
    char       *paths[8];
    bool        ok = true;
    int         i;
 
    /* Use a high relNumber in the current database to avoid collisions. */
    rl.locator.spcOid = DEFAULTTABLESPACE_OID;
    rl.locator.dbOid = MyDatabaseId;
    rl.locator.relNumber = 999089;
    rl.backend = INVALID_PROC_NUMBER;
 
    cfs_test_unlink_synthetic(rl);
 
    cfs = cfs_open(rl, MAIN_FORKNUM, CFS_OPEN_RDWR | CFS_OPEN_CREATE);
    if (cfs == NULL)
    {
        add_result("storage_unlink_swap_artifacts", "fail", "open failed");
        return;
    }
 
    /* Simulate the artifacts of an interrupted compaction swap. */
    paths[0] = psprintf("%s%s", cfs->cfp_path, ".cfsswap");
    paths[1] = psprintf("%s%s", cfs->cfp_path, ".new");
    paths[2] = psprintf("%s.tmp", cfs->cfp_path);
    paths[3] = psprintf("%s%s", cfs->map_path, ".new");
    paths[4] = psprintf("%s.tmp", cfs->map_path);
    paths[5] = pstrdup(cfs->cfp_path);
    paths[6] = pstrdup(cfs->map_path);
    paths[7] = pstrdup(cfs->jrn_path);
 
    for (i = 0; i < 5; i++)
    {
        const char  junk = 'x';
 
        if (!cfs_test_write_file(paths[i], &junk, 1))
            ok = false;
    }
 
    cfs_close(cfs);
    cfs_test_unlink_synthetic(rl);
 
    /* Nothing of the sidecar trio or the swap artifacts may survive. */
    for (i = 0; i < 8; i++)
    {
        struct stat st;
 
        if (ok && stat(paths[i], &st) == 0)
            ok = false;
        pfree(paths[i]);
    }
 
    add_result("storage_unlink_swap_artifacts", ok ? "ok" : "fail",
               ok ? "marker and .new/.tmp candidates removed"
               : "swap artifacts survived the drop");
}
 
/*
 * Scan the journal of 'cfs' and report how many RESIZE records it holds plus
 * the nblocks value of the last one (0 when none).  The single-block extend
 * path (cfs_write_page) must emit a RESIZE so that journal replay restores
 * nblocks deterministically, independent of the order UPDATE records are
 * applied.
 */
static void
cfs_test_count_journal_resizes(CfsRelation *cfs, int *n_resizes,
                               uint32 *last_nblocks)
{
    off_t       off;
    int         count = 0;
    uint32      last = 0;
 
    for (off = CFS_JOURNAL_HEADER_SIZE;; off += sizeof(CfsJournalEntry))
    {
        CfsJournalEntry je;
        ssize_t     n;
 
        n = pread(cfs->jrn_fd, &je, sizeof(je), off);
        if (n != (ssize_t) sizeof(je))
            break;
        if (cfs_journal_entry_validate(&je) != CFS_FORMAT_OK)
            break;
        if (je.op == CFS_JRN_OP_RESIZE)
        {
            count++;
            last = je.blocknum;
        }
    }
    *n_resizes = count;
    *last_nblocks = last;
}
 
/*
 * A pure map lookup must never change the logical size of the relation:
 * cfs_map_get_entry() may grow the internal array capacity, but nblocks is an
 * explicit operation performed only at genuine extend points.
 */
static void
test_storage_lookup_no_implicit_growth(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    char        detail[128];
    bool        ok = true;
 
    cfs_storage_setup(&fx, "lookup");
    if (fx.dir == NULL)
    {
        add_result("storage_lookup_no_implicit_growth", "fail", "setup failed");
        return;
    }
    cfs = cfs_storage_open_new(&fx);
 
    /* A lookup beyond the current size must not grow nblocks. */
    (void) cfs_map_get_entry(cfs, 10);
    if (cfs_map_nblocks(cfs) != 0)
        ok = false;
 
    snprintf(detail, sizeof(detail), "lookup nblocks=%u (expect 0)",
             cfs_map_nblocks(cfs));
    add_result("storage_lookup_no_implicit_growth", ok ? "ok" : "fail", detail);
    cfs_close(cfs);
    cfs_storage_teardown(&fx);
}
 
/*
 * A single-block extend through cfs_write_page() (the path taken by, e.g.,
 * index builds via cfs_smgr_extend) must journal an explicit RESIZE record,
 * exactly like cfs_zero_extend() does, so recovery restores nblocks without
 * depending on the order UPDATE records are replayed.
 */
static void
test_storage_write_page_journals_resize(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    unsigned char page[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    int         n_resizes = 0;
    uint32      last_resize = 0;
    char        detail[160];
    bool        ok = true;
 
    cfs_storage_setup(&fx, "wresize");
    if (fx.dir == NULL)
    {
        add_result("storage_write_page_journals_resize", "fail", "setup failed");
        return;
    }
    cfs = cfs_storage_open_new(&fx);
 
    cfs_test_fill_page(page, 0x60);
 
    /* Extend by a single block at index 5 (nblocks 0 -> 6). */
    if (cfs_write_page(cfs, 5, (const char *) page, &opts) != CFS_STORAGE_OK)
        ok = false;
    if (ok && cfs_map_nblocks(cfs) != 6)
        ok = false;
 
    /* The journal must contain a RESIZE record to nblocks=6. */
    cfs_test_count_journal_resizes(cfs, &n_resizes, &last_resize);
    if (ok && (n_resizes < 1 || last_resize != 6))
        ok = false;
 
    snprintf(detail, sizeof(detail),
             "nblocks=%u resizes=%d last_resize=%u (expect nblocks=6, resize=6)",
             cfs_map_nblocks(cfs), n_resizes, last_resize);
    add_result("storage_write_page_journals_resize", ok ? "ok" : "fail", detail);
    cfs_close(cfs);
    cfs_storage_teardown(&fx);
}
 
/*
 * Compaction test using the relation-locator API.  Updates one block many
 * times to accumulate dead records, compacts, and verifies the live data is
 * intact and the .cfp shrank.
 */
static void
test_storage_compaction(void)
{
    RelFileLocatorBackend rl;
    unsigned char page[TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    CfsCompactOptions copts = CFS_COMPACT_OPTIONS_DEFAULT;
    CfsCompactResult cres;
    CfsRelation *cfs;
    uint64      old_cfp = 0;
    char        detail[160];
    bool        ok = true;
    int         i;
 
    /* Use a high relNumber in the current database to avoid collisions. */
    rl.locator.spcOid = DEFAULTTABLESPACE_OID;
    rl.locator.dbOid = MyDatabaseId;
    rl.locator.relNumber = 999090;
    rl.backend = INVALID_PROC_NUMBER;
 
    cfs_test_unlink_synthetic(rl);
 
    cfs = cfs_create(rl, MAIN_FORKNUM);
    cfs_test_fill_page(page, 0x90);
 
    /* Repeatedly update block 0 to create many dead records. */
    for (i = 0; i < 60; i++)
    {
        page[0] = (unsigned char) i;
        if (cfs_write_page(cfs, 0, (const char *) page, &opts) != CFS_STORAGE_OK)
        {
            ok = false;
            break;
        }
    }
    old_cfp = cfs->cfp_write_off;
    cfs_close(cfs);
 
    if (ok && cfs_compact_relation(rl, MAIN_FORKNUM, &copts, &cres, InvalidOid) != CFS_STORAGE_OK)
        ok = false;
 
    if (ok)
    {
        cfs = cfs_open(rl, MAIN_FORKNUM, CFS_OPEN_RDWR);
        if (cfs == NULL)
            ok = false;
        else
        {
            if (cfs_read_page(cfs, 0, (char *) back) != CFS_STORAGE_OK ||
                memcmp(back, page, TEST_BLCKSZ) != 0)
                ok = false;
            if (cfs->cfp_write_off >= (off_t) old_cfp)
                ok = false;     /* compaction must shrink .cfp */
            cfs_close(cfs);
        }
    }
 
    cfs_test_unlink_synthetic(rl);
 
    snprintf(detail, sizeof(detail),
             "cfp %llu -> %llu bytes, live=%llu",
             (unsigned long long) old_cfp,
             (unsigned long long) cres.new_cfp_size,
             (unsigned long long) cres.live_blocks);
    add_result("storage_compaction", ok ? "ok" : "fail", detail);
}
 
/*
 * The dead-space accounting must not count the .cfp segments' rollover
 * padding as dead bytes: a record never crosses a segment boundary, so a
 * closed segment simply ends short of CFS_SEGMENT_SIZE, and that unwritten
 * tail is neither live data nor reclaimable by compaction.  The chain is
 * crafted directly as sparse files (the sizes matter, the content does
 * not): seg0 short by exactly PAD bytes, seg1 the small, still-growing
 * tail.
 */
static void
test_storage_chain_padding(void)
{
    CfsStorageFixture fx;
    uint64      total = 0;
    uint64      padding = ~(uint64) 0;
    const uint64 pad = 4096;
    uint64      pad_exact = ~(uint64) 0;
    uint64      pad_short = ~(uint64) 0;
    char        detail[160];
    bool        ok = true;
    int         fd;
 
    cfs_storage_setup(&fx, "chainpad");
    if (fx.dir == NULL)
    {
        add_result("storage_chain_padding", "fail", "setup failed");
        return;
    }
 
    /* Case 1: seg0 closed PAD bytes short, seg1 the growing tail. */
    fd = BasicOpenFile(fx.cfp_path, O_CREAT | O_RDWR | PG_BINARY);
    if (fd < 0 ||
        ftruncate(fd, (off_t) CFS_SEGMENT_SIZE - (off_t) pad) != 0)
        ok = false;
    if (fd >= 0)
        close(fd);
    {
        char       *seg1 = psprintf("%s.1", fx.cfp_path);
 
        fd = BasicOpenFile(seg1, O_CREAT | O_RDWR | PG_BINARY);
        if (fd < 0 || ftruncate(fd, 8192) != 0)
            ok = false;
        if (fd >= 0)
            close(fd);
        pfree(seg1);
    }
    if (ok && (!cfs_cfp_chain_stat(fx.cfp_path, &total, &padding) ||
               total != (uint64) CFS_SEGMENT_SIZE + 8192 ||
               padding != pad))
    {
        snprintf(detail, sizeof(detail),
                 "two segments: total=%llu padding=%llu (want %llu/%llu)",
                 (unsigned long long) total,
                 (unsigned long long) padding,
                 (unsigned long long) ((uint64) CFS_SEGMENT_SIZE + 8192),
                 (unsigned long long) pad);
        add_result("storage_chain_padding", "fail", detail);
        cfs_storage_teardown(&fx);
        return;
    }
 
    /*
     * Case 2: a single segment filled EXACTLY to the boundary - the lazy
     * rollover state (the next segment appears on the next append).  Its tail
     * must not be padding: an underflow here used to wrap the unsigned
     * arithmetic and report a huge value.
     */
    fd = BasicOpenFile(fx.cfp_path, O_RDWR | PG_BINARY);
    if (fd < 0 || ftruncate(fd, (off_t) CFS_SEGMENT_SIZE) != 0)
        ok = false;
    if (fd >= 0)
        close(fd);
    {
        char       *seg1 = psprintf("%s.1", fx.cfp_path);
 
        unlink(seg1);
        pfree(seg1);
    }
    if (ok && (!cfs_cfp_chain_stat(fx.cfp_path, &total, &padding) ||
               total != (uint64) CFS_SEGMENT_SIZE ||
               padding != 0))
        ok = false;
    pad_exact = padding;
 
    /* Case 3: a single short segment has no closed segment at all. */
    if (ok)
    {
        fd = BasicOpenFile(fx.cfp_path, O_RDWR | PG_BINARY);
        if (fd < 0 || ftruncate(fd, (off_t) CFS_SEGMENT_SIZE - 8192) != 0)
            ok = false;
        if (fd >= 0)
            close(fd);
        if (!cfs_cfp_chain_stat(fx.cfp_path, &total, &padding) ||
            total != (uint64) CFS_SEGMENT_SIZE - 8192 ||
            padding != 0)
            ok = false;
        pad_short = padding;
    }
 
    snprintf(detail, sizeof(detail),
             "exact-full pad=%llu, short-single pad=%llu",
             (unsigned long long) pad_exact,
             (unsigned long long) pad_short);
    add_result("storage_chain_padding", ok ? "ok" : "fail", detail);
    cfs_storage_teardown(&fx);
}
 
/*
 * Journal ABA hardening: a backend whose delta-replay cursor points into a
 * journal that was reset (checkpoint truncate / compaction swap) and then
 * grew back past the old cursor must not replay from the stale offset -
 * records sitting between the header and the cursor belong to the new
 * journal incarnation and would be silently skipped.  The refresh must
 * detect the incarnation change and do a full reload instead.
 *
 * Layout (journal records are 48 bytes, header 24):
 *   - h1 writes blocks 0..2   -> journal size 168, replay cursor synced=168
 *   - journal reset           -> size 24 (incarnation bumped, when supported)
 *   - h2 appends 5 records    -> size 264 > 168: the ABA state
 * A size-only check replays from offset 168 of the NEW journal, skipping
 * the RESIZE and the block-0/block-3 updates.
 */
static void
test_storage_journal_incarnation(void)
{
    CfsStorageFixture fx;
    CfsRelation *h1;
    CfsRelation *h2;
    unsigned char page0_v1[TEST_BLCKSZ];
    unsigned char page0_v2[TEST_BLCKSZ];
    unsigned char page3[TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    char        detail[128];
    bool        ok = true;
 
    cfs_storage_setup(&fx, "jrninc");
    if (fx.dir == NULL)
    {
        add_result("storage_journal_incarnation", "fail", "setup failed");
        return;
    }
 
    h1 = cfs_storage_open_new(&fx);
 
    /* Baseline: three writes, a snapshot, and a synced replay cursor. */
    cfs_test_fill_page(page0_v1, 0x41);
    if (cfs_write_page(h1, 0, (const char *) page0_v1, &opts) != CFS_STORAGE_OK ||
        cfs_write_page(h1, 1, (const char *) page0_v1, &opts) != CFS_STORAGE_OK ||
        cfs_write_page(h1, 2, (const char *) page0_v1, &opts) != CFS_STORAGE_OK)
        ok = false;
    if (ok && cfs_map_save_snapshot(h1) != CFS_STORAGE_OK)
        ok = false;
    if (ok && cfs_refresh_map(h1, true, CFS_LOAD_NORMAL) != CFS_STORAGE_OK)
        ok = false;
 
    /* Another actor resets the journal (checkpoint / compaction swap). */
    if (ok)
        cfs_journal_reset_file(fx.jrn_path, 0);
 
    /* The journal regrows past the old cursor: the ABA window. */
    cfs_test_fill_page(page0_v2, 0x42);
    cfs_test_fill_page(page3, 0x43);
    h2 = cfs_open_paths(fx.rl, MAIN_FORKNUM,
                        fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR);
    if (cfs_zero_extend(h2, 3, 3) != CFS_STORAGE_OK ||
        cfs_write_page(h2, 0, (const char *) page0_v2, &opts) != CFS_STORAGE_OK ||
        cfs_write_page(h2, 3, (const char *) page3, &opts) != CFS_STORAGE_OK ||
        cfs_write_page(h2, 4, (const char *) page3, &opts) != CFS_STORAGE_OK ||
        cfs_write_page(h2, 5, (const char *) page3, &opts) != CFS_STORAGE_OK)
        ok = false;
 
    /* The stale handle must notice the reset, not replay from offset 168. */
    if (ok && cfs_refresh_map(h1, true, CFS_LOAD_NORMAL) != CFS_STORAGE_OK)
        ok = false;
    if (ok && (cfs_read_page(h1, 0, (char *) back) != CFS_STORAGE_OK ||
               memcmp(page0_v2, back, TEST_BLCKSZ) != 0))
        ok = false;             /* block 0 update was skipped */
    if (ok && (cfs_read_page(h1, 3, (char *) back) != CFS_STORAGE_OK ||
               memcmp(page3, back, TEST_BLCKSZ) != 0))
        ok = false;             /* block 3 update was skipped */
    if (ok && cfs_map_nblocks(h1) != 6)
        ok = false;             /* RESIZE record was skipped */
 
    cfs_close(h2);
    cfs_close(h1);
 
    snprintf(detail, sizeof(detail), "truncate+regrow replay %s",
             ok ? "reloaded" : "started at stale offset");
    add_result("storage_journal_incarnation", ok ? "ok" : "fail", detail);
    cfs_storage_teardown(&fx);
}
 
/*
 * Snapshot reload must not resurrect pre-truncate data.
 *
 * A stale handle whose in-memory map array still covers the pre-truncate
 * size reloads the map after another actor truncated the relation and
 * checkpointed (snapshot with the smaller nblocks + journal reset).  The
 * reload reads only nblocks entries, so the array slots beyond nblocks keep
 * the pre-truncate entries unless the load re-initialises them.  Extending
 * the relation back over those slots must yield zero pages, never the data
 * that lived there before the truncate.
 */
static void
test_storage_snapshot_tail_invalidated(void)
{
    CfsStorageFixture fx;
    CfsRelation *h1;
    CfsRelation *h2;
    unsigned char page[TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    unsigned char zero[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    char        detail[128];
    int         i;
    bool        ok = true;
 
    cfs_storage_setup(&fx, "snaptail");
    if (fx.dir == NULL)
    {
        add_result("storage_snapshot_tail_invalidated", "fail", "setup failed");
        return;
    }
 
    h1 = cfs_storage_open_new(&fx);
    MemSet(zero, 0, TEST_BLCKSZ);
    cfs_test_fill_page(page, 0x60);
 
    /* h1: 200 written blocks, a snapshot, and a synced replay cursor. */
    for (i = 0; i < 200; i++)
    {
        if (cfs_write_page(h1, i, (const char *) page, &opts) != CFS_STORAGE_OK)
        {
            ok = false;
            break;
        }
    }
    if (ok && cfs_map_save_snapshot(h1) != CFS_STORAGE_OK)
        ok = false;
    if (ok && cfs_refresh_map(h1, true, CFS_LOAD_NORMAL) != CFS_STORAGE_OK)
        ok = false;
 
    /* Another actor truncates to 50 blocks and checkpoints. */
    h2 = cfs_open_paths(fx.rl, MAIN_FORKNUM,
                        fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR);
    if (ok && cfs_truncate(h2, 50) != CFS_STORAGE_OK)
        ok = false;
    if (ok && cfs_map_save_snapshot(h2) != CFS_STORAGE_OK)
        ok = false;
    if (ok)
        test_journal_reset(h2, ERROR);
 
    /*
     * Reload the map in h1's handle without recreating the array: only 50
     * entries come from the snapshot, while the array still covers the
     * pre-truncate size.  The snapshot save swapped the .cfsmap inode (atomic
     * rename), so repoint h1's descriptor at the current file first, exactly
     * as the non-swap full-reload branch of cfs_refresh_map() would see it.
     * (cfs_refresh_map() itself is not used here: the inode swap would steer
     * it into cfs_reopen(), which drops the whole array and cannot exhibit
     * the defect.)
     */
    if (ok)
    {
        close(h1->map_fd);
        h1->map_fd = BasicOpenFile(fx.map_path, O_RDWR | PG_BINARY);
        if (h1->map_fd < 0 || cfs_map_load(h1, true, CFS_LOAD_NORMAL) != CFS_STORAGE_OK)
            ok = false;
    }
    if (ok && cfs_map_nblocks(h1) != 50)
        ok = false;
 
    /* Extending back to 200 must surface zero pages, not pre-truncate data. */
    if (ok && cfs_zero_extend(h1, 50, 150) != CFS_STORAGE_OK)
        ok = false;
    if (ok && cfs_map_nblocks(h1) != 200)
        ok = false;
    if (ok && (cfs_read_page(h1, 100, (char *) back) != CFS_STORAGE_OK ||
               memcmp(back, zero, TEST_BLCKSZ) != 0))
        ok = false;             /* pre-truncate content resurrected */
 
    cfs_close(h2);
    cfs_close(h1);
 
    snprintf(detail, sizeof(detail),
             "truncate+reload+extend block 100 %s",
             ok ? "reads zero page" : "resurrected pre-truncate data");
    add_result("storage_snapshot_tail_invalidated", ok ? "ok" : "fail", detail);
    cfs_storage_teardown(&fx);
}
 
/*
 * A snapshot must record the real .cfp end-of-file, not the handle's
 * possibly stale append cursor.  A handle that has not appended since another
 * backend wrote more records would otherwise persist a cfp_size smaller than
 * the actual data chain.
 */
static void
test_storage_snapshot_cfp_size_from_eof(void)
{
    CfsStorageFixture fx;
    CfsRelation *h1;
    CfsRelation *h2;
    unsigned char page[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    struct stat st;
    uint64      reported = 0;
    uint64      real_eof = 0;
    char        detail[160];
    int         i;
    bool        ok = true;
 
    cfs_storage_setup(&fx, "cfpsize");
    if (fx.dir == NULL)
    {
        add_result("storage_snapshot_cfp_size_from_eof", "fail", "setup failed");
        return;
    }
 
    h1 = cfs_storage_open_new(&fx);
    cfs_test_fill_page(page, 0x70);
 
    /* h1 writes one block; its append cursor stops there. */
    if (cfs_write_page(h1, 0, (const char *) page, &opts) != CFS_STORAGE_OK)
        ok = false;
 
    /*
     * A second handle appends more blocks, advancing the real .cfp EOF past
     * h1's cursor.  h1 never learns about these appends (its local cursor is
     * not refreshed), which is exactly the stale-cursor case.
     */
    h2 = cfs_open_paths(fx.rl, MAIN_FORKNUM,
                        fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR);
    for (i = 1; i <= 3 && ok; i++)
    {
        if (cfs_write_page(h2, i, (const char *) page, &opts) !=
            CFS_STORAGE_OK)
            ok = false;
    }
 
    /* h1's snapshot must record the real .cfp EOF, not its stale cursor. */
    if (ok && cfs_map_save_snapshot(h1) != CFS_STORAGE_OK)
        ok = false;
 
    reported = h1->map_hdr.cfp_size;
    if (ok && stat(fx.cfp_path, &st) != 0)
        ok = false;
    real_eof = (uint64) st.st_size;
 
    if (ok && reported != real_eof)
        ok = false;
 
    cfs_close(h2);
    cfs_close(h1);
 
    snprintf(detail, sizeof(detail), "cfp_size=%llu eof=%llu %s",
             (unsigned long long) reported, (unsigned long long) real_eof,
             ok ? "match" : "mismatch");
    add_result("storage_snapshot_cfp_size_from_eof", ok ? "ok" : "fail", detail);
    cfs_storage_teardown(&fx);
}
 
/*
 * Torn-record visibility on the delta-replay read path.
 *
 * A reader refreshing its local map stops the journal delta replay at the
 * first invalid (torn) record.  This is the correct crash-recovery
 * semantics, but it is also exactly the mechanism that turns a record seen
 * *during* a concurrent append into a silent stale read: the reader settles
 * on the previous version and never sees the committed update, with no
 * error.  The read-path append-lock coordination (cfs_read_page_cached)
 * ensures a reader never observes such a torn record in the first place.
 *
 * This test pins the underlying invariant that coordination relies on: a
 * torn trailing record yields the last *valid* version, and completing the
 * record makes the latest committed version visible on the next refresh.
 */
static void
test_storage_torn_record_visibility(void)
{
    CfsStorageFixture fx;
    CfsRelation *h_w;           /* writer */
    CfsRelation *h_r;           /* reader */
    unsigned char pageA[TEST_BLCKSZ];
    unsigned char pageB[TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    char        detail[160];
    bool        ok = true;
    CfsMapEntry entryB;
    off_t       last_rec_off = 0;
 
    cfs_storage_setup(&fx, "tornrec");
    if (fx.dir == NULL)
    {
        add_result("storage_torn_record_visibility", "fail", "setup failed");
        return;
    }
 
    h_w = cfs_storage_open_new(&fx);
 
    /* Version A fully committed. */
    cfs_test_fill_page(pageA, 0x50);
    if (cfs_write_page(h_w, 0, (const char *) pageA, &opts) != CFS_STORAGE_OK)
        ok = false;
 
    /* Reader opens after A and syncs its replay cursor to the end. */
    h_r = cfs_open_paths(fx.rl, MAIN_FORKNUM,
                         fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR);
    if (ok && cfs_refresh_map(h_r, true, CFS_LOAD_NORMAL) != CFS_STORAGE_OK)
        ok = false;
    if (ok && (cfs_read_page(h_r, 0, (char *) back) != CFS_STORAGE_OK ||
               memcmp(pageA, back, TEST_BLCKSZ) != 0))
        ok = false;
 
    /* Version B fully committed through the writer. */
    cfs_test_fill_page(pageB, 0x60);
    if (ok && cfs_write_page(h_w, 0, (const char *) pageB, &opts) != CFS_STORAGE_OK)
        ok = false;
    if (ok)
        entryB = *cfs_map_get_entry(h_w, 0);    /* capture B's entry */
 
    /*
     * Tear B's journal record (the last one) by overwriting its lead bytes
     * with garbage, so CRC/magic validation fails — exactly like a reader
     * catching the 56-byte record mid-pwrite.  The offset of the last record
     * is derived from the journal file size.
     */
    if (ok)
    {
        int         jrn_fd = BasicOpenFile(fx.jrn_path, O_RDWR | PG_BINARY);
        struct stat st;
 
        if (jrn_fd >= 0 && fstat(jrn_fd, &st) == 0)
        {
            uint32      garbage = 0xDEADBEEF;
 
            last_rec_off = st.st_size - (off_t) CFS_JOURNAL_ENTRY_SIZE;
            if (pwrite(jrn_fd, &garbage, sizeof(garbage), last_rec_off)
                != (ssize_t) sizeof(garbage))
                ok = false;
        }
        else
            ok = false;
        if (jrn_fd >= 0)
            close(jrn_fd);
    }
 
    /* Reader refreshes: replay applies A and stops at the torn B record. */
    if (ok && cfs_refresh_map(h_r, true, CFS_LOAD_NORMAL) != CFS_STORAGE_OK)
        ok = false;
    if (ok && (cfs_read_page(h_r, 0, (char *) back) != CFS_STORAGE_OK ||
               memcmp(pageA, back, TEST_BLCKSZ) != 0))
        ok = false;             /* must see the last *valid* version A */
 
    /*
     * Complete B's record (as if the writer finished the pwrite): rewrite the
     * valid entry at the same offset.
     */
    if (ok)
    {
        int         jrn_fd = BasicOpenFile(fx.jrn_path, O_RDWR | PG_BINARY);
        CfsJournalEntry validB;
 
        cfs_journal_entry_init_update(&validB, 0, &entryB);
        if (jrn_fd >= 0)
        {
            if (pwrite(jrn_fd, &validB, sizeof(validB), last_rec_off)
                != (ssize_t) sizeof(validB))
                ok = false;
            close(jrn_fd);
        }
        else
            ok = false;
    }
 
    /* Reader refreshes again: now B is the latest committed version. */
    if (ok && cfs_refresh_map(h_r, true, CFS_LOAD_NORMAL) != CFS_STORAGE_OK)
        ok = false;
    if (ok && (cfs_read_page(h_r, 0, (char *) back) != CFS_STORAGE_OK ||
               memcmp(pageB, back, TEST_BLCKSZ) != 0))
        ok = false;             /* completed record must be visible */
 
    cfs_close(h_r);
    cfs_close(h_w);
 
    snprintf(detail, sizeof(detail),
             "torn->valid refresh %s", ok ? "ok" : "stale/missing version");
    add_result("storage_torn_record_visibility", ok ? "ok" : "fail", detail);
    cfs_storage_teardown(&fx);
}
 
/*
 * Torn tail must be physically truncated on open/replay.
 *
 * A crash mid-append leaves a garbage (torn) tail in .cfsjrn after the last
 * valid record.  Replay correctly stops at it, but unless the file is
 * physically truncated to the end of that last valid record, the append
 * cursor — derived from the raw file size — lands past the garbage, and the
 * next backend appends behind it.  Every later replay still stops on the
 * garbage, so those records are buried forever even though they are
 * physically present.
 *
 * This test assembles a journal with a valid prefix followed by a torn last
 * record, then reopens (full replay).  It verifies:
 *   (a) only the valid-prefix records are applied,
 *   (b) the journal file is physically truncated to the valid prefix,
 *   (c) the append cursor points at the end of the valid prefix,
 *   (d) a new record appended after reopen is visible on the next replay.
 *
 * The torn record with valid records behind it is not a tail but corruption;
 * test_storage_mid_journal_preserved covers that case.
 */
static void
test_storage_torn_tail_truncated(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    unsigned char pageA[TEST_BLCKSZ];
    unsigned char pageB[TEST_BLCKSZ];
    unsigned char pageC[TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    char        detail[256];
    bool        ok = true;
    off_t       valid_prefix;   /* end of the last valid record */
    struct stat st;
 
    cfs_storage_setup(&fx, "torntail");
    if (fx.dir == NULL)
    {
        add_result("storage_torn_tail_truncated", "fail", "setup failed");
        return;
    }
 
    cfs = cfs_storage_open_new(&fx);
 
    /* Two blocks: 4 journal records (RESIZE+UPDATE each). */
    cfs_test_fill_page(pageA, 0x50);
    cfs_test_fill_page(pageB, 0x60);
    if (cfs_write_page(cfs, 0, (const char *) pageA, &opts) != CFS_STORAGE_OK ||
        cfs_write_page(cfs, 1, (const char *) pageB, &opts) != CFS_STORAGE_OK)
        ok = false;
    cfs_close(cfs);
 
    if (!ok)
    {
        snprintf(detail, sizeof(detail), "write setup failed");
        add_result("storage_torn_tail_truncated", "fail", detail);
        cfs_storage_teardown(&fx);
        return;
    }
 
    /*
     * Build the defect scenario by hand: a torn last record, with nothing
     * behind it - the crash artifact of an interrupted append.
     */
    valid_prefix = (off_t) CFS_JOURNAL_HEADER_SIZE + 4 * CFS_JOURNAL_ENTRY_SIZE;
    {
        int         jrn_fd = BasicOpenFile(fx.jrn_path, O_RDWR | PG_BINARY);
        char        garbage[CFS_JOURNAL_ENTRY_SIZE];
 
        if (jrn_fd < 0)
            ok = false;
 
        /* Torn tail: a full entry of zero bytes (bad CRC/magic). */
        if (ok)
        {
            MemSet(garbage, 0, sizeof(garbage));
            if (pwrite(jrn_fd, garbage, sizeof(garbage), valid_prefix)
                != (ssize_t) sizeof(garbage))
                ok = false;
        }
 
        if (jrn_fd >= 0)
            close(jrn_fd);
    }
 
    if (!ok)
    {
        snprintf(detail, sizeof(detail), "journal tampering failed");
        add_result("storage_torn_tail_truncated", "fail", detail);
        cfs_storage_teardown(&fx);
        return;
    }
 
    /*
     * Reopen simulating the single-writer recovery scan: replay must stop at
     * the torn tail and, because CFS_OPEN_REPAIR_TAIL is set, truncate it.
     * (The normal lock-free open deliberately does not repair, since a
     * concurrent writer may be mid-append.)
     */
    cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM,
                         fx.cfp_path, fx.map_path, fx.jrn_path,
                         CFS_OPEN_RDWR | CFS_OPEN_REPAIR_TAIL);
 
    /* (a) only the valid-prefix records are applied. */
    if (cfs_map_nblocks(cfs) != 2)
        ok = false;
 
    /* (b) the journal file is physically truncated to the valid prefix. */
    if (stat(fx.jrn_path, &st) != 0 || st.st_size != valid_prefix)
        ok = false;
 
    /* (c) the append cursor points at the end of the valid prefix. */
    if (cfs->jrn_write_off != valid_prefix)
        ok = false;
 
    /* The valid-prefix data is still readable. */
    if (cfs_read_page(cfs, 0, (char *) back) != CFS_STORAGE_OK ||
        memcmp(pageA, back, TEST_BLCKSZ) != 0 ||
        cfs_read_page(cfs, 1, (char *) back) != CFS_STORAGE_OK ||
        memcmp(pageB, back, TEST_BLCKSZ) != 0)
        ok = false;
 
    /*
     * (d) A new record appended now must land right after the valid prefix
     * (not behind the old garbage) and survive a close/reopen replay.
     */
    cfs_test_fill_page(pageC, 0x70);
    if (cfs_write_page(cfs, 2, (const char *) pageC, &opts) != CFS_STORAGE_OK)
        ok = false;
    cfs_close(cfs);
 
    cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM,
                         fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR);
    if (cfs_map_nblocks(cfs) != 3)
        ok = false;
    if (ok && (cfs_read_page(cfs, 2, (char *) back) != CFS_STORAGE_OK ||
               memcmp(pageC, back, TEST_BLCKSZ) != 0))
        ok = false;
    cfs_close(cfs);
 
    snprintf(detail, sizeof(detail),
             "torn-tail truncation %s (nblocks=%u)",
             ok ? "ok" : "failed",
             ok ? 3u : 0u);
    add_result("storage_torn_tail_truncated", ok ? "ok" : "fail", detail);
    cfs_storage_teardown(&fx);
}
 
/*
 * Mid-journal corruption must survive the recovery open.
 *
 * A torn record with valid records behind it cannot come from a legal append
 * (appends only ever happen at EOF): it is corruption, and the records behind
 * it are the only durable trace of their changes.  The recovery open still
 * applies the valid prefix, but must leave the journal file untouched and
 * mark the handle unhealed instead of cutting the valid tail off.
 */
static void
test_storage_mid_journal_preserved(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    unsigned char pageA[TEST_BLCKSZ];
    unsigned char pageB[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    char        detail[256];
    bool        ok = true;
    off_t       torn_off;
    off_t       jrn_size;
    struct stat st;
 
    cfs_storage_setup(&fx, "midjrn");
    if (fx.dir == NULL)
    {
        add_result("storage_mid_journal_preserved", "fail", "setup failed");
        return;
    }
 
    cfs = cfs_storage_open_new(&fx);
 
    /* Two blocks: 4 journal records (RESIZE+UPDATE each). */
    cfs_test_fill_page(pageA, 0x80);
    cfs_test_fill_page(pageB, 0x90);
    if (cfs_write_page(cfs, 0, (const char *) pageA, &opts) != CFS_STORAGE_OK ||
        cfs_write_page(cfs, 1, (const char *) pageB, &opts) != CFS_STORAGE_OK)
        ok = false;
    cfs_close(cfs);
 
    torn_off = (off_t) CFS_JOURNAL_HEADER_SIZE + 4 * CFS_JOURNAL_ENTRY_SIZE;
    jrn_size = torn_off + 3 * (off_t) CFS_JOURNAL_ENTRY_SIZE;
    {
        int         jrn_fd = BasicOpenFile(fx.jrn_path, O_RDWR | PG_BINARY);
        char        garbage[CFS_JOURNAL_ENTRY_SIZE];
        CfsJournalEntry buried;
 
        if (jrn_fd < 0)
            ok = false;
 
        /* Torn record in the middle: a full entry of zero bytes. */
        if (ok)
        {
            MemSet(garbage, 0, sizeof(garbage));
            if (pwrite(jrn_fd, garbage, sizeof(garbage), torn_off)
                != (ssize_t) sizeof(garbage))
                ok = false;
        }
 
        /* Valid records behind it: the durable tail that must survive. */
        if (ok)
        {
            off_t       off = torn_off + (off_t) CFS_JOURNAL_ENTRY_SIZE;
 
            cfs_journal_entry_init_resize(&buried, 3);
            if (pwrite(jrn_fd, &buried, sizeof(buried), off)
                != (ssize_t) sizeof(buried))
                ok = false;
            off += (off_t) CFS_JOURNAL_ENTRY_SIZE;
            cfs_journal_entry_init_resize(&buried, 4);
            if (pwrite(jrn_fd, &buried, sizeof(buried), off)
                != (ssize_t) sizeof(buried))
                ok = false;
        }
        if (jrn_fd >= 0)
            close(jrn_fd);
    }
 
    if (!ok)
    {
        snprintf(detail, sizeof(detail), "journal tampering failed");
        add_result("storage_mid_journal_preserved", "fail", detail);
        cfs_storage_teardown(&fx);
        return;
    }
 
    /*
     * Reopen simulating the single-writer recovery scan: the valid prefix is
     * applied, but the journal is corruption, not a torn tail, so it is not
     * truncated and the handle is marked unhealed.
     */
    cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM,
                         fx.cfp_path, fx.map_path, fx.jrn_path,
                         CFS_OPEN_RDWR | CFS_OPEN_REPAIR_TAIL);
 
    if (cfs_map_nblocks(cfs) != 2)
        ok = false;
    if (stat(fx.jrn_path, &st) != 0 || st.st_size != jrn_size)
        ok = false;
    if (!cfs->unhealed_corruption)
        ok = false;
    cfs_close(cfs);
 
    snprintf(detail, sizeof(detail), "journal preserved %s (size=%lld)",
             ok ? "ok" : "failed", (long long) jrn_size);
    add_result("storage_mid_journal_preserved", ok ? "ok" : "fail", detail);
    cfs_storage_teardown(&fx);
}
 
/*
 * The phase-2 tail re-check: phase 1 classifies a torn tail, then a writer
 * may complete it or append past it before phase 2 takes the append lock.
 *
 * The predicate is tested directly: with the journal still ending at the
 * torn record it reports no change; one byte appended behind that record
 * makes it report a change, so the checkpoint must not reset the journal.
 */
static void
test_storage_tail_change_detected(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    unsigned char pageA[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    char        detail[256];
    bool        ok = true;
    off_t       torn_off;
 
    cfs_storage_setup(&fx, "tailchg");
    if (fx.dir == NULL)
    {
        add_result("storage_tail_change_detected", "fail", "setup failed");
        return;
    }
 
    cfs = cfs_storage_open_new(&fx);
    cfs_test_fill_page(pageA, 0xD0);
    if (cfs_write_page(cfs, 0, (const char *) pageA, &opts) != CFS_STORAGE_OK)
        ok = false;
    cfs_close(cfs);
    cfs = NULL;
 
    torn_off = (off_t) CFS_JOURNAL_HEADER_SIZE + 2 * CFS_JOURNAL_ENTRY_SIZE;
    {
        int         jrn_fd = BasicOpenFile(fx.jrn_path, O_RDWR | PG_BINARY);
        char        garbage[CFS_JOURNAL_ENTRY_SIZE];
 
        if (jrn_fd < 0)
            ok = false;
        if (ok)
        {
            MemSet(garbage, 0, sizeof(garbage));
            if (pwrite(jrn_fd, garbage, sizeof(garbage), torn_off) !=
                (ssize_t) sizeof(garbage))
                ok = false;
        }
        if (jrn_fd >= 0)
            close(jrn_fd);
    }
 
    if (ok)
    {
        cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM,
                             fx.cfp_path, fx.map_path, fx.jrn_path,
                             CFS_OPEN_RDWR);
        if (cfs == NULL)
            ok = false;
    }
 
    if (ok && cfs_journal_tail_changed(cfs, torn_off))
        ok = false;             /* still the torn tail phase 1 saw */
 
    /* A writer appends behind the torn record while phase 1 is parked. */
    if (ok)
    {
        int         jrn_fd = BasicOpenFile(fx.jrn_path, O_WRONLY | PG_BINARY);
 
        if (jrn_fd < 0)
            ok = false;
        else
        {
            if (pwrite(jrn_fd, "xx", 2, torn_off + CFS_JOURNAL_ENTRY_SIZE) != 2)
                ok = false;
            close(jrn_fd);
        }
    }
 
    if (ok && !cfs_journal_tail_changed(cfs, torn_off))
        ok = false;
    if (cfs != NULL)
        cfs_close(cfs);
 
    snprintf(detail, sizeof(detail), "tail change %s",
             ok ? "detected" : "not detected");
    add_result("storage_tail_change_detected", ok ? "ok" : "fail", detail);
    cfs_storage_teardown(&fx);
}
 
/*
 * A delta refresh over mid-journal corruption must rebuild the map instead of
 * serving the partially synced one.
 *
 * The baseline handle synced its map when the journal ended after block 0.
 * A second handle then appends records for blocks 1 and 2, and the first
 * appended record is corrupted with valid records still behind it.  The
 * delta replay cannot trust anything past the corruption, so it must signal
 * a full reload (-2); the full replay then reports the corruption and marks
 * the handle unhealed.  Without that, the refresh returned success with a
 * map that silently missed every later record until a full reopen.
 */
static void
test_storage_delta_mid_journal_reload(void)
{
    CfsStorageFixture fx;
    CfsRelation *baseline = NULL;
    CfsRelation *writer;
    unsigned char pageA[TEST_BLCKSZ];
    unsigned char pageB[TEST_BLCKSZ];
    unsigned char pageC[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    char        detail[256];
    bool        ok = true;
    off_t       first_new;
    int         rc;
 
    cfs_storage_setup(&fx, "deltamid");
    if (fx.dir == NULL)
    {
        add_result("storage_delta_mid_journal_reload", "fail",
                   "setup failed");
        return;
    }
 
    /* Block 0: two records (RESIZE + UPDATE), the baseline journal. */
    writer = cfs_storage_open_new(&fx);
    cfs_test_fill_page(pageA, 0xA0);
    if (cfs_write_page(writer, 0, (const char *) pageA, &opts) !=
        CFS_STORAGE_OK)
        ok = false;
    cfs_close(writer);
 
    first_new = (off_t) CFS_JOURNAL_HEADER_SIZE + 2 * CFS_JOURNAL_ENTRY_SIZE;
 
    if (ok)
    {
        /* This handle syncs its map at the two-record journal. */
        baseline = cfs_open_paths(fx.rl, MAIN_FORKNUM,
                                  fx.cfp_path, fx.map_path, fx.jrn_path,
                                  CFS_OPEN_RDWR);
        if (baseline == NULL)
            ok = false;
    }
 
    if (ok)
    {
        /* Four more records behind the baseline, two per block. */
        writer = cfs_open_paths(fx.rl, MAIN_FORKNUM,
                                fx.cfp_path, fx.map_path, fx.jrn_path,
                                CFS_OPEN_RDWR);
        cfs_test_fill_page(pageB, 0xB0);
        cfs_test_fill_page(pageC, 0xC0);
        if (writer == NULL ||
            cfs_write_page(writer, 1, (const char *) pageB, &opts) !=
            CFS_STORAGE_OK ||
            cfs_write_page(writer, 2, (const char *) pageC, &opts) !=
            CFS_STORAGE_OK)
            ok = false;
        if (writer != NULL)
            cfs_close(writer);
    }
 
    /* Corrupt the first appended record; three valid records follow it. */
    if (ok)
    {
        int         jrn_fd = BasicOpenFile(fx.jrn_path, O_RDWR | PG_BINARY);
        unsigned char b;
 
        if (jrn_fd < 0)
            ok = false;
        if (ok && pread(jrn_fd, &b, 1, first_new + 8) != 1)
            ok = false;
        if (ok)
        {
            b ^= 0xFF;
            if (pwrite(jrn_fd, &b, 1, first_new + 8) != 1)
                ok = false;
        }
        if (jrn_fd >= 0)
            close(jrn_fd);
    }
 
    if (ok)
    {
        rc = cfs_refresh_map(baseline, false, CFS_LOAD_NORMAL);
        if (rc != CFS_STORAGE_OK || !baseline->unhealed_corruption)
            ok = false;
 
        /*
         * The delta baseline must not advance past the corruption: a full
         * reload leaves map_synced_jrn_off alone, while the old swallow
         * advanced it to the journal end and then kept serving the map.
         */
        if (baseline->map_synced_jrn_off != first_new)
            ok = false;
    }
    if (baseline != NULL)
        cfs_close(baseline);
 
    snprintf(detail, sizeof(detail),
             "mid-journal delta %s (unhealed=%d)",
             ok ? "reloaded" : "failed",
             ok ? 1 : 0);
    add_result("storage_delta_mid_journal_reload", ok ? "ok" : "fail",
               detail);
    cfs_storage_teardown(&fx);
}
 
/*
 * Crash recovery with .cfp/.cfsjrn writeback reordering.
 *
 * Between checkpoints neither .cfp nor .cfsjrn is fsync'd, so after a power
 * loss a journal UPDATE record can be durable while the .cfp bytes it points
 * at are not (the kernel flushed the journal pages ahead of the data pages).
 * Replay must not trust such a record blindly: the record's own CRC is
 * valid, but there is no genuine CfsCompressedBlockHeader at the referenced
 * offset.  The correct handling is to skip that one record - leaving the
 * map entry for the block in its previous, durable state - and to keep
 * replaying the records that follow it (unlike a torn trailing record,
 * which stops the replay).  Ordinary WAL redo then re-applies the lost
 * change on top of the old page version, exactly as it does for
 * uncompressed relations.
 */
static void
test_storage_journal_skip_missing_data(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    unsigned char pageA[TEST_BLCKSZ];
    unsigned char pageB[TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    char        detail[128];
    bool        ok = true;
    uint64      bogus_off;
    size_t      i;
 
    cfs_storage_setup(&fx, "jrnskip");
    if (fx.dir == NULL)
    {
        add_result("storage_journal_skip_missing_data", "fail", "setup failed");
        return;
    }
 
    cfs = cfs_storage_open_new(&fx);
 
    /* A genuine write of block 0 (RESIZE + UPDATE journal records). */
    cfs_test_fill_page(pageA, 0x70);
    if (cfs_write_page(cfs, 0, (const char *) pageA, &opts) != CFS_STORAGE_OK)
        ok = false;
 
    /*
     * Simulate the crash window by hand: put garbage into .cfp at an aligned
     * offset past the written data (no genuine record header there), then
     * append a journal UPDATE record for block 1 that points at it.  The
     * record's own CRC is valid - only the referenced data is missing,
     * exactly what replay sees when .cfsjrn became durable ahead of the
     * referenced .cfp bytes.
     */
    if (ok)
    {
        CfsMapEntry bogus;
        CfsJournalEntry je;
        unsigned char garbage[CFS_BLOCK_ALIGN];
        int         cfp_fd;
        int         jrn_fd;
 
        bogus_off = CFS_ALIGN_UP((uint64) cfs->cfp_write_off) + CFS_BLOCK_ALIGN;
        memset(garbage, 0xA5, sizeof(garbage));
 
        cfp_fd = BasicOpenFile(fx.cfp_path, O_RDWR | PG_BINARY);
        if (cfp_fd < 0 ||
            pwrite(cfp_fd, garbage, sizeof(garbage), (off_t) bogus_off)
            != (ssize_t) sizeof(garbage))
            ok = false;
        if (cfp_fd >= 0)
            close(cfp_fd);
 
        cfs_map_entry_init(&bogus);
        bogus.physical_offset = bogus_off;
        bogus.compressed_size = 64;
        bogus.generation = 1;
        cfs_map_entry_crc_set(&bogus);
 
        cfs_journal_entry_init_update(&je, 1, &bogus);
 
        jrn_fd = BasicOpenFile(fx.jrn_path, O_RDWR | PG_BINARY);
        if (jrn_fd < 0 ||
            pwrite(jrn_fd, &je, sizeof(je), cfs->jrn_write_off)
            != (ssize_t) sizeof(je))
            ok = false;
        if (jrn_fd >= 0)
            close(jrn_fd);
    }
 
    /*
     * A genuine write of block 2 *after* the bogus record: proves that replay
     * continues past the skipped record instead of stopping at it.
     */
    cfs_test_fill_page(pageB, 0x71);
    if (ok && cfs_write_page(cfs, 2, (const char *) pageB, &opts) != CFS_STORAGE_OK)
        ok = false;
    cfs_close(cfs);
 
    /* Reopen without a checkpoint: the journal drives the whole map. */
    cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM,
                         fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR);
    if (cfs == NULL)
        ok = false;
 
    if (ok && cfs_map_nblocks(cfs) != 3)
        ok = false;
 
    /* Blocks 0 and 2 come from genuine records and must read back. */
    if (ok && (cfs_read_page(cfs, 0, (char *) back) != CFS_STORAGE_OK ||
               memcmp(pageA, back, TEST_BLCKSZ) != 0))
        ok = false;
    if (ok && (cfs_read_page(cfs, 2, (char *) back) != CFS_STORAGE_OK ||
               memcmp(pageB, back, TEST_BLCKSZ) != 0))
        ok = false;
 
    /*
     * The bogus record must NOT have been applied: block 1 keeps the
     * never-written state (invalid map offset, reads back as a zero page)
     * instead of pointing at bytes that never reached the disk.
     */
    if (ok && cfs_map_get_entry(cfs, 1)->physical_offset != CFS_ENTRY_INVALID_OFFSET)
        ok = false;
    if (ok)
    {
        MemSet(back, 0xFF, TEST_BLCKSZ);
        if (cfs_read_page(cfs, 1, (char *) back) != CFS_STORAGE_OK)
            ok = false;
        else
            for (i = 0; i < TEST_BLCKSZ; i++)
                if (back[i] != 0)
                {
                    ok = false;
                    break;
                }
    }
    if (cfs != NULL)
        cfs_close(cfs);
 
    snprintf(detail, sizeof(detail),
             "bogus UPDATE skipped, replay continued %s", ok ? "ok" : "FAILED");
    add_result("storage_journal_skip_missing_data", ok ? "ok" : "fail", detail);
    cfs_storage_teardown(&fx);
}
 
/*
 * test_storage_read_padding_garbage
 *      The write path zeroes the record's alignment padding so that records
 *      are canonical (see test_record_padding_zeroed).  The read path
 *      enforces the same canonicality contract: CfsDecompressPage() rejects
 *      a record whose payload padding is not zero as corruption, so bit rot
 *      confined to the padding bytes cannot slip through as data.  The
 *      independent .cfp fsck walk does not check the padding of individual
 *      records (it validates record boundaries and CRC-covered regions
 *      only), so the fsck verdict for the same damage stays clean — the
 *      read path is the authority here.
 *
 * The test writes one compressed block, flips the record's padding bytes
 * in .cfp directly, and reopens: the read must fail with corruption, and
 * fsck must stay clean (pinning both sides of the asymmetry).
 */
static void
test_storage_read_padding_garbage(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    unsigned char pageA[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    CfsFsckResult res;
    CfsFsckOptions fopts = CFS_FSCK_OPTIONS_DEFAULT;
    char        detail[160];
    bool        ok = true;
    CfsMapEntry *e;
    uint32      compressed_size;
    size_t      pad_off;
    size_t      pad_len;
    struct stat st;
    unsigned char *buf;
    int         fd;
    ssize_t     nread;
 
    cfs_storage_setup(&fx, "padg");
    if (fx.dir == NULL)
    {
        add_result("storage_read_padding_garbage", "fail", "setup failed");
        return;
    }
 
    cfs = cfs_storage_open_new(&fx);
 
    /* A compressible page yields a genuinely compressed record. */
    cfs_test_fill_page(pageA, 0x52);
    if (cfs_write_page(cfs, 0, (const char *) pageA, &opts) != CFS_STORAGE_OK)
        ok = false;
 
    /*
     * Locate the record's padding: [header (40B)][payload][pad to 8].  If the
     * compressed payload happens to be aligned there is no padding to
     * corrupt; report the case honestly instead of pretending coverage.
     */
    if (ok)
    {
        e = cfs_map_get_entry(cfs, 0);
        compressed_size = e->compressed_size;
        pad_len = CFS_RECORD_SIZE(compressed_size)
            - CFS_BLOCK_HEADER_SIZE - compressed_size;
    }
    cfs_close(cfs);
 
    if (!ok)
    {
        add_result("storage_read_padding_garbage", "fail", "write failed");
        cfs_storage_teardown(&fx);
        return;
    }
    if (pad_len == 0)
    {
        add_result("storage_read_padding_garbage", "skip",
                   "compressed payload is 8-byte aligned, no padding");
        cfs_storage_teardown(&fx);
        return;
    }
 
    /* Flip the padding bytes in .cfp (the CRC-covered payload is intact). */
    if (stat(fx.cfp_path, &st) != 0)
    {
        add_result("storage_read_padding_garbage", "fail", "stat failed");
        cfs_storage_teardown(&fx);
        return;
    }
    buf = palloc(st.st_size);
    fd = BasicOpenFile(fx.cfp_path, O_RDONLY | PG_BINARY);
    if (fd < 0 || (nread = read(fd, buf, st.st_size)) != st.st_size)
        ok = false;
    if (fd >= 0)
        close(fd);
 
    pad_off = CFS_CFP_BASE_OFFSET + CFS_BLOCK_HEADER_SIZE + compressed_size;
    if (ok)
    {
        memset(buf + pad_off, 0xAB, pad_len);
        ok = cfs_test_write_file(fx.cfp_path, buf, st.st_size);
    }
    pfree(buf);
 
    /*
     * The reader must refuse the record: the nonzero padding is corruption by
     * the canonicality contract, not dead space.
     */
    if (ok)
    {
        CfsRelation *h_r = cfs_open_paths(fx.rl, MAIN_FORKNUM,
                                          fx.cfp_path, fx.map_path,
                                          fx.jrn_path, CFS_OPEN_RDWR);
        unsigned char back[TEST_BLCKSZ];
 
        if (h_r == NULL ||
            cfs_read_page(h_r, 0, (char *) back) != CFS_STORAGE_CORRUPT)
            ok = false;
        if (h_r != NULL)
            cfs_close(h_r);
    }
 
    /*
     * The fsck walk stays clean: it does not validate the padding of
     * individual records (boundaries and CRC-covered regions only).
     */
    if (ok)
    {
        cfs_fsck_result_init(&res);
        cfs_fsck_cfp_file(fx.cfp_path, &fopts, &res);
        if (res.errors != 0 || res.torn_tails != 0)
            ok = false;
    }
 
    snprintf(detail, sizeof(detail),
             "read %s, fsck %s (asymmetry pinned)",
             ok ? "refuses garbage padding" : "ACCEPTED garbage padding",
             ok ? "clean" : "flagged");
    add_result("storage_read_padding_garbage", ok ? "ok" : "fail", detail);
    cfs_storage_teardown(&fx);
}
 
/*
 * D1 shared-tail protocol: with the relation's metadata slot pinned, the
 * append path takes its offset from the slot's authoritative cfp_tail and
 * publishes the new end back, instead of re-walking the segment chain on
 * every record.  The exercise drives every state of the protocol:
 *
 *   - a fresh slot is DIRTY, so the first append discovers the chain end;
 *   - after a successful append the tail is IDLE and equals the published
 *     cursor, and the next record lands exactly at that offset;
 *   - an IN_PROGRESS slot (a writer crashed between its pwrite and the
 *     tail publication) forces the next writer back onto the discover
 *     path without overwriting the orphaned record's successor;
 *   - a failed pwrite marks the slot DIRTY and the next append re-discovers;
 *   - every page written under the protocol reads back intact.
 */
static void
test_storage_shared_tail_protocol(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    unsigned char page[TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    uint64      tail = 0;
    CfsMapEntry *e0, *e1, *e2;
    off_t       off1 = 0,
                off2 = 0;
    int         rc;
    int         stage = 0;
    char        detail[160];
    bool        ok = true;
 
    cfs_storage_setup(&fx, "sharedtail");
    if (fx.dir == NULL)
    {
        add_result("storage_shared_tail_protocol", "fail", "setup failed");
        return;
    }
    fx.rl.locator.relNumber = 800770;
    cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
    cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM);
    cfs_map_cache_pin(fx.rl, MAIN_FORKNUM);
 
    cfs = cfs_storage_open_new(&fx);
    if (cfs == NULL)
    {
        add_result("storage_shared_tail_protocol", "fail", "open failed");
        cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM);
        cfs_storage_teardown(&fx);
        return;
    }
 
    /* RAW pages: fixed 8224-byte records make the offsets predictable. */
    opts.algorithm = CFS_ALGORITHM_RAW;
    opts.explicit_algorithm = true;
    opts.allow_raw_fallback = true;
    opts.min_gain_bytes = 1;
 
    /*
     * A freshly claimed slot is DIRTY: no trustworthy tail exists yet, so
     * this append must run the discover path and then publish the tail.
     */
    stage = 1;
    cfs_test_fill_page(page, 0x61);
    if (cfs_write_page(cfs, 0, (const char *) page, &opts) != CFS_STORAGE_OK)
        ok = false;
 
    stage = 2;
    if (ok && !cfs_cfp_tail_fetch(fx.rl, MAIN_FORKNUM, &tail))
        ok = false;
 
    stage = 3;
    e0 = ok ? cfs_map_get_entry(cfs, 0) : NULL;
    if (ok && (e0 == NULL || e0->physical_offset != CFS_CFP_BASE_OFFSET))
        ok = false;
 
    /*
     * IDLE tail: the next record must land exactly at the published tail
     * (no discover walk, no gap, no overwrite of the first record).
     */
    stage = 4;
    if (ok)
    {
        cfs_test_fill_page(page, 0x62);
        if (cfs_write_page(cfs, 1, (const char *) page, &opts) !=
            CFS_STORAGE_OK)
            ok = false;
    }
    stage = 5;
    e1 = ok ? cfs_map_get_entry(cfs, 1) : NULL;
    if (ok && e1 == NULL)
        ok = false;
    if (ok)
    {
        /*
         * Capture the offsets while the handle (and its map array) is
         * still open: the print at the end must not read freed memory.
         */
        off1 = (off_t) e1->physical_offset;
 
        /*
         * Crash-window simulation: mark the slot IN_PROGRESS as a writer
         * that died between its pwrite and the tail publication would
         * leave it.  The next append must refuse to trust the tail and
         * re-discover the chain end instead.
         */
        stage = 6;
        cfs_cfp_tail_begin(fx.rl, MAIN_FORKNUM);
 
        cfs_test_fill_page(page, 0x63);
        if (cfs_write_page(cfs, 2, (const char *) page, &opts) !=
            CFS_STORAGE_OK)
            ok = false;
    }
    stage = 7;
    e2 = ok ? cfs_map_get_entry(cfs, 2) : NULL;
    if (ok && e2 == NULL)
        ok = false;
    if (ok)
    {
        off2 = (off_t) e2->physical_offset;
 
        /* Strictly increasing offsets: nothing overwrote a predecessor. */
        stage = 8;
        if (off1 != (off_t) tail || off2 <= off1)
            ok = false;
 
        /*
         * Failed-pwrite path: the injected EIO must leave the slot DIRTY
         * (the published tail no longer describes the file end), and the
         * next append must recover through the discover path.
         */
        stage = 9;
        cfs_test_fill_page(page, 0x64);
        cfs_debug_fail_pwrite = 1;
        rc = cfs_write_page(cfs, 3, (const char *) page, &opts);
        cfs_debug_fail_pwrite = 0;
        if (rc == CFS_STORAGE_OK)
            ok = false;
        stage = 10;
        if (ok && cfs_cfp_tail_fetch(fx.rl, MAIN_FORKNUM, &tail))
            ok = false;         /* DIRTY must not answer a trusted tail */
 
        stage = 11;
        cfs_test_fill_page(page, 0x65);
        if (cfs_write_page(cfs, 3, (const char *) page, &opts) !=
            CFS_STORAGE_OK)
            ok = false;
    }
 
    /* Read back everything written under the protocol. */
    stage = 12;
    {
        unsigned char expect[4];
        int         blk;
        int         tag;
 
        expect[0] = 0x61;
        expect[1] = 0x62;
        expect[2] = 0x63;
        expect[3] = 0x65;
        for (blk = 0; blk < 4 && ok; blk++)
        {
            if (cfs_read_page(cfs, blk, (char *) back) != CFS_STORAGE_OK)
                ok = false;
            else
            {
                /* cfs_test_fill_page writes the ramp (tag + i) & 0x7F. */
                for (tag = 0; tag < TEST_BLCKSZ; tag++)
                {
                    if (back[tag] !=
                        (unsigned char) ((expect[blk] + tag) & 0x7F))
                    {
                        ok = false;
                        break;
                    }
                }
            }
        }
    }
 
    cfs_close(cfs);
    cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM);
    cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
    cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM);
 
    snprintf(detail, sizeof(detail),
             "stage=%d first=%llu second=%llu third=%llu %s",
             stage,
             (unsigned long long) CFS_CFP_BASE_OFFSET,
             ok ? (unsigned long long) off1 : 0ULL,
             ok ? (unsigned long long) off2 : 0ULL,
             ok ? "tail protocol held" : "protocol broken");
    add_result("storage_shared_tail_protocol", ok ? "ok" : "fail", detail);
    cfs_storage_teardown(&fx);
}
 
/*
 * D4 zero-copy RAW: CfsCompressPageNoCopy() must describe the very same
 * on-disk record as the contiguous CfsCompressPage() (byte-identical
 * gathered form, valid CRCs, correct round-trip) while pointing its
 * payload at the caller's page instead of copying 8 KiB into the scratch
 * buffer.  A compressed result keeps the contiguous contract.
 */
static void
test_compress_page_nocopy_raw(void)
{
    unsigned char page[TEST_BLCKSZ];
    unsigned char decompressed[TEST_BLCKSZ];
    unsigned char *scratch;
    unsigned char *gathered;
    size_t      scratch_sz;
    CfsCompressOptions opts;
    CfsCompressResult cres_copy;
    CfsCompressResult cres_vec;
    CfsDecompressStatus dstatus;
    char        detail[160];
    bool        ok = true;
 
    scratch_sz = CfsCompressScratchSize(sizeof(page));
    scratch = palloc(scratch_sz);
    gathered = palloc(2 * CFS_BLCKSZ + CFS_BLOCK_HEADER_SIZE);
 
    fill_pseudo_random(page, sizeof(page));
    memset(&opts, 0, sizeof(opts));
    opts.algorithm = CFS_ALGORITHM_RAW;
    opts.level = CFS_COMPRESS_LEVEL_DEFAULT;
    opts.min_gain_bytes = 1;
    opts.explicit_algorithm = true;
    opts.allow_raw_fallback = false;
 
    CfsCompressPage(page, sizeof(page), &opts, scratch, scratch_sz,
                    &cres_copy);
    CfsCompressPageNoCopy(page, sizeof(page), &opts, scratch, scratch_sz,
                          &cres_vec);
 
    if (!cres_copy.is_raw || !cres_vec.is_raw)
        ok = false;
    if (ok && (cres_copy.payload_external || !cres_vec.payload_external))
        ok = false;
 
    /*
     * The no-copy descriptor must point straight at the caller's page and
     * carry the exact record geometry: header 28, payload 8192, padding 4,
     * total 8224 (all values fixed by the on-disk format).
     */
    if (ok && (cres_vec.payload_data != page ||
               cres_vec.padding_bytes != CFS_RECORD_SIZE(CFS_BLCKSZ) -
               CFS_BLOCK_HEADER_SIZE - CFS_BLCKSZ))
        ok = false;
 
    /* Gather the vector form the way the record lands on disk. */
    if (ok)
    {
        memset(gathered, 0, cres_vec.total_size);
        memcpy(gathered, cres_vec.result_data, CFS_BLOCK_HEADER_SIZE);
        memcpy(gathered + CFS_BLOCK_HEADER_SIZE, cres_vec.payload_data,
               cres_vec.compressed_size);
        /* the padding stays zeroed by the memset above */
    }
 
    /* Byte-identical to the contiguous (pre-D4) record. */
    if (ok && memcmp(gathered, cres_copy.result_data, cres_copy.total_size) != 0)
        ok = false;
    if (ok && cres_vec.total_size != cres_copy.total_size)
        ok = false;
 
    /* The gathered record must validate and round-trip. */
    if (ok && !CfsVerifyBlockHeader(
            (const CfsCompressedBlockHeader *) gathered))
        ok = false;
    if (ok)
    {
        dstatus = CfsDecompressPage(gathered, cres_vec.total_size,
                                    decompressed, sizeof(decompressed), NULL);
        if (dstatus != CFS_DECOMPRESS_OK ||
            memcmp(decompressed, page, sizeof(page)) != 0)
            ok = false;
    }
 
    /* A compressed result keeps the contiguous contract in both forms. */
    if (ok && CfsCodecAvailable(CFS_ALGORITHM_LZ4))
    {
        CfsCompressResult cres_lz4;
 
        fill_constant(page, sizeof(page), 0x77);
        memset(&opts, 0, sizeof(opts));
        opts.algorithm = CFS_ALGORITHM_LZ4;
        opts.level = CFS_COMPRESS_LEVEL_DEFAULT;
        opts.min_gain_bytes = 1;
 
        CfsCompressPageNoCopy(page, sizeof(page), &opts, scratch, scratch_sz,
                              &cres_lz4);
        if (cres_lz4.is_raw || cres_lz4.payload_external)
            ok = false;
        if (ok)
        {
            dstatus = CfsDecompressPage(cres_lz4.result_data,
                                        cres_lz4.total_size,
                                        decompressed, sizeof(decompressed),
                                        NULL);
            if (dstatus != CFS_DECOMPRESS_OK ||
                memcmp(decompressed, page, sizeof(page)) != 0)
                ok = false;
        }
    }
 
    snprintf(detail, sizeof(detail),
             "raw record %zu bytes, pad %zu, %s",
             cres_vec.total_size, cres_vec.padding_bytes,
             ok ? "byte-identical, round-trip ok" : "mismatch");
    add_result("compress_page_nocopy_raw", ok ? "ok" : "fail", detail);
    pfree(gathered);
    pfree(scratch);
}
 
/* ================================================================
 * Shared-memory map cache, statistics, eviction and
 * the cached read/write integration.
 * ================================================================ */
 
/*
 * Build a synthetic permanent locator with a caller-chosen relNumber so
 * that every test case uses a distinct cache key (the shared cache
 * persists across tests within one backend session).
 */
static RelFileLocatorBackend
cfs_shmem_test_locator(Oid relnumber)
{
    RelFileLocatorBackend rl;
 
    rl.locator.spcOid = DEFAULTTABLESPACE_OID;
    rl.locator.dbOid = MyDatabaseId;
    rl.locator.relNumber = relnumber;
    rl.backend = INVALID_PROC_NUMBER;
    return rl;
}
 
static void
test_shmem_meta_pin(void)
{
    RelFileLocatorBackend rl = cfs_shmem_test_locator(800150);
    uint64      nblocks = 0;
    char        detail[160];
    bool        ok = true;
 
    cfs_map_cache_invalidate(rl, MAIN_FORKNUM);
 
    /* No metadata yet. */
    if (cfs_map_cache_get_nblocks(rl, MAIN_FORKNUM, &nblocks))
        ok = false;
 
    cfs_map_cache_pin(rl, MAIN_FORKNUM);
    cfs_map_cache_set_meta(rl, MAIN_FORKNUM, 42);
    if (!cfs_map_cache_get_nblocks(rl, MAIN_FORKNUM, &nblocks) || nblocks != 42)
        ok = false;
 
    /* Releasing drops the metadata slot. */
    cfs_map_cache_release_relation(rl, MAIN_FORKNUM);
    if (cfs_map_cache_get_nblocks(rl, MAIN_FORKNUM, &nblocks))
        ok = false;
 
    snprintf(detail, sizeof(detail), "meta/pin/release %s",
             ok ? "ok" : "failed");
    add_result("shmem_meta_pin", ok ? "ok" : "fail", detail);
}
 
static void
test_shmem_stats(void)
{
    RelFileLocatorBackend rl = cfs_shmem_test_locator(800200);
    CfsStatsSnapshot snap;
    char        detail[160];
    bool        ok = true;
 
    cfs_map_cache_invalidate(rl, MAIN_FORKNUM);
    cfs_stats_reset(rl, MAIN_FORKNUM);
 
    cfs_stats_count_read(rl, MAIN_FORKNUM, 100);
    cfs_stats_count_write(rl, MAIN_FORKNUM, 200, false);
    cfs_stats_count_write(rl, MAIN_FORKNUM, 300, true);
    cfs_stats_count_crc_failure(rl, MAIN_FORKNUM);
 
    if (!cfs_stats_snapshot(rl, MAIN_FORKNUM, &snap))
        ok = false;
    else if (snap.read_count != 1 || snap.write_count != 2 ||
             snap.crc_failures != 1 || snap.compressed_bytes != 200 ||
             snap.raw_bytes != 300 || snap.dead_bytes != 0 ||
             snap.dead_pages != 0)
        ok = false;
    cfs_stats_reset(rl, MAIN_FORKNUM);
    if (!cfs_stats_snapshot(rl, MAIN_FORKNUM, &snap))
        ok = false;
    else if (snap.read_count != 0 || snap.write_count != 0 ||
             snap.compressed_bytes != 0 || snap.crc_failures != 0)
        ok = false;
 
    snprintf(detail, sizeof(detail),
             "counters reads=%llu writes=%llu after reset reads=%llu",
             (unsigned long long) snap.read_count,
             (unsigned long long) snap.write_count,
             (unsigned long long) snap.read_count);
    add_result("shmem_stats", ok ? "ok" : "fail", detail);
}
 
static void
test_shmem_cached_io(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    unsigned char page[TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    CfsStatsSnapshot snap;
    char        detail[160];
    bool        ok = true;
 
    cfs_storage_setup(&fx, "cached_io");
    if (fx.dir == NULL)
    {
        add_result("shmem_cached_io", "fail", "setup failed");
        return;
    }
    fx.rl.locator.relNumber = 800300;
    cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM);
 
    cfs = cfs_storage_open_new(&fx);
    cfs_map_cache_pin(fx.rl, MAIN_FORKNUM);
    cfs_stats_reset(fx.rl, MAIN_FORKNUM);
 
    cfs_test_fill_page(page, 0xA0);
    if (cfs_write_page_cached(cfs, 0, (const char *) page, &opts) != 0)
        ok = false;
    /* First read populates the cache; second read is a cache hit. */
    if (ok && cfs_read_page_cached(cfs, 0, (char *) back) != 0)
        ok = false;
    if (ok && memcmp(page, back, TEST_BLCKSZ) != 0)
        ok = false;
    if (ok && cfs_read_page_cached(cfs, 0, (char *) back) != 0)
        ok = false;
 
    cfs_stats_snapshot(fx.rl, MAIN_FORKNUM, &snap);
    if (snap.write_count < 1 || snap.read_count < 1)
        ok = false;
 
    cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM);
    cfs_close(cfs);
 
    snprintf(detail, sizeof(detail),
             "cached write/read reads=%llu writes=%llu",
             (unsigned long long) snap.read_count,
             (unsigned long long) snap.write_count);
    add_result("shmem_cached_io", ok ? "ok" : "fail", detail);
    cfs_storage_teardown(&fx);
}
 
/*
 * A corrupt entry served from the shared cache (bad entry_crc) must be
 * rejected on the cache-hit path, with the block's cache slot dropped so the
 * next read falls back to the authoritative map.
 */
static void
test_read_cached_entry_corruption(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    unsigned char page[TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    CfsMapEntry bad;
    bool        ok = true;
 
    cfs_storage_setup(&fx, "cachemapcorrupt");
    if (fx.dir == NULL)
    {
        add_result("read_cached_entry_corruption", "fail", "setup failed");
        return;
    }
    fx.rl.locator.relNumber = 800360;
    cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM);
 
    cfs = cfs_storage_open_new(&fx);
    cfs_map_cache_pin(fx.rl, MAIN_FORKNUM);
 
    cfs_test_fill_page(page, 0x22);
    if (cfs_write_page_cached(cfs, 0, (const char *) page, &opts) != 0)
        ok = false;
 
    /* Publish an entry with a corrupted CRC into the shared segment. */
    cfs_map_entry_init(&bad);
    bad.physical_offset = CFS_CFP_BASE_OFFSET;
    bad.compressed_size = 1;
    bad.generation = 1;
    cfs_map_entry_crc_set(&bad);
    bad.entry_crc ^= 0x1;
    cfs_shared_map_store(fx.rl, MAIN_FORKNUM, 0, &bad,
                         cfs_map_cache_get_generation(fx.rl, MAIN_FORKNUM));
 
    /* The segment-hit read must reject the corrupt entry (ERROR by GUC). */
    if (ok)
    {
        bool        raised = false;
 
        PG_TRY();
        {
            (void) cfs_read_page_cached(cfs, 0, (char *) back);
        }
        PG_CATCH();
        {
            raised = true;
            FlushErrorState();
 
            /*
             * The error unwinding can leave a transient context current; back
             * to a durable one.
             */
            MemoryContextSwitchTo(TopMemoryContext);
        }
        PG_END_TRY();
        if (!raised)
            ok = false;
    }
 
    /* The corrupt entry must have been dropped, not just refused once. */
    if (ok && cfs_shared_map_lookup(fx.rl, MAIN_FORKNUM, 0, &bad, NULL))
        ok = false;
 
    cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM);
    cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
    cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM);
    cfs_close(cfs);
 
    add_result("read_cached_entry_corruption", ok ? "ok" : "fail",
               ok ? "corrupt cached entry rejected and invalidated"
               : "corrupt cached entry not rejected");
    cfs_storage_teardown(&fx);
}
 
static void
test_bg_pause_expiry(void)
{
    CfsBgStatus st;
    char        detail[160];
    bool        ok = true;
 
    /* An already-expired timed pause must self-heal on read. */
    cfs_bg_pause((int64) GetCurrentTimestamp() - 1000000);
    if (cfs_bg_is_paused())
        ok = false;
    MemSet(&st, 0, sizeof(st));
    cfs_bg_get_status(&st);
    if (st.paused || st.paused_until != 0)
        ok = false;
 
    /* An indefinite pause must hold. */
    cfs_bg_pause(0);
    if (!cfs_bg_is_paused())
        ok = false;
 
    /* Resume clears it. */
    cfs_bg_resume();
    if (cfs_bg_is_paused())
        ok = false;
 
    cfs_bg_resume();            /* never leave the worker paused */
 
    snprintf(detail, sizeof(detail), "pause/expiry/status %s",
             ok ? "ok" : "failed");
    add_result("bg_pause_expiry", ok ? "ok" : "fail", detail);
}
 
/*
 * A durable compaction swap replaces the .cfp inode while a writer's handle
 * still points at the old one (stale fds).  A cache hit must reopen such a
 * handle before reading through the cached offset: the offset is valid in
 * the NEW .cfp, and reading it through the old fd returns the pre-swap
 * bytes (or garbage).  cfs_handle_refresh_if_stale() must run on the hit
 * path when this handle's open_generation lags the current map generation.
 */
static void
test_shmem_stale_handle_hit(void)
{
    RelFileLocatorBackend rl;
    CfsRelation *h1;
    CfsRelation *h2;
    unsigned char v1[TEST_BLCKSZ];
    unsigned char v2[TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    CfsCompactOptions copts = CFS_COMPACT_OPTIONS_DEFAULT;
    CfsCompactResult cres;
    char        detail[160];
    bool        ok = true;
 
    rl.locator.spcOid = DEFAULTTABLESPACE_OID;
    rl.locator.dbOid = MyDatabaseId;
    rl.locator.relNumber = 999091;
    rl.backend = INVALID_PROC_NUMBER;
 
    cfs_test_unlink_synthetic(rl);
    cfs_map_cache_invalidate(rl, MAIN_FORKNUM);
 
    h1 = cfs_create(rl, MAIN_FORKNUM);
    cfs_map_cache_pin(rl, MAIN_FORKNUM);
 
    cfs_test_fill_page(v1, 0x10);
    cfs_test_fill_page(v2, 0x20);
 
    /* h1 publishes block 0 = v1 and reads it back (cache populated). */
    if (cfs_write_page_cached(h1, 0, (const char *) v1, &opts) != 0)
        ok = false;
    if (ok && cfs_read_page_cached(h1, 0, (char *) back) != 0)
        ok = false;
    if (ok && memcmp(back, v1, TEST_BLCKSZ) != 0)
        ok = false;
 
    /* Durable compaction swap: generation +1, h1 now holds stale fds. */
    if (ok && cfs_compact_relation(rl, MAIN_FORKNUM, &copts, &cres,
                                   InvalidOid) != CFS_STORAGE_OK)
        ok = false;
 
    /* h2 opens at the current generation and rewrites block 0 = v2. */
    h2 = cfs_open(rl, MAIN_FORKNUM, CFS_OPEN_RDWR);
    if (h2 == NULL)
        ok = false;
    else
    {
        if (cfs_write_page_cached(h2, 0, (const char *) v2, &opts) != 0)
            ok = false;
        cfs_close(h2);
    }
 
    /* h1 (stale fds) must reopen on the cache hit and read v2, not v1. */
    if (ok && cfs_read_page_cached(h1, 0, (char *) back) != 0)
        ok = false;
    if (ok && memcmp(back, v2, TEST_BLCKSZ) != 0)
        ok = false;
 
    cfs_map_cache_invalidate(rl, MAIN_FORKNUM);
    cfs_map_cache_release_relation(rl, MAIN_FORKNUM);
    cfs_close(h1);
    cfs_test_unlink_synthetic(rl);
 
    snprintf(detail, sizeof(detail), "stale handle reopened on hit %s",
             ok ? "ok" : "failed");
    add_result("shmem_stale_handle_hit", ok ? "ok" : "fail", detail);
}
 
/*
 * Publish guard: cfs_map_cache_publish_if_not_stale() must never
 * overwrite a cache entry that carries a newer per-block generation, so a
 * reader that fell behind a concurrent writer of the same block cannot
 * poison the shared cache with its older local entry.
 */
/*
 * Generation tagging: a publication must stamp the cache cell with the map
 * generation the entry's offsets belong to (the one captured when the
 * publishing reader refreshed its map), never with the generation current
 * at publication time.  Scenario: the reader captures the generation, a
 * compaction sweeps the cells and bumps the generation, and only then does
 * the reader publish offsets of the old generation.  The cell must carry
 * the captured (old) generation, so the lookup validation rejects it;
 * stamping it with the current one would serve a stale offset against the
 * new sidecar files.
 */
/*
 * Shared block-map segment pool API: store/lookup round trip, INVALID
 * sentinel miss, segment boundaries, truncate-range handling and relation
 * invalidation with the pool counters.
 */
static void
test_shared_map_api(void)
{
    RelFileLocatorBackend rl = cfs_shmem_test_locator(800710);
    CfsMapEntry in;
    CfsMapEntry out;
    uint64      in_use = 0;
    uint64      in_use0 = 0;
    uint64      loads = 0;
    uint64      evictions = 0;
    uint64      evictions0 = 0;
    uint64      capacity = 0;
    char        detail[160];
    bool        ok = true;
 
    cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM);
    cfs_shared_map_stats(&in_use0, &loads, &evictions0, &capacity);
    if (capacity == 0)
    {
        add_result("shared_map_api", "skip", "pool disabled");
        return;
    }
    /* Other relations may hold segments; assert on deltas. */
 
    /* A lookup before any store must miss. */
    if (cfs_shared_map_lookup(rl, MAIN_FORKNUM, 10, &out, NULL))
        ok = false;
 
    /* Store into block 10 and look it back up. */
    cfs_map_entry_init(&in);
    in.physical_offset = 4096;
    in.compressed_size = 1234;
    in.generation = 1;
    cfs_map_entry_crc_set(&in);
 
    if (!cfs_shared_map_store(rl, MAIN_FORKNUM, 10, &in,
                              cfs_map_cache_get_generation(rl, MAIN_FORKNUM)))
        ok = false;
    if (ok && !cfs_shared_map_lookup(rl, MAIN_FORKNUM, 10, &out, NULL))
        ok = false;
    else if (ok && (out.physical_offset != in.physical_offset ||
                    out.compressed_size != in.compressed_size ||
                    out.generation != in.generation))
        ok = false;
 
    /* An untouched block of the same segment is the INVALID sentinel. */
    if (ok && cfs_shared_map_lookup(rl, MAIN_FORKNUM, 11, &out, NULL))
        ok = false;
 
    /* A block of the next segment spans a second pool segment. */
    if (ok && !cfs_shared_map_store(rl, MAIN_FORKNUM,
                                    CFS_MAP_SEGMENT_BLOCKS + 5, &in,
                                    cfs_map_cache_get_generation(rl, MAIN_FORKNUM)))
        ok = false;
    if (ok && !cfs_shared_map_lookup(rl, MAIN_FORKNUM,
                                     CFS_MAP_SEGMENT_BLOCKS + 5, &out, NULL))
        ok = false;
 
    cfs_shared_map_stats(&in_use, &loads, &evictions, &capacity);
    if (ok && in_use - in_use0 != 2)
        ok = false;
 
    /* Relation invalidation drops everything and counts an eviction. */
    if (ok)
    {
        cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM);
        if (cfs_shared_map_lookup(rl, MAIN_FORKNUM, 10, &out, NULL))
            ok = false;
        cfs_shared_map_stats(&in_use, &loads, &evictions, &capacity);
        if (in_use - in_use0 != 0 || evictions - evictions0 == 0)
            ok = false;
    }
 
    snprintf(detail, sizeof(detail), "segment pool API %s",
             ok ? "ok" : "failed");
    add_result("shared_map_api", ok ? "ok" : "fail", detail);
}
 
/*
 * The pool must not serve rows at or above the metadata slot's current
 * logical size.  A truncate shrinks the slot (and
 * journals RESIZE) under the append lock but drops the resident segments
 * outside it, so a lookup racing in that window can still find the stale
 * segment; the nblocks gate must turn that into a plain miss.
 */
static void
test_shared_map_nblocks_gate(void)
{
    RelFileLocatorBackend rl = cfs_shmem_test_locator(800740);
    CfsMapEntry in;
    CfsMapEntry out;
    char        detail[160];
    bool        ok = true;
 
    cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM);
 
    cfs_map_entry_init(&in);
    in.physical_offset = 4096;
    in.compressed_size = 1234;
    in.generation = 1;
    cfs_map_entry_crc_set(&in);
 
    /* Publish the logical size the way the write path does, then store. */
    cfs_map_cache_set_meta(rl, MAIN_FORKNUM, 100);
    if (!cfs_shared_map_store(rl, MAIN_FORKNUM, 5, &in,
                              cfs_map_cache_get_generation(rl, MAIN_FORKNUM)) ||
        !cfs_shared_map_store(rl, MAIN_FORKNUM, 50, &in,
                              cfs_map_cache_get_generation(rl, MAIN_FORKNUM)) ||
        !cfs_shared_map_store(rl, MAIN_FORKNUM, 95, &in,
                              cfs_map_cache_get_generation(rl, MAIN_FORKNUM)))
        ok = false;
 
    /* All rows are served while nblocks == 100. */
    if (ok && !cfs_shared_map_lookup(rl, MAIN_FORKNUM, 95, &out, NULL))
        ok = false;
 
    /*
     * The truncate window: the slot size (and generation) is already shrunk,
     * the stale segments are still resident.
     */
    if (ok)
        cfs_map_cache_truncate(rl, MAIN_FORKNUM, 40);
 
    /* Rows at or above the new size must miss; rows below still hit. */
    if (ok && cfs_shared_map_lookup(rl, MAIN_FORKNUM, 50, &out, NULL))
        ok = false;
    if (ok && cfs_shared_map_lookup(rl, MAIN_FORKNUM, 95, &out, NULL))
        ok = false;
    if (ok && !cfs_shared_map_lookup(rl, MAIN_FORKNUM, 5, &out, NULL))
        ok = false;
 
    cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM);
 
    snprintf(detail, sizeof(detail), "nblocks gate %s",
             ok ? "ok" : "served stale rows");
    add_result("shared_map_nblocks_gate", ok ? "ok" : "fail", detail);
}
 
/*
 * Segment eviction: filling more distinct segments than the pool holds
 * must evict by LRU (oldest store first), keep the pool fully used and
 * leave evicted lookups as plain misses.
 */
static void
test_shared_map_eviction(void)
{
    RelFileLocatorBackend rl = cfs_shmem_test_locator(800720);
    CfsMapEntry in;
    CfsMapEntry out;
    uint64      in_use = 0;
    uint64      loads = 0;
    uint64      evictions = 0;
    uint64      capacity = 0;
    char        detail[160];
    bool        ok = true;
    int         i;
 
    cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM);
    cfs_shared_map_stats(&in_use, &loads, &evictions, &capacity);
    if (capacity == 0)
    {
        add_result("shared_map_eviction", "skip", "pool disabled");
        return;
    }
 
    cfs_map_entry_init(&in);
    in.physical_offset = 4096;
    in.compressed_size = 100;
    in.generation = 1;
    cfs_map_entry_crc_set(&in);
 
    /* Fill capacity + 10 distinct segments: ten LRU evictions must occur. */
    for (i = 0; i < (int) capacity + 10; i++)
    {
        if (!cfs_shared_map_store(rl, MAIN_FORKNUM,
                                  (BlockNumber) i * CFS_MAP_SEGMENT_BLOCKS, &in,
                                  cfs_map_cache_get_generation(rl, MAIN_FORKNUM)))
        {
            ok = false;
            break;
        }
    }
 
    if (ok)
    {
        uint64      evictions_after;
 
        cfs_shared_map_stats(&in_use, &loads, &evictions_after, &capacity);
        if (in_use != capacity)
            ok = false;
        if (evictions_after - evictions < 10)
            ok = false;
    }
 
    /* The very first (oldest) segment was evicted: its lookup misses. */
    if (ok && cfs_shared_map_lookup(rl, MAIN_FORKNUM, 0, &out, NULL))
        ok = false;
 
    /* The newest segment survived. */
    if (ok && !cfs_shared_map_lookup(rl, MAIN_FORKNUM,
                                     (BlockNumber) ((int) capacity + 9) *
                                     CFS_MAP_SEGMENT_BLOCKS, &out, NULL))
        ok = false;
 
    cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM);
 
    snprintf(detail, sizeof(detail), "eviction %s",
             ok ? "ok" : "failed");
    add_result("shared_map_eviction", ok ? "ok" : "fail", detail);
}
 
/*
 * Eviction with a pinned relation: an open handle pins the relation's
 * metadata slot, but that pin protects the slot, not the pool segments.
 * Filling the pool beyond capacity with segments of the pinned relation
 * must still evict by usage_count order — otherwise a relation larger
 * than the pool keeps the pool exhausted forever and every further read
 * of the relation pays the authoritative fallback.
 */
static void
test_shared_map_eviction_pinned(void)
{
    RelFileLocatorBackend rl = cfs_shmem_test_locator(800730);
    CfsMapEntry in;
    CfsMapEntry out;
    uint64      in_use = 0;
    uint64      evictions = 0;
    uint64      evictions_after = 0;
    uint64      capacity = 0;
    char        detail[160];
    bool        ok = true;
    int         i;
 
    cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM);
    cfs_shared_map_stats(&in_use, NULL, &evictions, &capacity);
    if (capacity == 0)
    {
        add_result("shared_map_eviction_pinned", "skip", "pool disabled");
        return;
    }
 
    cfs_map_entry_init(&in);
    in.physical_offset = 4096;
    in.compressed_size = 100;
    in.generation = 1;
    cfs_map_entry_crc_set(&in);
 
    /* The relation stays pinned for the whole fill, like an open handle. */
    cfs_map_cache_pin(rl, MAIN_FORKNUM);
 
    for (i = 0; i < (int) capacity + 10; i++)
    {
        if (!cfs_shared_map_store(rl, MAIN_FORKNUM,
                                  (BlockNumber) i * CFS_MAP_SEGMENT_BLOCKS,
                                  &in,
                                  cfs_map_cache_get_generation(rl, MAIN_FORKNUM)))
        {
            ok = false;
            break;
        }
    }
 
    if (ok)
    {
        cfs_shared_map_stats(&in_use, NULL, &evictions_after, &capacity);
        if (in_use != capacity)
            ok = false;
        if (evictions_after - evictions < 10)
            ok = false;
    }
 
    /* The oldest segments were evicted even though the relation is pinned. */
    if (ok && cfs_shared_map_lookup(rl, MAIN_FORKNUM, 0, &out, NULL))
        ok = false;
    if (ok && !cfs_shared_map_lookup(rl, MAIN_FORKNUM,
                                     (BlockNumber) ((int) capacity + 9) *
                                     CFS_MAP_SEGMENT_BLOCKS, &out, NULL))
        ok = false;
 
    cfs_map_cache_unpin(rl, MAIN_FORKNUM);
    cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM);
 
    snprintf(detail, sizeof(detail), "pinned eviction %s",
             ok ? "ok" : "failed");
    add_result("shared_map_eviction_pinned", ok ? "ok" : "fail", detail);
}
 
/*
 * A repeated store of an already resident key must be a plain update, not a
 * victim search: with a full pool the old acquire path evicted an unrelated
 * segment before it even looked the key up.
 */
static void
test_shared_map_resident_store_no_evict(void)
{
    RelFileLocatorBackend rl = cfs_shmem_test_locator(800810);
    CfsMapEntry in;
    uint64      capacity = 0;
    uint64      ev0 = 0;
    uint64      ev1 = 0;
    uint64      gen;
    char        detail[160];
    bool        ok = true;
    int         i;
 
    cfs_shared_map_stats(NULL, NULL, NULL, &capacity);
    if (capacity < 2)
    {
        add_result("shared_map_resident_store_no_evict", "skip",
                   "pool too small");
        return;
    }
 
    cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM);
    gen = cfs_map_cache_get_generation(rl, MAIN_FORKNUM);
    cfs_map_entry_init(&in);
    in.physical_offset = 4096;
    in.compressed_size = 100;
    in.generation = 1;
    cfs_map_entry_crc_set(&in);
 
    /*
     * Fill the pool with distinct keys.  Other tests may already hold
     * segments, so use the last key inserted as the guaranteed resident one
     * rather than assuming key 0 survived the fill.
     */
    for (i = 0; i < (int) capacity; i++)
        if (!cfs_shared_map_store(rl, MAIN_FORKNUM,
                                  (BlockNumber) i * CFS_MAP_SEGMENT_BLOCKS,
                                  &in, gen))
            ok = false;
 
    /* Make the target resident, then measure only the repeated stores. */
    if (!cfs_shared_map_store(rl, MAIN_FORKNUM,
                              (BlockNumber) (capacity - 1) *
                              CFS_MAP_SEGMENT_BLOCKS, &in, gen))
        ok = false;
 
    cfs_shared_map_stats(NULL, NULL, &ev0, NULL);
    for (i = 0; i < 10; i++)
        if (!cfs_shared_map_store(rl, MAIN_FORKNUM,
                                  (BlockNumber) (capacity - 1) *
                                  CFS_MAP_SEGMENT_BLOCKS, &in, gen))
            ok = false;
    cfs_shared_map_stats(NULL, NULL, &ev1, NULL);
 
    if (ok && ev1 != ev0)
        ok = false;
    if (ok && !cfs_shared_map_lookup(rl, MAIN_FORKNUM,
                                     (BlockNumber) (capacity - 1) *
                                     CFS_MAP_SEGMENT_BLOCKS, &in, NULL))
        ok = false;
 
    cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM);
    snprintf(detail, sizeof(detail), "resident store evictions %llu",
             (unsigned long long) (ev1 - ev0));
    add_result("shared_map_resident_store_no_evict", ok ? "ok" : "fail",
               detail);
}
 
/*
 * Clock sweep: a segment touched by a hit must survive the next victim
 * selection even with a full pool; an untouched segment is evicted instead.
 */
static void
test_shared_map_clock_sweep(void)
{
    RelFileLocatorBackend rl = cfs_shmem_test_locator(800830);
    CfsMapEntry in;
    uint64      capacity = 0;
    uint64      gen;
    char        detail[160];
    bool        ok = true;
    int         i;
 
    cfs_shared_map_stats(NULL, NULL, NULL, &capacity);
    if (capacity < 3)
    {
        add_result("shared_map_clock_sweep", "skip", "pool too small");
        return;
    }
 
    cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM);
    gen = cfs_map_cache_get_generation(rl, MAIN_FORKNUM);
    cfs_map_entry_init(&in);
    in.physical_offset = 4096;
    in.compressed_size = 100;
    in.generation = 1;
    cfs_map_entry_crc_set(&in);
 
    for (i = 0; i < (int) capacity; i++)
        if (!cfs_shared_map_store(rl, MAIN_FORKNUM,
                                  (BlockNumber) i * CFS_MAP_SEGMENT_BLOCKS,
                                  &in, gen))
            ok = false;
 
    /* Key 0 becomes the recently used segment. */
    if (ok && !cfs_shared_map_lookup(rl, MAIN_FORKNUM, 0, &in, NULL))
        ok = false;
 
    /* A new key needs a victim: key 0 must not be the one. */
    if (ok && !cfs_shared_map_store(rl, MAIN_FORKNUM,
                                    (BlockNumber) capacity *
                                    CFS_MAP_SEGMENT_BLOCKS, &in, gen))
        ok = false;
    if (ok && !cfs_shared_map_lookup(rl, MAIN_FORKNUM, 0, &in, NULL))
        ok = false;
 
    cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM);
    snprintf(detail, sizeof(detail), "clock sweep %s",
             ok ? "kept the hot segment" : "evicted the hot segment");
    add_result("shared_map_clock_sweep", ok ? "ok" : "fail", detail);
}
 
/*
 * Segment loading: cfs_shared_map_ensure() reads a segment straight from
 * the .cfsmap snapshot.  After a checkpoint the loaded entries must match
 * the authoritative per-handle map, and blocks beyond the snapshot stay
 * INVALID (a miss, filled by the journal-replay path).
 */
static void
test_shared_map_ensure(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    unsigned char page[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    CfsMapEntry out;
    uint64      capacity = 0;
    uint64      loads_before = 0;
    uint64      loads_after = 0;
    char        detail[160];
    bool        ok = true;
 
    cfs_shared_map_stats(NULL, NULL, NULL, &capacity);
    if (capacity == 0)
    {
        add_result("shared_map_ensure", "skip", "pool disabled");
        return;
    }
 
    cfs_storage_setup(&fx, "segload");
    if (fx.dir == NULL)
    {
        add_result("shared_map_ensure", "fail", "setup failed");
        return;
    }
 
    cfs = cfs_storage_open_new(&fx);
    cfs_test_fill_page(page, 0x71);
    if (cfs_write_page(cfs, 0, (const char *) page, &opts) != CFS_STORAGE_OK ||
        cfs_write_page(cfs, 1, (const char *) page, &opts) != CFS_STORAGE_OK)
        ok = false;
 
    if (ok)
    {
        /* Checkpoint: snapshot + journal reset. */
        cfs_map_save_snapshot(cfs);
        test_journal_reset(cfs, ERROR);
    }
    cfs_close(cfs);
    if (!ok)
    {
        snprintf(detail, sizeof(detail), "ensure setup failed");
        add_result("shared_map_ensure", "fail", detail);
        cfs_storage_teardown(&fx);
        return;
    }
 
    /* Fresh handle: its own map load is the reference for the segment. */
    cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM,
                         fx.cfp_path, fx.map_path, fx.jrn_path,
                         CFS_OPEN_RDWR);
    if (cfs == NULL)
    {
        add_result("shared_map_ensure", "fail", "reopen failed");
        cfs_storage_teardown(&fx);
        return;
    }
 
    cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
 
    /* Load the segment covering blocks 0..1 from the snapshot. */
    if (cfs_shared_map_ensure(cfs, 0) != CFS_STORAGE_OK)
        ok = false;
 
    /* The loaded entry must match the handle's authoritative map. */
    if (ok && !cfs_shared_map_lookup(fx.rl, MAIN_FORKNUM, 0, &out, NULL))
        ok = false;
    if (ok && (out.physical_offset != cfs->map[0].physical_offset ||
               out.compressed_size != cfs->map[0].compressed_size ||
               out.generation != cfs->map[0].generation))
        ok = false;
 
    /*
     * A second ensure on the same segment is a cheap residency hit (no new
     * snapshot load); a block beyond the snapshot inside the loaded segment
     * stays INVALID.
     */
    cfs_shared_map_stats(NULL, &loads_before, NULL, NULL);
    if (ok && cfs_shared_map_ensure(cfs, 1) != CFS_STORAGE_OK)
        ok = false;
    cfs_shared_map_stats(NULL, &loads_after, NULL, NULL);
    if (loads_after != loads_before)
        ok = false;
    if (ok && cfs_shared_map_lookup(fx.rl, MAIN_FORKNUM, 100, &out, NULL))
        ok = false;
 
    cfs_close(cfs);
    cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
    cfs_storage_teardown(&fx);
 
    snprintf(detail, sizeof(detail), "segment load %s",
             ok ? "ok" : "failed");
    add_result("shared_map_ensure", ok ? "ok" : "fail", detail);
}
 
/*
 * A resident segment tagged with an older relation generation must never
 * satisfy a read through a handle opened after the generation bump: the
 * old offsets belong to the pre-truncate sidecar pair.  The reader has to
 * retry through eviction/reload and return the real page, not a zero page.
 */
static void
test_shared_map_generation_gate(void)
{
    CfsStorageFixture fx;
    CfsRelation *h;
    CfsRelation *lazy;
    unsigned char page[TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    char        cfp_path[MAXPGPATH];
    char        map_path[MAXPGPATH];
    char        jrn_path[MAXPGPATH];
    char        detail[160];
    bool        ok = true;
 
    cfs_storage_setup(&fx, "seggengate");
    if (fx.dir == NULL)
    {
        add_result("shared_map_generation_gate", "fail", "setup failed");
        return;
    }
    fx.rl.locator.relNumber = 800745;
    cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
    cfs_map_cache_pin(fx.rl, MAIN_FORKNUM);
    strlcpy(cfp_path, fx.cfp_path, sizeof(cfp_path));
    strlcpy(map_path, fx.map_path, sizeof(map_path));
    strlcpy(jrn_path, fx.jrn_path, sizeof(jrn_path));
 
    h = cfs_storage_open_new(&fx);
    cfs_test_fill_page(page, 0x77);
    if (cfs_write_page(h, 0, (const char *) page, &opts) != CFS_STORAGE_OK)
        ok = false;
    /* A snapshot lets the stale segment be reloaded after the bump. */
    if (ok && cfs_map_save_snapshot(h) != CFS_STORAGE_OK)
        ok = false;
    if (ok)
        cfs_map_cache_set_meta(fx.rl, MAIN_FORKNUM, 1);
    cfs_close(h);
 
    /* Warm the segment under the old generation. */
    lazy = cfs_test_open_lazy(fx.rl, cfp_path, map_path, jrn_path);
    if (lazy == NULL ||
        cfs_read_page_cached(lazy, 0, (char *) back) != CFS_STORAGE_OK ||
        memcmp(back, page, TEST_BLCKSZ) != 0)
        ok = false;
    if (lazy)
        cfs_close(lazy);
 
    /*
     * Bump the generation without invalidating the pool: the segment stays
     * resident with the old rel_generation, while a new handle opens with the
     * new one.  The stale segment must be evicted and reloaded, not treated
     * as proof that block 0 was never written.
     */
    cfs_map_cache_truncate(fx.rl, MAIN_FORKNUM, 1);
    lazy = cfs_test_open_lazy(fx.rl, cfp_path, map_path, jrn_path);
    if (lazy == NULL)
        ok = false;
    else
    {
        if (cfs_read_page_cached(lazy, 0, (char *) back) != CFS_STORAGE_OK ||
            memcmp(back, page, TEST_BLCKSZ) != 0)
            ok = false;
        cfs_close(lazy);
    }
 
    cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM);
    cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
    cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM);
 
    snprintf(detail, sizeof(detail), "generation gate %s",
             ok ? "ok" : "served a zero/stale page");
    add_result("shared_map_generation_gate", ok ? "ok" : "fail", detail);
    cfs_storage_teardown(&fx);
}
 
static void
test_shared_map_short_read(void)
{
    CfsStorageFixture fx;
    CfsRelation *h;
    CfsRelation *lazy;
    unsigned char page[TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    char        cfp_path[MAXPGPATH];
    char        map_path[MAXPGPATH];
    char        jrn_path[MAXPGPATH];
    uint64      in_use_before = 0;
    uint64      in_use_after = 0;
    char        detail[160];
    bool        ok = true;
    int         fd;
 
    cfs_storage_setup(&fx, "segshort");
    if (fx.dir == NULL)
    {
        add_result("shared_map_short_read", "fail", "setup failed");
        return;
    }
    fx.rl.locator.relNumber = 800747;
    cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
    cfs_map_cache_pin(fx.rl, MAIN_FORKNUM);
    strlcpy(cfp_path, fx.cfp_path, sizeof(cfp_path));
    strlcpy(map_path, fx.map_path, sizeof(map_path));
    strlcpy(jrn_path, fx.jrn_path, sizeof(jrn_path));
 
    h = cfs_storage_open_new(&fx);
    cfs_test_fill_page(page, 0x66);
    if (cfs_write_page(h, 0, (const char *) page, &opts) != CFS_STORAGE_OK ||
        cfs_write_page(h, 1, (const char *) page, &opts) != CFS_STORAGE_OK)
        ok = false;
    if (ok && cfs_map_save_snapshot(h) != CFS_STORAGE_OK)
        ok = false;
    cfs_close(h);
 
    /* Keep the header but cut the entry range in half. */
    fd = open(fx.map_path, O_WRONLY);
    if (fd < 0 ||
        ftruncate(fd, CFS_MAP_HEADER_SIZE + CFS_MAP_ENTRY_SIZE / 2) != 0)
        ok = false;
    if (fd >= 0)
        close(fd);
 
    cfs_shared_map_stats(&in_use_before, NULL, NULL, NULL);
    lazy = cfs_test_open_lazy(fx.rl, cfp_path, map_path, jrn_path);
    if (lazy == NULL)
        ok = false;
    else
    {
        /*
         * A partial trailing row is a torn write and the loader ignores it
         * (the row count is the floored file size).  The journal still holds
         * the covering record, so the torn block reads back healed - never as
         * a fabricated zero page and never as an error.
         */
        if (cfs_read_page_cached(lazy, 0, (char *) back) != 0 ||
            memcmp(page, back, TEST_BLCKSZ) != 0)
            ok = false;
        cfs_close(lazy);
    }
 
    cfs_shared_map_stats(&in_use_after, NULL, NULL, NULL);
 
    /*
     * A torn tail no longer aborts the segment load; the journal-healed
     * segment legitimately lands in the pool.
     */
 
    cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM);
    cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
    cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM);
 
    snprintf(detail, sizeof(detail), "torn tail ignored, healed from journal (%s)",
             ok ? "healed" : "data lost");
    add_result("shared_map_short_read", ok ? "ok" : "fail", detail);
    cfs_storage_teardown(&fx);
}
 
/*
 * A corrupt journal record with valid records after it is not a torn tail.
 * The segment replay used to stop at it with DEBUG1 and then mark the
 * segment journal_synced, so the pool served the stale snapshot entry to
 * every backend.  It must escalate like the full replay does and leave the
 * segment unsynchronised instead.
 */
static void
test_shared_map_segment_replay_corruption(void)
{
    CfsStorageFixture fx;
    CfsRelation *h;
    CfsRelation *lazy = NULL;
    unsigned char page[TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    CfsJournalEntry je;
    uint64      capacity = 0;
    char        cfp_path[MAXPGPATH];
    char        map_path[MAXPGPATH];
    char        jrn_path[MAXPGPATH];
    char        detail[160];
    bool        raised = false;
    bool        ok = true;
    int         fd = -1;
 
    cfs_shared_map_stats(NULL, NULL, NULL, &capacity);
    if (capacity == 0)
    {
        add_result("shared_map_replay_corruption", "skip", "pool disabled");
        return;
    }
 
    cfs_storage_setup(&fx, "segjrncorrupt");
    if (fx.dir == NULL)
    {
        add_result("shared_map_replay_corruption", "fail", "setup failed");
        return;
    }
    fx.rl.locator.relNumber = 800749;
    cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
    cfs_map_cache_pin(fx.rl, MAIN_FORKNUM);
    strlcpy(cfp_path, fx.cfp_path, sizeof(cfp_path));
    strlcpy(map_path, fx.map_path, sizeof(map_path));
    strlcpy(jrn_path, fx.jrn_path, sizeof(jrn_path));
 
    h = cfs_storage_open_new(&fx);
 
    /* Snapshot version A of block 0. */
    cfs_test_fill_page(page, 0xA1);
    if (cfs_write_page(h, 0, (const char *) page, &opts) != CFS_STORAGE_OK)
        ok = false;
    if (ok && cfs_map_save_snapshot(h) != CFS_STORAGE_OK)
        ok = false;
    if (ok)
        test_journal_reset(h, ERROR);
 
    /* Journal now holds version B of block 0, then a valid block-1 record. */
    cfs_test_fill_page(page, 0xB2);
    if (ok && cfs_write_page(h, 0, (const char *) page, &opts)
        != CFS_STORAGE_OK)
        ok = false;
    cfs_test_fill_page(page, 0xC3);
    if (ok && cfs_write_page(h, 1, (const char *) page, &opts)
        != CFS_STORAGE_OK)
        ok = false;
    cfs_close(h);
 
    /*
     * Corrupt the first record, leaving the second one valid: this is the
     * non-tail shape a legal append cannot produce.
     */
    if (ok)
    {
        struct stat st;
        uint32      garbage = 0xDEADBEEF;
 
        fd = BasicOpenFile(fx.jrn_path, O_RDWR | PG_BINARY);
        if (fd < 0)
            ok = false;
        else if (fstat(fd, &st) != 0 ||
                 st.st_size < (off_t) (CFS_JOURNAL_HEADER_SIZE +
                                       2 * CFS_JOURNAL_ENTRY_SIZE) ||
                 pread(fd, &je, sizeof(je),
                       CFS_JOURNAL_HEADER_SIZE) != sizeof(je) ||
                 je.op != CFS_JRN_OP_UPDATE || je.blocknum != 0)
            ok = false;
        else if (pwrite(fd, &garbage, sizeof(garbage),
                        CFS_JOURNAL_HEADER_SIZE) != sizeof(garbage))
            ok = false;
    }
    if (fd >= 0)
        close(fd);
 
    if (ok)
    {
        cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
        lazy = cfs_test_open_lazy(fx.rl, cfp_path, map_path, jrn_path);
        if (lazy == NULL)
            ok = false;
        else
            lazy->strict = true;
    }
 
    if (ok)
    {
        MemoryContext oldcontext = TopMemoryContext;
        ResourceOwner oldowner = CurrentResourceOwner;
 
        MemoryContextSwitchTo(TopMemoryContext);
 
        /*
         * The read raises while holding the append lock, so use an internal
         * subtransaction to get the full cleanup and keep testing.
         */
        BeginInternalSubTransaction(NULL);
        PG_TRY();
        {
            (void) cfs_read_page_cached(lazy, 0, (char *) back);
            ReleaseCurrentSubTransaction();
            MemoryContextSwitchTo(oldcontext);
            CurrentResourceOwner = oldowner;
        }
        PG_CATCH();
        {
            ErrorData  *edata;
 
            MemoryContextSwitchTo(oldcontext);
            edata = CopyErrorData();
            raised = (edata->message != NULL &&
                      strstr(edata->message, "corruption") != NULL);
            FreeErrorData(edata);
            FlushErrorState();
            RollbackAndReleaseCurrentSubTransaction();
            MemoryContextSwitchTo(oldcontext);
            CurrentResourceOwner = oldowner;
        }
        PG_END_TRY();
    }
 
    if (lazy != NULL)
        cfs_close(lazy);
    if (ok && !raised)
        ok = false;
 
    cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM);
    cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
    cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM);
 
    snprintf(detail, sizeof(detail), "mid-journal corruption %s",
             raised ? "rejected" : "served stale page");
    add_result("shared_map_replay_corruption", ok ? "ok" : "fail", detail);
    cfs_storage_teardown(&fx);
}
 
/*
 * Journal incarnation vs the segment sync cursor.  A checkpoint truncates
 * the journal (bumping its incarnation) while a pool segment survives with
 * a stale jrn_synced_off; two shapes must be handled:
 *
 *  - shrink: the journal shrank below the segment's cursor and a written
 *    block now lives only in the fresh .cfsmap snapshot — the segment must
 *    re-merge it instead of answering "never written";
 *  - regrow (ABA): the new-incarnation journal grows back past the stale
 *    cursor — replaying from the stale cursor silently skips the records
 *    below it.
 *
 * The full handle's storage-layer writes (cfs_write_page) append journal
 * records without publishing into the pool segment — exactly the
 * journal-only situation a failed store produces in production.
 */
static void
test_shared_map_journal_aba(void)
{
    CfsStorageFixture fx;
    CfsRelation *h;
    CfsRelation *lazy;
    unsigned char page[TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    CfsMapEntry bad;
    uint64      capacity = 0;
    char        cfp_path[MAXPGPATH];
    char        map_path[MAXPGPATH];
    char        jrn_path[MAXPGPATH];
    char        detail[160];
    bool        ok = true;
    int         i;
 
    cfs_shared_map_stats(NULL, NULL, NULL, &capacity);
    if (capacity == 0)
    {
        add_result("shared_map_journal_aba", "skip", "pool disabled");
        return;
    }
 
    cfs_storage_setup(&fx, "segjrnbump");
    if (fx.dir == NULL)
    {
        add_result("shared_map_journal_aba", "fail", "setup failed");
        return;
    }
    fx.rl.locator.relNumber = 800730;
    cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
    cfs_map_cache_pin(fx.rl, MAIN_FORKNUM);
    strlcpy(cfp_path, fx.cfp_path, sizeof(cfp_path));
    strlcpy(map_path, fx.map_path, sizeof(map_path));
    strlcpy(jrn_path, fx.jrn_path, sizeof(jrn_path));
 
    h = cfs_storage_open_new(&fx);
 
    /*
     * Phase A: snapshot v1, truncate the journal, warm the segment and
     * advance its sync cursor to the current journal end.
     */
    cfs_test_fill_page(page, 0x11);
    if (cfs_write_page(h, 0, (const char *) page, &opts) != CFS_STORAGE_OK)
        ok = false;
    if (ok && cfs_map_save_snapshot(h) != CFS_STORAGE_OK)
        ok = false;
    if (ok)
        test_journal_reset(h, WARNING);
    if (ok)
    {
        lazy = cfs_test_open_lazy(fx.rl, cfp_path, map_path, jrn_path);
        if (lazy == NULL ||
            cfs_read_page_cached(lazy, 0, (char *) back) != CFS_STORAGE_OK ||
            memcmp(back, page, TEST_BLCKSZ) != 0)
            ok = false;
        if (lazy)
            cfs_close(lazy);
    }
    cfs_test_fill_page(page, 0x22);
    if (ok && cfs_write_page(h, 1, (const char *) page, &opts)
        != CFS_STORAGE_OK)
        ok = false;
    if (ok)
        cfs_map_cache_set_meta(fx.rl, MAIN_FORKNUM, 2);
    if (ok)
    {
        lazy = cfs_test_open_lazy(fx.rl, cfp_path, map_path, jrn_path);
        if (lazy == NULL ||
            cfs_read_page_cached(lazy, 1, (char *) back) != CFS_STORAGE_OK ||
            memcmp(back, page, TEST_BLCKSZ) != 0)
            ok = false;
        if (lazy)
            cfs_close(lazy);
    }
 
    /*
     * Phase B (shrink): block 2 is written journal-only, then snapshot v2
     * absorbs it and the journal is truncated.  Reading it must resolve
     * through the fresh snapshot, not return a zero page.
     */
    cfs_test_fill_page(page, 0x33);
    if (ok && cfs_write_page(h, 2, (const char *) page, &opts)
        != CFS_STORAGE_OK)
        ok = false;
    if (ok)
        cfs_map_cache_set_meta(fx.rl, MAIN_FORKNUM, 3);
    if (ok && cfs_map_save_snapshot(h) != CFS_STORAGE_OK)
        ok = false;
    if (ok)
        test_journal_reset(h, WARNING);
    if (ok)
    {
        lazy = cfs_test_open_lazy(fx.rl, cfp_path, map_path, jrn_path);
        if (lazy == NULL ||
            cfs_read_page_cached(lazy, 2, (char *) back) != CFS_STORAGE_OK ||
            memcmp(back, page, TEST_BLCKSZ) != 0)
            ok = false;
        if (lazy)
            cfs_close(lazy);
    }
 
    /*
     * Phase C (ABA): rewrite block 1 (its record lands near the journal
     * header, below the stale cursor), regrow the journal past the cursor
     * with block-0 rewrites, then force a block-1 miss with a poisoned
     * (bad-CRC) entry.  The miss path must replay from the journal header and
     * return the rewrite.
     */
    cfs_test_fill_page(page, 0x44);
    if (ok && cfs_write_page(h, 1, (const char *) page, &opts)
        != CFS_STORAGE_OK)
        ok = false;
    cfs_test_fill_page(page, 0x55);
    for (i = 0; ok && i < 10; i++)
    {
        if (cfs_write_page(h, 0, (const char *) page, &opts)
            != CFS_STORAGE_OK)
            ok = false;
    }
    if (ok)
    {
        cfs_map_entry_init(&bad);
        bad.physical_offset = CFS_CFP_BASE_OFFSET;
        bad.compressed_size = 1;
        bad.generation = 1;
        cfs_map_entry_crc_set(&bad);
        bad.entry_crc ^= 0x1;
        cfs_shared_map_store(fx.rl, MAIN_FORKNUM, 1, &bad,
                             cfs_map_cache_get_generation(fx.rl, MAIN_FORKNUM));
 
        /*
         * First read rejects the poisoned entry (ERROR); the retry must
         * resolve through the journal replay.
         */
        lazy = cfs_test_open_lazy(fx.rl, cfp_path, map_path, jrn_path);
        if (lazy == NULL)
            ok = false;
        else
        {
            bool        raised = false;
 
            PG_TRY();
            {
                (void) cfs_read_page_cached(lazy, 1, (char *) back);
            }
            PG_CATCH();
            {
                raised = true;
                FlushErrorState();
 
                /*
                 * The error unwinding can leave a transient context current;
                 * back to a durable one.
                 */
                MemoryContextSwitchTo(TopMemoryContext);
            }
            PG_END_TRY();
            if (!raised)
                ok = false;
            /* The retry must resolve the rewrite (payload 0x44). */
            cfs_test_fill_page(page, 0x44);
            if (ok && (cfs_read_page_cached(lazy, 1, (char *) back)
                       != CFS_STORAGE_OK ||
                       memcmp(back, page, TEST_BLCKSZ) != 0))
                ok = false;
            cfs_close(lazy);
        }
    }
 
    cfs_close(h);
    cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
    cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM);
    cfs_storage_teardown(&fx);
 
    snprintf(detail, sizeof(detail), "journal truncation vs segment sync %s",
             ok ? "ok" : "failed");
    add_result("shared_map_journal_aba", ok ? "ok" : "fail", detail);
}
 
/*
 * Truncate vs snapshot merge: a segment's RESIZE-cleared slots must not be
 * resurrected by a later .cfsmap merge.  The storage-layer truncate
 * journals RESIZE (the smgr path then drops the relation's segments), but
 * the on-disk .cfsmap stays wide until the next checkpoint — publishing or
 * merging a segment from it refills the cleared slots with pre-truncate
 * entries unless the journal (whose RESIZE is the only post-truncate
 * truth) is replayed after the merge.
 */
static void
test_shared_map_truncate_resurrect(void)
{
    CfsStorageFixture fx;
    CfsRelation *h;
    CfsRelation *lazy;
    unsigned char page[TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    unsigned char zeros[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    CfsMapEntry bad;
    uint64      capacity = 0;
    char        cfp_path[MAXPGPATH];
    char        map_path[MAXPGPATH];
    char        jrn_path[MAXPGPATH];
    char        detail[160];
    bool        ok = true;
 
    cfs_shared_map_stats(NULL, NULL, NULL, &capacity);
    if (capacity == 0)
    {
        add_result("shared_map_truncate_resurrect", "skip", "pool disabled");
        return;
    }
 
    cfs_storage_setup(&fx, "segtruncres");
    if (fx.dir == NULL)
    {
        add_result("shared_map_truncate_resurrect", "fail", "setup failed");
        return;
    }
    fx.rl.locator.relNumber = 800740;
    cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
    cfs_map_cache_pin(fx.rl, MAIN_FORKNUM);
    MemSet(zeros, 0, sizeof(zeros));
 
    /*
     * Snapshot the fixture paths into stack buffers: a PG_CATCH elsewhere in
     * the run can leave CurrentMemoryContext pointing at a context that a
     * later error unwinds, and psprintf'd path copies allocated there must
     * not outlive it.
     */
    strlcpy(cfp_path, fx.cfp_path, sizeof(cfp_path));
    strlcpy(map_path, fx.map_path, sizeof(map_path));
    strlcpy(jrn_path, fx.jrn_path, sizeof(jrn_path));
 
    h = cfs_storage_open_new(&fx);
 
    /* Three written blocks; the (wide) snapshot v1 covers them all. */
    cfs_test_fill_page(page, 0x11);
    if (cfs_write_page(h, 0, (const char *) page, &opts) != CFS_STORAGE_OK)
        ok = false;
    cfs_test_fill_page(page, 0x22);
    if (ok && cfs_write_page(h, 1, (const char *) page, &opts)
        != CFS_STORAGE_OK)
        ok = false;
    cfs_test_fill_page(page, 0x33);
    if (ok && cfs_write_page(h, 2, (const char *) page, &opts)
        != CFS_STORAGE_OK)
        ok = false;
    if (ok && cfs_map_save_snapshot(h) != CFS_STORAGE_OK)
        ok = false;
 
    /*
     * Truncate to one block (journal RESIZE; the smgr path mirrors this with
     * a segment invalidation and a meta update), then read block 0: the
     * replay applies the resize and clears blocks 1-2.
     */
    if (ok)
        cfs_truncate(h, 1);
    if (ok)
    {
        cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
        cfs_map_cache_set_meta(fx.rl, MAIN_FORKNUM, 1);
 
        lazy = cfs_test_open_lazy(fx.rl, cfp_path, map_path, jrn_path);
        cfs_test_fill_page(page, 0x11);
        if (lazy == NULL ||
            cfs_read_page_cached(lazy, 0, (char *) back) != CFS_STORAGE_OK ||
            memcmp(back, page, TEST_BLCKSZ) != 0)
            ok = false;
        if (lazy)
            cfs_close(lazy);
    }
 
    /*
     * A corrupt block-0 entry drops the slot and un-loads the snapshot part,
     * exactly like a failed store would.
     */
    if (ok)
    {
        cfs_map_entry_init(&bad);
        bad.physical_offset = CFS_CFP_BASE_OFFSET;
        bad.compressed_size = 1;
        bad.generation = 1;
        cfs_map_entry_crc_set(&bad);
        bad.entry_crc ^= 0x1;
        cfs_shared_map_store(fx.rl, MAIN_FORKNUM, 0, &bad,
                             cfs_map_cache_get_generation(fx.rl, MAIN_FORKNUM));
 
        lazy = cfs_test_open_lazy(fx.rl, cfp_path, map_path, jrn_path);
        if (lazy == NULL)
            ok = false;
        else
        {
            bool        raised = false;
 
            PG_TRY();
            {
                (void) cfs_read_page_cached(lazy, 0, (char *) back);
            }
            PG_CATCH();
            {
                raised = true;
                FlushErrorState();
 
                /*
                 * The error unwinding can leave a transient context current;
                 * back to a durable one.
                 */
                MemoryContextSwitchTo(TopMemoryContext);
            }
            PG_END_TRY();
            if (!raised)
                ok = false;
            cfs_close(lazy);
        }
    }
 
    /*
     * Re-extend back to three blocks (journal RESIZE only, no writes): blocks
     * 1-2 are extension gaps and must read as zero pages, and block 0 must
     * resolve back to its payload — never to the truncated pre-truncate
     * entries the stale wide .cfsmap still carries.
     */
    if (ok && cfs_zero_extend(h, 1, 2) != CFS_STORAGE_OK)
        ok = false;
    if (ok)
    {
        cfs_map_cache_set_meta(fx.rl, MAIN_FORKNUM, 3);
        lazy = cfs_test_open_lazy(fx.rl, cfp_path, map_path, jrn_path);
        if (lazy == NULL)
            ok = false;
        else
        {
            if (cfs_read_page_cached(lazy, 1, (char *) back)
                != CFS_STORAGE_OK ||
                memcmp(back, zeros, TEST_BLCKSZ) != 0)
                ok = false;
            cfs_test_fill_page(page, 0x11);
            if (ok && (cfs_read_page_cached(lazy, 0, (char *) back)
                       != CFS_STORAGE_OK ||
                       memcmp(back, page, TEST_BLCKSZ) != 0))
                ok = false;
            cfs_close(lazy);
        }
    }
 
    cfs_close(h);
    cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
    cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM);
    cfs_storage_teardown(&fx);
 
    snprintf(detail, sizeof(detail), "truncate resurrection %s",
             ok ? "ok" : "failed");
    add_result("shared_map_truncate_resurrect", ok ? "ok" : "fail", detail);
}
 
/*
 * Pool exhaustion: every segment held by one pinned relation must make
 * another relation's allocation fail gracefully (no crash, no double
 * mapping), and releasing the pin must make room again.
 */
/*
 * A pinned relation must not exhaust the pool: with the pool full of the
 * pinned relation's segments a competitor is still admitted — the slot
 * pin protects the metadata slot, not the segments, and cold segments
 * are evicted by the clock sweep.  (This used to assert the opposite:
 * before the policy change the competitor's store failed and the read
 * degraded to the authoritative fallback forever.)
 */
static void
test_shared_map_pool_exhaustion(void)
{
    RelFileLocatorBackend rl1 = cfs_shmem_test_locator(800750);
    RelFileLocatorBackend rl2 = cfs_shmem_test_locator(800760);
    CfsMapEntry in;
    uint64      in_use = 0;
    uint64      evictions = 0;
    uint64      evictions0 = 0;
    uint64      capacity = 0;
    char        detail[160];
    bool        ok = true;
    int         i;
 
    cfs_shared_map_invalidate_relation(rl1, MAIN_FORKNUM);
    cfs_shared_map_invalidate_relation(rl2, MAIN_FORKNUM);
    cfs_shared_map_stats(NULL, NULL, NULL, &capacity);
    if (capacity == 0)
    {
        add_result("shared_map_pool_exhaustion", "skip", "pool disabled");
        return;
    }
 
    cfs_map_entry_init(&in);
    in.physical_offset = 4096;
    in.compressed_size = 100;
    in.generation = 1;
    cfs_map_entry_crc_set(&in);
 
    /* Fill the whole pool with rl1's segments and keep rl1 pinned. */
    cfs_map_cache_pin(rl1, MAIN_FORKNUM);
    for (i = 0; i < (int) capacity; i++)
    {
        if (!cfs_shared_map_store(rl1, MAIN_FORKNUM,
                                  i * CFS_MAP_SEGMENT_BLOCKS + 1, &in,
                                  cfs_map_cache_get_generation(rl1, MAIN_FORKNUM)))
            ok = false;
    }
    cfs_shared_map_stats(&in_use, NULL, NULL, &capacity);
    if (ok && in_use != capacity)
        ok = false;
    cfs_shared_map_stats(NULL, NULL, &evictions0, NULL);
 
    /* rl2 is still admitted: a cold rl1 segment is evicted for it. */
    if (ok && !cfs_shared_map_store(rl2, MAIN_FORKNUM, 1, &in,
                                    cfs_map_cache_get_generation(rl2, MAIN_FORKNUM)))
        ok = false;
    if (ok && !cfs_shared_map_lookup(rl2, MAIN_FORKNUM, 1, &in, NULL))
        ok = false;
    cfs_shared_map_stats(&in_use, NULL, &evictions, NULL);
    if (ok && (in_use != capacity || evictions <= evictions0))
        ok = false;
 
    cfs_map_cache_unpin(rl1, MAIN_FORKNUM);
    cfs_shared_map_invalidate_relation(rl1, MAIN_FORKNUM);
    cfs_shared_map_invalidate_relation(rl2, MAIN_FORKNUM);
 
    snprintf(detail, sizeof(detail), "pinned admission %s",
             ok ? "ok" : "failed");
    add_result("shared_map_pool_exhaustion", ok ? "ok" : "fail", detail);
}
 
/*
 * The write path must not resolve the old entry through the segment pool:
 * with the relation-wide generation it no longer calls ensure(), so a pure
 * write stream loads no .cfsmap segments at all (the former write path paid
 * a full segment replay after every eviction).  Reads still go through the
 * ensure/sync path and must return what was written.
 */
static void
test_shared_map_write_no_load(void)
{
    CfsStorageFixture fx;
    CfsRelation *h;
    unsigned char page[TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    uint64      capacity = 0;
    uint64      loads0 = 0;
    uint64      loads1 = 0;
    char        detail[160];
    bool        ok = true;
    int         i;
 
    cfs_shared_map_stats(NULL, NULL, NULL, &capacity);
    if (capacity == 0)
    {
        add_result("shared_map_write_no_load", "skip", "pool disabled");
        return;
    }
 
    cfs_storage_setup(&fx, "writenoload");
    if (fx.dir == NULL)
    {
        add_result("shared_map_write_no_load", "fail", "setup failed");
        return;
    }
    fx.rl.locator.relNumber = 800770;
    cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
    cfs_map_cache_pin(fx.rl, MAIN_FORKNUM);
 
    h = cfs_storage_open_new(&fx);
    cfs_test_fill_page(page, 0x61);
 
    cfs_shared_map_stats(NULL, &loads0, NULL, NULL);
    for (i = 0; i < 100; i++)
    {
        if (cfs_write_page_cached(h, i, (const char *) page, &opts)
            != CFS_STORAGE_OK)
            ok = false;
    }
    cfs_shared_map_stats(NULL, &loads1, NULL, NULL);
    if (loads1 != loads0)
        ok = false;
 
    for (i = 0; ok && i < 100; i++)
    {
        if (cfs_read_page_cached(h, i, (char *) back) != CFS_STORAGE_OK ||
            memcmp(page, back, TEST_BLCKSZ) != 0)
            ok = false;
    }
 
    cfs_close(h);
    cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM);
    cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
    cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM);
 
    snprintf(detail, sizeof(detail), "write loaded %llu segments, reads %s",
             (unsigned long long) (loads1 - loads0),
             ok ? "ok" : "failed");
    add_result("shared_map_write_no_load", ok ? "ok" : "fail", detail);
    cfs_storage_teardown(&fx);
}
 
/*
 * E2: a pool whose every segment is pinned by relation A cannot serve
 * relation B, so the read must degrade to the authoritative private map
 * instead of failing.  The data comes back, no ERROR is raised, and
 * fallback_reads accounts for the degradation.
 */
static void
test_shared_map_fallback_read(void)
{
    CfsStorageFixture fxB;
    CfsRelation *h;
    CfsRelation *lazy;
    RelFileLocatorBackend rlA = cfs_shmem_test_locator(800780);
    unsigned char page[TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    CfsMapEntry in;
    uint64      capacity = 0;
    uint64      in_use = 0;
    uint64      fb0;
    uint64      fb1;
    char        detail[160];
    bool        ok = true;
    int         i;
 
    cfs_shared_map_stats(NULL, NULL, NULL, &capacity);
    if (capacity < 2)
    {
        add_result("shared_map_fallback_read", "skip", "pool too small");
        return;
    }
 
    cfs_storage_setup(&fxB, "fallback");
    if (fxB.dir == NULL)
    {
        add_result("shared_map_fallback_read", "fail", "setup failed");
        return;
    }
    fxB.rl.locator.relNumber = 800790;
    cfs_shared_map_invalidate_relation(rlA, MAIN_FORKNUM);
    cfs_shared_map_invalidate_relation(fxB.rl, MAIN_FORKNUM);
 
    /* Relation B: one block on disk, journal-only. */
    cfs_map_cache_pin(fxB.rl, MAIN_FORKNUM);
    h = cfs_storage_open_new(&fxB);
    cfs_test_fill_page(page, 0x71);
    if (cfs_write_page(h, 0, (const char *) page, &opts) != CFS_STORAGE_OK)
        ok = false;
    cfs_close(h);
 
    /* Relation A: pin it and occupy every pool segment. */
    cfs_map_cache_pin(rlA, MAIN_FORKNUM);
    cfs_map_entry_init(&in);
    in.physical_offset = 4096;
    in.compressed_size = 100;
    in.generation = 1;
    cfs_map_entry_crc_set(&in);
    for (i = 0; ok && i < (int) capacity; i++)
    {
        if (!cfs_shared_map_store(rlA, MAIN_FORKNUM,
                                  (BlockNumber) i * CFS_MAP_SEGMENT_BLOCKS,
                                  &in,
                                  cfs_map_cache_get_generation(rlA, MAIN_FORKNUM)))
            ok = false;
    }
    cfs_shared_map_stats(&in_use, NULL, NULL, &capacity);
    if (ok && in_use != capacity)
        ok = false;
 
    /*
     * A pinned relation no longer protects its segments, so simulate a
     * genuinely unallocatable pool (all segments reserved) with the test-only
     * switch: the read must degrade to the authoritative fallback and still
     * return the data.
     */
    fb0 = cfs_shared_map_fallback_reads();
    cfs_test_pool_block_victim = true;
    lazy = cfs_open_paths(fxB.rl, MAIN_FORKNUM, fxB.cfp_path, fxB.map_path,
                          fxB.jrn_path, CFS_OPEN_RDWR | CFS_OPEN_LAZY_MAP);
    if (lazy == NULL)
        ok = false;
    else
    {
        if (cfs_read_page_cached(lazy, 0, (char *) back) != CFS_STORAGE_OK ||
            memcmp(page, back, TEST_BLCKSZ) != 0)
            ok = false;
        cfs_close(lazy);
    }
    cfs_test_pool_block_victim = false;
    fb1 = cfs_shared_map_fallback_reads();
    if (ok && fb1 <= fb0)
        ok = false;
 
    cfs_map_cache_unpin(rlA, MAIN_FORKNUM);
    cfs_shared_map_invalidate_relation(rlA, MAIN_FORKNUM);
    cfs_shared_map_invalidate_relation(fxB.rl, MAIN_FORKNUM);
    cfs_map_cache_invalidate(fxB.rl, MAIN_FORKNUM);
    cfs_map_cache_release_relation(fxB.rl, MAIN_FORKNUM);
 
    snprintf(detail, sizeof(detail), "fallback_reads +%llu, data %s",
             (unsigned long long) (fb1 - fb0),
             ok ? "ok" : "mismatch or ERROR");
    add_result("shared_map_fallback_read", ok ? "ok" : "fail", detail);
    cfs_storage_teardown(&fxB);
}
 
/*
 * Unhealed snapshot corruption must fail every read, in both the pool and
 * the authoritative fallback path, and must never come back as a zero
 * page.  The journal is empty (a fresh checkpoint), so
 * nothing can heal the corrupted row.
 */
static void
test_shared_map_unhealed_corruption(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    CfsRelation *lazy = NULL;
    unsigned char page[TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    CfsMapEntry out;
    uint64      capacity = 0;
    char        detail[160];
    bool        ok = true;
    bool        auth0_ok = false;
    bool        auth1_ok = false;
    bool        pool0_ok = false;
    bool        pool1_ok = false;
    bool        pool1_again_ok = false;
    bool        lookup_ok = false;
 
    cfs_shared_map_stats(NULL, NULL, NULL, &capacity);
    if (capacity == 0)
    {
        add_result("shared_map_unhealed_corruption", "skip",
                   "pool disabled");
        return;
    }
 
    cfs_storage_setup(&fx, "unhealed");
    if (fx.dir == NULL)
    {
        add_result("shared_map_unhealed_corruption", "fail", "setup failed");
        return;
    }
    fx.rl.locator.relNumber = 800890;
    cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
    cfs_map_cache_pin(fx.rl, MAIN_FORKNUM);
 
    cfs = cfs_storage_open_new(&fx);
    cfs_test_fill_page(page, 0x51);
    if (cfs_write_page(cfs, 0, (const char *) page, &opts) != CFS_STORAGE_OK ||
        cfs_write_page(cfs, 1, (const char *) page, &opts) != CFS_STORAGE_OK)
        ok = false;
    if (ok)
    {
        /* Checkpoint: snapshot + empty journal. */
        cfs_map_save_snapshot(cfs);
        cfs_journal_reset_point(cfs, cfs_map_live_summary(cfs), ERROR);
    }
    cfs_close(cfs);
    if (!ok)
    {
        add_result("shared_map_unhealed_corruption", "fail",
                   "setup write failed");
        cfs_storage_teardown(&fx);
        return;
    }
 
    /* Flip one byte of block 1's row: non-zero content, bad entry_crc. */
    {
        int         fd = BasicOpenFile(fx.map_path, O_RDWR | PG_BINARY);
        char        b;
 
        if (fd < 0 ||
            pg_pread(fd, &b, 1, CFS_MAP_HEADER_SIZE + 1 * CFS_MAP_ENTRY_SIZE) != 1)
            ok = false;
        else
        {
            b ^= (char) 0xFF;
            if (pg_pwrite(fd, &b, 1,
                          CFS_MAP_HEADER_SIZE + 1 * CFS_MAP_ENTRY_SIZE) != 1)
                ok = false;
        }
        if (fd >= 0)
            close(fd);
    }
    if (!ok)
    {
        add_result("shared_map_unhealed_corruption", "fail",
                   "could not corrupt the map row");
        cfs_storage_teardown(&fx);
        return;
    }
 
    /*
     * Authoritative path: the pool is forced unallocatable, so the read
     * resolves through the scratch segment.  The healthy block 0 still reads;
     * the corrupted block 1 returns CORRUPT instead of a zero page.
     */
    cfs_test_pool_block_victim = true;
    lazy = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path, fx.map_path,
                          fx.jrn_path, CFS_OPEN_RDWR | CFS_OPEN_LAZY_MAP);
    if (lazy == NULL)
        ok = false;
    else
    {
        /*
         * The quarantine is per BLOCK: the healthy block 0 of the same
         * segment still reads, while block 1 (whose row is torn and has no
         * covering journal record) fails through the corruption report.
         */
        if (cfs_read_page_cached(lazy, 0, (char *) back) == CFS_STORAGE_OK)
            auth0_ok = true;
        if (cfs_read_page_cached(lazy, 1, (char *) back) == CFS_STORAGE_CORRUPT)
            auth1_ok = true;
        cfs_close(lazy);
        lazy = NULL;
    }
    cfs_test_pool_block_victim = false;
 
    /*
     * Pool path: the segment loads with the corrupt row, is flagged and never
     * serves - every read of the block fails again (the repeated read is the
     * regression: a published segment used to hand out a zeroed page from the
     * second read on).
     */
    cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
    lazy = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path, fx.map_path,
                          fx.jrn_path, CFS_OPEN_RDWR | CFS_OPEN_LAZY_MAP);
    if (lazy == NULL)
        ok = false;
    else
    {
        if (cfs_read_page_cached(lazy, 0, (char *) back) == CFS_STORAGE_OK)
            pool0_ok = true;
        if (cfs_read_page_cached(lazy, 1, (char *) back) == CFS_STORAGE_CORRUPT)
            pool1_ok = true;
        if (cfs_read_page_cached(lazy, 1, (char *) back) == CFS_STORAGE_CORRUPT)
            pool1_again_ok = true;
        if (!cfs_shared_map_lookup(fx.rl, MAIN_FORKNUM, 1, &out, NULL))
            lookup_ok = true;
        cfs_close(lazy);
    }
    ok = ok && auth0_ok && auth1_ok && pool0_ok && pool1_ok &&
        pool1_again_ok && lookup_ok;
 
    snprintf(detail, sizeof(detail),
             "block quarantined: auth %d/%d pool %d/%d again %d lookup %d",
             (int) auth0_ok, (int) auth1_ok, (int) pool0_ok, (int) pool1_ok,
             (int) pool1_again_ok, (int) lookup_ok);
    add_result("shared_map_unhealed_corruption", ok ? "ok" : "fail", detail);
    cfs_map_cache_unpin(fx.rl, MAIN_FORKNUM);
    cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM);
    cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM);
    cfs_storage_teardown(&fx);
}
 
/*
 * E4: cfs_shared_map_invalidate_relation must walk only the segments of
 * the requested relation (the per-relation index), not the whole pool.  Two
 * relations share the pool; invalidating one drops exactly its segments,
 * leaves the other resident and is idempotent.
 */
static void
test_shared_map_invalidate_index(void)
{
    RelFileLocatorBackend rlA = cfs_shmem_test_locator(800855);
    RelFileLocatorBackend rlB = cfs_shmem_test_locator(800856);
    CfsMapEntry in;
    CfsMapEntry out;
    uint64      capacity = 0;
    uint64      gen;
    uint64      ev0 = 0;
    uint64      ev1 = 0;
    uint64      ev2 = 0;
    char        detail[160];
    bool        ok = true;
    int         i;
 
    cfs_shared_map_invalidate_relation(rlA, MAIN_FORKNUM);
    cfs_shared_map_invalidate_relation(rlB, MAIN_FORKNUM);
    cfs_shared_map_stats(NULL, NULL, NULL, &capacity);
    if (capacity < 8)
    {
        add_result("shared_map_invalidate_index", "skip", "pool too small");
        return;
    }
 
    cfs_map_entry_init(&in);
    in.physical_offset = 4096;
    in.compressed_size = 100;
    in.generation = 1;
    cfs_map_entry_crc_set(&in);
    gen = cfs_map_cache_get_generation(rlA, MAIN_FORKNUM);
 
    /*
     * Four segments per relation.  Each B segment is looked up right after
     * its store so the clock sweep keeps it while A is filled.
     */
    for (i = 0; i < 4; i++)
    {
        BlockNumber blk = (BlockNumber) (1000 + i) * CFS_MAP_SEGMENT_BLOCKS;
 
        if (!cfs_shared_map_store(rlB, MAIN_FORKNUM, blk, &in, gen) ||
            !cfs_shared_map_lookup(rlB, MAIN_FORKNUM, blk, &out, NULL))
            ok = false;
    }
    for (i = 0; i < 4; i++)
        if (!cfs_shared_map_store(rlA, MAIN_FORKNUM,
                                  (BlockNumber) i * CFS_MAP_SEGMENT_BLOCKS,
                                  &in, gen))
            ok = false;
 
    cfs_shared_map_stats(NULL, NULL, &ev0, NULL);
    cfs_shared_map_invalidate_relation(rlA, MAIN_FORKNUM);
    cfs_shared_map_stats(NULL, NULL, &ev1, NULL);
 
    /* Exactly A's four segments were evicted. */
    if (ok && ev1 - ev0 != 4)
        ok = false;
 
    /* A is gone, B is untouched. */
    if (ok && cfs_shared_map_lookup(rlA, MAIN_FORKNUM, 0, &out, NULL))
        ok = false;
    if (ok && !cfs_shared_map_lookup(rlB, MAIN_FORKNUM,
                                     (BlockNumber) 1000 * CFS_MAP_SEGMENT_BLOCKS,
                                     &out, NULL))
        ok = false;
 
    /* A second invalidation finds nothing and evicts nothing. */
    cfs_shared_map_invalidate_relation(rlA, MAIN_FORKNUM);
    cfs_shared_map_stats(NULL, NULL, &ev2, NULL);
    if (ok && ev2 != ev1)
        ok = false;
 
    cfs_shared_map_invalidate_relation(rlB, MAIN_FORKNUM);
 
    snprintf(detail, sizeof(detail), "relation index %s",
             ok ? "scoped the invalidation" : "touched or missed segments");
    add_result("shared_map_invalidate_index", ok ? "ok" : "fail", detail);
}
 
/*
 * The clock-sweep usage counter belongs to the id, not to the descriptor
 * instance: after eviction/invalidation the id must start cold again, or a
 * recycled segment inherits a stale "hot" count and distorts victim
 * selection.
 */
static void
test_shared_map_usage_reset(void)
{
#ifdef USE_ASSERT_CHECKING
    RelFileLocatorBackend rl = cfs_shmem_test_locator(800880);
    CfsMapEntry in;
    uint64      capacity = 0;
    int         id;
    uint32      usage_before;
    uint32      usage_after;
    char        detail[160];
    bool        ok = true;
    int         i;
 
    cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM);
    cfs_shared_map_stats(NULL, NULL, NULL, &capacity);
    if (capacity == 0)
    {
        add_result("shared_map_usage_reset", "skip", "pool disabled");
        return;
    }
 
    cfs_map_entry_init(&in);
    in.physical_offset = 4096;
    in.compressed_size = 100;
    in.generation = 1;
    cfs_map_entry_crc_set(&in);
    if (!cfs_shared_map_store(rl, MAIN_FORKNUM, 0, &in,
                              cfs_map_cache_get_generation(rl, MAIN_FORKNUM)))
        ok = false;
    for (i = 0; ok && i < CFS_MAP_SEG_USAGE_MAX + 2; i++)
        if (!cfs_shared_map_lookup(rl, MAIN_FORKNUM, 0, &in, NULL))
            ok = false;
 
    id = cfs_shared_map_test_segment_id(rl, MAIN_FORKNUM, 0);
    usage_before = cfs_shared_map_test_desc_usage(id);
    cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM);
    usage_after = cfs_shared_map_test_desc_usage(id);
 
    if (ok && usage_before != CFS_MAP_SEG_USAGE_MAX)
        ok = false;
    if (ok && usage_after != 0)
        ok = false;
 
    /* The decrement is "only if positive", so a cold id cannot underflow. */
    cfs_shared_map_test_set_desc_usage(id, 1);
    cfs_shared_map_test_dec_desc_usage(id);
    cfs_shared_map_test_dec_desc_usage(id);
    if (ok && cfs_shared_map_test_desc_usage(id) != 0)
        ok = false;
 
    snprintf(detail, sizeof(detail), "usage reset %u -> %u, no underflow",
             usage_before, usage_after);
    add_result("shared_map_usage_reset", ok ? "ok" : "fail", detail);
#else
    add_result("shared_map_usage_reset", "skip", "requires assertions");
#endif
}
 
/*
 * DROP DATABASE must drop only the segments of the dropped database.  The
 * keys carry dbOid, so a full pool reset would throw away every other
 * database's warm segments for no correctness gain.
 */
static void
test_shared_map_drop_database(void)
{
    RelFileLocatorBackend rlA = cfs_shmem_test_locator(800870);
    RelFileLocatorBackend rlB = cfs_shmem_test_locator(800871);
    CfsMapEntry in;
    CfsMapEntry out;
    uint64      in_use0;
    uint64      in_use1;
    uint64      capacity = 0;
    uint64      genA;
    uint64      genB;
    char        detail[160];
    bool        ok = true;
    int         i;
    Oid         dbA = 900001;
    Oid         dbB = 900002;
 
    rlA.locator.dbOid = dbA;
    rlB.locator.dbOid = dbB;
 
    cfs_shared_map_invalidate_relation(rlA, MAIN_FORKNUM);
    cfs_shared_map_invalidate_relation(rlB, MAIN_FORKNUM);
    cfs_shared_map_stats(NULL, NULL, NULL, &capacity);
    if (capacity < 4)
    {
        add_result("shared_map_drop_database", "skip", "pool too small");
        return;
    }
 
    cfs_map_entry_init(&in);
    in.physical_offset = 4096;
    in.compressed_size = 100;
    in.generation = 1;
    cfs_map_entry_crc_set(&in);
    genA = cfs_map_cache_get_generation(rlA, MAIN_FORKNUM);
    genB = cfs_map_cache_get_generation(rlB, MAIN_FORKNUM);
 
    for (i = 0; i < 2; i++)
    {
        BlockNumber blk = (BlockNumber) i * CFS_MAP_SEGMENT_BLOCKS;
 
        if (!cfs_shared_map_store(rlA, MAIN_FORKNUM, blk, &in, genA))
            ok = false;
        if (!cfs_shared_map_store(rlB, MAIN_FORKNUM, blk, &in, genB))
            ok = false;
        if (!cfs_shared_map_lookup(rlA, MAIN_FORKNUM, blk, &out, NULL))
            ok = false;
        if (!cfs_shared_map_lookup(rlB, MAIN_FORKNUM, blk, &out, NULL))
            ok = false;
    }
 
    cfs_shared_map_stats(&in_use0, NULL, NULL, NULL);
    cfs_drop_database_caches(dbA);
    cfs_shared_map_stats(&in_use1, NULL, NULL, NULL);
 
    if (in_use1 != in_use0 - 2)
        ok = false;
    if (cfs_shared_map_lookup(rlA, MAIN_FORKNUM, 0, &out, NULL))
        ok = false;
    if (!cfs_shared_map_lookup(rlB, MAIN_FORKNUM, 0, &out, NULL))
        ok = false;
    if (!cfs_shared_map_lookup(rlB, MAIN_FORKNUM,
                               CFS_MAP_SEGMENT_BLOCKS, &out, NULL))
        ok = false;
 
    cfs_shared_map_invalidate_relation(rlB, MAIN_FORKNUM);
 
    snprintf(detail, sizeof(detail), "drop database %s",
             ok ? "kept other databases" : "reset the whole pool");
    add_result("shared_map_drop_database", ok ? "ok" : "fail", detail);
}
 
/*
 * C2: a segment published from the .cfsmap snapshot without a journal
 * replay must be invisible to lookups until the sync catches it up.  The
 * snapshot holds v1, the journal holds both v1 and the newer v2; after the
 * read path syncs the segment, v2 must be served (not v1, not a zero page).
 */
static void
test_shared_map_publish_unsynced(void)
{
#ifdef USE_ASSERT_CHECKING
    CfsStorageFixture fx;
    CfsRelation *h;
    CfsRelation *lazy;
    unsigned char page[TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    CfsMapEntry expected;
    CfsMapEntry out;
    uint64      capacity = 0;
    char        cfp_path[MAXPGPATH];
    char        map_path[MAXPGPATH];
    char        jrn_path[MAXPGPATH];
    char        detail[160];
    bool        ok = true;
 
    cfs_shared_map_stats(NULL, NULL, NULL, &capacity);
    if (capacity == 0)
    {
        add_result("shared_map_publish_unsynced", "skip", "pool disabled");
        return;
    }
 
    cfs_storage_setup(&fx, "segunsynced");
    if (fx.dir == NULL)
    {
        add_result("shared_map_publish_unsynced", "fail", "setup failed");
        return;
    }
    fx.rl.locator.relNumber = 800795;
    cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
    cfs_map_cache_pin(fx.rl, MAIN_FORKNUM);
    strlcpy(cfp_path, fx.cfp_path, sizeof(cfp_path));
    strlcpy(map_path, fx.map_path, sizeof(map_path));
    strlcpy(jrn_path, fx.jrn_path, sizeof(jrn_path));
 
    h = cfs_storage_open_new(&fx);
 
    /* Snapshot v1, then a journal-only v2 that the snapshot does not know. */
    cfs_test_fill_page(page, 0x41);
    if (cfs_write_page(h, 0, (const char *) page, &opts) != CFS_STORAGE_OK)
        ok = false;
    if (ok && cfs_map_save_snapshot(h) != CFS_STORAGE_OK)
        ok = false;
    cfs_test_fill_page(page, 0x42);
    if (ok && cfs_write_page(h, 0, (const char *) page, &opts)
        != CFS_STORAGE_OK)
        ok = false;
    if (ok)
        expected = h->map[0];
    cfs_close(h);
 
    lazy = cfs_test_open_lazy(fx.rl, cfp_path, map_path, jrn_path);
    if (lazy == NULL)
        ok = false;
    if (ok && !cfs_shared_map_test_publish_unsynced(lazy, 0))
        ok = false;
 
    /* C2: the unsynced segment must be treated as a miss. */
    if (ok && cfs_shared_map_lookup(fx.rl, MAIN_FORKNUM, 0, &out, NULL))
        ok = false;
 
    /* The miss path syncs the segment and must serve the journal version. */
    if (ok)
    {
        cfs_test_fill_page(page, 0x42);
        if (cfs_read_page_cached(lazy, 0, (char *) back) != CFS_STORAGE_OK ||
            memcmp(back, page, TEST_BLCKSZ) != 0)
            ok = false;
    }
 
    /* After the sync the entry is visible and carries the newer offset. */
    if (ok && (!cfs_shared_map_lookup(fx.rl, MAIN_FORKNUM, 0, &out, NULL) ||
               out.physical_offset != expected.physical_offset ||
               out.generation != expected.generation))
        ok = false;
 
    if (lazy)
        cfs_close(lazy);
    cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM);
    cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
    cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM);
 
    snprintf(detail, sizeof(detail), "unsynced segment %s",
             ok ? "served only after sync" : "leaked or served a stale entry");
    add_result("shared_map_publish_unsynced", ok ? "ok" : "fail", detail);
    cfs_storage_teardown(&fx);
#else
    add_result("shared_map_publish_unsynced", "skip",
               "requires assertions");
#endif
}
 
/*
 * I4: a competitor merges the snapshot between ensure()'s buffer load and
 * its segment phase.  The descriptor is then already loaded, so ensure()
 * must report success instead of pretending it lost the race and sending
 * the reader to the authoritative path.
 */
static void
test_shared_map_merge_race(void)
{
#ifdef USE_ASSERT_CHECKING
    CfsStorageFixture fx;
    CfsRelation *lazy;
    CfsRelation *h;
    CfsMapEntry in;
    uint64      capacity = 0;
    uint64      gen;
    char        cfp_path[MAXPGPATH];
    char        map_path[MAXPGPATH];
    char        jrn_path[MAXPGPATH];
    char        detail[160];
    bool        ok = true;
 
    cfs_shared_map_stats(NULL, NULL, NULL, &capacity);
    if (capacity == 0)
    {
        add_result("shared_map_merge_race", "skip", "pool disabled");
        return;
    }
 
    cfs_storage_setup(&fx, "segmergerace");
    if (fx.dir == NULL)
    {
        add_result("shared_map_merge_race", "fail", "setup failed");
        return;
    }
    fx.rl.locator.relNumber = 800796;
    cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
    cfs_map_cache_pin(fx.rl, MAIN_FORKNUM);
    strlcpy(cfp_path, fx.cfp_path, sizeof(cfp_path));
    strlcpy(map_path, fx.map_path, sizeof(map_path));
    strlcpy(jrn_path, fx.jrn_path, sizeof(jrn_path));
 
    /* Materialise the sidecars so the lazy handle below can open them. */
    h = cfs_storage_open_new(&fx);
    if (h == NULL)
        ok = false;
    else
        cfs_close(h);
 
    /*
     * A store-created segment holds only journaled entries: its snapshot part
     * is not loaded yet, which is what sends ensure() through the merge path
     * the hook races with.
     */
    gen = cfs_map_cache_get_generation(fx.rl, MAIN_FORKNUM);
    cfs_map_entry_init(&in);
    in.physical_offset = 4096;
    in.compressed_size = 100;
    in.generation = 1;
    cfs_map_entry_crc_set(&in);
    if (!cfs_shared_map_store(fx.rl, MAIN_FORKNUM, 0, &in, gen))
        ok = false;
 
    lazy = cfs_test_open_lazy(fx.rl, cfp_path, map_path, jrn_path);
    if (lazy == NULL)
        ok = false;
    if (ok && !cfs_shared_map_test_merge_race(lazy, 0))
        ok = false;
 
    if (ok)
    {
        int         ensure_rc;
 
        cfs_append_lock_acquire(fx.rl, MAIN_FORKNUM, LW_SHARED);
        ensure_rc = cfs_shared_map_ensure(lazy, 0);
        cfs_append_lock_release(fx.rl, MAIN_FORKNUM);
        if (ensure_rc != CFS_STORAGE_OK)
            ok = false;
    }
 
    if (lazy)
        cfs_close(lazy);
    cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM);
    cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
    cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM);
 
    snprintf(detail, sizeof(detail), "concurrent merge %s",
             ok ? "reported as success" : "misreported as a miss");
    add_result("shared_map_merge_race", ok ? "ok" : "fail", detail);
    cfs_storage_teardown(&fx);
#else
    add_result("shared_map_merge_race", "skip", "requires assertions");
#endif
}
 
/*
 * I9: an in-flight reservation left behind by a backend that died before
 * publishing its segment must not block the next store of the same key and
 * must not leak a pool segment (regression guard; reaping was added with
 * the reservation table itself).
 */
static void
test_shared_map_orphan_reservation(void)
{
#ifdef USE_ASSERT_CHECKING
    RelFileLocatorBackend rl = cfs_shmem_test_locator(800820);
    CfsMapEntry in;
    CfsMapEntry out;
    uint64      in_use0 = 0;
    uint64      in_use1 = 0;
    uint64      in_use2 = 0;
    uint64      capacity = 0;
    uint64      gen;
    int         id0 = -1;
    int         id1 = -1;
    char        detail[160];
    bool        ok = true;
 
    cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM);
    cfs_shared_map_stats(&in_use0, NULL, NULL, &capacity);
    if (capacity == 0)
    {
        add_result("shared_map_orphan_reservation", "skip", "pool disabled");
        return;
    }
 
    cfs_map_entry_init(&in);
    in.physical_offset = 4096;
    in.compressed_size = 100;
    in.generation = 1;
    cfs_map_entry_crc_set(&in);
    gen = cfs_map_cache_get_generation(rl, MAIN_FORKNUM);
 
    id0 = cfs_shared_map_test_reserve_orphan(rl, MAIN_FORKNUM, 0);
    if (id0 < 0)
        ok = false;
    if (ok && !cfs_shared_map_store(rl, MAIN_FORKNUM, 0, &in, gen))
        ok = false;
    if (ok)
    {
        id1 = cfs_shared_map_test_segment_id(rl, MAIN_FORKNUM, 0);
        if (id1 != id0)
            ok = false;
    }
    if (ok && !cfs_shared_map_lookup(rl, MAIN_FORKNUM, 0, &out, NULL))
        ok = false;
    else if (ok && out.physical_offset != in.physical_offset)
        ok = false;
 
    /* The store owns exactly one new segment: no leak, no double mapping. */
    cfs_shared_map_stats(&in_use1, NULL, NULL, NULL);
    if (ok && in_use1 != in_use0 + 1)
        ok = false;
 
    cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM);
    cfs_shared_map_stats(&in_use2, NULL, NULL, NULL);
    if (ok && in_use2 != in_use0)
        ok = false;
 
    snprintf(detail, sizeof(detail),
             "orphan reservation %s (id %d -> %d)",
             ok ? "reused the same id without a leak" : "blocked or leaked a segment",
             id0, id1);
    add_result("shared_map_orphan_reservation", ok ? "ok" : "fail", detail);
#else
    add_result("shared_map_orphan_reservation", "skip",
               "requires assertions");
#endif
}
 
static void
test_shmem_invalidate(void)
{
    RelFileLocatorBackend rl = cfs_shmem_test_locator(800500);
    CfsMapEntry in;
    CfsMapEntry out;
    uint64      capacity = 0;
    char        detail[160];
    bool        ok = true;
 
    cfs_shared_map_stats(NULL, NULL, NULL, &capacity);
    if (capacity == 0)
    {
        add_result("shmem_invalidate", "skip", "pool disabled");
        return;
    }
 
    cfs_map_cache_pin(rl, MAIN_FORKNUM);
 
    cfs_map_entry_init(&in);
    in.physical_offset = 8192;
    in.compressed_size = 1000;
    in.generation = 1;
    cfs_map_entry_crc_set(&in);
    if (!cfs_shared_map_store(rl, MAIN_FORKNUM, 7, &in,
                              cfs_map_cache_get_generation(rl, MAIN_FORKNUM)))
        ok = false;
    if (!cfs_shared_map_lookup(rl, MAIN_FORKNUM, 7, &out, NULL))
        ok = false;
 
    cfs_map_cache_invalidate(rl, MAIN_FORKNUM);
    cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM);
    if (cfs_shared_map_lookup(rl, MAIN_FORKNUM, 7, &out, NULL))
        ok = false;             /* entry must be gone after invalidation */
 
    snprintf(detail, sizeof(detail), "invalidate %s", ok ? "ok" : "failed");
    add_result("shmem_invalidate", ok ? "ok" : "fail", detail);
}
 
/*
 * Mirror of the static cfs_cache_hash_rel() in cfs_shmem.c, used to pick
 * synthetic locators that hash into the same metadata partition.  Must be
 * kept in sync with the production hash.
 */
static uint32
test_cache_hash_rel(RelFileLocatorBackend rlocator, ForkNumber forknum)
{
    uint32      h;
 
    h = rlocator.locator.spcOid;
    h = (h << 5) - h + rlocator.locator.dbOid;
    h = (h << 5) - h + rlocator.locator.relNumber;
    h = (h << 5) - h + (uint32) rlocator.backend;
    h = (h << 5) - h + (uint32) forknum;
    return (h == 0) ? 1 : h;
}
 
/*
 * Metadata cache overflow: fill one metadata partition with dirty
 * (non-evictable) relations, then verify that a further relation hashing
 * to the same partition is rejected with a hard ERROR (no silent skip,
 * no overflow counter — the relation cannot operate without its metadata
 * slot, which now also carries the per-relation append lock).
 */
static void
test_shmem_meta_overflow(void)
{
    RelFileLocatorBackend rls[CFS_MAP_CACHE_RELS_PER_PART + 1];
    CfsEffectiveOptions opts;
    uint32      target_part = 0;
    int         found = 0;
    bool        raised = false;
    bool        ok = true;
    Oid         rn;
    int         i;
 
    for (rn = 810000; found <= CFS_MAP_CACHE_RELS_PER_PART && rn < 815000; rn++)
    {
        RelFileLocatorBackend rl = cfs_shmem_test_locator(rn);
        uint32      part = test_cache_hash_rel(rl, MAIN_FORKNUM) &
            (CFS_MAP_CACHE_NUM_PARTITIONS - 1);
 
        if (found == 0)
            target_part = part;
        if (part == target_part)
            rls[found++] = rl;
    }
 
    opts.is_cfs = true;
    opts.algorithm = CFS_ALGORITHM_LZ4;
    opts.level = 3;
    opts.min_gain_bytes = 512;
 
    /* Occupy every slot of the partition with dirty metadata. */
    for (i = 0; i < CFS_MAP_CACHE_RELS_PER_PART; i++)
    {
        cfs_map_cache_invalidate(rls[i], MAIN_FORKNUM);
        cfs_publish_options(rls[i], MAIN_FORKNUM, &opts);
        cfs_map_cache_set_meta(rls[i], MAIN_FORKNUM, 10);
    }
 
    /*
     * One more relation hashing to the same partition: the slot pool is
     * exhausted (all slots dirty), so cfs_meta_get_or_create must raise ERROR
     * instead of silently skipping the relation.
     */
    PG_TRY();
    {
        cfs_publish_options(rls[CFS_MAP_CACHE_RELS_PER_PART], MAIN_FORKNUM,
                            &opts);
    }
    PG_CATCH();
    {
        ErrorData  *edata;
        MemoryContext oldcontext = MemoryContextSwitchTo(TopMemoryContext);
 
        edata = CopyErrorData();
        raised = (edata->sqlerrcode == ERRCODE_CONFIGURATION_LIMIT_EXCEEDED);
        MemoryContextSwitchTo(oldcontext);
        FlushErrorState();
    }
    PG_END_TRY();
 
    if (!raised)
        ok = false;
 
    /* Clean up: make the slots evictable again and drop them. */
    for (i = 0; i < CFS_MAP_CACHE_RELS_PER_PART; i++)
    {
        cfs_map_cache_clear_dirty(rls[i], MAIN_FORKNUM);
        cfs_map_cache_invalidate(rls[i], MAIN_FORKNUM);
    }
 
    add_result("shmem_meta_overflow", ok ? "ok" : "fail",
               ok ? "excess relation rejected with ERROR"
               : "overflow not handled");
}
 
/*
 * QDB-1516 T1: hash chains under collisions.  Engineer many distinct keys
 * that share one partition (the low hash bits collide), run far past the
 * partition's slot capacity so the chains grow, slots evict and get
 * re-created, and verify find / get_or_create / eviction / invalidation
 * keep answering with exactly the right slot on both the metadata and the
 * statistics side.  The LRU order within the partition is deterministic:
 * every key is touched exactly once, in index order, so after the loop the
 * partition must hold the highest-indexed keys and none of the rest.
 */
#define CHAIN_TEST_KEYS     64
 
static void
test_shmem_chains(void)
{
    RelFileLocatorBackend rls[CHAIN_TEST_KEYS];
    CfsStatsSnapshot snap;
    uint32  target_part = 0;
    uint64  nblocks = 0;
    int     found = 0;
    int     meta_cap;
    int     stats_cap;
    int     i;
    bool    ok = true;
    Oid     rn;
 
    /*
     * Brute-force relfilenodes hashing into one partition, exactly like
     * test_shmem_meta_overflow() does (the hash mirror above must stay in
     * sync with cfs_cache_hash_rel()).
     */
    for (rn = 840000; found < CHAIN_TEST_KEYS && rn < 860000; rn++)
    {
        RelFileLocatorBackend rl = cfs_shmem_test_locator(rn);
        uint32  part = test_cache_hash_rel(rl, MAIN_FORKNUM) &
            (CFS_MAP_CACHE_NUM_PARTITIONS - 1);
 
        if (found == 0)
            target_part = part;
        if (part == target_part)
            rls[found++] = rl;
    }
    if (found < CHAIN_TEST_KEYS)
    {
        add_result("shmem_chains", "fail", "not enough colliding keys");
        return;
    }
 
    /* Idempotent across runs: drop any state of these keys first. */
    for (i = 0; i < CHAIN_TEST_KEYS; i++)
    {
        cfs_map_cache_invalidate(rls[i], MAIN_FORKNUM);
        cfs_stats_reset(rls[i], MAIN_FORKNUM);
    }
 
    /* Fill the partition far past its metadata capacity. */
    for (i = 0; i < CHAIN_TEST_KEYS; i++)
        cfs_map_cache_set_meta(rls[i], MAIN_FORKNUM, (uint64) (1000 + i));
 
    meta_cap = cfs_map_cache_rels_per_partition;
 
    /* The most recent key is served through its chain. */
    if (!cfs_map_cache_get_nblocks(rls[CHAIN_TEST_KEYS - 1], MAIN_FORKNUM,
                                   &nblocks) ||
        nblocks != (uint64) (1000 + CHAIN_TEST_KEYS - 1))
        ok = false;
 
    /*
     * With more keys than slots, the earliest keys were evicted (LRU) and
     * must not be found through anybody's chain.
     */
    if (ok && CHAIN_TEST_KEYS > meta_cap &&
        cfs_map_cache_get_nblocks(rls[0], MAIN_FORKNUM, &nblocks))
        ok = false;
 
    /*
     * A long-evicted key is found again after re-creation (the chain link
     * of the recycled slot must follow the new key, not the victim's).
     * The re-created slot evicts the oldest survivor instead.
     */
    cfs_map_cache_set_meta(rls[20], MAIN_FORKNUM, 5000);
    if (!cfs_map_cache_get_nblocks(rls[20], MAIN_FORKNUM, &nblocks) ||
        nblocks != 5000)
        ok = false;
    if (ok && !cfs_map_cache_get_nblocks(rls[CHAIN_TEST_KEYS - 1],
                                         MAIN_FORKNUM, &nblocks))
        ok = false;
 
    /* Invalidation removes exactly its own slot, chain included. */
    cfs_map_cache_invalidate(rls[20], MAIN_FORKNUM);
    if (cfs_map_cache_get_nblocks(rls[20], MAIN_FORKNUM, &nblocks))
        ok = false;
    if (ok && !cfs_map_cache_get_nblocks(rls[CHAIN_TEST_KEYS - 1],
                                         MAIN_FORKNUM, &nblocks))
        ok = false;
 
    /* The statistics domain: same collision load, shared-lock accounting. */
    for (i = 0; i < CHAIN_TEST_KEYS; i++)
        cfs_stats_count_read(rls[i], MAIN_FORKNUM, 100);
 
    stats_cap = cfs_stats_slots_per_partition;
 
    if (!cfs_stats_snapshot(rls[CHAIN_TEST_KEYS - 1], MAIN_FORKNUM, &snap) ||
        snap.read_count != 1 || snap.decompress_count != 1)
        ok = false;
    if (ok && CHAIN_TEST_KEYS > stats_cap &&
        cfs_stats_snapshot(rls[0], MAIN_FORKNUM, &snap))
        ok = false;
 
    /*
     * Reset clears exactly one relation's counters.  rls[20] was evicted
     * by the load above, so re-create its slot first: the reset must then
     * zero it while the untouched neighbor keeps its counter.
     */
    cfs_stats_count_read(rls[20], MAIN_FORKNUM, 100);
    cfs_stats_reset(rls[20], MAIN_FORKNUM);
    if (!cfs_stats_snapshot(rls[20], MAIN_FORKNUM, &snap) ||
        snap.read_count != 0 || snap.crc_failures != 0 ||
        snap.last_reset == 0)
        ok = false;
    if (ok && (!cfs_stats_snapshot(rls[CHAIN_TEST_KEYS - 1], MAIN_FORKNUM,
                                   &snap) || snap.read_count != 1))
        ok = false;
 
    /* Cleanup: leave no slot of these keys behind. */
    for (i = 0; i < CHAIN_TEST_KEYS; i++)
    {
        cfs_map_cache_invalidate(rls[i], MAIN_FORKNUM);
        cfs_stats_reset(rls[i], MAIN_FORKNUM);
    }
 
    add_result("shmem_chains", ok ? "ok" : "fail",
               ok ? "64 colliding keys, chains keep exact slots"
               : "chain find/evict/invalidate mismatch");
}
 
/*
 * Pin reaper: a slot pin left behind by a process that died hard (the
 * test hook records one for an already-dead pid) must not exhaust the
 * partition - when no slot is reclaimable, the dead owner's pins are
 * reaped and the next pin succeeds instead of raising the overflow
 * error.
 */
static void
test_shmem_pin_reaper(void)
{
    RelFileLocatorBackend rls[CFS_MAP_CACHE_RELS_PER_PART + 1];
    char        detail[160] = {0};
    uint32      target_part = 0;
    bool        raised = false;
    bool        ok = true;
    Oid         rn;
    int         found = 0;
    int         i;
 
    for (rn = 820000; found <= CFS_MAP_CACHE_RELS_PER_PART && rn < 825000; rn++)
    {
        RelFileLocatorBackend rl = cfs_shmem_test_locator(rn);
        uint32      part = test_cache_hash_rel(rl, MAIN_FORKNUM) &
            (CFS_MAP_CACHE_NUM_PARTITIONS - 1);
 
        if (found == 0)
            target_part = part;
        if (part == target_part)
            rls[found++] = rl;
    }
 
    for (i = 0; i < found; i++)
        cfs_map_cache_invalidate(rls[i], MAIN_FORKNUM);
 
    /* rls[0]: one orphaned pin from a dead process. */
    if (cfs_map_cache_test_pin_orphan(rls[0], MAIN_FORKNUM) !=
        (int) target_part)
    {
        ok = false;
        snprintf(detail, sizeof(detail), "pin reaper failed at orphan1");
    }
 
    /* Live pins fill the rest of the partition. */
    for (i = 1; i < CFS_MAP_CACHE_RELS_PER_PART; i++)
        cfs_map_cache_pin(rls[i], MAIN_FORKNUM);
 
    /*
     * One more relation of the same partition: every slot is pinned, but one
     * pin belongs to a dead process - the pin must succeed after the reaper
     * returns that slot, not raise the overflow error.
     */
    PG_TRY();
    {
        cfs_map_cache_pin(rls[CFS_MAP_CACHE_RELS_PER_PART], MAIN_FORKNUM);
    }
    PG_CATCH();
    {
        ErrorData  *edata;
        MemoryContext oldcontext = MemoryContextSwitchTo(TopMemoryContext);
 
        edata = CopyErrorData();
        raised = (edata->sqlerrcode == ERRCODE_CONFIGURATION_LIMIT_EXCEEDED);
        MemoryContextSwitchTo(oldcontext);
        FlushErrorState();
    }
    PG_END_TRY();
 
    if (raised)
    {
        ok = false;
        snprintf(detail, sizeof(detail), "pin reaper failed at overflow");
    }
 
    /*
     * Reaper invariants, checked deterministically in place of the
     * two-backend race the reaper guards against (I1/I2 name the broken one
     * in the detail line):
     *
     * I1. Idempotence: a second run must find nothing, so two reapers racing
     * for one record can never double-subtract from a slot. I2. Live owners
     * keep their pins: reaping an orphan recorded for a slot this process
     * also pins live must leave the live pin counted (2 -> 1), and unpinning
     * it must bring the refcount to zero.  A reaper that wrongly swallowed
     * the live pin shows up as 2 -> 0, a no-op reaper as 2 -> 2.
     */
    {
        const char *inv = "";
        char        invbuf[48];
        int         rc_a;
        int         rc;
 
        if (cfs_map_cache_test_reap_dead_pins())
            inv = "I1";
 
        /* Free one slot so the next orphan can own a real slot again. */
        cfs_map_cache_unpin(rls[CFS_MAP_CACHE_RELS_PER_PART], MAIN_FORKNUM);
 
        if (cfs_map_cache_test_pin_orphan(rls[0], MAIN_FORKNUM) !=
            (int) target_part)
            inv = "orphan";
        cfs_map_cache_pin(rls[0], MAIN_FORKNUM);
 
        rc_a = cfs_map_cache_test_slot_refcount(rls[0], MAIN_FORKNUM);
        (void) cfs_map_cache_test_reap_dead_pins();
        rc = cfs_map_cache_test_slot_refcount(rls[0], MAIN_FORKNUM);
        if (rc_a != 2 || rc != 1)
        {
            snprintf(invbuf, sizeof(invbuf), "live-refcount %d->%d",
                     rc_a, rc);
            inv = invbuf;
        }
 
        cfs_map_cache_unpin(rls[0], MAIN_FORKNUM);
        if (cfs_map_cache_test_slot_refcount(rls[0], MAIN_FORKNUM) != 0)
            inv = "zero-refcount";
 
        if (inv[0] != '\0')
        {
            ok = false;
            snprintf(detail, sizeof(detail), "pin reaper failed at %s", inv);
        }
    }
 
    /* Cleanup: drop the live pins and every slot of the partition. */
    for (i = 1; i <= CFS_MAP_CACHE_RELS_PER_PART; i++)
        cfs_map_cache_unpin(rls[i], MAIN_FORKNUM);
    for (i = 0; i < found; i++)
        cfs_map_cache_invalidate(rls[i], MAIN_FORKNUM);
 
    if (ok)
        snprintf(detail, sizeof(detail), "pin reaper ok");
    else if (detail[0] == '\0')
        snprintf(detail, sizeof(detail), "pin reaper failed");
    add_result("shmem_pin_reaper", ok ? "ok" : "fail", detail);
}
 
/*
 * Post-commit publication must degrade instead of raising ERROR: after the
 * durable commit an ERROR is no longer abortable and would escalate to
 * PANIC ("cannot abort transaction ... it was already committed").  With
 * every slot of the partition dirty, the postcommit publication warns,
 * skips the entry, and leaves no slot behind; once the partition has room
 * again, the same publication goes through.
 */
static void
test_shmem_publish_postcommit_overflow(void)
{
    RelFileLocatorBackend rls[CFS_MAP_CACHE_RELS_PER_PART + 1];
    CfsEffectiveOptions opts;
    CfsEffectiveOptions cached;
    uint32      target_part = 0;
    int         found = 0;
    bool        ok = true;
    Oid         rn;
    int         i;
 
    for (rn = 820000; found <= CFS_MAP_CACHE_RELS_PER_PART && rn < 825000; rn++)
    {
        RelFileLocatorBackend rl = cfs_shmem_test_locator(rn);
        uint32      part = test_cache_hash_rel(rl, MAIN_FORKNUM) &
            (CFS_MAP_CACHE_NUM_PARTITIONS - 1);
 
        if (found == 0)
            target_part = part;
        if (part == target_part)
            rls[found++] = rl;
    }
 
    opts.is_cfs = true;
    opts.algorithm = CFS_ALGORITHM_LZ4;
    opts.level = 3;
    opts.min_gain_bytes = 512;
 
    /* Occupy every slot of the partition with dirty metadata. */
    for (i = 0; i < CFS_MAP_CACHE_RELS_PER_PART; i++)
    {
        cfs_map_cache_invalidate(rls[i], MAIN_FORKNUM);
        cfs_publish_options(rls[i], MAIN_FORKNUM, &opts);
        cfs_map_cache_set_meta(rls[i], MAIN_FORKNUM, 10);
    }
 
    /*
     * The postcommit publication for one more relation of the same partition
     * must not raise: the WARNING path skips the entry, so no slot may appear
     * for it.
     */
    cfs_publish_options_postcommit(rls[CFS_MAP_CACHE_RELS_PER_PART],
                                   MAIN_FORKNUM, &opts);
    if (cfs_get_options(rls[CFS_MAP_CACHE_RELS_PER_PART], MAIN_FORKNUM,
                        &cached))
        ok = false;
 
    /* Clean up the partition: the same publication now succeeds. */
    for (i = 0; i < CFS_MAP_CACHE_RELS_PER_PART; i++)
    {
        cfs_map_cache_clear_dirty(rls[i], MAIN_FORKNUM);
        cfs_map_cache_invalidate(rls[i], MAIN_FORKNUM);
    }
    cfs_publish_options_postcommit(rls[CFS_MAP_CACHE_RELS_PER_PART],
                                   MAIN_FORKNUM, &opts);
    if (!cfs_get_options(rls[CFS_MAP_CACHE_RELS_PER_PART], MAIN_FORKNUM,
                         &cached) ||
        cached.level != opts.level || !cached.is_cfs)
        ok = false;
    cfs_map_cache_invalidate(rls[CFS_MAP_CACHE_RELS_PER_PART], MAIN_FORKNUM);
 
    add_result("shmem_publish_postcommit_overflow", ok ? "ok" : "fail",
               ok ? "post-commit overflow degraded to a WARNING and a skip"
               : "post-commit overflow not tolerated");
}
 
/*
 * Truncate / invalidate of the cached relation metadata: the metadata slot
 * must be updated exactly once, under its own partition lock, and the
 * cached logical size must shrink while the relation options survive.
 */
static void
test_shmem_truncate_meta(void)
{
    RelFileLocatorBackend rl = cfs_shmem_test_locator(800600);
    CfsEffectiveOptions opts;
    CfsEffectiveOptions out_opts;
    uint64      nblocks = 0;
    uint64      gen_before = 0;
    bool        ok = true;
 
    cfs_map_cache_invalidate(rl, MAIN_FORKNUM);
 
    opts.is_cfs = true;
    opts.algorithm = CFS_ALGORITHM_LZ4;
    opts.level = 3;
    opts.min_gain_bytes = 512;
 
    cfs_map_cache_pin(rl, MAIN_FORKNUM);
    cfs_publish_options(rl, MAIN_FORKNUM, &opts);
    cfs_map_cache_set_meta(rl, MAIN_FORKNUM, 100);
    gen_before = cfs_map_cache_get_generation(rl, MAIN_FORKNUM);
 
    cfs_map_cache_truncate(rl, MAIN_FORKNUM, 40);
 
    /* Logical size shrank ... */
    if (!cfs_map_cache_get_nblocks(rl, MAIN_FORKNUM, &nblocks) || nblocks != 40)
        ok = false;
    /* ... the generation was bumped (the truncate/compaction marker) ... */
    if (cfs_map_cache_get_generation(rl, MAIN_FORKNUM) == gen_before)
        ok = false;
    /* ... and the relation options survived the truncate. */
    if (!cfs_get_options(rl, MAIN_FORKNUM, &out_opts) || !out_opts.is_cfs)
        ok = false;
 
    /* Invalidate drops the metadata slot entirely. */
    cfs_map_cache_invalidate(rl, MAIN_FORKNUM);
    if (cfs_map_cache_get_nblocks(rl, MAIN_FORKNUM, &nblocks))
        ok = false;
 
    cfs_map_cache_release_relation(rl, MAIN_FORKNUM);
 
    add_result("shmem_truncate_meta", ok ? "ok" : "fail",
               ok ? "truncate shrank meta, invalidate dropped it"
               : "truncate/invalidate metadata mishandled");
}
 
/*
 * Duplicate-key hardening: after an LRU/truncate "hole" appears in a cache
 * partition before an existing entry, updating that entry must reuse its
 * current slot rather than insert a second copy into the hole.  Observable
 * through the eviction counter: with a duplicate the partition looks full
 * and the next insert of a new key evicts; without it the hole absorbs the
 * new key and no eviction happens.
 */
/*
 * Generation check on cache hit: a cached entry published before a
 * truncation/compaction generation bump must not be served from the cache.
 * A page is written through the cached path (publishing v1), then rewritten
 * directly (v2, bypassing the shared cache); after a generation bump the
 * cached read must return v2, not the stale cached v1.
 */
static void
test_shmem_generation_check(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    unsigned char page_v1[TEST_BLCKSZ];
    unsigned char page_v2[TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    bool        ok = true;
 
    cfs_storage_setup(&fx, "gencheck");
    if (fx.dir == NULL)
    {
        add_result("shmem_generation_check", "fail", "setup failed");
        return;
    }
    fx.rl.locator.relNumber = 800720;
    cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM);
 
    cfs = cfs_storage_open_new(&fx);
    cfs_map_cache_pin(fx.rl, MAIN_FORKNUM);
 
    /* v1 through the cached path: published into the shared cache. */
    cfs_test_fill_page(page_v1, 0x31);
    if (cfs_write_page_cached(cfs, 5, (const char *) page_v1, &opts) != 0)
        ok = false;
 
    /* v2 directly: journal + local map move on, the segment keeps v1. */
    cfs_test_fill_page(page_v2, 0x32);
    if (ok && cfs_write_page(cfs, 5, (const char *) page_v2, &opts) != 0)
        ok = false;
 
    /*
     * The direct write bypassed the segment pool (single-writer storage API);
     * drop the relation's resident segments the way a truncate does, so the
     * next read re-resolves them through the journal delta.
     */
    cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
 
    /* The read must re-resolve through the journal and serve v2. */
    if (ok && (cfs_read_page_cached(cfs, 5, (char *) back) != 0 ||
               memcmp(page_v2, back, TEST_BLCKSZ) != 0))
        ok = false;
 
    /*
     * Segment generation tag: a publication carries the publishing
     * generation, so a reader can reject a hit whose tag disagrees with its
     * handle's.  A truncate bumps the relation generation (the
     * compaction/truncate swap marker) without dropping pool segments — the
     * surviving tag must then disagree with the live generation.
     */
    {
        CfsMapEntry in;
        CfsMapEntry out;
        uint64      gen_before = 0;
        uint64      gen_after = 0;
        uint64      seg_gen = 0;
 
        gen_before = cfs_map_cache_get_generation(fx.rl, MAIN_FORKNUM);
        cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
 
        /*
         * Publish the logical size the way the production write path does:
         * the pool serves only blocks below the slot's nblocks, and block 7
         * is otherwise beyond the size published by the single cached write
         * of block 5.
         */
        cfs_map_cache_set_meta(fx.rl, MAIN_FORKNUM, 8);
        cfs_map_entry_init(&in);
        in.physical_offset = 4096;
        in.compressed_size = 100;
        in.generation = 1;
        cfs_map_entry_crc_set(&in);
        if (!cfs_shared_map_store(fx.rl, MAIN_FORKNUM, 7, &in,
                                  cfs_map_cache_get_generation(fx.rl, MAIN_FORKNUM)))
            ok = false;
        if (ok && !cfs_shared_map_lookup(fx.rl, MAIN_FORKNUM, 7,
                                         &out, &seg_gen))
            ok = false;
        if (ok && seg_gen != gen_before)
            ok = false;
 
        cfs_map_cache_truncate(fx.rl, MAIN_FORKNUM, 8);
        gen_after = cfs_map_cache_get_generation(fx.rl, MAIN_FORKNUM);
        if (ok && gen_after == gen_before)
            ok = false;
        if (ok && seg_gen == gen_after)
            ok = false;         /* stale tag would be served to current
                                 * readers */
    }
 
    cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
    cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM);
    cfs_close(cfs);
 
    add_result("shmem_generation_check", ok ? "ok" : "fail",
               ok ? "stale-generation hit rejected" : "stale entry served");
    cfs_storage_teardown(&fx);
}
 
/*
 * crc_failures observability: a cache invalidation must NOT reset the
 * relation's statistics counters; only an explicit reset may clear them.
 */
static void
test_shmem_crc_survives_invalidate(void)
{
    RelFileLocatorBackend rl = cfs_shmem_test_locator(800730);
    CfsStatsSnapshot snap;
    bool        ok = true;
 
    cfs_map_cache_invalidate(rl, MAIN_FORKNUM);
    cfs_stats_reset(rl, MAIN_FORKNUM);
 
    cfs_stats_count_crc_failure(rl, MAIN_FORKNUM);
    if (!cfs_stats_snapshot(rl, MAIN_FORKNUM, &snap) || snap.crc_failures != 1)
        ok = false;
 
    /* Ordinary invalidation must leave the counter alive. */
    cfs_map_cache_invalidate(rl, MAIN_FORKNUM);
    if (!cfs_stats_snapshot(rl, MAIN_FORKNUM, &snap) || snap.crc_failures != 1)
        ok = false;
 
    /* An explicit reset still clears it. */
    cfs_stats_reset(rl, MAIN_FORKNUM);
    if (!cfs_stats_snapshot(rl, MAIN_FORKNUM, &snap) || snap.crc_failures != 0)
        ok = false;
 
    add_result("shmem_crc_survives_invalidate", ok ? "ok" : "fail",
               ok ? "crc_failures survives invalidate, reset clears"
               : "invalidate wiped crc_failures");
}
 
/* Probe context + callback for cfs_for_each_cfs_relation(). */
typedef struct CfsEnumProbe
{
    RelFileLocatorBackend target;
    bool        found;
}           CfsEnumProbe;
 
static void
test_enum_probe_cb(RelFileLocatorBackend rlocator, ForkNumber forknum,
                   void *arg)
{
    CfsEnumProbe *probe = (CfsEnumProbe *) arg;
 
    if (forknum == MAIN_FORKNUM &&
        rlocator.locator.spcOid == probe->target.locator.spcOid &&
        rlocator.locator.dbOid == probe->target.locator.dbOid &&
        rlocator.locator.relNumber == probe->target.locator.relNumber &&
        rlocator.backend == probe->target.backend)
        probe->found = true;
}
 
/*
 * Point invalidation on CRC failure: a CRC error while reading one cached
 * block must drop only that block's cache entry.  The cached entries of the
 * other blocks of the same relation and, crucially, the relation metadata
 * slot (which carries the policy fields — is_cfs included — and
 * dirty_checkpoint for checkpoint enumeration) must survive; a repeated
 * read must still detect the real on-disk corruption instead of masking it.
 */
static void
test_shmem_crc_point_invalidate(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    unsigned char pages[3][TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    CfsWriteOptions opts = cfs_test_write_opts();
    CfsEffectiveOptions popts;
    CfsMapEntry cached;
    CfsMapEntry out;
    CfsEnumProbe probe;
    uint64      nblocks = 0;
    uint64      in_use_before = 0;
    uint64      in_use_after = 0;
    uint64      evictions_before = 0;
    uint64      evictions_after = 0;
    int         rc1 = CFS_STORAGE_OK;
    int         rc2 = CFS_STORAGE_OK;
    int         i;
    bool        ok = true;
 
    cfs_storage_setup(&fx, "crc_point");
    if (fx.dir == NULL)
    {
        add_result("shmem_crc_point_invalidate", "fail", "setup failed");
        return;
    }
    fx.rl.locator.relNumber = 800740;
    cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM);
 
    popts.is_cfs = true;
    popts.algorithm = CFS_ALGORITHM_LZ4;
    popts.level = 3;
    popts.min_gain_bytes = 512;
 
    cfs = cfs_storage_open_new(&fx);
    cfs_map_cache_pin(fx.rl, MAIN_FORKNUM);
    cfs_publish_options(fx.rl, MAIN_FORKNUM, &popts);
 
    /* Write three blocks through the cached path (publishes all three). */
    for (i = 0; i < 3; i++)
    {
        cfs_test_fill_page(pages[i], (unsigned char) (0x40 + i));
        if (cfs_write_page_cached(cfs, i, (const char *) pages[i],
                                  &opts) != 0)
        {
            ok = false;
            break;
        }
    }
 
    /*
     * Corrupt the .cfp payload of block 1's record: flip the first payload
     * byte so the payload CRC check in CfsDecompressPage() fails.
     */
    if (ok)
    {
        int         cfp_fd;
        unsigned char b;
 
        if (!cfs_shared_map_lookup(fx.rl, MAIN_FORKNUM, 1, &cached, NULL))
            ok = false;
        cfp_fd = BasicOpenFile(fx.cfp_path, O_RDWR | PG_BINARY);
        if (ok && cfp_fd >= 0 &&
            pread(cfp_fd, &b, 1,
                  (off_t) cached.physical_offset + CFS_BLOCK_HEADER_SIZE) == 1)
        {
            b ^= 0xFF;
            if (pwrite(cfp_fd, &b, 1,
                       (off_t) cached.physical_offset + CFS_BLOCK_HEADER_SIZE) != 1)
                ok = false;
        }
        else
            ok = false;
        if (cfp_fd >= 0)
            close(cfp_fd);
    }
 
    /* The cached read of block 1 must fail with an integrity error. */
    cfs_shared_map_stats(&in_use_before, NULL, &evictions_before, NULL);
    if (ok)
        rc1 = cfs_read_page_cached(cfs, 1, (char *) back);
    if (rc1 != CFS_STORAGE_CORRUPT)
        ok = false;
    cfs_shared_map_stats(&in_use_after, NULL, &evictions_after, NULL);
    if (in_use_after != in_use_before ||
        evictions_after != evictions_before)
        ok = false;
 
    /*
     * The corrupt entry is gone, and the segment as a whole is now a
     * deliberate lookup miss until the read path replays the journal again
     * (journal_synced == false): a bare lookup of blocks 0 and 2 must not
     * serve them in that window either.  Their survival is verified through
     * the read path below, which re-syncs the segment first.
     */
    if (cfs_shared_map_lookup(fx.rl, MAIN_FORKNUM, 1, &out, NULL))
        ok = false;
 
    /* The metadata slot must survive with its logical size ... */
    if (!cfs_map_cache_get_nblocks(fx.rl, MAIN_FORKNUM, &nblocks) ||
        nblocks != 3)
        ok = false;
 
    /*
     * ... and its CFS-ness marker (is_cfs), so checkpoint enumeration still
     * finds it.
     */
    probe.target = fx.rl;
    probe.found = false;
    cfs_for_each_cfs_relation(test_enum_probe_cb, &probe);
    if (!probe.found)
        ok = false;
 
    /*
     * A repeat read must still report the real corruption (the miss path
     * re-reads through the authoritative map), not mask it.
     */
    if (ok)
        rc2 = cfs_read_page_cached(cfs, 1, (char *) back);
    if (rc2 != CFS_STORAGE_CORRUPT)
        ok = false;
 
    /* The surviving entries must still serve the correct pages. */
    if (ok &&
        (cfs_read_page_cached(cfs, 0, (char *) back) != 0 ||
         memcmp(pages[0], back, TEST_BLCKSZ) != 0))
        ok = false;
    if (ok &&
        (cfs_read_page_cached(cfs, 2, (char *) back) != 0 ||
         memcmp(pages[2], back, TEST_BLCKSZ) != 0))
        ok = false;
 
    /*
     * Full cleanup: drop every leftover entry of this relation so later tests
     * sharing the global cache observe a deterministic slot count.
     */
    cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM);
    cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM);
    cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM);
    cfs_close(cfs);
 
    add_result("shmem_crc_point_invalidate", ok ? "ok" : "fail",
               ok ? "CRC error dropped one entry; meta slot survived"
               : "CRC error invalidated too much (or masked corruption)");
    cfs_storage_teardown(&fx);
}
 
/* ================================================================
 * .cfp segmentation (RELSEG_SIZE boundary rollover)
 * ================================================================ */
 
/*
 * Drive the append cursor of a synthetic relation past CFS_SEGMENT_SIZE
 * (1 GiB) with RAW records, then verify:
 *   - the ".cfp.1" segment exists and the tail records landed in it;
 *   - every block reads back correctly through the global->segment offset
 *     translation, both before and after a close/reopen cycle;
 *   - the streaming fsck validates the whole >1 GiB chain with no errors
 *     (this is the regression test for the MaxAllocSize palloc failure:
 *     the old whole-file checker died on files this size);
 *   - the journal generation stream is monotonic for a single writer.
 */
static void
test_segment_rollover(void)
{
    CfsStorageFixture fx;
    CfsRelation *cfs;
    CfsWriteOptions opts = CFS_WRITE_OPTIONS_INIT;
    unsigned char page[TEST_BLCKSZ];
    unsigned char back[TEST_BLCKSZ];
    uint64      nwrites = 0;
    struct stat st;
    char       *seg1_path;
    char        detail[160];
    bool        ok = true;
    const char *why = "";
 
    cfs_storage_setup(&fx, "segroll");
    if (fx.dir == NULL)
    {
        add_result("segment_rollover", "fail", "setup failed");
        return;
    }
 
    /* RAW records: deterministic 8232-byte records, no codec involved. */
    opts.algorithm = CFS_ALGORITHM_RAW;
    opts.explicit_algorithm = true;
    opts.allow_raw_fallback = true;
    opts.min_gain_bytes = 1;
 
    cfs = cfs_storage_open_new(&fx);
 
    /* Fill block 0 past the segment boundary. */
    cfs_test_fill_page(page, 0x55);
    while ((uint64) cfs->cfp_write_off < (uint64) CFS_SEGMENT_SIZE)
    {
        if (cfs_write_page(cfs, 0, (const char *) page, &opts) != CFS_STORAGE_OK)
        {
            ok = false;
            why = "write past boundary failed";
            break;
        }
        nwrites++;
    }
 
    /* Blocks 1 and 2 land entirely inside segment 1. */
    if (ok)
    {
        cfs_test_fill_page(page, 0x66);
        if (cfs_write_page(cfs, 1, (const char *) page, &opts) != CFS_STORAGE_OK ||
            cfs_write_page(cfs, 2, (const char *) page, &opts) != CFS_STORAGE_OK)
        {
            ok = false;
            why = "write into segment 1 failed";
        }
    }
 
    /* The chain must span two segments now. */
    seg1_path = psprintf("%s.1", fx.cfp_path);
    if (ok && stat(seg1_path, &st) != 0)
    {
        ok = false;
        why = ".cfp.1 missing after rollover";
    }
 
    /* The last version of block 0 crossed the boundary. */
    if (ok && cfs->map[0].physical_offset < (uint64) CFS_SEGMENT_SIZE)
    {
        ok = false;
        why = "block 0 tail version not in segment 1";
    }
 
    /* Read back through the boundary before and after reopen. */
    if (ok)
    {
        cfs_test_fill_page(page, 0x55);
        if (cfs_read_page(cfs, 0, (char *) back) != CFS_STORAGE_OK ||
            memcmp(page, back, TEST_BLCKSZ) != 0)
        {
            ok = false;
            why = "block 0 read-back mismatch";
        }
        cfs_test_fill_page(page, 0x66);
        if (ok && (cfs_read_page(cfs, 1, (char *) back) != CFS_STORAGE_OK ||
                   memcmp(page, back, TEST_BLCKSZ) != 0))
        {
            ok = false;
            why = "block 1 read-back mismatch";
        }
    }
    cfs_close(cfs);
 
    if (ok)
    {
        cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM,
                             fx.cfp_path, fx.map_path, fx.jrn_path,
                             CFS_OPEN_RDWR);
        cfs_test_fill_page(page, 0x55);
        if (cfs_read_page(cfs, 0, (char *) back) != CFS_STORAGE_OK ||
            memcmp(page, back, TEST_BLCKSZ) != 0)
        {
            ok = false;
            why = "block 0 mismatch after reopen";
        }
        cfs_test_fill_page(page, 0x66);
        if (ok && (cfs_read_page(cfs, 2, (char *) back) != CFS_STORAGE_OK ||
                   memcmp(page, back, TEST_BLCKSZ) != 0))
        {
            ok = false;
            why = "block 2 mismatch after reopen";
        }
 
        /*
         * Persist a real map snapshot so the fsck below validates live
         * entries (including offsets beyond the segment boundary) rather than
         * the bare header of a freshly created fixture.
         */
        if (ok && cfs_map_save_snapshot(cfs) != CFS_STORAGE_OK)
        {
            ok = false;
            why = "map snapshot failed";
        }
        cfs_close(cfs);
    }
 
    snprintf(detail, sizeof(detail), "writes=%llu%s%s",
             (unsigned long long) nwrites, ok ? "" : " FAILED: ",
             ok ? "" : why);
    add_result("segment_rollover", ok ? "ok" : "fail", detail);
 
    /*
     * Streaming fsck over the >1 GiB chain.  The old whole-file checker died
     * with "invalid memory alloc request size" here.
     */
    {
        CfsFsckResult res;
        CfsFsckOptions fopts = CFS_FSCK_OPTIONS_DEFAULT;
 
        cfs_fsck_result_init(&res);
        cfs_fsck_map_file(fx.map_path, fx.cfp_path, &fopts, &res, NULL);
        cfs_fsck_journal_file(fx.jrn_path, &fopts, &res, NULL);
        cfs_fsck_cfp_file(fx.cfp_path, &fopts, &res);
 
        snprintf(detail, sizeof(detail),
                 "errors=%llu gen_anomalies=%llu cfp_records=%llu",
                 (unsigned long long) res.errors,
                 (unsigned long long) res.generation_violations,
                 (unsigned long long) res.cfp_records);
        add_result("segment_fsck_big_file",
                   (res.errors == 0 && res.generation_violations == 0 &&
                    res.cfp_records == nwrites + 2) ? "ok" : "fail",
                   detail);
    }
 
    pfree(seg1_path);
    cfs_storage_teardown(&fx);
}
 
/*
 * A live map entry with generation == 0 is corruption: every written entry
 * carries generation >= 1.
 */
static void
test_fsck_generation_zero_map(void)
{
    CfsFsckFixture fx;
    CfsFsckResult res;
    CfsFsckOptions opts = CFS_FSCK_OPTIONS_DEFAULT;
    char        detail[128];
    CfsMapEntry e;
    char        buf[CFS_MAP_HEADER_SIZE + CFS_MAP_ENTRY_SIZE];
    CfsMapPrologue mhdr;
 
    if (!cfs_fsck_setup(&fx, "gen0map", FSCK_MODE_CLEAN))
    {
        add_result("fsck_generation_zero_map", "fail", "setup failed");
        return;
    }
 
    /* Rewrite the map with a zero-generation live entry. */
    cfs_map_entry_init(&e);
    e.physical_offset = CFS_CFP_BASE_OFFSET;
    e.compressed_size = 100;
    e.generation = 0;
    cfs_map_entry_crc_set(&e);
    cfs_map_prologue_init(&mhdr);
    memcpy(buf, &mhdr, sizeof(mhdr));
    memcpy(buf + sizeof(mhdr), &e, sizeof(e));
    if (!cfs_test_write_file(fx.map_path, buf, sizeof(buf)))
    {
        add_result("fsck_generation_zero_map", "fail", "rewrite failed");
        cfs_fsck_teardown(&fx);
        return;
    }
 
    cfs_fsck_result_init(&res);
    cfs_fsck_map_file(fx.map_path, fx.cfp_path, &opts, &res, NULL);
 
    snprintf(detail, sizeof(detail), "gen_violations=%llu errors=%llu",
             (unsigned long long) res.generation_violations,
             (unsigned long long) res.errors);
    add_result("fsck_generation_zero_map",
               (res.generation_violations > 0 && res.errors > 0) ? "ok" : "fail",
               detail);
    cfs_fsck_teardown(&fx);
}
 
/*
 * A journal UPDATE record with generation == 0 is corruption (hard error).
 */
static void
test_fsck_generation_zero_journal(void)
{
    CfsFsckFixture fx;
    CfsFsckResult res;
    CfsFsckOptions opts = CFS_FSCK_OPTIONS_DEFAULT;
    char        detail[128];
    CfsMapEntry e;
    CfsJournalEntry je;
    CfsJournalFileHeader jhdr;
    char        buf[CFS_JOURNAL_HEADER_SIZE + CFS_JOURNAL_ENTRY_SIZE];
 
    if (!cfs_fsck_setup(&fx, "gen0jrn", FSCK_MODE_CLEAN))
    {
        add_result("fsck_generation_zero_journal", "fail", "setup failed");
        return;
    }
 
    cfs_map_entry_init(&e);
    e.physical_offset = CFS_CFP_BASE_OFFSET;
    e.compressed_size = 100;
    e.generation = 0;
    cfs_map_entry_crc_set(&e);
    cfs_journal_entry_init_update(&je, 0, &e);
    cfs_journal_header_init(&jhdr);
    memcpy(buf, &jhdr, sizeof(jhdr));
    memcpy(buf + sizeof(jhdr), &je, sizeof(je));
    if (!cfs_test_write_file(fx.jrn_path, buf, sizeof(buf)))
    {
        add_result("fsck_generation_zero_journal", "fail", "rewrite failed");
        cfs_fsck_teardown(&fx);
        return;
    }
 
    cfs_fsck_result_init(&res);
    cfs_fsck_journal_file(fx.jrn_path, &opts, &res, NULL);
 
    snprintf(detail, sizeof(detail), "gen_violations=%llu errors=%llu",
             (unsigned long long) res.generation_violations,
             (unsigned long long) res.errors);
    add_result("fsck_generation_zero_journal",
               (res.generation_violations > 0 && res.errors > 0) ? "ok" : "fail",
               detail);
    cfs_fsck_teardown(&fx);
}
 
/*
 * A journal UPDATE record whose outer CRC is valid but whose embedded
 * new_entry is invalid (offset inside the reserved lead-in, or an
 * oversized compressed_size) must be flagged by fsck.
 */
static void
test_fsck_journal_bad_new_entry(void)
{
    CfsFsckFixture fx;
    CfsFsckResult res;
    CfsFsckOptions opts = CFS_FSCK_OPTIONS_DEFAULT;
    CfsMapEntry e;
    CfsJournalEntry je;
    CfsJournalFileHeader jhdr;
    char        buf[CFS_JOURNAL_HEADER_SIZE + CFS_JOURNAL_ENTRY_SIZE];
    bool        ok = true;
 
    if (!cfs_fsck_setup(&fx, "badnewentry", FSCK_MODE_CLEAN))
    {
        add_result("fsck_journal_bad_new_entry", "fail", "setup failed");
        return;
    }
 
    /* Case 1: new_entry offset inside the reserved lead-in. */
    cfs_map_entry_init(&e);
    e.physical_offset = 1;      /* < CFS_CFP_BASE_OFFSET */
    e.compressed_size = 100;
    e.generation = 1;
    cfs_map_entry_crc_set(&e);
    cfs_journal_entry_init_update(&je, 0, &e);
    cfs_journal_header_init(&jhdr);
    memcpy(buf, &jhdr, sizeof(jhdr));
    memcpy(buf + sizeof(jhdr), &je, sizeof(je));
    if (!cfs_test_write_file(fx.jrn_path, buf, sizeof(buf)))
        ok = false;
    if (ok)
    {
        cfs_fsck_result_init(&res);
        cfs_fsck_journal_file(fx.jrn_path, &opts, &res, NULL);
        if (res.offset_out_of_range < 1 || res.errors < 1)
            ok = false;
    }
 
    /*
     * Case 2: new_entry with an oversized compressed_size (a field error).
     */
    cfs_map_entry_init(&e);
    e.physical_offset = CFS_CFP_BASE_OFFSET;
    e.compressed_size = CFS_BLCKSZ + 1; /* invalid */
    e.generation = 1;
    cfs_map_entry_crc_set(&e);
    cfs_journal_entry_init_update(&je, 0, &e);
    cfs_journal_header_init(&jhdr);
    memcpy(buf, &jhdr, sizeof(jhdr));
    memcpy(buf + sizeof(jhdr), &je, sizeof(je));
    if (!cfs_test_write_file(fx.jrn_path, buf, sizeof(buf)))
        ok = false;
    if (ok)
    {
        cfs_fsck_result_init(&res);
        cfs_fsck_journal_file(fx.jrn_path, &opts, &res, NULL);
 
        /*
         * The entry CRC was recomputed, so this single record must be counted
         * as a field failure only, never as a CRC failure.
         */
        if (res.field_failures < 1 || res.crc_failures != 0 || res.errors < 1)
            ok = false;
    }
 
    add_result("fsck_journal_bad_new_entry", ok ? "ok" : "fail",
               ok ? "bad new_entry offset/field flagged"
               : "bad new_entry not flagged");
    cfs_fsck_teardown(&fx);
}
 
/*
 * A non-increasing generation sequence in the journal is flagged as an
 * anomaly but is not a hard error (multi-backend writers may legitimately
 * compute the generation from a stale local map).
 */
static void
test_fsck_generation_regression(void)
{
    CfsFsckFixture fx;
    CfsFsckResult res;
    CfsFsckOptions opts = CFS_FSCK_OPTIONS_DEFAULT;
    char        detail[128];
    CfsMapEntry e;
    CfsJournalEntry je;
    CfsJournalFileHeader jhdr;
    char        buf[CFS_JOURNAL_HEADER_SIZE + 2 * CFS_JOURNAL_ENTRY_SIZE];
    size_t      off;
 
    if (!cfs_fsck_setup(&fx, "genregr", FSCK_MODE_CLEAN))
    {
        add_result("fsck_generation_regression", "fail", "setup failed");
        return;
    }
 
    cfs_map_entry_init(&e);
    e.physical_offset = CFS_CFP_BASE_OFFSET;
    e.compressed_size = 100;
 
    cfs_journal_header_init(&jhdr);
    memcpy(buf, &jhdr, sizeof(jhdr));
    off = sizeof(jhdr);
 
    e.generation = 2;
    cfs_map_entry_crc_set(&e);
    cfs_journal_entry_init_update(&je, 0, &e);
    memcpy(buf + off, &je, sizeof(je));
    off += sizeof(je);
 
    e.generation = 1;           /* regression */
    cfs_map_entry_crc_set(&e);
    cfs_journal_entry_init_update(&je, 0, &e);
    memcpy(buf + off, &je, sizeof(je));
    off += sizeof(je);
 
    if (!cfs_test_write_file(fx.jrn_path, buf, off))
    {
        add_result("fsck_generation_regression", "fail", "rewrite failed");
        cfs_fsck_teardown(&fx);
        return;
    }
 
    cfs_fsck_result_init(&res);
    cfs_fsck_journal_file(fx.jrn_path, &opts, &res, NULL);
 
    snprintf(detail, sizeof(detail), "gen_violations=%llu errors=%llu",
             (unsigned long long) res.generation_violations,
             (unsigned long long) res.errors);
    add_result("fsck_generation_regression",
               (res.generation_violations == 1 && res.errors == 0) ? "ok" : "fail",
               detail);
    cfs_fsck_teardown(&fx);
}
 
/*
 * Craft a .cfsjrn file holding 'nblocks' unique, valid UPDATE records
 * (blocknum 0..nblocks-1, generation 1).  Lets the test drive the generation
 * tracker to its cap without a real workload.
 */
static bool
cfs_test_write_journal(const char *path, uint32 nblocks)
{
    CfsMapEntry e;
    CfsJournalEntry je;
    CfsJournalFileHeader jhdr;
    char       *buf;
    size_t      total = sizeof(jhdr) + (size_t) nblocks * CFS_JOURNAL_ENTRY_SIZE;
    size_t      off;
    uint32      i;
    bool        ok;
 
    cfs_map_entry_init(&e);
    e.physical_offset = CFS_CFP_BASE_OFFSET;
    e.compressed_size = 100;
    e.generation = 1;
    cfs_map_entry_crc_set(&e);
    cfs_journal_entry_init_update(&je, 0, &e);
    cfs_journal_header_init(&jhdr);
 
    buf = palloc(total);
    memcpy(buf, &jhdr, sizeof(jhdr));
    off = sizeof(jhdr);
    for (i = 0; i < nblocks; i++)
    {
        je.blocknum = i;
        cfs_journal_entry_crc_set(&je);
        memcpy(buf + off, &je, sizeof(je));
        off += sizeof(je);
    }
 
    ok = cfs_test_write_file(path, buf, total);
    pfree(buf);
    return ok;
}
 
/*
 * The per-block generation tracker is capped: a journal with more unique
 * blocks than CFS_FSCK_GEN_TRACK_MAX degrades the monotonicity check (no hard
 * errors), while a smaller journal keeps it fully active.
 */
static void
test_fsck_generation_tracker_cap(void)
{
    CfsFsckFixture fx;
    CfsFsckResult res;
    CfsFsckOptions opts = CFS_FSCK_OPTIONS_DEFAULT;
    bool        ok = true;
 
    if (!cfs_fsck_setup(&fx, "gencap", FSCK_MODE_CLEAN))
    {
        add_result("fsck_generation_tracker_cap", "fail", "setup failed");
        return;
    }
 
    /* Below the cap: the monotonicity check stays active. */
    if (!cfs_test_write_journal(fx.jrn_path, 100))
        ok = false;
    if (ok)
    {
        cfs_fsck_result_init(&res);
        cfs_fsck_journal_file(fx.jrn_path, &opts, &res, NULL);
        if (res.generation_check_degraded || res.errors != 0)
            ok = false;
    }
 
    /* Above the cap: monotonicity degrades, but no hard errors. */
    if (ok && !cfs_test_write_journal(fx.jrn_path,
                                      (uint32) CFS_FSCK_GEN_TRACK_MAX + 1))
        ok = false;
    if (ok)
    {
        cfs_fsck_result_init(&res);
        cfs_fsck_journal_file(fx.jrn_path, &opts, &res, NULL);
        if (!res.generation_check_degraded || res.errors != 0)
            ok = false;
    }
 
    add_result("fsck_generation_tracker_cap", ok ? "ok" : "fail",
               ok ? "tracker degrades above cap, clean below"
               : "tracker cap misbehaved");
    cfs_fsck_teardown(&fx);
}
 
/*
 * Try to open the fixture relation; return true when cfs_open_paths()
 * rejects it with the "larger than the segment size" corruption error.
 */
static bool
test_segment_open_rejected(CfsFsckFixture * fx)
{
    CfsRelation *cfs = NULL;
    bool        rejected = false;
 
    PG_TRY();
    {
        RelFileLocatorBackend rl;
 
        rl.locator.spcOid = DEFAULTTABLESPACE_OID;
        rl.locator.dbOid = 16384;
        rl.locator.relNumber = 99991;
        rl.backend = INVALID_PROC_NUMBER;
 
        cfs = cfs_open_paths(rl, MAIN_FORKNUM,
                             fx->cfp_path, fx->map_path, fx->jrn_path,
                             CFS_OPEN_RDWR);
    }
    PG_CATCH();
    {
        ErrorData  *edata;
        MemoryContext oldcontext = MemoryContextSwitchTo(TopMemoryContext);
 
        edata = CopyErrorData();
        if (strstr(edata->message, "larger than the segment size") != NULL)
            rejected = true;
        MemoryContextSwitchTo(oldcontext);
        FlushErrorState();
    }
    PG_END_TRY();
 
    if (cfs != NULL)
        cfs_close(cfs);
    return rejected;
}
 
/*
 * The engine never writes a segment larger than CFS_SEGMENT_SIZE, so an
 * oversized one is corruption regardless of what the rest of the chain
 * looks like: a lone oversized ".cfp" and an oversized ".cfp" followed by
 * a ".cfp.1" must both be rejected at open.
 */
static void
test_segment_oversized_rejected(void)
{
    CfsFsckFixture fx;
    bool        rejected_lone;
    bool        rejected_mixed;
    char        detail[128];
    int         fd;
    char        zero[CFS_CFP_BASE_OFFSET] = {0};
 
    if (!cfs_fsck_setup(&fx, "bigseg", FSCK_MODE_CLEAN))
    {
        add_result("segment_oversized_rejected", "fail", "setup failed");
        return;
    }
 
    /*
     * Inflate ".cfp" past CFS_SEGMENT_SIZE (sparse: lead-in plus a hole).
     */
    fd = BasicOpenFile(fx.cfp_path, O_RDWR | PG_BINARY);
    if (fd < 0 ||
        write(fd, zero, sizeof(zero)) != sizeof(zero) ||
        ftruncate(fd, (off_t) CFS_SEGMENT_SIZE + 8192) != 0)
    {
        add_result("segment_oversized_rejected", "fail", "inflate failed");
        if (fd >= 0)
            close(fd);
        cfs_fsck_teardown(&fx);
        return;
    }
    close(fd);
 
    /* Case 1: a lone oversized segment 0. */
    rejected_lone = test_segment_open_rejected(&fx);
 
    /* Case 2: a stray ".cfp.1" on top of it — a mixed chain. */
    if (!cfs_test_write_file(psprintf("%s.1", fx.cfp_path), zero, sizeof(zero)))
    {
        add_result("segment_oversized_rejected", "fail", "seg1 failed");
        cfs_fsck_teardown(&fx);
        return;
    }
    rejected_mixed = test_segment_open_rejected(&fx);
 
    snprintf(detail, sizeof(detail), "lone=%d mixed=%d",
             (int) rejected_lone, (int) rejected_mixed);
    add_result("segment_oversized_rejected",
               (rejected_lone && rejected_mixed) ? "ok" : "fail", detail);
    unlink(psprintf("%s.1", fx.cfp_path));
    cfs_fsck_teardown(&fx);
}
 
PG_FUNCTION_INFO_V1(cfs_run_tests);
PG_FUNCTION_INFO_V1(test_cfs_roundtrip);
PG_FUNCTION_INFO_V1(test_cfs_corrupt_crc);
PG_FUNCTION_INFO_V1(test_cfs_codec_available);
PG_FUNCTION_INFO_V1(cfs_run_format_tests);
PG_FUNCTION_INFO_V1(cfs_run_path_tests);
PG_FUNCTION_INFO_V1(cfs_run_fsck_tests);
PG_FUNCTION_INFO_V1(cfs_run_storage_tests);
PG_FUNCTION_INFO_V1(cfs_run_shmem_tests);
PG_FUNCTION_INFO_V1(cfs_run_shmem_hook_tests);
PG_FUNCTION_INFO_V1(cfs_run_segment_tests);
PG_FUNCTION_INFO_V1(cfs_relation_policy);
 
Datum
test_cfs_roundtrip(PG_FUNCTION_ARGS)
{
    CfsAlgorithm algorithm = parse_algorithm_text(PG_GETARG_TEXT_PP(0));
    bytea      *payload = PG_GETARG_BYTEA_PP(1);
    int32       level = PG_GETARG_INT32(2);
    unsigned char page[TEST_BLCKSZ];
    unsigned char decompressed[TEST_BLCKSZ];
    unsigned char *scratch;
    size_t      scratch_sz;
    CfsCompressOptions opts = CFS_COMPRESS_OPTIONS_INIT;
    CfsCompressResult cres;
    CfsDecompressResult dres;
    CfsDecompressStatus dstatus;
    bool        ok;
 
    if (!CfsCodecAvailable(algorithm))
    {
        PG_RETURN_BOOL(algorithm == CFS_ALGORITHM_RAW ? false : true);
    }
 
    fill_page_from_payload(page, payload);
    scratch_sz = CfsCompressScratchSize(sizeof(page));
    scratch = palloc(scratch_sz);
    opts.algorithm = algorithm;
    opts.level = level;
    opts.min_gain_bytes = 1;
    opts.explicit_algorithm = true;
    opts.allow_raw_fallback = true;
 
    ereport(DEBUG1,
            (errmsg("CFS: test round-trip for algorithm %s",
                    CfsAlgorithmGetName(algorithm))));
 
    CfsCompressPage(page, sizeof(page), &opts, scratch, scratch_sz,
                    &cres);
 
    dstatus = CfsDecompressPage(cres.result_data, cres.total_size,
                                decompressed, sizeof(decompressed), &dres);
    ok = (dstatus == CFS_DECOMPRESS_OK &&
          dres.decompressed_size == sizeof(page) &&
          memcmp(page, decompressed, sizeof(page)) == 0);
    pfree(scratch);
    PG_RETURN_BOOL(ok);
}
 
Datum
test_cfs_corrupt_crc(PG_FUNCTION_ARGS)
{
    CfsAlgorithm algorithm = parse_algorithm_text(PG_GETARG_TEXT_PP(0));
    unsigned char page[TEST_BLCKSZ];
    unsigned char decompressed[TEST_BLCKSZ];
    unsigned char *scratch;
    size_t      scratch_sz;
    CfsCompressOptions opts = CFS_COMPRESS_OPTIONS_INIT;
    CfsCompressResult cres;
    CfsDecompressStatus dstatus;
    CfsCompressedBlockHeader *hdr;
 
    if (!CfsCodecAvailable(algorithm))
    {
        PG_RETURN_TEXT_P(cstring_to_text("skip"));
    }
 
    fill_constant(page, sizeof(page), 0x7F);
    scratch_sz = CfsCompressScratchSize(sizeof(page));
    scratch = palloc(scratch_sz);
    opts.algorithm = algorithm;
    opts.level = CFS_COMPRESS_LEVEL_DEFAULT;
    opts.min_gain_bytes = 1;
    opts.explicit_algorithm = true;
    opts.allow_raw_fallback = true;
 
    CfsCompressPage(page, sizeof(page), &opts, scratch, scratch_sz,
                    &cres);
    hdr = (CfsCompressedBlockHeader *) cres.result_data;
    hdr->data_crc ^= 0x00000001u;
    dstatus = CfsDecompressPage(cres.result_data, cres.total_size,
                                decompressed, sizeof(decompressed), NULL);
    pfree(scratch);
 
    if (dstatus == CFS_DECOMPRESS_BAD_DATA || dstatus == CFS_DECOMPRESS_BAD_HDR)
    {
        PG_RETURN_TEXT_P(cstring_to_text("ok"));
    }
    PG_RETURN_TEXT_P(cstring_to_text("fail"));
}
 
Datum
test_cfs_codec_available(PG_FUNCTION_ARGS)
{
    CfsAlgorithm algorithm = parse_algorithm_text(PG_GETARG_TEXT_PP(0));
 
    PG_RETURN_BOOL(CfsCodecAvailable(algorithm));
}
 
/*
 * SQL-callable entry point: run every CFS codec test case and return one
 * row per case with columns (test_name, result, detail).
 */
Datum
cfs_run_tests(PG_FUNCTION_ARGS)
{
    ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
    Tuplestorestate *tupstore;
    TupleDesc   tupdesc;
    int         i;
    Datum       values[3];
    bool        nulls[3];
 
    /*
     * Run the tests in TopMemoryContext so that any codec state cached by
     * CfsCodecStateCreate() (a static per-backend cache) is not allocated in
     * the caller's per-query context — which would be destroyed at the end
     * of the statement and leave dangling pointers in the cache for the next
     * invocation.  We destroy the whole cache before returning so the next
     * call starts from a clean slate.
     */
    MemoryContext oldcontext = MemoryContextSwitchTo(TopMemoryContext);
 
    InitMaterializedSRF(fcinfo, MAT_SRF_USE_EXPECTED_DESC);
 
    tupdesc = rsinfo->setDesc;
    tupstore = rsinfo->setResult;
 
    /* Reset accumulator and run all tests. */
    test_result_count = 0;
    test_raw_codec();
    test_lz4_codec();
    test_zstd_codec();
    test_extended_codec(CFS_ALGORITHM_PGLZ, pglz_extended_names);
    test_extended_codec(CFS_ALGORITHM_ZLIB, zlib_extended_names);
    test_lz4_level_roundtrip();
    test_codec_max_level();
    test_default_write_opts_level();
    test_default_level_for();
    test_policy_flags_roundtrip();
    test_raw_page_roundtrip();
    test_compress_page_lz4();
    test_incompressible_raw_fallback();
    test_crc_corruption_detection();
    test_decompress_original_size_rejected();
    test_decompress_codec_unavailable();
    test_record_padding_zeroed();
    test_record_padding_checked();
    test_scratch_and_alignment();
    test_compress_page_size_rejected();
 
    memset(nulls, 0, sizeof(nulls));
    for (i = 0; i < test_result_count; i++)
    {
        CfsTestResult *r = &test_results[i];
 
        values[0] = CStringGetTextDatum(r->test_name);
        values[1] = CStringGetTextDatum(r->result);
        values[2] = CStringGetTextDatum(r->detail);
        tuplestore_putvalues(tupstore, tupdesc, values, nulls);
    }
 
    /* Release any codec state cached during this run. */
    CfsCodecStateDestroyAll();
 
    MemoryContextSwitchTo(oldcontext);
 
    return (Datum) 0;
}
 
/*
 * Shared result-set emitter for the format test runners.  The caller is
 * expected to have populated the static test_results[] accumulator and to have
 * executed within TopMemoryContext.
 */
static void
cfs_emit_test_results(PG_FUNCTION_ARGS)
{
    ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
    Tuplestorestate *tupstore;
    TupleDesc   tupdesc;
    int         i;
    Datum       values[3];
    bool        nulls[3];
 
    InitMaterializedSRF(fcinfo, MAT_SRF_USE_EXPECTED_DESC);
    tupdesc = rsinfo->setDesc;
    tupstore = rsinfo->setResult;
 
    memset(nulls, 0, sizeof(nulls));
    for (i = 0; i < test_result_count; i++)
    {
        CfsTestResult *r = &test_results[i];
 
        values[0] = CStringGetTextDatum(r->test_name);
        values[1] = CStringGetTextDatum(r->result);
        values[2] = CStringGetTextDatum(r->detail);
        tuplestore_putvalues(tupstore, tupdesc, values, nulls);
    }
}
 
Datum
cfs_run_format_tests(PG_FUNCTION_ARGS)
{
    MemoryContext oldcontext = MemoryContextSwitchTo(TopMemoryContext);
 
    test_result_count = 0;
    test_format_map_header();
    test_format_map_entry();
    test_format_journal_header();
    test_format_journal_entry();
    test_format_block_header();
 
    cfs_emit_test_results(fcinfo);
 
    CfsCodecStateDestroyAll();
    MemoryContextSwitchTo(oldcontext);
 
    return (Datum) 0;
}
 
Datum
cfs_run_path_tests(PG_FUNCTION_ARGS)
{
    MemoryContext oldcontext = MemoryContextSwitchTo(TopMemoryContext);
 
    test_result_count = 0;
    test_path_helpers();
 
    cfs_emit_test_results(fcinfo);
 
    MemoryContextSwitchTo(oldcontext);
 
    return (Datum) 0;
}
 
Datum
cfs_run_fsck_tests(PG_FUNCTION_ARGS)
{
    MemoryContext oldcontext = MemoryContextSwitchTo(TopMemoryContext);
 
    test_result_count = 0;
    test_fsck_clean_relation();
    test_fsck_corrupt_map();
    test_fsck_torn_journal();
    test_fsck_offset_out_of_range();
    test_fsck_live_entries_missing_cfp();
    test_fsck_empty_map_no_cfp();
    test_fsck_journal_bad_new_entry();
    test_fsck_torn_cfp_header();
    test_fsck_torn_cfp_record();
    test_fsck_corrupt_cfp_record();
    test_fsck_cross_check();
    test_fsck_resize_shrink_grow();
    test_recovery_scan_strict_names();
 
    cfs_emit_test_results(fcinfo);
 
    CfsCodecStateDestroyAll();
    MemoryContextSwitchTo(oldcontext);
 
    return (Datum) 0;
}
 
Datum
cfs_run_storage_tests(PG_FUNCTION_ARGS)
{
    MemoryContext oldcontext = MemoryContextSwitchTo(TopMemoryContext);
 
    test_result_count = 0;
    test_storage_create_open();
    test_storage_write_read();
    test_storage_update_generation();
    test_storage_fold_skips_missing_cfp();
    test_cfs_journal_apply_sink();
    test_storage_segment_replay_header();
    test_storage_next_generation();
    test_storage_journal_replay();
    test_storage_checkpoint();
    test_read_record_size_guard();
    test_map_sparse_hole_zero_page();
    test_map_corrupt_row_healed();
 
    test_storage_crash_after_cfp();
    test_storage_zero_extend_truncate();
    test_storage_zero_extend_overflow();
    test_storage_truncate_journal_resize_only();
    test_storage_reopen_closes_fds_on_error();
    test_storage_unlink_swap_artifacts();
    test_storage_lookup_no_implicit_growth();
    test_storage_write_page_journals_resize();
    test_storage_compaction();
    test_storage_journal_incarnation();
    test_storage_chain_padding();
    test_storage_snapshot_tail_invalidated();
    test_storage_snapshot_cfp_size_from_eof();
    test_storage_torn_record_visibility();
    test_storage_torn_tail_truncated();
    test_storage_mid_journal_preserved();
    test_storage_delta_mid_journal_reload();
    test_storage_tail_change_detected();
    test_storage_journal_skip_missing_data();
    test_storage_read_padding_garbage();
    test_storage_shared_tail_protocol();
    test_compress_page_nocopy_raw();
 
    cfs_emit_test_results(fcinfo);
 
    CfsCodecStateDestroyAll();
    MemoryContextSwitchTo(oldcontext);
 
    return (Datum) 0;
}
 
Datum
cfs_run_segment_tests(PG_FUNCTION_ARGS)
{
    MemoryContext oldcontext = MemoryContextSwitchTo(TopMemoryContext);
 
    test_result_count = 0;
    test_fsck_generation_zero_map();
    test_fsck_generation_zero_journal();
    test_fsck_generation_regression();
    test_fsck_generation_tracker_cap();
    test_segment_oversized_rejected();
    test_segment_rollover();
 
    cfs_emit_test_results(fcinfo);
 
    CfsCodecStateDestroyAll();
    MemoryContextSwitchTo(oldcontext);
 
    return (Datum) 0;
}
 
Datum
cfs_run_shmem_tests(PG_FUNCTION_ARGS)
{
    MemoryContext oldcontext = MemoryContextSwitchTo(TopMemoryContext);
 
    test_result_count = 0;
    test_shmem_meta_pin();
    test_shmem_stats();
    test_shmem_chains();
    test_shmem_cached_io();
    test_read_cached_entry_corruption();
    test_shmem_invalidate();
    test_shmem_meta_overflow();
    test_shmem_pin_reaper();
    test_shmem_publish_postcommit_overflow();
    test_shmem_truncate_meta();
    test_shmem_generation_check();
    test_shmem_crc_survives_invalidate();
    test_shmem_crc_point_invalidate();
    test_bg_pause_expiry();
    test_shmem_stale_handle_hit();
    test_shared_map_api();
    test_shared_map_nblocks_gate();
    test_shared_map_eviction();
    test_shared_map_eviction_pinned();
    test_shared_map_ensure();
    test_shared_map_resident_store_no_evict();
    test_shared_map_clock_sweep();
    test_shared_map_generation_gate();
    test_shared_map_short_read();
    test_shared_map_segment_replay_corruption();
    test_shared_map_journal_aba();
    test_shared_map_truncate_resurrect();
    test_shared_map_pool_exhaustion();
    test_shared_map_write_no_load();
    test_shared_map_fallback_read();
    test_shared_map_unhealed_corruption();
    test_shared_map_invalidate_index();
    test_shared_map_drop_database();
 
    cfs_emit_test_results(fcinfo);
 
    CfsCodecStateDestroyAll();
    MemoryContextSwitchTo(oldcontext);
 
    return (Datum) 0;
}
 
/*
 * Assert-only shared-map tests.  They are split off the main shmem set so
 * that the regression output does not depend on whether the server was
 * built with assertions; the TAP test drives this function and skips when
 * debug_assertions is off.
 */
Datum
cfs_run_shmem_hook_tests(PG_FUNCTION_ARGS)
{
    MemoryContext oldcontext = MemoryContextSwitchTo(TopMemoryContext);
 
    test_result_count = 0;
    test_shared_map_publish_unsynced();
    test_shared_map_merge_race();
    test_shared_map_orphan_reservation();
    test_shared_map_usage_reset();
 
    cfs_emit_test_results(fcinfo);
 
    CfsCodecStateDestroyAll();
    MemoryContextSwitchTo(oldcontext);
 
    return (Datum) 0;
}
 
/* ------------------------------------------------------------------
 * Relation policy inspection helper.
 *
 * cfs_relation_policy(regclass) returns the CFS policy of the named relation
 * as it is effective for the current session: whether CFS is enabled and,
 * if so, the algorithm plus level / min_gain_bytes resolved the same way
 * the write path resolves them (explicit stored value, else the session's
 * cfs_default_* GUCs).  It exercises RelationUsesCfs() and
 * CfsEffectiveOptionsFromRelation() from the SQL surface so that the
 * reloptions / GUC / inheritance behaviour can be validated by regression
 * tests.
 * ------------------------------------------------------------------ */
Datum
cfs_relation_policy(PG_FUNCTION_ARGS)
{
    Oid         reloid = PG_GETARG_OID(0);
    Relation    rel;
    CfsEffectiveOptions opts;
    TupleDesc   tupdesc;
    Datum       values[4];
    bool        nulls[4];
    HeapTuple   tuple;
 
    if (!OidIsValid(reloid))
        PG_RETURN_NULL();
 
    if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
        elog(ERROR, "return type must be a row type");
 
    rel = relation_open(reloid, AccessShareLock);
 
    /*
     * CfsEffectiveOptionsFromRelation handles every relkind safely: an
     * index resolves through its own stored policy (no parent lookup),
     * and non-StdRdOptions relkinds (views/composite-types/sequences) are
     * recognized internally and return is_cfs=false without casting
     * rd_options.  No outer gate needed.
     */
    CfsEffectiveOptionsFromRelation(rel, &opts);
 
    /*
     * Resolve unset fields from the session GUCs, mirroring the write path
     * (cfs_smgr_write_opts): the probe reports what a write in this session
     * would use right now.
     */
    if (opts.is_cfs)
    {
        if (!opts.level_set)
            opts.level = (opts.algorithm != CFS_ALGORITHM_RAW) ?
                cfs_default_level_for(opts.algorithm) :
                CFS_COMPRESS_LEVEL_DEFAULT;
        if (!opts.min_gain_bytes_set)
            opts.min_gain_bytes = cfs_default_min_gain_bytes;
    }
 
    MemSet(nulls, 0, sizeof(nulls));
    values[0] = BoolGetDatum(opts.is_cfs);
 
    if (opts.is_cfs)
    {
        values[1] = CStringGetTextDatum(CfsAlgorithmGetName(opts.algorithm));
        values[2] = Int32GetDatum(opts.level);
        values[3] = Int32GetDatum(opts.min_gain_bytes);
    }
    else
    {
        nulls[1] = true;
        nulls[2] = true;
        nulls[3] = true;
    }
 
    relation_close(rel, AccessShareLock);
 
    tuple = heap_form_tuple(tupdesc, values, nulls);
 
    PG_RETURN_DATUM(HeapTupleGetDatum(tuple));
}
 
/* ------------------------------------------------------------------
 * cfs_relation_has_sidecars(regclass)
 *
 * Returns true when at least one CFS sidecar file (.cfp / .cfsmap / .cfsjrn)
 * exists on disk for the relation's main fork.  Used by the regression test
 * to verify that the storage manager creates sidecars when a relation uses
 * CFS and removes them on DROP.
 * ------------------------------------------------------------------ */
PG_FUNCTION_INFO_V1(cfs_relation_has_sidecars);
 
Datum
cfs_relation_has_sidecars(PG_FUNCTION_ARGS)
{
    Oid         reloid = PG_GETARG_OID(0);
    Relation    rel;
    RelFileLocatorBackend rl;
    bool        result;
 
    if (!OidIsValid(reloid))
        PG_RETURN_NULL();
 
    rel = relation_open(reloid, AccessShareLock);
 
    rl.locator = rel->rd_locator;
    rl.backend = rel->rd_backend;
 
    /*
     * cfs_exists() returns false for unsupported (temp) locators, which is
     * the correct answer here.
     */
    result = cfs_exists(rl, MAIN_FORKNUM);
 
    relation_close(rel, AccessShareLock);
 
    PG_RETURN_BOOL(result);
}
 
/* ------------------------------------------------------------------
 * cfs_test_defer_publish(regclass, int)
 *
 * Resolve the relation's current effective CFS policy, set the level to the
 * given value, and queue it for deferred publication (as if an ALTER had
 * changed the tuning).  Exercises cfs_publish_options_deferred() from the
 * SQL surface so the pre-commit / abort flush semantics can be validated by
 * a regression test.
 * ------------------------------------------------------------------ */
PG_FUNCTION_INFO_V1(cfs_test_defer_publish);
 
Datum
cfs_test_defer_publish(PG_FUNCTION_ARGS)
{
    Oid         reloid = PG_GETARG_OID(0);
    int         level = PG_GETARG_INT32(1);
    Relation    rel;
    RelFileLocatorBackend rl;
    CfsEffectiveOptions opts;
 
    if (!OidIsValid(reloid))
        PG_RETURN_NULL();
 
    rel = relation_open(reloid, AccessShareLock);
 
    CfsEffectiveOptionsFromRelation(rel, &opts);
    if (!opts.is_cfs)
    {
        relation_close(rel, AccessShareLock);
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("relation is not a CFS relation")));
    }
 
    opts.level = level;
    opts.level_set = true;
 
    rl.locator = rel->rd_locator;
    rl.backend = rel->rd_backend;
 
    cfs_publish_options_deferred(rl, MAIN_FORKNUM, &opts);
 
    relation_close(rel, AccessShareLock);
 
    PG_RETURN_VOID();
}
 
/* ------------------------------------------------------------------
 * cfs_test_publish_pending(regclass)
 *
 * Report whether the relation has a deferred policy publication queued in the
 * current transaction (cfs_publish_is_pending).
 * ------------------------------------------------------------------ */
PG_FUNCTION_INFO_V1(cfs_test_publish_pending);
 
Datum
cfs_test_publish_pending(PG_FUNCTION_ARGS)
{
    Oid         reloid = PG_GETARG_OID(0);
    Relation    rel;
    RelFileLocatorBackend rl;
    bool        pending;
 
    if (!OidIsValid(reloid))
        PG_RETURN_NULL();
 
    rel = relation_open(reloid, AccessShareLock);
    rl.locator = rel->rd_locator;
    rl.backend = rel->rd_backend;
 
    pending = cfs_publish_is_pending(rl, MAIN_FORKNUM);
 
    relation_close(rel, AccessShareLock);
 
    PG_RETURN_BOOL(pending);
}
 
/* ------------------------------------------------------------------
 * cfs_test_shared_level(regclass)
 *
 * Return the level currently stored in the shared-memory policy cache for the
 * relation, or NULL when no CFS policy is published there.  Exercises
 * cfs_get_options() from the SQL surface.
 * ------------------------------------------------------------------ */
PG_FUNCTION_INFO_V1(cfs_test_shared_level);
 
Datum
cfs_test_shared_level(PG_FUNCTION_ARGS)
{
    Oid         reloid = PG_GETARG_OID(0);
    Relation    rel;
    RelFileLocatorBackend rl;
    CfsEffectiveOptions opts;
 
    if (!OidIsValid(reloid))
        PG_RETURN_NULL();
 
    rel = relation_open(reloid, AccessShareLock);
    rl.locator = rel->rd_locator;
    rl.backend = rel->rd_backend;
 
    if (!cfs_get_options(rl, MAIN_FORKNUM, &opts) || !opts.is_cfs)
    {
        relation_close(rel, AccessShareLock);
        PG_RETURN_NULL();
    }
 
    relation_close(rel, AccessShareLock);
 
    PG_RETURN_INT32(opts.level);
}
 
/* ------------------------------------------------------------------
 * cfs_test_publish_pending_at(oid)
 *
 * Report whether the given relfilenode (current database, default
 * tablespace, regular backend) has a deferred policy publication queued in
 * the current transaction.  Lets a test inspect a storage node the
 * relation itself no longer uses (e.g. after a rewrite).
 * ------------------------------------------------------------------ */
PG_FUNCTION_INFO_V1(cfs_test_publish_pending_at);
 
Datum
cfs_test_publish_pending_at(PG_FUNCTION_ARGS)
{
    Oid         filenode = PG_GETARG_OID(0);
    RelFileLocatorBackend rl;
 
    rl.locator.spcOid = MyDatabaseTableSpace;
    rl.locator.dbOid = MyDatabaseId;
    rl.locator.relNumber = filenode;
    rl.backend = INVALID_PROC_NUMBER;
 
    PG_RETURN_BOOL(cfs_publish_is_pending(rl, MAIN_FORKNUM));
}
 
/* ------------------------------------------------------------------
 * cfs_test_shared_level_at(oid)
 *
 * Return the level currently stored in the shared-memory policy cache for
 * the given relfilenode (current database, default tablespace), or NULL
 * when no CFS policy is published there.
 * ------------------------------------------------------------------ */
PG_FUNCTION_INFO_V1(cfs_test_shared_level_at);
 
Datum
cfs_test_shared_level_at(PG_FUNCTION_ARGS)
{
    Oid         filenode = PG_GETARG_OID(0);
    RelFileLocatorBackend rl;
    CfsEffectiveOptions opts;
 
    rl.locator.spcOid = MyDatabaseTableSpace;
    rl.locator.dbOid = MyDatabaseId;
    rl.locator.relNumber = filenode;
    rl.backend = INVALID_PROC_NUMBER;
 
    if (!cfs_get_options(rl, MAIN_FORKNUM, &opts) || !opts.is_cfs)
        PG_RETURN_NULL();
 
    PG_RETURN_INT32(opts.level);
}
 
/* ------------------------------------------------------------------
 * cfs_test_journal_header(oid)
 *
 * Dump the .cfsjrn header summary (incarnation, max_generation) of a
 * relation fork together with the same totals computed directly from the
 * .cfsmap entries, so tests can assert that every journal reset stamped
 * the monotone watermark and that dead-space arithmetic matches the map
 *.  Raises ERROR when either sidecar is missing or its
 * header fails validation.
 * ------------------------------------------------------------------ */
PG_FUNCTION_INFO_V1(cfs_test_journal_header);
 
Datum
cfs_test_journal_header(PG_FUNCTION_ARGS)
{
    Oid         filenode = PG_GETARG_OID(0);
    RelFileLocatorBackend rl;
    CfsJournalFileHeader jhdr;
    CfsMapPrologue mhdr;
    CfsMapEntry *entries = NULL;
    TupleDesc   tupdesc;
    Datum       values[3];
    bool        nulls[3];
    HeapTuple   tuple;
    uint64      nblocks = 0;
    uint32      map_max_generation = 0;
    uint64      i;
    int         fd;
    char       *path;
 
    rl.locator.spcOid = MyDatabaseTableSpace;
    rl.locator.dbOid = MyDatabaseId;
    rl.locator.relNumber = filenode;
    rl.backend = INVALID_PROC_NUMBER;
 
    if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
        elog(ERROR, "return type must be a row type");
 
    path = cfs_make_filename(rl, MAIN_FORKNUM, CFS_FILE_JOURNAL);
    fd = BasicOpenFile(path, O_RDONLY | PG_BINARY);
    if (fd < 0)
        ereport(ERROR,
                (errcode_for_file_access(),
                 errmsg("could not open journal \"%s\": %m", path)));
    if (cfs_pread_all(fd, &jhdr, sizeof(jhdr), 0) != CFS_STORAGE_OK ||
        cfs_journal_header_validate(&jhdr) != CFS_FORMAT_OK)
    {
        close(fd);
        ereport(ERROR,
                (errcode(ERRCODE_DATA_CORRUPTED),
                 errmsg("invalid journal header in \"%s\"", path)));
    }
    close(fd);
    pfree(path);
 
    path = cfs_make_filename(rl, MAIN_FORKNUM, CFS_FILE_MAP);
    fd = BasicOpenFile(path, O_RDONLY | PG_BINARY);
    if (fd < 0)
        ereport(ERROR,
                (errcode_for_file_access(),
                 errmsg("could not open page map \"%s\": %m", path)));
    if (cfs_pread_all(fd, &mhdr, sizeof(mhdr), 0) != CFS_STORAGE_OK ||
        cfs_map_prologue_validate(&mhdr) != CFS_FORMAT_OK)
    {
        close(fd);
        ereport(ERROR,
                (errcode(ERRCODE_DATA_CORRUPTED),
                 errmsg("invalid page map header in \"%s\"", path)));
    }
    nblocks = 0;
    {
        off_t       map_size = lseek(fd, 0, SEEK_END);
 
        if (map_size >= 0)
            nblocks = cfs_map_rows_from_size((uint64) map_size);
    }
    if (nblocks > 0)
    {
        entries = palloc(nblocks * CFS_MAP_ENTRY_SIZE);
        if (cfs_pread_all(fd, entries, nblocks * CFS_MAP_ENTRY_SIZE,
                          CFS_MAP_HEADER_SIZE) != CFS_STORAGE_OK)
        {
            close(fd);
            ereport(ERROR,
                    (errcode_for_file_access(),
                     errmsg("could not read page map entries from \"%s\"", path)));
        }
    }
    close(fd);
    pfree(path);
 
    for (i = 0; i < nblocks; i++)
    {
        CfsMapEntry *e = &entries[i];
 
        if (cfs_map_entry_validate(e, false) != CFS_FORMAT_OK)
            continue;
        if (e->generation > map_max_generation)
            map_max_generation = e->generation;
    }
    if (entries != NULL)
        pfree(entries);
 
    MemSet(nulls, 0, sizeof(nulls));
    values[0] = Int32GetDatum(jhdr.incarnation);
    values[1] = Int32GetDatum(jhdr.max_generation);
    values[2] = Int64GetDatum((int64) map_max_generation);
 
    tuple = heap_form_tuple(tupdesc, values, nulls);
 
    PG_RETURN_DATUM(HeapTupleGetDatum(tuple));
}
 
/* ------------------------------------------------------------------
 * cfs_test_slot_present_at(oid)
 *
 * True when the shared-memory policy cache holds a slot for the given
 * relfilenode (current database, default tablespace), regardless of what
 * the slot says — unlike cfs_test_shared_level_at, which reports NULL
 * both for a missing slot and for one lying is_cfs=false.
 * ------------------------------------------------------------------ */
PG_FUNCTION_INFO_V1(cfs_test_slot_present_at);
 
Datum
cfs_test_slot_present_at(PG_FUNCTION_ARGS)
{
    Oid         filenode = PG_GETARG_OID(0);
    RelFileLocatorBackend rl;
 
    rl.locator.spcOid = MyDatabaseTableSpace;
    rl.locator.dbOid = MyDatabaseId;
    rl.locator.relNumber = filenode;
    rl.backend = INVALID_PROC_NUMBER;
 
    PG_RETURN_BOOL(cfs_slot_present(rl, MAIN_FORKNUM));
}
 
/* ------------------------------------------------------------------
 * cfs_test_publish_false_at(oid)
 *
 * Publish a "not a CFS relation" policy into the shared-memory policy
 * cache for the given relfilenode (current database, default
 * tablespace): a controlled imitation of a stale cache slot lying about
 * a node whose sidecar files still exist on disk.
 * ------------------------------------------------------------------ */
PG_FUNCTION_INFO_V1(cfs_test_publish_false_at);
 
Datum
cfs_test_publish_false_at(PG_FUNCTION_ARGS)
{
    Oid         filenode = PG_GETARG_OID(0);
    RelFileLocatorBackend rl;
    CfsEffectiveOptions opts;
 
    rl.locator.spcOid = MyDatabaseTableSpace;
    rl.locator.dbOid = MyDatabaseId;
    rl.locator.relNumber = filenode;
    rl.backend = INVALID_PROC_NUMBER;
 
    memset(&opts, 0, sizeof(opts));
    opts.is_cfs = false;
 
    cfs_publish_options(rl, MAIN_FORKNUM, &opts);
 
    PG_RETURN_VOID();
}
 
/* ------------------------------------------------------------------
 * cfs_test_sidecars_at(oid)
 *
 * True when the given relfilenode (current database, default
 * tablespace) has CFS sidecar files on disk, regardless of any cached
 * policy.
 * ------------------------------------------------------------------ */
PG_FUNCTION_INFO_V1(cfs_test_sidecars_at);
 
Datum
cfs_test_sidecars_at(PG_FUNCTION_ARGS)
{
    Oid         filenode = PG_GETARG_OID(0);
    RelFileLocatorBackend rl;
 
    rl.locator.spcOid = MyDatabaseTableSpace;
    rl.locator.dbOid = MyDatabaseId;
    rl.locator.relNumber = filenode;
    rl.backend = INVALID_PROC_NUMBER;
 
    PG_RETURN_BOOL(cfs_exists(rl, MAIN_FORKNUM));
}
 
/* ------------------------------------------------------------------
 * cfs_relation_last_record(regclass)
 *
 * Walk the append-only record stream of the relation's .cfp file
 * (segment 0 only; the regression tests never produce a segmented
 * file) and report the LAST record's on-disk header fields plus the
 * total record count.
 *
 * The record header carries the algorithm but NOT the compression
 * level (decompression never needs it), so the probe reports sizes:
 * two structurally identical pages written under different effective
 * levels must produce records with different compressed_size.  This
 * is how the regression tests pin the write path's runtime level
 * resolve to the actual bytes on disk instead of trusting the
 * session-visible policy.
 * ------------------------------------------------------------------ */
PG_FUNCTION_INFO_V1(cfs_relation_last_record);
 
Datum
cfs_relation_last_record(PG_FUNCTION_ARGS)
{
    Oid         reloid = PG_GETARG_OID(0);
    Relation    rel;
    RelFileLocatorBackend rl;
    char       *relpath;
    char       *path;
    FILE       *f;
    long        file_size;
    long        off;
    uint64      nrecords = 0;
    CfsCompressedBlockHeader last;
    TupleDesc   tupdesc;
    Datum       values[4];
    bool        nulls[4];
    HeapTuple   tuple;
 
    if (!OidIsValid(reloid))
        PG_RETURN_NULL();
 
    rel = relation_open(reloid, AccessShareLock);
    rl.locator = rel->rd_locator;
    rl.backend = rel->rd_backend;
    relation_close(rel, AccessShareLock);
 
    relpath = cfs_make_filename(rl, MAIN_FORKNUM, CFS_FILE_DATA);
    if (relpath == NULL)
        PG_RETURN_NULL();
    path = psprintf("%s/%s", DataDir, relpath);
 
    f = AllocateFile(path, PG_BINARY_R);
    if (f == NULL)
        PG_RETURN_NULL();       /* no sidecar: nothing recorded yet */
 
    if (fseek(f, 0, SEEK_END) != 0 || (file_size = ftell(f)) < 0)
    {
        FreeFile(f);
        ereport(ERROR,
                (errcode(ERRCODE_IO_ERROR),
                 errmsg("could not determine size of \"%s\"", path)));
    }
 
    MemSet(nulls, 0, sizeof(nulls));
    memset(&last, 0, sizeof(last));
 
    /*
     * Records start after the reserved lead-in and follow each other
     * contiguously; each header's compressed_size tells where the next record
     * begins (the same walk cfs_fsck_cfp_file() performs).
     */
    off = CFS_CFP_BASE_OFFSET;
    while (off + (long) CFS_BLOCK_HEADER_SIZE <= file_size)
    {
        CfsCompressedBlockHeader hdr;
        long        rec_size;
 
        if (fseek(f, off, SEEK_SET) != 0 ||
            fread(&hdr, 1, CFS_BLOCK_HEADER_SIZE, f) != CFS_BLOCK_HEADER_SIZE)
            ereport(ERROR,
                    (errcode(ERRCODE_IO_ERROR),
                     errmsg("could not read record header at offset %ld of \"%s\"",
                            off, path)));
 
        if (hdr.magic != CFS_BLOCK_MAGIC || hdr.version != CFS_FORMAT_VERSION)
            ereport(ERROR,
                    (errcode(ERRCODE_DATA_CORRUPTED),
                     errmsg("invalid CFS record header at offset %ld of \"%s\"",
                            off, path)));
 
        rec_size = (long) CFS_RECORD_SIZE(hdr.compressed_size);
        if (rec_size <= 0 || off + rec_size > file_size)
            ereport(ERROR,
                    (errcode(ERRCODE_DATA_CORRUPTED),
                     errmsg("truncated CFS record at offset %ld of \"%s\"",
                            off, path)));
 
        last = hdr;
        nrecords++;
        off += rec_size;
    }
 
    FreeFile(f);
 
    if (nrecords == 0)
        PG_RETURN_NULL();
 
    if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
        elog(ERROR, "return type must be a row type");
 
    values[0] =
        CStringGetTextDatum(CfsAlgorithmGetName((CfsAlgorithm) last.algorithm));
    values[1] = Int64GetDatum((int64) last.original_size);
    values[2] = Int64GetDatum((int64) last.compressed_size);
    values[3] = Int64GetDatum((int64) nrecords);
 
    tuple = heap_form_tuple(tupdesc, values, nulls);
    PG_RETURN_DATUM(HeapTupleGetDatum(tuple));
}
 
/*
 * Test-only: drop the shared metadata slot, read block 0 through the smgr
 * bridge (which opens the lazy CFS handle) and report the nblocks value the
 * bridge published, if any.  A lazy handle only knows the .cfsmap snapshot,
 * so publishing its size would hide journal-only extensions.
 */
PG_FUNCTION_INFO_V1(cfs_test_smgr_read_meta);
 
Datum
cfs_test_smgr_read_meta(PG_FUNCTION_ARGS)
{
    Oid         relid = PG_GETARG_OID(0);
    Relation    rel;
    RelFileLocatorBackend rl;
    SMgrRelation reln;
    char       *buf;
    uint64      nblocks = 0;
    bool        have_nblocks;
 
    rel = RelationIdGetRelation(relid);
    if (!RelationIsValid(rel))
        ereport(ERROR,
                (errcode(ERRCODE_UNDEFINED_TABLE),
                 errmsg("relation with OID %u does not exist", relid)));
 
    rl.locator = rel->rd_locator;
    rl.backend = INVALID_PROC_NUMBER;
    cfs_map_cache_invalidate(rl, MAIN_FORKNUM);
 
    reln = smgropen(rl.locator, INVALID_PROC_NUMBER);
    buf = palloc(CFS_BLCKSZ);
    smgrread(reln, MAIN_FORKNUM, 0, buf);
    pfree(buf);
 
    have_nblocks = cfs_map_cache_get_nblocks(rl, MAIN_FORKNUM, &nblocks);
    smgrclose(reln);
    RelationClose(rel);
 
    if (have_nblocks)
        PG_RETURN_INT64((int64) nblocks);
    PG_RETURN_NULL();
}
 
/*
 * Test-only: measure a relation's size through the smgr bridge with a cold
 * metadata slot and report how many throwaway full-map handles the path
 * opened.  The size path measures the sidecar pair (stat(.cfsmap) plus the
 * journal's last RESIZE) and never builds a map of its own (QDB-1516), so
 * the answer must be 0 for every pool size.
 */
PG_FUNCTION_INFO_V1(cfs_test_smgr_size_full_opens);
 
Datum
cfs_test_smgr_size_full_opens(PG_FUNCTION_ARGS)
{
    Oid         relid = PG_GETARG_OID(0);
    Relation    rel;
    RelFileLocatorBackend rl;
    SMgrRelation reln;
    uint64      before;
    uint64      opens;
 
    rel = RelationIdGetRelation(relid);
    if (!RelationIsValid(rel))
        ereport(ERROR,
                (errcode(ERRCODE_UNDEFINED_TABLE),
                 errmsg("relation with OID %u does not exist", relid)));
 
    rl.locator = rel->rd_locator;
    rl.backend = INVALID_PROC_NUMBER;
    cfs_map_cache_invalidate(rl, MAIN_FORKNUM);
 
    reln = smgropen(rl.locator, INVALID_PROC_NUMBER);
    before = cfs_smgr_full_map_open_count();
    (void) smgrnblocks(reln, MAIN_FORKNUM);
    opens = cfs_smgr_full_map_open_count() - before;
    smgrclose(reln);
    RelationClose(rel);
 
    PG_RETURN_INT64((int64) opens);
}
 
/* --------------------------------------------------------------------
 * cfs_test_checkpoint_full_opens(oid)
 *
 * Run a real immediate checkpoint (the flags the SQL CHECKPOINT command
 * uses) and report how many throwaway full-map handles the checkpoint
 * path opened for THIS relation.  The count is per-relation, so a
 * background full-map open of some unrelated relation cannot mask or
 * fake the measurement (the cluster-wide counter could do both).  The
 * checkpoint's cost must track the journal, not the table: folding a
 * handful of journal records must not assemble the relation's complete
 * in-memory page map.
 * ------------------------------------------------------------------ */
PG_FUNCTION_INFO_V1(cfs_test_checkpoint_full_opens);
 
Datum
cfs_test_checkpoint_full_opens(PG_FUNCTION_ARGS)
{
    Oid         relid = PG_GETARG_OID(0);
    Relation    rel;
    RelFileLocatorBackend rl;
    uint64      before;
    uint64      after;
 
    rel = RelationIdGetRelation(relid);
    if (!RelationIsValid(rel))
        ereport(ERROR,
                (errcode(ERRCODE_UNDEFINED_TABLE),
                 errmsg("relation with OID %u does not exist", relid)));
 
    rl.locator = rel->rd_locator;
    rl.backend = INVALID_PROC_NUMBER;
 
    before = cfs_shared_full_map_opens_rel(rl, MAIN_FORKNUM);
    RequestCheckpoint(CHECKPOINT_FAST | CHECKPOINT_FORCE |
                      CHECKPOINT_WAIT);
    after = cfs_shared_full_map_opens_rel(rl, MAIN_FORKNUM);
 
    RelationClose(rel);
 
    /*
     * An evicted slot would read 0 again; the test keeps it pinned-dirty, so
     * a genuine drop shows up as after < before instead.
     */
    if (after < before)
        ereport(ERROR,
                (errcode(ERRCODE_INTERNAL_ERROR),
                 errmsg("full-map-open counter of relation %u went backwards",
                        relid)));
 
    PG_RETURN_INT64((int64) (after - before));
}
 
/* --------------------------------------------------------------------
 * cfs_test_immedsync(oid)
 *
 * Run smgrimmedsync() on the relation's main fork: the SQL-reachable way
 * to open a CFS full map handle lock-free on demand (the immedsync path
 * the bulk writer takes).
 * ------------------------------------------------------------------ */
PG_FUNCTION_INFO_V1(cfs_test_immedsync);
 
Datum
cfs_test_immedsync(PG_FUNCTION_ARGS)
{
    Oid         relid = PG_GETARG_OID(0);
    Relation    rel;
 
    rel = RelationIdGetRelation(relid);
    if (!RelationIsValid(rel))
        ereport(ERROR,
                (errcode(ERRCODE_UNDEFINED_TABLE),
                 errmsg("relation with OID %u does not exist", relid)));
 
    smgrimmedsync(RelationGetSmgr(rel), MAIN_FORKNUM);
    RelationClose(rel);
 
    PG_RETURN_BOOL(true);
}
 
/* --------------------------------------------------------------------
 * cfs_test_smgr_truncate(oid, int)
 *
 * Truncate the relation's main fork through smgrtruncate(), i.e. through
 * the backend's cached SMgrRelation and its cached CFS handle.  SQL
 * TRUNCATE allocates a new relfilenode and VACUUM reads every page before
 * it truncates, so both reopen the handle on the way; this wrapper is the
 * only SQL-reachable way to drive cfs_smgr_truncate() with a handle that
 * predates a sidecar swap (an immedsync, which does not bump the shared
 * generation).
 * ------------------------------------------------------------------ */
PG_FUNCTION_INFO_V1(cfs_test_smgr_truncate);
 
Datum
cfs_test_smgr_truncate(PG_FUNCTION_ARGS)
{
    Oid         relid = PG_GETARG_OID(0);
    int32       target = PG_GETARG_INT32(1);
    Relation    rel;
    SMgrRelation reln;
    ForkNumber  forknum = MAIN_FORKNUM;
    BlockNumber old_nblocks;
    BlockNumber nblocks;
    CfsEffectiveOptions opts;
 
    rel = RelationIdGetRelation(relid);
    if (!RelationIsValid(rel))
        ereport(ERROR,
                (errcode(ERRCODE_UNDEFINED_TABLE),
                 errmsg("relation with OID %u does not exist", relid)));
 
    CfsEffectiveOptionsFromRelation(rel, &opts);
    if (!opts.is_cfs)
    {
        RelationClose(rel);
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("relation is not a CFS relation")));
    }
 
    /*
     * smgrtruncate() requires an exclusive lock on the relation, so other
     * backends process the smgr invalidation it sends.
     */
    LockRelation(rel, AccessExclusiveLock);
 
    reln = RelationGetSmgr(rel);
    old_nblocks = smgrnblocks(reln, MAIN_FORKNUM);
    if (target < 0 || (BlockNumber) target > old_nblocks)
    {
        UnlockRelation(rel, AccessExclusiveLock);
        RelationClose(rel);
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("truncation target %d is outside relation size %u",
                        target, old_nblocks)));
    }
 
    nblocks = (BlockNumber) target;
    smgrtruncate(reln, &forknum, 1, &old_nblocks, &nblocks);
 
    UnlockRelation(rel, AccessExclusiveLock);
    RelationClose(rel);
 
    PG_RETURN_BOOL(true);
}
 
/*
 * Report whether the pin-owner registry was created.  It must exist for
 * every cfs_map_memory value (0 included): metadata slots are pinned and
 * reaped with the pool off just the same.
 */
PG_FUNCTION_INFO_V1(cfs_test_map_pin_registry);
 
Datum
cfs_test_map_pin_registry(PG_FUNCTION_ARGS)
{
    PG_RETURN_BOOL(cfs_map_cache_test_pin_registry_live());
}
 
/* ------------------------------------------------------------------
 * cfs_test_tail_write(relnumber, blocknum) -> bigint
 * cfs_test_tail_verify(relnumber, nblocks) -> bigint
 * cfs_test_tail_cleanup(relnumber) -> boolean
 *
 * The D1 two-backend exercise: write one page of a synthetic CFS
 * relation through the REAL locked write path (metadata slot pinned,
 * append lock taken, handle refreshed, cfs_write_page_cached), the same
 * sequence the smgr layer runs, and return the record's physical .cfp
 * offset.  Two sessions calling this alternately must produce strictly
 * increasing offsets: a backend that appended at a stale per-handle tail
 * would return an offset its peer already used (and overwrite its
 * record), which cfs_test_tail_verify detects as duplicated offsets or
 * as corrupted read-back data.
 *
 * The page of block b is filled with the byte pattern (b & 0xFF), so
 * verify can check every byte of every block without carrying the
 * written tags around.
 * ------------------------------------------------------------------ */
static RelFileLocatorBackend
cfs_tail_locator(int64 relnumber)
{
    RelFileLocatorBackend rl;
 
    rl.locator.spcOid = MyDatabaseTableSpace;
    rl.locator.dbOid = MyDatabaseId;
    rl.locator.relNumber = (RelFileNumber) relnumber;
    rl.backend = INVALID_PROC_NUMBER;
    return rl;
}
 
PG_FUNCTION_INFO_V1(cfs_test_tail_write);
 
Datum
cfs_test_tail_write(PG_FUNCTION_ARGS)
{
    int64       relnumber = PG_GETARG_INT64(0);
    int32       blocknum = PG_GETARG_INT32(1);
    RelFileLocatorBackend rl = cfs_tail_locator(relnumber);
    CfsRelation *cfs;
    CfsWriteOptions opts = cfs_test_write_opts();
    unsigned char page[TEST_BLCKSZ];
    CfsMapEntry *e;
    int64       off;
 
    cfs_map_cache_pin(rl, MAIN_FORKNUM);
 
    cfs = cfs_open(rl, MAIN_FORKNUM, CFS_OPEN_RDWR | CFS_OPEN_CREATE);
    if (cfs == NULL)
    {
        cfs_map_cache_unpin(rl, MAIN_FORKNUM);
        ereport(ERROR,
                (errcode(ERRCODE_INTERNAL_ERROR),
                 errmsg("cfs_test_tail_write: could not open sidecars")));
    }
 
    cfs_test_fill_page(page, (unsigned char) (blocknum & 0xFF));
 
    /*
     * Materialise the handle's local map array before the write: a full
     * handle of a fresh relation allocates it lazily, and the write path
     * only mirrors the new entry into a non-NULL local map (the journal
     * and the shared pool always get it).  With the array in place the
     * offset read below comes from the local mirror of the write.
     */
    (void) cfs_map_get_entry(cfs, blocknum);
 
    /*
     * The locked write path exactly as cfs_smgr runs it: pin the metadata
     * slot, then let cfs_write_page_cached take the append lock, refresh
     * the stale handle and journal the map update itself.
     */
    if (cfs_write_page_cached(cfs, blocknum, (const char *) page,
                              &opts) != CFS_STORAGE_OK)
    {
        cfs_close(cfs);
        cfs_map_cache_unpin(rl, MAIN_FORKNUM);
        ereport(ERROR,
                (errcode(ERRCODE_INTERNAL_ERROR),
                 errmsg("cfs_test_tail_write: write failed")));
    }
 
    e = cfs_map_get_entry(cfs, blocknum);
    off = (e != NULL) ? (int64) e->physical_offset : -1;
 
    cfs_close(cfs);
    cfs_map_cache_unpin(rl, MAIN_FORKNUM);
 
    PG_RETURN_INT64(off);
}
 
/*
 * Verification result codes of cfs_test_tail_verify: the verified block
 * count (>= 0) on success, -1 an invalid map entry, -2 a duplicated or
 * non-increasing record offset, -3 a failed open, -4 a failed read and
 * -5 a content mismatch.
 */
PG_FUNCTION_INFO_V1(cfs_test_tail_verify);
 
Datum
cfs_test_tail_verify(PG_FUNCTION_ARGS)
{
    int64       relnumber = PG_GETARG_INT64(0);
    int32       nblocks = PG_GETARG_INT32(1);
    RelFileLocatorBackend rl = cfs_tail_locator(relnumber);
    CfsRelation *cfs;
    unsigned char back[TEST_BLCKSZ];
    uint64      prev_off = 0;
    int32       blk;
    int         tag;
 
    cfs = cfs_open(rl, MAIN_FORKNUM, CFS_OPEN_RDWR);
    if (cfs == NULL)
        PG_RETURN_INT64(-3);
 
    /*
     * The exercise numbers its blocks from 1 (see the TAP test): verify
     * exactly the blocks the writers wrote.
     */
    for (blk = 1; blk <= nblocks; blk++)
    {
        CfsMapEntry *e = cfs_map_get_entry(cfs, blk);
 
        if (e == NULL || e->physical_offset == CFS_ENTRY_INVALID_OFFSET)
        {
            cfs_close(cfs);
            PG_RETURN_INT64(-1);
        }
 
        /* Appends only: every record must sit strictly past its peer. */
        if (e->physical_offset <= prev_off)
        {
            cfs_close(cfs);
            PG_RETURN_INT64(-2);
        }
        prev_off = e->physical_offset;
 
        if (cfs_read_page(cfs, blk, (char *) back) != CFS_STORAGE_OK)
        {
            cfs_close(cfs);
            PG_RETURN_INT64(-4);
        }
        for (tag = 0; tag < TEST_BLCKSZ; tag++)
        {
            /* cfs_test_fill_page writes the ramp (tag + i) & 0x7F. */
            if (back[tag] !=
                (unsigned char) (((blk & 0xFF) + tag) & 0x7F))
            {
                cfs_close(cfs);
                PG_RETURN_INT64(-5);
            }
        }
    }
 
    cfs_close(cfs);
 
    PG_RETURN_INT64((int64) nblocks);
}
 
PG_FUNCTION_INFO_V1(cfs_test_tail_cleanup);
 
Datum
cfs_test_tail_cleanup(PG_FUNCTION_ARGS)
{
    int64       relnumber = PG_GETARG_INT64(0);
    RelFileLocatorBackend rl = cfs_tail_locator(relnumber);
 
    cfs_map_cache_invalidate(rl, MAIN_FORKNUM);
    cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM);
    cfs_test_unlink_synthetic(rl);
 
    PG_RETURN_BOOL(true);
}
 
/* ================================================================
 * QDB-1513: batched read path (cfs_map_contiguous_run /
 * cfs_read_pages_batch / cfs_read_records_span)
 * ================================================================
 */
 
/*
 * Open a full (private-map) read handle for a real CFS relation.
 * Returns NULL when the relation has no sidecars.
 */
static CfsRelation *
cfs_test_batch_open(Oid reloid, RelFileLocatorBackend *rl_out)
{
    Relation    rel;
    RelFileLocatorBackend rl;
 
    rel = relation_open(reloid, AccessShareLock);
    rl.locator = rel->rd_locator;
    rl.backend = rel->rd_backend;
    relation_close(rel, AccessShareLock);
 
    if (rl_out != NULL)
        *rl_out = rl;
 
    return cfs_open(rl, MAIN_FORKNUM, CFS_OPEN_RDONLY);
}
 
/*
 * SQL-callable: exercise the batched read path against a real CFS relation
 * through a full (private-map) handle.  Reports the advisory contiguous-run
 * length at block 0 and the maximum over the relation, then re-reads every
 * page in chunks of 16 through cfs_read_pages_batch() and compares each
 * page byte-for-byte with the per-block cfs_read_page_cached() result.
 * Pre-fills the batch buffers with a poison pattern so an unfilled buffer
 * can never compare equal by accident.  Returns (run0, run_max,
 * pages_checked, batch_ok).
 */
PG_FUNCTION_INFO_V1(cfs_test_read_batch);
 
Datum
cfs_test_read_batch(PG_FUNCTION_ARGS)
{
    Oid         reloid = PG_GETARG_OID(0);
    CfsRelation *cfs;
    TupleDesc   tupdesc;
    HeapTuple   tuple;
    Datum       values[4];
    bool        nulls[4];
    uint64      nblocks;
    BlockNumber blk;
    uint32      run0 = 0;
    uint32      run_max = 0;
    uint64      pages_checked = 0;
    bool        batch_ok = true;
    char       *single;
    void      **buffers;
    int         i;
    const int   chunk = 16;
 
    cfs = cfs_test_batch_open(reloid, NULL);
    if (cfs == NULL)
        ereport(ERROR,
                (errcode(ERRCODE_INTERNAL_ERROR),
                 errmsg("test_cfs: relation %u has no CFS sidecars", reloid)));
 
    nblocks = cfs->map_hdr.nblocks;
 
    if (nblocks > 0)
    {
        run0 = (uint32) cfs_map_contiguous_run(cfs, 0, chunk);
        for (blk = 0; blk < nblocks; blk++)
        {
            uint32      run = (uint32) cfs_map_contiguous_run(cfs, blk,
                                                             chunk);
 
            if (run > run_max)
                run_max = run;
        }
    }
 
    single = (char *) palloc(CFS_BLCKSZ);
    buffers = (void **) palloc(chunk * sizeof(void *));
    for (i = 0; i < chunk; i++)
        buffers[i] = palloc(CFS_BLCKSZ);
 
    for (blk = 0; blk < nblocks && batch_ok; blk += chunk)
    {
        BlockNumber n = Min((BlockNumber) chunk, (BlockNumber) (nblocks - blk));
        int         rc;
        BlockNumber b;
 
        for (b = 0; b < n; b++)
            MemSet(buffers[b], 0xAA, CFS_BLCKSZ);
 
        rc = cfs_read_pages_batch(cfs, blk, buffers, n, NULL, NULL);
        if (rc != CFS_STORAGE_OK)
        {
            batch_ok = false;
            break;
        }
 
        for (b = 0; b < n; b++)
        {
            if (cfs_read_page_cached(cfs, blk + b, single)
                != CFS_STORAGE_OK ||
                memcmp(buffers[b], single, CFS_BLCKSZ) != 0)
            {
                batch_ok = false;
                break;
            }
            pages_checked++;
        }
    }
 
    for (i = 0; i < chunk; i++)
        pfree(buffers[i]);
    pfree(buffers);
    pfree(single);
    cfs_close(cfs);
 
    if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
        elog(ERROR, "return type must be a row type");
 
    MemSet(nulls, 0, sizeof(nulls));
    values[0] = Int32GetDatum((int32) run0);
    values[1] = Int32GetDatum((int32) run_max);
    values[2] = Int64GetDatum((int64) pages_checked);
    values[3] = BoolGetDatum(batch_ok);
 
    tuple = heap_form_tuple(tupdesc, values, nulls);
    PG_RETURN_DATUM(HeapTupleGetDatum(tuple));
}
 
/*
 * SQL-callable: corrupt one payload byte of 'blockno's record directly in
 * .cfp (the map entry stays valid), batch-read the range [first, first+n)
 * through cfs_read_pages_batch() and demand CFS_STORAGE_CORRUPT with
 * fail_block == blockno, then restore the byte and demand a clean read of
 * the same range.  The caller picks a block whose neighbours form a
 * contiguous run, so the corrupted record is exercised through the span
 * reader, not the per-block fallback.  Returns 'ok' / 'fail: <reason>'.
 */
PG_FUNCTION_INFO_V1(cfs_test_read_batch_corrupt);
 
Datum
cfs_test_read_batch_corrupt(PG_FUNCTION_ARGS)
{
    Oid         reloid = PG_GETARG_OID(0);
    BlockNumber blockno = (BlockNumber) PG_GETARG_INT32(1);
    RelFileLocatorBackend rl;
    CfsRelation *cfs;
    CfsMapEntry *e;
    const char *reason = NULL;
    char       *base_path;
    char       *seg_path;
    uint64      rec_off;
    off_t       file_off;
    int         fd;
    char        b;
    void      **buffers;
    int         fail_code = 0;
    BlockNumber fail_block = 0;
    int         rc;
    int         i;
    const int   nreq = 8;
 
    cfs = cfs_test_batch_open(reloid, &rl);
    if (cfs == NULL)
        PG_RETURN_TEXT_P(cstring_to_text("fail: no sidecars"));
 
    if ((uint64) blockno >= cfs->map_hdr.nblocks)
    {
        cfs_close(cfs);
        PG_RETURN_TEXT_P(cstring_to_text("fail: block out of range"));
    }
 
    e = &cfs->map[blockno];
    if (!CFS_MAP_ENTRY_VALID(e))
    {
        cfs_close(cfs);
        PG_RETURN_TEXT_P(cstring_to_text("fail: block has no record"));
    }
 
    rec_off = e->physical_offset;
    base_path = cfs_make_filename(rl, MAIN_FORKNUM, CFS_FILE_DATA);
    seg_path = cfs_segment_path(base_path, CFS_CFP_SEGNO((off_t) rec_off));
    file_off = CFS_CFP_SEG_OFF((off_t) rec_off) + CFS_BLOCK_HEADER_SIZE + 2;
 
    b = 0;
    fd = BasicOpenFile(seg_path, O_RDWR | PG_BINARY);
    if (fd < 0 || pg_pread(fd, &b, 1, file_off) != 1)
        reason = "fail: could not read the record byte";
    else
    {
        char        flipped = (char) (b ^ 0xFF);
 
        if (pg_pwrite(fd, &flipped, 1, file_off) != 1)
            reason = "fail: could not corrupt the record byte";
    }
    if (fd >= 0)
        close(fd);
 
    buffers = (void **) palloc(nreq * sizeof(void *));
    for (i = 0; i < nreq; i++)
        buffers[i] = palloc(CFS_BLCKSZ);
 
    if (reason == NULL)
    {
        rc = cfs_read_pages_batch(cfs, 0, buffers, (BlockNumber) nreq,
                                  &fail_code, &fail_block);
        if (rc != CFS_STORAGE_CORRUPT || fail_code != CFS_STORAGE_CORRUPT ||
            fail_block != blockno)
            reason = "fail: corrupted record not reported exactly";
    }
 
    if (reason == NULL)
    {
        /* Restore the byte: the range must read cleanly again. */
        fd = BasicOpenFile(seg_path, O_RDWR | PG_BINARY);
        if (fd < 0 || pg_pwrite(fd, &b, 1, file_off) != 1)
            reason = "fail: could not restore the record byte";
        else
        {
            rc = cfs_read_pages_batch(cfs, 0, buffers,
                                      (BlockNumber) nreq, NULL, NULL);
            if (rc != CFS_STORAGE_OK)
                reason = "fail: clean range read after restore";
        }
        if (fd >= 0)
            close(fd);
    }
 
    for (i = 0; i < nreq; i++)
        pfree(buffers[i]);
    pfree(buffers);
    cfs_close(cfs);
 
    if (reason != NULL)
        PG_RETURN_TEXT_P(cstring_to_text(reason));
    PG_RETURN_TEXT_P(cstring_to_text("ok"));
}
 
/*
 * Test-only independent oracle for the small, single-segment LZ4 fixture.
 * Validate every physical record, including obsolete records, and return
 * the requested full page and payload with independent reference matches.
 */
PG_FUNCTION_INFO_V1(cfs_test_lz4_record);
Datum
cfs_test_lz4_record(PG_FUNCTION_ARGS)
{
#ifndef USE_LZ4
    elog(ERROR, "LZ4 support is required for the test oracle");
    PG_RETURN_NULL();
#else
    Oid relid = PG_GETARG_OID(0);
    int32 wanted = PG_GETARG_INT32(1);
    Relation rel;
    RelFileLocatorBackend rl;
    char *filename;
    char *relpath;
    FILE *fp;
    long end;
    int64 offset = CFS_CFP_BASE_OFFSET;
    int64 count = 0;
    int64 selected_offset = 0;
    int64 selected_end = 0;
    bytea *selected_page = NULL;
    bytea *selected_payload = NULL;
    char page[TEST_BLCKSZ];
    char payload[LZ4_COMPRESSBOUND(TEST_BLCKSZ)];
    char fast[LZ4_COMPRESSBOUND(TEST_BLCKSZ)];
    char hc[LZ4_COMPRESSBOUND(TEST_BLCKSZ)];
    int fast_size;
    int hc_size;
    int selected_size;
    TupleDesc desc;
    Datum values[7];
    bool nulls[7] = {false};
 
    if (wanted <= 0)
        elog(ERROR, "record number must be positive");
    rel = relation_open(relid, AccessShareLock);
    rl.locator = rel->rd_locator;
    rl.backend = rel->rd_backend;
    relpath = cfs_make_filename(rl, MAIN_FORKNUM, CFS_FILE_DATA);
    if (!relpath)
        elog(ERROR, "missing CFS test record path");
    filename = psprintf("%s/%s", DataDir, relpath);
    pfree(relpath);
    fp = AllocateFile(filename, PG_BINARY_R);
    if (!fp)
        elog(ERROR, "cannot open CFS test record file");
    if (fseek(fp, 0, SEEK_END) != 0 || (end = ftell(fp)) < offset)
        elog(ERROR, "invalid CFS test record file length");
    while (offset < end)
    {
        CfsCompressedBlockHeader hdr;
        pg_crc32c crc;
        size_t record_size;
        size_t pad;
        size_t j;
 
        if (end - offset < sizeof(hdr) ||
            fseek(fp, offset, SEEK_SET) != 0 ||
            fread(&hdr, 1, sizeof(hdr), fp) != sizeof(hdr))
            elog(ERROR, "incomplete CFS test record header");
        INIT_CRC32C(crc);
        COMP_CRC32C(crc, &hdr, offsetof(CfsCompressedBlockHeader, hdr_crc));
        FIN_CRC32C(crc);
        if (hdr.magic != CFS_BLOCK_MAGIC || hdr.version != CFS_FORMAT_VERSION ||
            !EQ_CRC32C(crc, hdr.hdr_crc))
            elog(ERROR, "invalid CFS test header CRC");
        if (hdr.algorithm != CFS_ALGORITHM_LZ4)
            elog(ERROR, "CFS test record is not LZ4");
        if (hdr.original_size != TEST_BLCKSZ ||
            hdr.compressed_size <= 0 ||
            hdr.compressed_size > sizeof(payload))
            elog(ERROR, "invalid CFS test record size");
        record_size = CFS_RECORD_SIZE(hdr.compressed_size);
        if (record_size > end - offset ||
            fread(payload, 1, hdr.compressed_size, fp) != hdr.compressed_size)
            elog(ERROR, "incomplete CFS test payload");
        INIT_CRC32C(crc);
        COMP_CRC32C(crc, payload, hdr.compressed_size);
        FIN_CRC32C(crc);
        if (!EQ_CRC32C(crc, hdr.data_crc) ||
            LZ4_decompress_safe(payload, page, hdr.compressed_size,
                                TEST_BLCKSZ) != TEST_BLCKSZ)
            elog(ERROR, "invalid CFS test payload");
        INIT_CRC32C(crc);
        COMP_CRC32C(crc, page, TEST_BLCKSZ);
        FIN_CRC32C(crc);
        if (!EQ_CRC32C(crc, hdr.orig_crc))
            elog(ERROR, "invalid CFS test page CRC");
        pad = record_size - sizeof(hdr) - hdr.compressed_size;
        for (j = 0; j < pad; j++)
            if (fgetc(fp) != 0)
                elog(ERROR, "invalid CFS test record padding");
        count++;
        if (count == wanted)
        {
            selected_offset = offset;
            selected_end = offset + record_size;
            selected_page = palloc(VARHDRSZ + TEST_BLCKSZ);
            SET_VARSIZE(selected_page, VARHDRSZ + TEST_BLCKSZ);
            memcpy(VARDATA(selected_page), page, TEST_BLCKSZ);
            selected_payload = palloc(VARHDRSZ + hdr.compressed_size);
            SET_VARSIZE(selected_payload, VARHDRSZ + hdr.compressed_size);
            memcpy(VARDATA(selected_payload), payload, hdr.compressed_size);
        }
        offset += record_size;
    }
    FreeFile(fp);
    pfree(filename);
    relation_close(rel, AccessShareLock);
    if (!selected_page)
        elog(ERROR, "CFS test record %d does not exist", wanted);
    fast_size = LZ4_compress_fast(VARDATA(selected_page), fast, TEST_BLCKSZ,
                                 sizeof(fast), 2);
    hc_size = LZ4_compress_HC(VARDATA(selected_page), hc, TEST_BLCKSZ,
                             sizeof(hc), 12);
    if (fast_size <= 0 || hc_size <= 0 ||
        (fast_size == hc_size && memcmp(fast, hc, fast_size) == 0))
        elog(ERROR, "LZ4 reference payloads are not distinct");
    selected_size = VARSIZE(selected_payload) - VARHDRSZ;
    if (get_call_result_type(fcinfo, NULL, &desc) != TYPEFUNC_COMPOSITE)
        elog(ERROR, "composite result required");
    values[0] = Int64GetDatum(count);
    values[1] = Int64GetDatum(selected_offset);
    values[2] = Int64GetDatum(selected_end);
    values[3] = PointerGetDatum(selected_page);
    values[4] = PointerGetDatum(selected_payload);
    values[5] = BoolGetDatum(selected_size == fast_size &&
                              memcmp(VARDATA(selected_payload), fast, fast_size) == 0);
    values[6] = BoolGetDatum(selected_size == hc_size &&
                              memcmp(VARDATA(selected_payload), hc, hc_size) == 0);
    PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(BlessTupleDesc(desc),
                                                     values, nulls)));
#endif
}