Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 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
# Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group
#
# src/test/recovery/t/502_cfs_durability.pl
#
# Durability and corruption-handling contracts of the CFS storage layer:
#   * a CRC mismatch on a .cfp block payload raises a regular ERROR by
#     default, and PANICs the whole cluster with
#     cfs_checksum_failure = panic;
#   * every index AM (btree/hash/gin/gist/brin/spgist) can be built and
#     read back through the CFS storage layer with zstd compression, with
#     the codec state safely reused across query cycles;
#   * cfs_recovery_strict turns a corrupt .cfsjrn header discovered during
#     crash recovery from a tolerable WARNING into a fatal startup error;
#   * an fsync() failure of a CFS sidecar during a checkpoint escalates to
#     PANIC (via data_sync_elevel), exactly like md.c treats an fsync
#     failure of a base relation segment — a checkpoint that "succeeds"
#     without durable data would let the WAL needed to rebuild the
#     relation be recycled;
#   * a checkpoint persists .cfsmap snapshots only for CFS relations
#     written since the last checkpoint (dirty_checkpoint), not for
#     every occupied metadata slot.
 
use strict;
use warnings FATAL => 'all';
 
use Config;
 
use PostgreSQL::Test::Cluster;
use PostgreSQL::Test::Utils;
use Test::More;
 
# True when the server was configured with the given --with-<codec> flag;
# the codec-specific subtests skip on builds without the codec.
sub codec_built
{
    my ($node, $codec) = @_;
    my $configure = $node->safe_psql('postgres',
        "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'");
    return $configure =~ /--with-$codec/;
}
 
 
# ---------------------------------------------------------------------------
# Checksum failure: ERROR by default, PANIC on demand
#
# With cfs_checksum_failure = panic, a CRC mismatch on a CFS block payload
# must bring the server down (PANIC) rather than just failing the current
# query.  With the default (error), the same corruption must produce a
# regular ERROR and leave the server up.
#
# The corruption is a single flipped byte deep inside the .cfp payload
# (past the block header), so the block parses but its content fails the
# post-decompression CRC check routed through cfs_report_corruption().
# ---------------------------------------------------------------------------
{
    my $node = PostgreSQL::Test::Cluster->new('cfs_checksum_panic');
    $node->init;
    $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s");
    $node->start;
 
    if (!codec_built($node, 'lz4'))
    {
        plan skip_all =>
          'LZ4 support not built, skipping CFS checksum panic test';
    }
 
    # Build a CFS table with at least a few compressed pages.
    $node->safe_psql('postgres',
        "CREATE TABLE panic_t (id int, data text) WITH (algorithm = 'lz4')");
    $node->safe_psql('postgres',
            "INSERT INTO panic_t SELECT g, repeat('p' || g, 300) "
          . "FROM generate_series(1, 300) g");
    $node->safe_psql('postgres', "CHECKPOINT");
 
    # Resolve the sidecar path while the server is still up, then stop
    # cleanly.
    my $dd = $node->data_dir;
    my $path =
      $node->safe_psql('postgres', "SELECT pg_relation_filepath('panic_t')");
    my $cfp = "$dd/$path.cfp";
    ok(-f $cfp, '.cfp sidecar exists for the CFS table');
 
    $node->stop('fast');
 
    # Flip a single byte deep in the payload region (offset 200 is well
    # past any CompressedBlockHeader at the start of the first record).
    {
        open my $fh, '+<:raw', $cfp or die "open $cfp: $!";
        seek($fh, 200, 0) or die "seek: $!";
        my $b;
        read($fh, $b, 1);
        seek($fh, 200, 0) or die "seek: $!";
        my $flipped = ord($b) ^ 0xFF;
        print $fh chr($flipped);
        close($fh);
    }
    pass('flipped one payload byte in the .cfp');
 
    # Default (error): reading the corrupted block fails the query, server
    # stays.
    $node->start;
    # Reading block 0 (the corrupted one) errors out; use the non-fatal
    # psql() so the ERROR does not abort the test harness.
    my ($ret, $stdout, $stderr) =
      $node->psql('postgres', "SELECT count(*) FROM panic_t");
    like(
        $stderr,
        qr/corruption|checksum|decompress/i,
        'corrupted block reports a CRC/decompression error'
    ) or note("query rc=$ret stderr=$stderr");
    $node->safe_psql('postgres', "SELECT 1");  # server still up in error mode
    pass('server stays up under cfs_checksum_failure=error');
 
    # panic: reading the corrupted block must force the whole cluster
    # down.
    $node->safe_psql('postgres',
        "ALTER SYSTEM SET cfs_checksum_failure = 'panic'");
    $node->safe_psql('postgres', "SELECT pg_reload_conf()");
    $node->reload;
 
    # Trigger a read of the corrupted block; expect the connection to drop
    # because the backend PANICs.
    ($ret, $stdout, $stderr) =
      $node->psql('postgres', "SELECT count(*) FROM panic_t");
    isnt($ret, 0, 'read of corrupted block under panic mode fails');
 
    # Under PANIC the whole cluster goes down.  init() sets
    # restart_after_crash = off, so the server stays down and there is no
    # postmaster to stop any more; use fail_ok so the harness teardown
    # does not bail out on the missing PID.
    $node->stop('immediate', fail_ok => 1);
}
 
# ---------------------------------------------------------------------------
# zstd-compressed indexes of every AM
#
# Every index AM (btree/hash/gin/gist/brin/spgist) can be built and read
# back through the CFS storage layer with zstd compression, both with an
# explicit policy and via inheritance from a zstd-compressed table.
#
# The zstd codec state holds live ZSTD_CCtx / ZSTD_DCtx pointers and is
# cached per backend across queries, so it must outlive any per-query
# memory context; a state allocated in a transient context would dangle
# after the query that created it and crash the next decompress call.
# (LZ4 is unaffected because its block API is stateless.)  This test
# stresses the codec reuse path by building and reading zstd indexes
# across multiple query cycles.
# ---------------------------------------------------------------------------
subtest 'zstd-compressed indexes of every AM' => sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_zstd_index');
    $node->init;
    $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s");
    $node->append_conf('postgresql.conf', "cfs_bg_period_ms = 36000000");
    $node->start;
 
    if (!codec_built($node, 'zstd'))
    {
        plan skip_all =>
          'Zstd support required, skipping CFS zstd-index test';
    }
 
    # 1. A zstd-compressed heap.  Force a zstd decompression in a
    #    *previous* query (which allocates the codec state), then build
    #    zstd indexes in *later* queries that reuse the cached state.
    $node->safe_psql('postgres',
            "CREATE TABLE t_z (id int, data text, tags text[], pt point) "
          . "WITH (algorithm = 'zstd')");
    $node->safe_psql('postgres',
            "INSERT INTO t_z (id, data, tags, pt) "
          . "SELECT g, md5(g::text), ARRAY[md5(g::text)], point(g, g) "
          . "FROM generate_series(1, 500) g");
 
    # Heap read in a separate query so the zstd codec state is created and
    # cached before the index builds below.
    my $sum = $node->safe_psql('postgres',
        "SELECT md5(string_agg(data, '' ORDER BY id)) FROM t_z");
    is(length($sum), 32, 'zstd heap read round-trips through decompression');
 
    # 2. Build one zstd index per AM with an explicit algorithm and read
    #    it back in a separate query each, exercising cross-query
    #    codec-state reuse.
    $node->safe_psql('postgres',
            "CREATE INDEX ix_zbtree ON t_z USING btree (id) "
          . "WITH (algorithm = 'zstd', level = 3)");
    $node->safe_psql('postgres',
            "CREATE INDEX ix_zhash ON t_z USING hash (data) "
          . "WITH (algorithm = 'zstd')");
    $node->safe_psql('postgres',
            "CREATE INDEX ix_zgin ON t_z USING gin (tags) "
          . "WITH (algorithm = 'zstd')");
    $node->safe_psql('postgres',
            "CREATE INDEX ix_zgist ON t_z USING gist (pt) "
          . "WITH (algorithm = 'zstd')");
    $node->safe_psql('postgres',
            "CREATE INDEX ix_zbrin ON t_z USING brin (id) "
          . "WITH (algorithm = 'zstd')");
    $node->safe_psql('postgres',
            "CREATE INDEX ix_zspgist ON t_z USING spgist (data) "
          . "WITH (algorithm = 'zstd')");
 
    $node->safe_psql('postgres', "SET enable_seqscan = off");
    is( $node->safe_psql(
            'postgres', "SELECT count(*) FROM t_z WHERE id = 42"),
        1,
        'zstd btree index lookup');
    is( $node->safe_psql(
            'postgres', "SELECT count(*) FROM t_z WHERE data = md5('42')"),
        1,
        'zstd hash index lookup');
    is( $node->safe_psql(
            'postgres',
            "SELECT count(*) FROM t_z WHERE tags @> ARRAY[md5('42')]"),
        1,
        'zstd gin index lookup');
    is( $node->safe_psql(
            'postgres',
            "SELECT count(*) FROM t_z WHERE pt <@ box(point(0,0),point(5,5))"
        ),
        5,
        'zstd gist index lookup');
    is( $node->safe_psql(
            'postgres', "SELECT count(*) FROM t_z WHERE id < 10"),
        9,
        'zstd brin index lookup');
    is( $node->safe_psql(
            'postgres', "SELECT count(*) FROM t_z WHERE data = md5('42')"),
        1,
        'zstd spgist index lookup');
 
    # 3. Inherited policy: a zstd index on the zstd table WITHOUT an
    #    explicit algorithm inherits zstd and must round-trip through the
    #    same codec path.  Per the explicit-only reloptions contract, the
    #    inheriting index stores the table's algorithm and only its
    #    explicitly stored auxiliary keys (t_z has none, so the algorithm
    #    alone is copied); unset fields resolve from the session GUCs at
    #    write time and the index is independent of the table afterwards.
    $node->safe_psql('postgres',
        "CREATE INDEX ix_inh ON t_z USING btree (data)");
    is( $node->safe_psql(
            'postgres',
            "SELECT reloptions::text FROM pg_class WHERE oid = 'ix_inh'::regclass"
        ),
        '{algorithm=zstd}',
        'inheriting zstd index stores the table algorithm and explicit keys');
    my $inh_path =
      $node->safe_psql('postgres', "SELECT pg_relation_filepath('ix_inh')");
    ok( -f $node->data_dir . "/$inh_path.cfp",
        'inheriting zstd index has CFS sidecar files');
    is( $node->safe_psql(
            'postgres',
            "SET enable_seqscan = off; SELECT count(*) FROM t_z WHERE data = md5('7')"
        ),
        1,
        'inherited zstd index usable');
 
    # 4. Cross-statement codec reuse stress: interleave zstd heap writes
    #    (which compress) and zstd index reads (which decompress) across
    #    many query cycles.  Use fresh data values so lookups are
    #    unambiguous.
    for my $i (1 .. 20)
    {
        $node->safe_psql('postgres', "SET enable_seqscan = off");
        $node->safe_psql('postgres',
                "INSERT INTO t_z (id, data, tags, pt) "
              . "VALUES (9000+$i, 'stress_$i', ARRAY['stress_$i'], "
              . "point(9000+$i, 9000+$i))");
        my $n = $node->safe_psql('postgres',
            "SELECT count(*) FROM t_z WHERE tags @> ARRAY['stress_$i']");
        is($n, 1, "zstd gin lookup after intermixed insert #$i");
    }
 
    # 5. The zstd-compressed indexes survive a clean restart (on-disk
    #    pages are decompressed correctly by a fresh backend that
    #    allocates a brand-new codec state).
    $node->safe_psql('postgres', "CHECKPOINT");
    $node->restart();
 
    is( $node->safe_psql(
            'postgres',
            "SET enable_seqscan = off; SELECT count(*) FROM t_z WHERE id = 42"
        ),
        1,
        'zstd btree index usable after restart');
    is( $node->safe_psql(
            'postgres',
            "SET enable_seqscan = off; "
              . "SELECT count(*) FROM t_z WHERE pt <@ box(point(0,0),point(5,5))"
        ),
        5,
        'zstd gist index usable after restart');
    is($node->safe_psql('postgres', "SELECT count(*) FROM t_z"),
        520, 'row count is correct after restart');
 
    $node->stop('immediate');
};
 
# ---------------------------------------------------------------------------
# A corrupt .cfsjrn header aborts startup in every mode
#
# The journal header is structural damage: without a valid header the
# records cannot be interpreted at all, so no replay decision can be made
# safely.  Mirror vanilla PostgreSQL, where an invalid WAL record is fatal
# in every mode — there is no "treat the journal as empty" escape hatch,
# with or without cfs_recovery_strict (the GUC remains meaningful for the
# record-level cases: torn and skipped records).
#
# The corruption zeroes the 4-byte journal magic at offset 0 (header
# validation fails on bad magic).  The failed startup must leave the
# on-disk files untouched — the snapshot is not rewritten, the journal is
# not truncated — so the corruption stays diagnosable on disk.
#
# cfs_recovery_strict is PGC_POSTMASTER, so each direction is flipped with
# append_conf() + restart: after the first failed start the server is down
# and cannot execute ALTER SYSTEM.
# ---------------------------------------------------------------------------
subtest 'corrupt .cfsjrn header aborts startup in every mode' => sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_jrn_fatal');
    $node->init;
    $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s");
    $node->start;
 
    if (!codec_built($node, 'lz4'))
    {
        plan skip_all =>
          'LZ4 support not built, skipping CFS journal-header corruption test';
    }
 
    # Build a CFS table, flush a clean map snapshot via CHECKPOINT, then
    # write past the checkpoint so the journal holds records at the stop
    # (the scan only opens a relation for a NON-empty journal).  An
    # immediate stop keeps the journal records on disk; WAL redo recovers
    # the rows at a later successful start.
    $node->safe_psql('postgres',
            "CREATE TABLE jrn_fatal_t (id int, payload text) "
          . "WITH (algorithm = 'lz4')");
    $node->safe_psql('postgres',
            "INSERT INTO jrn_fatal_t SELECT g, repeat('s' || g, 80) "
          . "FROM generate_series(1, 500) g");
    $node->safe_psql('postgres', "CHECKPOINT");
    $node->safe_psql('postgres',
            "INSERT INTO jrn_fatal_t SELECT g, repeat('s' || g, 80) "
          . "FROM generate_series(501, 600) g");
 
    my $data_dir = $node->data_dir;
    my $rel_path =
      $node->safe_psql('postgres',
        "SELECT pg_relation_filepath('jrn_fatal_t')");
    my $jrn = "$data_dir/$rel_path.cfsjrn";
    my $map = "$data_dir/$rel_path.cfsmap";
    ok(-f $jrn, '.cfsjrn sidecar exists for the CFS table');
 
    # Crash so the journal keeps its records past the header.
    $node->stop('immediate');
    ok(-s $jrn > 16, 'journal holds records at the stop');
 
    # Zero the 4-byte journal magic at offset 0.  Overwriting (not XOR)
    # keeps the corruption identical across both directions below.
    {
        open my $fh, '+<:raw', $jrn or die "open $jrn: $!";
        seek($fh, 0, 0) or die "seek: $!";
        print $fh "\x00\x00\x00\x00";
        close($fh);
    }
    pass('zeroed the .cfsjrn header magic');
 
    # Remember the exact bytes: neither failed startup may rewrite them.
    my $map_before = PostgreSQL::Test::Utils::slurp_file($map);
    my $jrn_before = PostgreSQL::Test::Utils::slurp_file($jrn);
 
    # Direction 1: strict = on.  The corrupt header must abort recovery.
    $node->append_conf('postgresql.conf', "cfs_recovery_strict = on");
 
    my $log_off = -s $node->logfile;
 
    # restart_after_crash is off (set by init), so a failed startup stays
    # down and start(fail_ok => 1) returns 0.
    my $started = $node->start(fail_ok => 1);
    ok(!$started,
        'server does NOT start with cfs_recovery_strict=on and corrupt .cfsjrn'
    );
 
    # The server must refuse connections.
    my ($ret, $stdout, $stderr) = $node->psql('postgres', "SELECT 1");
    isnt($ret, 0, 'connection rejected while recovery is aborted');
 
    $node->log_check('strict=on recovery abort message',
        $log_off, log_like => [qr/corrupt page map journal/i]);
 
    # Direction 2: strict = off on the SAME corruption must refuse as
    # well — the header check is not gated on the GUC anymore.
    $node->append_conf('postgresql.conf', "cfs_recovery_strict = off");
 
    $log_off = -s $node->logfile;
    $started = $node->start(fail_ok => 1);
    ok(!$started,
        'server does NOT start with cfs_recovery_strict=off either');
 
    $node->log_check('strict=off recovery abort message',
        $log_off, log_like => [qr/corrupt page map journal/i]);
 
    # Neither failed startup rewrote the sidecars: the evidence is intact.
    is(PostgreSQL::Test::Utils::slurp_file($map),
        $map_before, '.cfsmap is left untouched by the failed startups');
    is(PostgreSQL::Test::Utils::slurp_file($jrn),
        $jrn_before, '.cfsjrn is left untouched by the failed startups');
};
 
# ---------------------------------------------------------------------------
# A corrupt per-entry CRC in .cfsmap surfaces at the first read of the block
#
# Unlike the header (covered above), a bit-rotten map entry is block-local
# damage: the startup scan has no reason to walk every entry (the
# header-only path exists precisely because a clean journal needs no
# replay), so the server starts fine and the corruption surfaces when a
# backend first trusts the entry — a WARNING plus CFS_STORAGE_CORRUPT
# routed through the shared corruption-reporting path (a regular ERROR by
# default).
#
# The corruption flips one byte of block 0's entry_crc field itself (map
# offset CFS_MAP_HEADER_SIZE + offsetof(CfsMapEntry, entry_crc) = 8 + 16),
# which deterministically breaks the CRC without touching any other field.
#
# The corrupt row loads as INVALID and, with an empty
# journal (the checkpoint truncated it), the post-replay validation routes
# the damage through cfs_report_corruption() - a WARNING during the
# recovery scan (strict off) and a client-facing ERROR when a backend
# loads the map for the first read.  The observable outcome is unchanged:
# the server starts, the SELECT fails.
# ---------------------------------------------------------------------------
subtest 'corrupt .cfsmap entry CRC surfaces at first read' => sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_map_entry_crc');
    $node->init;
    $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s");
    $node->start;
 
    if (!codec_built($node, 'lz4'))
    {
        plan skip_all =>
          'LZ4 support not built, skipping CFS map-entry corruption test';
    }
 
    $node->safe_psql('postgres',
            "CREATE TABLE map_entry_t (id int, payload text) "
          . "WITH (algorithm = 'lz4')");
    $node->safe_psql('postgres',
            "INSERT INTO map_entry_t SELECT g, repeat('e' || g, 80) "
          . "FROM generate_series(1, 500) g");
 
    # Flush the map snapshot so block 0's entry lives in .cfsmap (not only
    # in the journal), then crash: the entries stay on disk as written.
    $node->safe_psql('postgres', "CHECKPOINT");
 
    # Resolve the sidecar path while the server is still up.
    my $data_dir = $node->data_dir;
    my $rel_path =
      $node->safe_psql('postgres',
        "SELECT pg_relation_filepath('map_entry_t')");
    my $map = "$data_dir/$rel_path.cfsmap";
    ok(-f $map, '.cfsmap sidecar exists for the CFS table');
 
    $node->stop('immediate');
 
    # Flip one byte of block 0's entry_crc field (map offset 24:
    # 8-byte map prologue + 16-byte offsetof(CfsMapEntry, entry_crc)).
    {
        open my $fh, '+<:raw', $map or die "open $map: $!";
        seek($fh, 24, 0) or die "seek: $!";
        my $byte;
        read($fh, $byte, 1) or die "read: $!";
        seek($fh, 24, 0) or die "seek: $!";
        print $fh chr(ord($byte) ^ 0xff);
        close($fh);
    }
    pass('flipped block 0 entry_crc in .cfsmap');
 
    my $map_before = PostgreSQL::Test::Utils::slurp_file($map);
 
    # The header is intact, so the startup scan must NOT abort: the server
    # accepts connections and the entry damage stays latent until read.
    ok($node->start,
        'server starts with a corrupt map entry (header intact)');
 
    # The first read of block 0 must refuse to serve it instead of
    # decompressing through a corrupted entry.  The client-facing ERROR
    # comes from cfs_report_corruption(); the entry-level detail rides as
    # the DETAIL line of that report (segment path: "invalid page map
    # entry"; the authoritative-map fallback keeps the load-time wording).
    my ($ret, $stdout, $stderr) =
      $node->psql('postgres', "SELECT count(*) FROM map_entry_t");
    isnt($ret, 0, 'SELECT fails on a corrupted map entry');
    like(
        $stderr,
        qr/checksum or format corruption.*block 0/,
        'client-facing corruption error names block 0');
 
    $node->log_check('entry-level corruption detail in the log',
        0, log_like => [qr/(checksum or format error in compressed page|invalid page map entry for block 0|page map entry failed its checksum)/]);
 
    # The failed read did not rewrite the map.
    is(PostgreSQL::Test::Utils::slurp_file($map),
        $map_before, '.cfsmap is left untouched by the failed read');
};
 
# ---------------------------------------------------------------------------
# fsync failure of a CFS sidecar during a checkpoint
#
# Durability contract: an fsync() failure of a CFS sidecar (.cfp /
# .cfsjrn) during a checkpoint must be fatal for the whole cluster (PANIC
# via data_sync_elevel), exactly like md.c treats an fsync failure of a
# base relation segment.  A checkpoint that "succeeds" without durable
# data lets the WAL segments needed to rebuild the relation be recycled,
# so after the next crash the data is irrecoverable.
#
# The fsync failure is injected deterministically through the debug GUC
# cfs_debug_fail_fsync (default 0, a complete no-op in production): when
# it is greater than zero, the CFS fsync wrapper simulates an EIO instead
# of doing a real fsync.
# ---------------------------------------------------------------------------
subtest 'fsync failure of a CFS sidecar' => sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_ckpt_fsync');
    $node->init;
    # Keep background checkpoints out of the way; the test drives its own.
    $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s");
    $node->start;
 
    if (!codec_built($node, 'zstd'))
    {
        plan skip_all =>
          'zstd support not built, skipping CFS checkpoint fsync test';
    }
 
    # A dirty CFS relation whose .cfp will be fsync'd by the next
    # checkpoint.
    $node->safe_psql('postgres',
        "CREATE TABLE ckpt_t (id int, data text) WITH (algorithm = 'zstd')");
    $node->safe_psql('postgres',
            "INSERT INTO ckpt_t SELECT g, repeat('x', 200) "
          . "FROM generate_series(1, 50) g");
 
    # Reload the debug injection GUC into the checkpointer, then request a
    # checkpoint: the checkpointer fsyncs the .cfp/.cfsjrn sidecars, which
    # now fail synthetically.
    $node->safe_psql('postgres',
        "ALTER SYSTEM SET cfs_debug_fail_fsync = 100");
    $node->reload;
 
    # CHECKPOINT runs in the checkpointer; use the non-fatal psql() so a
    # PANIC (which tears the connection down) does not abort the harness.
    my ($ret, $stdout, $stderr) = $node->psql('postgres', 'CHECKPOINT');
    isnt($ret, 0,
        'checkpoint with an injected fsync failure does not succeed');
 
    # Under data_sync_elevel() the failure escalates to PANIC, bringing
    # the whole cluster down.  restart_after_crash defaults to off for a
    # TAP cluster, so the postmaster is gone; stop() must tolerate the
    # missing PID.
    my $log = $node->log_content();
    like(
        $log,
        qr/CFS: fsync of.*failed/,
        'log records the CFS sidecar fsync failure');
    like($log, qr/PANIC/,
        'fsync failure on a CFS checkpoint escalates to PANIC');
 
    $node->stop('immediate', fail_ok => 1);
};
 
# ---------------------------------------------------------------------------
# Write-path and read-path I/O failures of a CFS relation
#
# A pwrite()/pread() failure of a sidecar (the ENOSPC/EIO class) must fail
# the current statement loudly and leave the server up and the relation
# usable.  The write path is driven through pg_cfs_compact - the compaction
# copy goes through the same cfs_pwrite_all() as record appends, but runs
# in a user backend, so the failure surfaces as a regular ERROR (an
# injected write failure under the buffer manager would fire in the
# bgwriter, a different and timing-dependent contract).  The read path is
# driven through a plain SELECT: both the synchronous and the AIO read
# funnel through the injected point.  In both cases the live pair must be
# untouched, and once the transient condition is gone the next statement
# succeeds.  Mirror vanilla PostgreSQL, where an I/O error of a base
# relation segment errors the query without taking the cluster down.
#
# The failures are injected deterministically through the debug GUCs
# cfs_debug_fail_pwrite / cfs_debug_fail_read (default 0, complete no-ops
# in production): when set to N, the next N writes (cfs_pwrite_all - every
# CFS write: record appends, journal appends, the compaction copy) or reads
# (cfs_read_raw_record) fail with EIO.
#
# Both GUCs are PGC_SIGHUP, so every process - background ones included -
# receives the counter on reload.  A background process (bgwriter,
# checkpointer, autovacuum) spending the injected failure in the window
# between the reload and the target command would leave the subtest
# falsely green; the subtest relies on that not happening: the preceding
# CHECKPOINT flushed all CFS writes, checkpoint_timeout = 30s keeps the
# checkpointer quiet across the window, and the tables are too small for
# autovacuum to bother.  The window is narrow and the assumption is
# accepted deliberately.
# ---------------------------------------------------------------------------
subtest 'pwrite and pread failures of a CFS relation' => sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_io_eio');
    $node->init;
    $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s");
    $node->start;
 
    if (!codec_built($node, 'lz4'))
    {
        plan skip_all =>
          'LZ4 support not built, skipping CFS I/O failure test';
    }
 
    # Two flushed versions of every page: dead space, so the compaction
    # below has something to copy.
    $node->safe_psql('postgres',
            "CREATE TABLE io_eio_t (id int, payload text) "
          . "WITH (algorithm = 'lz4')");
    $node->safe_psql('postgres',
            "INSERT INTO io_eio_t SELECT g, repeat('w' || g, 80) "
          . "FROM generate_series(1, 500) g");
    $node->safe_psql('postgres', 'CHECKPOINT');
    $node->safe_psql('postgres',
        "UPDATE io_eio_t SET payload = repeat('z' || id, 80)");
    $node->safe_psql('postgres', 'CHECKPOINT');
 
    my $dd = $node->data_dir;
    my $rel_path =
      $node->safe_psql('postgres', "SELECT pg_relation_filepath('io_eio_t')");
    my $cfp_file = "$dd/$rel_path.cfp";
    my $size_before = -s $cfp_file;
    my $ck = $node->safe_psql('postgres',
        "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM io_eio_t");
 
    # --- Write path: the compaction copy fails on the injected pwrite -----
    $node->safe_psql('postgres',
        "ALTER SYSTEM SET cfs_debug_fail_pwrite = 1");
    $node->reload;
 
    my ($ret, $stdout, $stderr) =
      $node->psql('postgres', "SELECT pg_cfs_compact('io_eio_t')");
    isnt($ret, 0, 'pg_cfs_compact fails on an injected pwrite failure');
 
    # The failed compaction is a failed transaction: no commit marker, no
    # candidates, the live pair untouched, the relation still readable.
    ok(!-f "$cfp_file.cfsswap",
        'no commit marker after the failed compaction');
    ok(!-f "$cfp_file.new", 'no .cfp.new candidate after the failure');
    is(-s $cfp_file, $size_before,
        'live .cfp untouched by the failed compaction');
    is( $node->safe_psql(
            'postgres',
            "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM io_eio_t"),
        $ck,
        'relation still readable after the failed compaction');
 
    # The counter is spent: the next compaction succeeds and reclaims.
    $node->safe_psql('postgres', "ALTER SYSTEM RESET cfs_debug_fail_pwrite");
    $node->reload;
    like(
        $node->safe_psql('postgres', "SELECT pg_cfs_compact('io_eio_t')"),
        qr/reclaimed \d+/,
        'next compaction succeeds after the transient write failure');
    is( $node->safe_psql(
            'postgres',
            "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM io_eio_t"),
        $ck,
        'data unchanged by the successful compaction');
 
    # --- Read path: one injected pread failure ----------------------------
    # Evict the table's pages so the read really goes through the CFS smgr
    # path, then fail the first record read.
    $node->safe_psql('postgres', 'CHECKPOINT');
    $node->restart;
 
    $node->safe_psql('postgres', "ALTER SYSTEM SET cfs_debug_fail_read = 1");
    $node->reload;
 
    ($ret, $stdout, $stderr) =
      $node->psql('postgres', "SELECT count(*) FROM io_eio_t");
    isnt($ret, 0, 'SELECT fails on an injected pread failure');
    like(
        $stderr,
        qr/CFS: could not read block/,
        'read failure reported to the client');
 
    # The server stays up and the very next read succeeds.  The injection
    # counter is per-process (every backend starts with the GUC value), so
    # the follow-up read must run in the SAME session that already spent
    # it: with on_error_stop disabled psql continues past the failed
    # statement, and the second statement reads the whole table undisturbed.
    ($ret, $stdout, $stderr) = $node->psql(
        'postgres',
        "SELECT count(*) FROM io_eio_t; "
          . "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM io_eio_t",
        on_error_stop => 0);
    is($ret, 0, 'psql script with one failed statement completes');
    like(
        $stderr,
        qr/CFS: could not read block/,
        'first statement of the follow-up read failed as spent');
    $stdout =~ s/^\s+|\s+$//g;
    is($stdout, $ck,
        'next read in the same session succeeds after the read failure');
 
    $node->safe_psql('postgres', "ALTER SYSTEM RESET cfs_debug_fail_read");
    $node->reload;
    $node->stop('fast');
};
 
# ---------------------------------------------------------------------------
# Journal truncate failure of a CFS checkpoint
#
# Truncating the .cfsjrn back to its bare header is the last durability
# step of the CFS checkpoint protocol; afterwards the relation's
# dirty_checkpoint mark is cleared.  A truncation that fails must
# therefore fail the checkpoint itself (data_sync_elevel, i.e. PANIC
# with the default data_sync_retry = off) — a checkpoint that
# "succeeds" without the truncation would clear the dirty mark while
# the journal keeps growing, silently losing the error on every future
# checkpoint, in contrast with every other durability failure around
# it (fsync of .cfp/.cfsjrn, journal header rewrite) which is already
# fatal.
#
# The failure is injected deterministically through the debug GUC
# cfs_debug_fail_truncate (default 0, a complete no-op in production):
# when it is greater than zero, the next journal truncations pretend
# pg_truncate() failed with EIO.  After the failure the server must
# come back with the injection disabled and truncate the journal on
# the next checkpoint.
# ---------------------------------------------------------------------------
subtest 'journal truncate failure of a CFS checkpoint' => sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_ckpt_truncate');
    $node->init;
    # Keep background checkpoints out of the way; the test drives its own.
    $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s");
    $node->start;
 
    plan skip_all =>
      'zstd support not built, skipping CFS journal truncate failure test'
      if !codec_built($node, 'zstd');
 
    # A dirty CFS relation: the next checkpoint persists its map snapshot
    # and truncates its journal.
    $node->safe_psql('postgres',
        "CREATE TABLE ckpt_jrn (id int, data text) WITH (algorithm = 'zstd')"
    );
    $node->safe_psql('postgres',
            "INSERT INTO ckpt_jrn SELECT g, repeat('x', 200) "
          . "FROM generate_series(1, 50) g");
 
    # Resolve the sidecar path while the server is up.
    my $dd = $node->data_dir;
    my $path =
      $node->safe_psql('postgres', "SELECT pg_relation_filepath('ckpt_jrn')");
    my $cfsjrn = "$dd/$path.cfsjrn";
    ok(-f $cfsjrn, '.cfsjrn sidecar exists for the CFS table');
 
    # Load the debug injection into the checkpointer and request a
    # checkpoint: the journal truncation step now fails synthetically.
    $node->append_conf('postgresql.conf', 'cfs_debug_fail_truncate = 1');
    $node->reload;
 
    # CHECKPOINT runs in the checkpointer; use the non-fatal psql() so a
    # PANIC (which tears the connection down) does not abort the harness.
    my ($ret, $stdout, $stderr) = $node->psql('postgres', 'CHECKPOINT');
    isnt($ret, 0,
        'checkpoint with an injected journal truncate failure does not succeed'
    );
 
    # Under data_sync_elevel() the failure escalates to PANIC, bringing
    # the whole cluster down.  restart_after_crash defaults to off for a
    # TAP cluster, so the postmaster is gone; stop() must tolerate the
    # missing PID.
    my $log = $node->log_content();
    like(
        $log,
        qr/could not truncate journal/,
        'log records the journal truncate failure');
    like($log, qr/PANIC/,
        'journal truncate failure on a CFS checkpoint escalates to PANIC');
 
    # Short-circuit the red case: the steps below assume the server is
    # down (the checkpoint must have PANIC'd the cluster).
    return if $ret == 0;
 
    # The postmaster may still be shutting down after the PANIC; stop()
    # tolerates the already-gone PID and waits for the shutdown to finish.
    $node->stop('immediate', fail_ok => 1);
 
    # Disable the injection again (the server is down, so edit the file
    # directly) and restart: crash recovery replays the table, the
    # end-of-recovery checkpoint truncates the journal for real and the
    # server must come up.
    my $conf = $node->data_dir . '/postgresql.conf';
    my $conf_text = PostgreSQL::Test::Utils::slurp_file($conf);
    $conf_text =~ s/^cfs_debug_fail_truncate = 1$//m;
    open my $cfh, '>', $conf or die "open $conf: $!";
    print $cfh $conf_text;
    close $cfh;
 
    $node->start;
 
    ok(-s $cfsjrn < 1024,
        '.cfsjrn is truncated back to its bare header after recovery');
 
    is($node->safe_psql('postgres', 'SELECT count(*) FROM ckpt_jrn'),
        '50', 'CFS table survives the crash intact');
};
 
# ---------------------------------------------------------------------------
# Journal truncate failure during crash recovery
#
# The recovery scan also truncates each replayed journal (after saving
# the map snapshot).  Unlike the checkpoint's truncation, this one is the
# idempotent tail step of an operation the next restart simply repeats,
# so a failure must stay a WARNING there: the server comes up, the
# journal keeps its records, and a later restart with the failure gone
# truncates it.  Escalating the recovery path like the checkpoint
# (data_sync_elevel, i.e. PANIC with the default data_sync_retry = off)
# would kill the startup process and crash-loop the cluster over a
# cosmetic failure.
#
# The failure is injected through cfs_debug_fail_truncate (see the
# checkpoint subtest above); the GUC takes effect from postgresql.conf
# at startup, so the injection is armed before crash recovery runs.
# The counter is per-process, so the freshly forked checkpointer re-arms
# the fault for its end-of-recovery checkpoint and the cluster dies
# there — that is the checkpoint contract of the subtest above, not the
# regression under test.  What must NOT happen is the recovery scan
# itself escalating: its truncate failure has to stay a WARNING that
# recovery runs past (the following "checkpoint starting" and redo lines
# prove the scan completed), with the only escalation coming from the
# end-of-recovery checkpoint afterwards.
# ---------------------------------------------------------------------------
subtest 'journal truncate failure during crash recovery' => sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_recov_truncate');
    $node->init;
    # Keep background checkpoints out of the way so the journal keeps
    # its records until the crash.
    $node->append_conf('postgresql.conf',
        "checkpoint_timeout = 30min\nmax_wal_size = 1GB");
    $node->start;
 
    plan skip_all =>
      'zstd support not built, skipping CFS recovery truncate failure test'
      if !codec_built($node, 'zstd');
 
    # A dirty CFS relation whose journal still holds records when the
    # server crashes: the recovery scan replays them, saves the map
    # snapshot and tries to truncate the journal.
    $node->safe_psql('postgres',
        "CREATE TABLE recov_jrn (id int, data text) WITH (algorithm = 'zstd')"
    );
    $node->safe_psql('postgres',
            "INSERT INTO recov_jrn SELECT g, repeat('x', 200) "
          . "FROM generate_series(1, 50) g");
 
    # Resolve the sidecar path while the server is up.
    my $dd = $node->data_dir;
    my $path =
      $node->safe_psql('postgres',
        "SELECT pg_relation_filepath('recov_jrn')");
    my $cfsjrn = "$dd/$path.cfsjrn";
    ok(-f $cfsjrn, '.cfsjrn sidecar exists for the CFS table');
 
    # Crash before any checkpoint truncates the journal.
    $node->stop('immediate');
 
    # Arm the injection for the recovery scan and start.  The start
    # itself is expected to die: the re-armed fault also fails the
    # end-of-recovery checkpoint (PANIC), so only tolerate the failure
    # here — the assertions below read the log either way.
    $node->append_conf('postgresql.conf', 'cfs_debug_fail_truncate = 1');
    $node->start(fail_ok => 1);
 
    # The scan's own truncate failure must be a WARNING that recovery
    # runs past: the end-of-recovery checkpoint only starts afterwards,
    # and any PANIC about the truncation must belong to that checkpoint,
    # never to the scan.
    my $log = $node->log_content();
    like(
        $log,
        qr/WARNING:  CFS: could not truncate journal.*checkpoint starting: end-of-recovery.*PANIC:  CFS: could not truncate journal/s,
        'recovery scan tolerates its truncate failure; only the end-of-recovery checkpoint escalates'
    );
 
    # The postmaster may be gone after the checkpoint PANIC; stop()
    # tolerates the already-gone PID.
    $node->stop('immediate', fail_ok => 1);
 
    # The failure is gone on the next boot: the journal still holds its
    # records (only the truncation failed), so the recovery scan repeats
    # the replay, snapshot and truncation for real.
    my $conf = $node->data_dir . '/postgresql.conf';
    my $conf_text = PostgreSQL::Test::Utils::slurp_file($conf);
    $conf_text =~ s/^cfs_debug_fail_truncate = 1$//m;
    open my $cfh, '>', $conf or die "open $conf: $!";
    print $cfh $conf_text;
    close $cfh;
 
    ok($node->start,
        'server starts once the injected truncate failure is cleared');
 
    ok(-s $cfsjrn < 1024,
        '.cfsjrn is truncated back to its bare header after recovery');
 
    is($node->safe_psql('postgres', 'SELECT count(*) FROM recov_jrn'),
        '50', 'CFS table survives the crash intact');
};
 
# ---------------------------------------------------------------------------
# Checkpoint persists map snapshots only for dirty CFS relations
#
# A checkpoint must persist .cfsmap snapshots only for the CFS relations
# written since the last checkpoint (dirty_checkpoint), not for every
# occupied metadata slot: an idle relation already has a durable snapshot
# from the checkpoint that last wrote it, and re-fsync'ing its sidecars
# would be wasted work.
#
# The checkpointer logs "CFS: checkpoint persisted N relation map
# snapshot(s)" at DEBUG1, so the test counts real work by reading the
# server log.  Both tables are written once before the baseline
# checkpoint, so both occupy a metadata slot; afterwards only one of
# them is written, and a checkpoint must report exactly 1 snapshot,
# while a checkpoint with no intervening writes must report nothing.
# ---------------------------------------------------------------------------
subtest 'checkpoint persists map snapshots only for dirty CFS relations' =>
  sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_ckpt_dirty_only');
    $node->init;
    # Keep background checkpoints out of the way; the test drives its own.
    $node->append_conf('postgresql.conf',
            "log_min_messages = debug1\n"
          . "checkpoint_timeout = 30min\n"
          . "max_wal_size = 1GB\n"
          . "autovacuum = off\n");
    $node->start;
 
    if (!codec_built($node, 'zstd'))
    {
        plan skip_all =>
          'zstd support not built, skipping CFS checkpoint dirty-filter test';
    }
 
    # Two CFS tables, int-only so no toast relations muddle the count.  One
    # row each, so that both occupy a metadata slot with a live policy.
    $node->safe_psql('postgres',
        "CREATE TABLE cfs_written (id int) WITH (algorithm = 'zstd')");
    $node->safe_psql('postgres',
        "CREATE TABLE cfs_idle (id int) WITH (algorithm = 'zstd')");
    $node->safe_psql('postgres', "INSERT INTO cfs_written VALUES (1)");
    $node->safe_psql('postgres', "INSERT INTO cfs_idle VALUES (1)");
 
    # Baseline checkpoint: both relations are snapshotted and both slots are
    # clean afterwards.
    $node->safe_psql('postgres', "CHECKPOINT");
    my $offset = -s $node->logfile;
 
    # Write to one table only; the checkpoint must persist exactly one map
    # snapshot; the idle table is not re-snapshotted.
    $node->safe_psql('postgres',
        "INSERT INTO cfs_written SELECT g FROM generate_series(2, 100) g");
    $node->safe_psql('postgres', "CHECKPOINT");
    my $log = PostgreSQL::Test::Utils::slurp_file($node->logfile, $offset);
    like(
        $log,
        qr/CFS: checkpoint persisted 1 relation map snapshot/,
        'checkpoint after writing one of two CFS tables persists 1 snapshot');
    unlike(
        $log,
        qr/CFS: checkpoint persisted [02-9]\d* relation map snapshot/,
        'idle CFS table is not re-snapshotted');
 
    # No writes at all since the previous checkpoint: no snapshots at all
    # (the message is emitted only when at least one relation is processed).
    $offset = -s $node->logfile;
    $node->safe_psql('postgres', "CHECKPOINT");
    $log = PostgreSQL::Test::Utils::slurp_file($node->logfile, $offset);
    unlike(
        $log,
        qr/CFS: checkpoint persisted/,
        'checkpoint without intervening writes persists nothing');
 
    # The other table is still picked up once it is written.
    $offset = -s $node->logfile;
    $node->safe_psql('postgres',
        "INSERT INTO cfs_idle SELECT g FROM generate_series(2, 100) g");
    $node->safe_psql('postgres', "CHECKPOINT");
    $log = PostgreSQL::Test::Utils::slurp_file($node->logfile, $offset);
    like(
        $log,
        qr/CFS: checkpoint persisted 1 relation map snapshot/,
        'previously idle table is snapshotted after a new write');
    unlike(
        $log,
        qr/CFS: checkpoint persisted [02-9]\d* relation map snapshot/,
        'the table not written since the last checkpoint stays untouched');
 
  };
 
# ---------------------------------------------------------------------------
# Corruption surfaced through the AIO read_stream path.
#
# CFS readv is completed inline: the blocks are decompressed in the
# originating backend and the IO result carries either the block count or a
# negative failure code, which the completion callback turns into
# PGAIO_RS_ERROR and the report callback raises as the query's ERROR.  A
# read failure must therefore reach a read_stream consumer exactly like a
# synchronous one — same ERROR text (the centralised corruption handler,
# so the cfs_checksum_failure GUC keeps its meaning), a live session
# afterwards, and a reproducible error on retry (the IO accounting is not
# stuck after the failure).
#
# Note: no deterministic RED is possible for the delivery contract itself
# (the pre-fix code failed with the same message); this section pins the
# contract: error text, session survival and repeatable failure.
# ---------------------------------------------------------------------------
subtest
  'corrupted page delivered through read_stream raises a clean ERROR' => sub {
    # A tiny shared_buffers so a seq scan of a few MB goes past the buffer
    # cache and is served through read_stream / startreadv.
    my $node = PostgreSQL::Test::Cluster->new('cfs_rs_corrupt');
    $node->init;
    $node->append_conf('postgresql.conf',
        "shared_buffers = 1MB\ncheckpoint_timeout = 30min");
    $node->start;
 
    if (!codec_built($node, 'lz4'))
    {
        plan skip_all =>
          'LZ4 support not built, skipping CFS read_stream corruption test';
    }
 
    # A CFS table well past shared_buffers so a seq scan streams reads.
    $node->safe_psql('postgres',
            "CREATE TABLE rs_t (id int, payload text) "
          . "WITH (algorithm = 'lz4')");
    $node->safe_psql('postgres',
            "INSERT INTO rs_t SELECT g, repeat('rs' || g, 300) "
          . "FROM generate_series(1, 1000) g");
    $node->safe_psql('postgres', "CHECKPOINT");
 
    my $dd = $node->data_dir;
    my $path =
      $node->safe_psql('postgres', "SELECT pg_relation_filepath('rs_t')");
    my $cfp = "$dd/$path.cfp";
    ok(-f $cfp, '.cfp sidecar exists for the streaming table');
 
    $node->stop('fast');
 
    # Flip one byte deep in the payload region (same technique as the
    # checksum-panic section above: parses, but fails the post-
    # decompression CRC).
    {
        open my $fh, '+<:raw', $cfp or die "open $cfp: $!";
        seek($fh, 200, 0) or die "seek: $!";
        my $b;
        read($fh, $b, 1);
        seek($fh, 200, 0);
        print $fh chr(ord($b) ^ 0xFF);
        close($fh);
    }
    pass('flipped one payload byte in the .cfp');
 
    $node->start;
 
    # One long-lived session: the first scan fails, the session survives
    # and a retry fails identically.  ON_ERROR_STOP is off so psql keeps
    # serving after the expected ERRORs.
    my $bp = $node->background_psql(
        'postgres',
        timeout => 60,
        on_error_stop => 0);
    $bp->query_until(qr/FIRST_DONE/,
        "\\echo FIRST_MARKER\nSELECT count(*) FROM rs_t; \\echo FIRST_DONE\n"
    );
 
    # The ERROR is raised through the centralised corruption path, keeping
    # the cfs_checksum_failure GUC semantics and the usual message text.
    my $log1 = $node->log_content;
    like(
        $log1,
        qr/ERROR:.*CFS: checksum or format corruption in relation/,
        'first streaming scan failed with the corruption ERROR');
 
    # The session is alive after the failed IO...
    $bp->query_until(qr/ALIVE/, "SELECT 'session-alive'; \\echo ALIVE\n");
 
    # ...and a retry reproduces the failure (IO accounting not stuck).
    $bp->query_until(qr/SECOND_DONE/,
        "SELECT count(*) FROM rs_t; \\echo SECOND_DONE\n");
 
    my $log2 = $node->log_content;
    my $corruption_count = () =
      $log2 =~ /CFS: checksum or format corruption/g;
    is($corruption_count, 2,
        'retried streaming scan reproduces the corruption ERROR');
 
    $bp->quit;
 
    # The server itself stays up.
    is($node->safe_psql('postgres', "SELECT 1"),
        1, 'server stays up after the streamed corruption ERROR');
 
    $node->stop('fast');
  };
 
# ---------------------------------------------------------------------------
# Structural map corruption hit during an AIO read is caught and delivered
# through the normal AIO failure path.
#
# With the shared map pool off (cfs_map_memory = 0) every persistent smgr
# handle owns a private map.  A long-lived reader therefore keeps a loaded
# map; another backend writes, a CHECKPOINT rewrites the snapshot and resets
# the journal, the .cfsmap prologue is corrupted out of band, and the next
# streaming read has to reload the stale map inside cfs_smgr_startreadv().
# There cfs_read_blocks_status() raises, and the catch must convert the ERROR
# into the inline AIO failure code, complete the handle exactly once, and let
# the consumer re-report it through cfs_report_corruption() - no crash, no
# leaked append lock, no lost session.
# ---------------------------------------------------------------------------
subtest 'corrupt map prologue is caught inside an AIO read' => sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_aio_map_corrupt');
    $node->init;
    $node->append_conf('postgresql.conf',
            "shared_buffers = 1MB\n"
          . "cfs_map_memory = 0\n"
          . "checkpoint_timeout = 30min\n"
          . "log_min_messages = debug1\n");
    $node->start;
 
    if (!codec_built($node, 'lz4'))
    {
        plan skip_all =>
          'LZ4 support not built, skipping CFS AIO map-refresh test';
    }
 
    # A table well past the 1MB buffer cache, snapshotted by CHECKPOINT so
    # the .cfsmap has a prologue to corrupt.
    $node->safe_psql('postgres',
            "CREATE TABLE aio_map_t (id int, payload text) "
          . "WITH (algorithm = 'lz4')");
    $node->safe_psql('postgres',
            "INSERT INTO aio_map_t SELECT g, repeat('am' || g, 300) "
          . "FROM generate_series(1, 1000) g");
    $node->safe_psql('postgres', "CHECKPOINT");
 
    my $data_dir = $node->data_dir;
    my $rel_path = $node->safe_psql('postgres',
        "SELECT pg_relation_filepath('aio_map_t')");
    my $cfsmap = "$data_dir/$rel_path.cfsmap";
    ok(-f $cfsmap, '.cfsmap sidecar exists for the AIO table');
 
    $node->safe_psql('postgres', "VACUUM aio_map_t");
    $node->safe_psql('postgres', "CHECKPOINT");
    my $vm_before = $node->safe_psql('postgres', "SELECT pg_relation_size('aio_map_t', 'vm')");
    diag("VM before reader: $vm_before");
    # Long-lived reader: the scan opens the persistent full-map handle and
    # evicts most pages from the tiny cache.  Parallel workers are off so
    # the handle under test belongs to this session.
    my $reader = $node->background_psql(
        'postgres',
        timeout => 60,
        on_error_stop => 0);
    my $first = $reader->query_until(qr/FIRST_DONE/,
            "SET max_parallel_workers_per_gather = 0;\n"
          . "SELECT count(*) FROM aio_map_t; \\echo FIRST_DONE\n");
    unlike($first, qr/ERROR:/, 'initial streaming read succeeds');
 
    # A second backend writes to the table, so the next CHECKPOINT has a
    # dirty relation to fold: it rewrites the .cfsmap snapshot and resets the
    # journal, bumping the incarnation.  The reader's map is then stale by
    # incarnation, which is what forces a full reload (a mere journal append
    # would take the delta-replay path and never read the prologue).
    my $writer = $node->background_psql(
        'postgres',
        timeout => 60,
        on_error_stop => 0);
    my $ins = $writer->query_until(qr/INS_DONE/,
            "INSERT INTO aio_map_t "
          . "SELECT g, repeat('b' || g, 300) FROM generate_series(1001, 1100) g; "
          . "\\echo INS_DONE\n");
    unlike($ins, qr/ERROR:/, 'journal append before corruption succeeds');
    my $vm_after = $node->safe_psql('postgres', "SELECT pg_relation_size('aio_map_t', 'vm')");
    diag("VM after writer: $vm_after");
    cmp_ok($vm_before, '>', 0, 'VM precreated before opening reader');
    is($vm_after, $vm_before, 'writer did not extend VM');
 
    $node->safe_psql('postgres', "CHECKPOINT");
 
    # Zero the 4-byte map magic of the freshly written snapshot, as in the
    # fatal-header test above.
    {
        open my $fh, '+<:raw', $cfsmap or die "open $cfsmap: $!";
        seek($fh, 0, 0) or die "seek: $!";
        print $fh "\x00\x00\x00\x00";
        close($fh);
    }
    pass('zeroed the .cfsmap prologue magic');
 
    my $failed_off = -s $node->logfile;
    $reader->query_until(qr/READ_DONE/,
        "SELECT count(*) FROM aio_map_t; \\echo READ_DONE\n");
 
    # psql sends the ERROR to stderr, so assert on the server log: the AIO
    # consumer reports the converted failure through cfs_report_corruption().
    $node->log_check(
        'streaming read fails through the AIO report',
        $failed_off,
        log_like =>
          [qr/ERROR:.*CFS: checksum or format corruption in relation/]);
 
    # The DEBUG1 line proves the ERROR was raised inside the synchronous
    # read and converted by the catch, not raised directly by the loader.
    $node->log_check(
        'caught prologue ERROR is logged at DEBUG1',
        $failed_off,
        log_like =>
          [qr/synchronous AIO read failed:.*checksum or format corruption/]);
 
    # The session survives the converted failure.
    my $alive = $reader->query_until(qr/ALIVE/,
        "SELECT 'session-alive'; \\echo ALIVE\n");
    like($alive, qr/session-alive/, 'reader session survives the failure');
 
    # A retry takes the same path instead of hanging on a leaked append lock.
    my $retry_off = -s $node->logfile;
    $reader->query_until(qr/RETRY_DONE/,
        "SELECT count(*) FROM aio_map_t; \\echo RETRY_DONE\n");
    $node->log_check(
        'retry reports the corruption again',
        $retry_off,
        log_like =>
          [qr/ERROR:.*CFS: checksum or format corruption in relation/]);
    $node->log_check('retry also went through the caught AIO ERROR path',
        $retry_off, log_like => [qr/synchronous AIO read failed/]);
 
    $reader->quit;
    $writer->quit;
 
    is($node->safe_psql('postgres', "SELECT 1"),
        1, 'server stays up after the AIO map-refresh failure');
 
    $node->stop('fast');
};
 
# ---------------------------------------------------------------------------
# Structural map corruption caught in the pool-miss path.
#
# With a one-segment pool, streaming a second relation evicts the first
# relation's segment.  Corrupting the first relation's .cfsmap prologue and
# reading it again forces cfs_shared_map_ensure() to load the segment inside
# the shared append-lock window; the loader raises, and the catch must
# release the append lock before rethrowing into cfs_smgr_startreadv(), which
# converts the error into the normal AIO failure.  A leaked lock would make
# the retry hang.
# ---------------------------------------------------------------------------
subtest 'corrupt map prologue is caught on a pool miss' => sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_aio_pool_miss');
    $node->init;
    $node->append_conf('postgresql.conf',
            "shared_buffers = 1MB\n"
          . "cfs_map_memory = 1\n"
          . "checkpoint_timeout = 30min\n"
          . "log_min_messages = debug1\n");
    $node->start;
 
    if (!codec_built($node, 'lz4'))
    {
        plan skip_all =>
          'LZ4 support not built, skipping CFS pool-miss corruption test';
    }
 
    $node->safe_psql('postgres',
            "CREATE TABLE pool_miss_a (id int, payload text) "
          . "WITH (algorithm = 'lz4')");
    $node->safe_psql('postgres',
            "CREATE TABLE pool_miss_b (id int, payload text) "
          . "WITH (algorithm = 'lz4')");
    $node->safe_psql('postgres',
            "INSERT INTO pool_miss_a SELECT g, repeat('pa' || g, 300) "
          . "FROM generate_series(1, 1000) g");
    $node->safe_psql('postgres',
            "INSERT INTO pool_miss_b SELECT g, repeat('pb' || g, 300) "
          . "FROM generate_series(1, 1000) g");
    $node->safe_psql('postgres', "CHECKPOINT");
 
    my $data_dir = $node->data_dir;
    my $rel_path = $node->safe_psql('postgres',
        "SELECT pg_relation_filepath('pool_miss_a')");
    my $cfsmap = "$data_dir/$rel_path.cfsmap";
    ok(-f $cfsmap, '.cfsmap sidecar exists for the pool-miss table');
 
    # The tiny pool has one segment: scanning B evicts A's segment.
    my $reader = $node->background_psql(
        'postgres',
        timeout => 60,
        on_error_stop => 0);
    my $first = $reader->query_until(qr/A_DONE/,
            "SET max_parallel_workers_per_gather = 0;\n"
          . "SELECT count(*) FROM pool_miss_a; \\echo A_DONE\n");
    unlike($first, qr/ERROR:/, 'first relation read succeeds');
    my $second = $reader->query_until(qr/B_DONE/,
        "SELECT count(*) FROM pool_miss_b; \\echo B_DONE\n");
    unlike($second, qr/ERROR:/, 'second relation evicts the first segment');
 
    {
        open my $fh, '+<:raw', $cfsmap or die "open $cfsmap: $!";
        seek($fh, 0, 0) or die "seek: $!";
        print $fh "\x00\x00\x00\x00";
        close($fh);
    }
    pass('zeroed the .cfsmap prologue magic');
 
    my $failed_off = -s $node->logfile;
    $reader->query_until(qr/READ_DONE/,
        "SELECT count(*) FROM pool_miss_a; \\echo READ_DONE\n");
    $node->log_check(
        'pool-miss read fails through the AIO report',
        $failed_off,
        log_like =>
          [qr/ERROR:.*CFS: checksum or format corruption in relation/]);
    $node->log_check(
        'caught pool-miss ERROR is logged at DEBUG1',
        $failed_off,
        log_like =>
          [qr/synchronous AIO read failed:.*checksum or format corruption/]);
 
    # The append lock was released: this retry would hang on a leaked lock.
    my $retry_off = -s $node->logfile;
    $reader->query_until(qr/RETRY_DONE/,
        "SELECT count(*) FROM pool_miss_a; \\echo RETRY_DONE\n");
    $node->log_check(
        'retry reports the pool-miss corruption again',
        $retry_off,
        log_like =>
          [qr/ERROR:.*CFS: checksum or format corruption in relation/]);
 
    $reader->quit;
 
    is($node->safe_psql('postgres', "SELECT 1"),
        1, 'server stays up after the pool-miss failure');
 
    $node->stop('fast');
};
 
# ---------------------------------------------------------------------------
# Corrupt .cfsmap header is fatal regardless of cfs_recovery_strict
#
# The .cfsmap header is a synchronisation point: the data of every block
# below the last checkpoint lives only in the .cfp + .cfsmap pair, WAL does
# not cover it.  A corrupt header must therefore be a hard error in every
# mode — substituting an empty map (the old non-strict behaviour) and
# replaying the journal on top of it would silently lose all
# pre-checkpoint blocks and then overwrite the snapshot, destroying the
# evidence, exactly like vanilla PostgreSQL treats an invalid WAL record
# as FATAL in every mode.
#
# The table is written past a checkpoint before an immediate stop, so the
# journal holds records: the startup scan has to open the sidecars and
# thus trips over the corrupt header regardless of the journal size.
# ---------------------------------------------------------------------------
subtest 'corrupt .cfsmap header is fatal regardless of strict' => sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_map_hdr');
    $node->init;
    $node->append_conf('postgresql.conf', "checkpoint_timeout = 30min");
    $node->start;
 
    if (!codec_built($node, 'lz4'))
    {
        plan skip_all =>
          'LZ4 support not built, skipping CFS map-header corruption test';
    }
 
    # Fill the snapshot via CHECKPOINT, then write past it so the journal
    # holds records at the stop (the immediate stop takes no checkpoint).
    $node->safe_psql('postgres',
        "CREATE TABLE map_t (id int, payload text) WITH (algorithm = 'lz4')");
    $node->safe_psql('postgres',
            "INSERT INTO map_t SELECT g, repeat('m' || g, 80) "
          . "FROM generate_series(1, 500) g");
    $node->safe_psql('postgres', "CHECKPOINT");
    $node->safe_psql('postgres',
            "INSERT INTO map_t SELECT g, repeat('m' || g, 80) "
          . "FROM generate_series(501, 600) g");
 
    my $data_dir = $node->data_dir;
    my $rel_path =
      $node->safe_psql('postgres', "SELECT pg_relation_filepath('map_t')");
    my $cfsmap = "$data_dir/$rel_path.cfsmap";
    ok(-f $cfsmap, '.cfsmap sidecar exists for the CFS table');
 
    # Crash (no shutdown checkpoint: the journal keeps its records).
    $node->stop('immediate');
 
    # Zero the 4-byte map magic at offset 0 so the header validation fails
    # on bad magic.  Overwriting (not XOR) keeps the helper idempotent.
    {
        open my $fh, '+<:raw', $cfsmap or die "open $cfsmap: $!";
        seek($fh, 0, 0) or die "seek: $!";
        print $fh "\x00\x00\x00\x00";
        close($fh);
    }
    pass('zeroed the .cfsmap header magic');
 
    # Remember the exact bytes of the whole triple: the failed startup must
    # leave it untouched (no snapshot rewrite, no journal truncation), so
    # the corruption stays diagnosable on disk.
    my $cfsjrn = "$data_dir/$rel_path.cfsjrn";
    my $cfp = "$data_dir/$rel_path.cfp";
    my $cfsmap_before = PostgreSQL::Test::Utils::slurp_file($cfsmap);
    my $cfsjrn_before = PostgreSQL::Test::Utils::slurp_file($cfsjrn);
    my $cfp_before = PostgreSQL::Test::Utils::slurp_file($cfp);
 
    # strict = off is the default, but pin it so the assertion cannot ride
    # on a future default change (the GUC is PGC_POSTMASTER).
    $node->append_conf('postgresql.conf', "cfs_recovery_strict = off");
 
    # The server must refuse to start: the corrupt map header is a hard
    # error in every mode.
    my $log_off = -s $node->logfile;
    my $started = $node->start(fail_ok => 1);
    ok(!$started,
        'server does NOT start with a corrupt .cfsmap header (strict=off)');
 
    my ($ret, $stdout, $stderr) = $node->psql('postgres', "SELECT 1");
    isnt($ret, 0, 'connection rejected after the corrupt .cfsmap header');
 
    $node->log_check('corrupt map header is reported',
        $log_off, log_like => [qr/corrupt page map snapshot/i]);
 
    # The failed startup rewrote nothing: the corrupt header is still on
    # disk byte for byte, and no half-written snapshot temp file remains.
    is(PostgreSQL::Test::Utils::slurp_file($cfsmap),
        $cfsmap_before, '.cfsmap is left untouched by the failed startup');
    is(PostgreSQL::Test::Utils::slurp_file($cfsjrn),
        $cfsjrn_before, '.cfsjrn is left untouched by the failed startup');
    is(PostgreSQL::Test::Utils::slurp_file($cfp),
        $cfp_before, '.cfp is left untouched by the failed startup');
    ok(!-f "$cfsmap.tmp", 'no leftover .cfsmap.tmp from a snapshot rewrite');
};
 
# ---------------------------------------------------------------------------
# Corrupt sidecar headers are fatal even with an empty journal
#
# The startup scan skips relations whose journal holds only its 16-byte
# header (the clean post-checkpoint state), so their sidecars are not
# opened and the headers are not validated on the normal open path.  A
# corrupt .cfsmap/.cfsjrn header must still abort the startup scan:
# otherwise the "fatal in every mode" contract only holds for relations
# with un-checkpointed journal records, and the corruption of a clean
# relation surfaces at the first backend access (or never) instead of at
# startup.
#
# The corruption zeroes the 4-byte header magic at offset 0 of one
# sidecar at a time; the bytes are restored between scenarios so a
# single node covers both files and a final healthy start.
# ---------------------------------------------------------------------------
subtest 'corrupt sidecar headers are fatal even with an empty journal' =>
  sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_empty_jrn_hdr');
    $node->init;
    $node->append_conf('postgresql.conf', "checkpoint_timeout = 30min");
    $node->start;
 
    if (!codec_built($node, 'lz4'))
    {
        plan skip_all =>
          'LZ4 support not built, skipping CFS empty-journal header corruption test';
    }
 
    # Two CFS tables with a saved snapshot and an EMPTY journal: the
    # CHECKPOINT flushes the map snapshots and truncates the journals to
    # their bare headers, and nothing is written past it (the immediate
    # stop takes no checkpoint).
    $node->safe_psql('postgres',
            "CREATE TABLE map_empty_t (id int, payload text) "
          . "WITH (algorithm = 'lz4')");
    $node->safe_psql('postgres',
            "INSERT INTO map_empty_t SELECT g, repeat('p' || g, 80) "
          . "FROM generate_series(1, 500) g");
    $node->safe_psql('postgres',
            "CREATE TABLE jrn_empty_t (id int, payload text) "
          . "WITH (algorithm = 'lz4')");
    $node->safe_psql('postgres',
            "INSERT INTO jrn_empty_t SELECT g, repeat('q' || g, 80) "
          . "FROM generate_series(1, 500) g");
    $node->safe_psql('postgres', "CHECKPOINT");
 
    my $data_dir = $node->data_dir;
    my $map_rel =
      $node->safe_psql('postgres',
        "SELECT pg_relation_filepath('map_empty_t')");
    my $jrn_rel =
      $node->safe_psql('postgres',
        "SELECT pg_relation_filepath('jrn_empty_t')");
    my $map = "$data_dir/$map_rel.cfsmap";
    my $jrn = "$data_dir/$jrn_rel.cfsjrn";
    ok(-f $map, '.cfsmap sidecar exists for the first CFS table');
    ok(-f $jrn, '.cfsjrn sidecar exists for the second CFS table');
 
    # Crash with the journals holding only their headers.
    $node->stop('immediate');
    cmp_ok(-s $map, '>', 24, 'map snapshot is non-empty');
    cmp_ok(-s $jrn, '<=', 16, 'journal holds only its header');
 
    # strict = off is the default, but pin it (the GUC is PGC_POSTMASTER):
    # the header check must not depend on it.
    $node->append_conf('postgresql.conf', "cfs_recovery_strict = off");
 
    # Scenario A: a corrupt .cfsmap header must abort the startup.
    my $map_before = PostgreSQL::Test::Utils::slurp_file($map);
    {
        open my $fh, '+<:raw', $map or die "open $map: $!";
        seek($fh, 0, 0) or die "seek: $!";
        print $fh "\x00\x00\x00\x00";
        close($fh);
    }
    pass('zeroed the .cfsmap header magic');
 
    my $log_off = -s $node->logfile;
    my $started = $node->start(fail_ok => 1);
    ok(!$started,
        'server does NOT start with a corrupt .cfsmap header and empty journal'
    );
    $node->log_check('corrupt map header is reported at startup',
        $log_off, log_like => [qr/corrupt page map snapshot/i]);
 
    # Scenario B: restore the map, corrupt the .cfsjrn header instead.
    my $jrn_before = PostgreSQL::Test::Utils::slurp_file($jrn);
    {
        open my $fh, '+<:raw', $map or die "open $map: $!";
        seek($fh, 0, 0) or die "seek: $!";
        print $fh substr($map_before, 0, 4);
        close($fh);
    }
    {
        open my $fh, '+<:raw', $jrn or die "open $jrn: $!";
        seek($fh, 0, 0) or die "seek: $!";
        print $fh "\x00\x00\x00\x00";
        close($fh);
    }
    pass('restored the .cfsmap magic and zeroed the .cfsjrn magic');
 
    $log_off = -s $node->logfile;
    $started = $node->start(fail_ok => 1);
    ok(!$started,
        'server does NOT start with a corrupt .cfsjrn header and empty journal'
    );
    $node->log_check('corrupt journal header is reported at startup',
        $log_off, log_like => [qr/corrupt page map journal/i]);
 
    # Healthy headers must not trip the check: the same node starts.
    {
        open my $fh, '+<:raw', $jrn or die "open $jrn: $!";
        seek($fh, 0, 0) or die "seek: $!";
        print $fh substr($jrn_before, 0, 4);
        close($fh);
    }
    pass('restored the .cfsjrn magic');
 
    $started = $node->start();
    ok($started, 'server starts with valid headers and empty journals');
 
    $node->stop('fast');
  };
 
# ---------------------------------------------------------------------------
# Orphan sidecar set left by an interrupted drop
#
# Removing a CFS relation's sidecars at commit time (DROP / VACUUM FULL /
# REINDEX) walks .cfp -> .cfsmap -> .cfsjrn; a crash inside that window
# leaves a partial set on disk.  The startup scan must treat a partial set
# as an orphan of a *committed* drop: log a WARNING naming what was found,
# remove the leftovers and continue — a leftover from a legal crash must
# never abort startup (mirrors RemovePgTempFiles and vanilla's idempotent
# redo-unlink, which tolerate ENOENT instead of failing).
#
# The emulation removes only the .cfp while the server is down, which is
# byte-for-byte the state a crash between the first and second unlink
# produces.
# ---------------------------------------------------------------------------
subtest 'orphan sidecar set left by an interrupted drop' => sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_orphan');
    $node->init;
    $node->append_conf('postgresql.conf', "checkpoint_timeout = 30min");
    $node->start;
 
    if (!codec_built($node, 'lz4'))
    {
        plan skip_all =>
          'LZ4 support not built, skipping CFS orphan sidecar set test';
    }
 
    $node->safe_psql('postgres',
        "CREATE TABLE orph_t (id int, payload text) WITH (algorithm = 'lz4')"
    );
    $node->safe_psql('postgres',
            "INSERT INTO orph_t SELECT g, repeat('o' || g, 80) "
          . "FROM generate_series(1, 200) g");
    $node->safe_psql('postgres', "CHECKPOINT");
 
    my $dd = $node->data_dir;
    my $path =
      $node->safe_psql('postgres', "SELECT pg_relation_filepath('orph_t')");
    my $cfp = "$dd/$path.cfp";
    my $cfsmap = "$dd/$path.cfsmap";
    my $cfsjrn = "$dd/$path.cfsjrn";
    ok( -f $cfp && -f $cfsmap && -f $cfsjrn,
        'full sidecar set exists for the CFS table');
 
    $node->stop('fast');
 
    # Emulate the crash-inside-the-drop-window state: .cfp already gone,
    # .cfsmap and .cfsjrn still present.
    unlink($cfp);
    ok( !-f $cfp && -f $cfsmap && -f $cfsjrn,
        'partial sidecar set in place (.cfp removed)');
 
    my $log_off = -s $node->logfile;
    my $started = $node->start(fail_ok => 1);
    ok($started, 'server starts over an orphan sidecar set');
 
    $node->log_check('orphan set warning',
        $log_off, log_like => [qr/incomplete sidecar set/i]);
 
    # The leftovers are gone: the set was removed completely.
    ok( !-f $cfp && !-f $cfsmap && !-f $cfsjrn,
        'orphaned sidecar files are removed by recovery');
 
    is($node->safe_psql('postgres', "SELECT 1"),
        1, 'server fully operational after the orphan cleanup');
 
    $node->stop('fast');
};
 
# ---------------------------------------------------------------------------
# cfs_recovery_strict escalates journal record corruption
#
# The GUC promises that torn or skipped journal records are fatal in strict
# mode.  Two corruptions exercise the two record-level cases:
#
#   * skip: every journal UPDATE references .cfp data past a truncation, so
#     replay skips the records (the referenced data is missing).  Strict
#     must abort startup through the centralised corruption handler;
#     non-strict must start and log the skip WARNING.
#
#   * torn mid-file: one flipped byte in the middle of the journal body
#     breaks a record's CRC while more records follow it — unlike a torn
#     TAIL (the normal crash artifact, covered by the crash tests), data
#     exists past the damage.  Strict must abort startup; non-strict must
#     start and log the torn-record WARNING.
#
# The data itself is not asserted afterwards: the .cfp truncation of the
# skip scenario deliberately damages pre-checkpoint records, so only the
# startup behaviour and the log are pinned here.
# ---------------------------------------------------------------------------
subtest 'cfs_recovery_strict escalates journal record corruption' => sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_strict_records');
    $node->init;
    # A tiny shared_buffers forces page evictions during the second
    # INSERT, so the journal holds real UPDATE records (a page that only
    # lives in the buffer cache dies with the crash and never reaches the
    # journal — the RESIZE-only case skips nothing).
    $node->append_conf('postgresql.conf',
        "checkpoint_timeout = 30min\nshared_buffers = 128kB");
    $node->start;
 
    if (!codec_built($node, 'lz4'))
    {
        plan skip_all =>
          'LZ4 support not built, skipping CFS strict journal records test';
    }
 
    # --- skip scenario: journal records without durable .cfp data ---------
    $node->safe_psql('postgres',
        "CREATE TABLE skip_t (id int, payload text) WITH (algorithm = 'lz4')"
    );
    $node->safe_psql('postgres',
            "INSERT INTO skip_t SELECT g, repeat(md5(g::text), 50) "
          . "FROM generate_series(1, 500) g");
    $node->safe_psql('postgres', "CHECKPOINT");
    $node->safe_psql('postgres',
            "INSERT INTO skip_t SELECT g, repeat(md5(g::text), 50) "
          . "FROM generate_series(1, 700) g");
 
    my $dd = $node->data_dir;
    my $skip_path =
      $node->safe_psql('postgres', "SELECT pg_relation_filepath('skip_t')");
    my $skip_cfp = "$dd/$skip_path.cfp";
    my $skip_jrn = "$dd/$skip_path.cfsjrn";
    ok(-s $skip_cfp > 65536, '.cfp is large enough for the truncation');
 
    $node->stop('immediate');
    ok(-s $skip_jrn > 512,
        'journal holds UPDATE records from the evicted pages');
 
    # Truncate the .cfp to its bare lead-in (8 bytes): every journal UPDATE
    # now points past EOF, so replay must skip each one.
    {
        open my $fh, '+<:raw', $skip_cfp or die "open $skip_cfp: $!";
        truncate($fh, 8) or die "truncate $skip_cfp: $!";
        close($fh);
    }
    pass('truncated the .cfp below every journal-referenced offset');
 
    # Direction 1: strict = on must abort startup.
    $node->append_conf('postgresql.conf', "cfs_recovery_strict = on");
    my $log_off = -s $node->logfile;
    my $started = $node->start(fail_ok => 1);
    ok(!$started, 'strict=on: skipped journal record aborts startup');
    $node->log_check('strict=on skip escalation message',
        $log_off, log_like => [qr/checksum or format corruption/i]);
 
    # Direction 2: strict = off starts and logs the skip WARNING.
    $node->append_conf('postgresql.conf', "cfs_recovery_strict = off");
    $log_off = -s $node->logfile;
    $started = $node->start(fail_ok => 1);
    ok($started, 'strict=off: server starts over skipped journal records');
    $node->log_check('strict=off skip warning',
        $log_off, log_like => [qr/skipping journal UPDATE for block/i]);
 
    $node->stop('fast');
 
    # --- torn mid-file scenario -------------------------------------------
    $node->start;
    $node->safe_psql('postgres',
        "CREATE TABLE torn_t (id int, payload text) WITH (algorithm = 'lz4')"
    );
    $node->safe_psql('postgres',
            "INSERT INTO torn_t SELECT g, repeat(md5(g::text), 50) "
          . "FROM generate_series(1, 500) g");
    $node->safe_psql('postgres', "CHECKPOINT");
    $node->safe_psql('postgres',
            "INSERT INTO torn_t SELECT g, repeat(md5(g::text), 50) "
          . "FROM generate_series(1, 700) g");
 
    my $torn_path =
      $node->safe_psql('postgres', "SELECT pg_relation_filepath('torn_t')");
    my $torn_jrn = "$dd/$torn_path.cfsjrn";
 
    $node->stop('immediate');
    ok(-s $torn_jrn > 4096, 'journal holds many records');
 
    # Flip one byte in the middle of the journal body: the record covering
    # that offset fails its CRC while later records still follow it.
    {
        my $pos = 16 + int(((-s $torn_jrn) - 16) / 2);
        open my $fh, '+<:raw', $torn_jrn or die "open $torn_jrn: $!";
        seek($fh, $pos, 0) or die "seek: $!";
        my $b;
        read($fh, $b, 1);
        seek($fh, $pos, 0);
        print $fh chr(ord($b) ^ 0xFF);
        close($fh);
    }
    pass('flipped one byte in the middle of the journal body');
 
    # Direction 1: strict = on must abort startup.
    $node->append_conf('postgresql.conf', "cfs_recovery_strict = on");
    $log_off = -s $node->logfile;
    $started = $node->start(fail_ok => 1);
    ok(!$started, 'strict=on: mid-journal torn record aborts startup');
    $node->log_check('strict=on torn escalation message',
        $log_off, log_like => [qr/checksum or format corruption/i]);
 
    # Direction 2: strict = off starts and logs the torn WARNING.
    $node->append_conf('postgresql.conf', "cfs_recovery_strict = off");
    $log_off = -s $node->logfile;
    $started = $node->start(fail_ok => 1);
    ok($started, 'strict=off: server starts over a mid-journal torn record');
    $node->log_check('strict=off torn warning',
        $log_off, log_like => [qr/torn record/i]);
 
    $node->stop('fast');
};
 
# Flip one byte inside the payload of the journal record starting at $pos.
# The byte sits after the record's magic/op/blocknum and inside the CRC
# coverage, so the record parses but its entry_crc no longer matches.
sub flip_journal_byte
{
    my ($jrn, $pos) = @_;
 
    open my $fh, '+<:raw', $jrn or die "open $jrn: $!";
    seek($fh, $pos, 0) or die "seek: $!";
    my $b;
    read($fh, $b, 1);
    seek($fh, $pos, 0) or die "seek: $!";
    print $fh chr(ord($b) ^ 0xFF);
    close($fh);
}
 
# ---------------------------------------------------------------------------
# Mid-journal corruption aborts the checkpoint and preserves the tail
#
# A record that cannot be interpreted while valid records still follow it
# cannot come from a legal append (appends only ever happen at EOF), so it is
# corruption, not a crash artifact.  The records behind it are the only
# durable trace of their changes: folding the journal up to the damage and
# resetting would drop them for good.  The checkpoint must abort instead and
# leave the journal untouched, so a later checkpoint (after the damage is
# repaired) folds the whole valid journal.  The error is raised in the
# checkpointer, so it is asserted through the server log.
# ---------------------------------------------------------------------------
subtest 'mid-journal corruption aborts the checkpoint and keeps the tail' =>
  sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_mid_journal');
    $node->init;
 
    # Tiny shared_buffers force page evictions, so the journal holds real
    # UPDATE records (the same trick as the strict subtest above).  No shared
    # map pool: every process owns a full map.
    $node->append_conf('postgresql.conf',
            "checkpoint_timeout = 30min\nshared_buffers = 128kB\n"
          . "autovacuum = off\ncfs_map_memory = 0");
    $node->start;
 
    if (!codec_built($node, 'lz4'))
    {
        plan skip_all => 'LZ4 support not built';
    }
 
    $node->safe_psql('postgres',
        "CREATE TABLE mid_t (id int, payload text) WITH (algorithm = 'lz4')");
    $node->safe_psql('postgres',
            "INSERT INTO mid_t SELECT g, repeat(md5(g::text), 50) "
          . "FROM generate_series(1, 500) g");
    $node->safe_psql('postgres', 'CHECKPOINT');
    $node->safe_psql('postgres',
            "INSERT INTO mid_t SELECT g, repeat(md5(g::text), 50) "
          . "FROM generate_series(501, 1200) g");
 
    my $dd = $node->data_dir;
    my $path =
      $node->safe_psql('postgres', "SELECT pg_relation_filepath('mid_t')");
    my $jrn = "$dd/$path.cfsjrn";
    my $jrn_before = -s $jrn;
    ok($jrn_before > 512, 'the journal holds records to corrupt');
 
    # Corrupt the FIRST record (journal header 16 bytes + 16 into the
    # 48-byte entry): valid records still follow it, so the stop is mid-file.
    flip_journal_byte($jrn, 16 + 16);
 
    # CHECKPOINT itself only reports "checkpoint request failed" to the
    # client; the ERROR that matters is emitted by the checkpointer.
    my $log_off = -s $node->logfile;
    $node->psql('postgres', 'CHECKPOINT');
    $node->wait_for_log(qr/middle of .*\.cfsjrn/, $log_off);
    pass('the checkpoint aborts on mid-journal corruption');
    is(-s $jrn, $jrn_before,
        'the journal is not reset: the valid tail survives');
 
    # The tail must survive a restart too: startup recovery used to truncate
    # the journal at the first torn record.  Crash-restart before the repair
    # so the recovery scan sees the same mid-file stop.  WAL redo re-writes
    # the pages lost from shared_buffers and appends their journal records at
    # EOF, so the journal may grow; what matters is that recovery did not cut
    # it back to the torn offset (a truncation would leave 16 bytes).
    $node->stop('immediate');
    $node->start;
    cmp_ok(-s $jrn, '>=', $jrn_before,
        'recovery does not truncate the journal at a mid-file torn record');
 
    # Repair the byte: nothing else touched the journal, so the next
    # checkpoint must fold every record and reset the journal.
    flip_journal_byte($jrn, 16 + 16);
    $node->safe_psql('postgres', 'CHECKPOINT');
    is(-s $jrn, 16, 'the repaired journal is folded and reset');
    is($node->safe_psql('postgres', 'SELECT count(*) FROM mid_t'),
        '1200', 'no row is lost');
 
    $node->stop('fast');
  };
 
# ---------------------------------------------------------------------------
# A torn journal TAIL is still tolerated
#
# The last record of the file being uninterpretable is the normal artifact
# of a crash in the middle of an append: nothing follows it, so no valid
# record is at risk.  The checkpoint folds the records before it, drops the
# torn one with the journal reset and succeeds.
# ---------------------------------------------------------------------------
subtest 'torn journal tail does not abort the checkpoint' => sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_torn_tail');
    $node->init;
    $node->append_conf('postgresql.conf',
            "checkpoint_timeout = 30min\nshared_buffers = 128kB\n"
          . "autovacuum = off");
    $node->start;
 
    if (!codec_built($node, 'lz4'))
    {
        plan skip_all => 'LZ4 support not built';
    }
 
    $node->safe_psql('postgres',
        "CREATE TABLE tail_t (id int, payload text) WITH (algorithm = 'lz4')"
    );
    $node->safe_psql('postgres',
            "INSERT INTO tail_t SELECT g, repeat(md5(g::text), 50) "
          . "FROM generate_series(1, 500) g");
    $node->safe_psql('postgres', 'CHECKPOINT');
    $node->safe_psql('postgres',
            "INSERT INTO tail_t SELECT g, repeat(md5(g::text), 50) "
          . "FROM generate_series(501, 700) g");
 
    my $dd = $node->data_dir;
    my $path =
      $node->safe_psql('postgres', "SELECT pg_relation_filepath('tail_t')");
    my $jrn = "$dd/$path.cfsjrn";
    my $jrn_before = -s $jrn;
    ok($jrn_before > 512,
        'journal holds UPDATE records from the evicted pages');
 
    # The last record starts at (size - 48); corrupt a byte of its payload.
    flip_journal_byte($jrn, $jrn_before - 48 + 16);
 
    # A torn tail must not fail the checkpoint: safe_psql dies otherwise.
    $node->safe_psql('postgres', 'CHECKPOINT');
    is(-s $jrn, 16, 'the torn tail is dropped with the journal reset');
 
    my $count = $node->safe_psql('postgres', 'SELECT count(*) FROM tail_t');
    cmp_ok($count, '>=', 500, 'the relation is readable after the drop');
    is($node->safe_psql('postgres', 'SELECT count(*) FROM tail_t'),
        $count, 'the row set is stable across reads');
 
    $node->stop('fast');
};
 
# ---------------------------------------------------------------------------
# Recovery opens a relation's sidecars only when its journal holds records
#
# The startup scan walks the names on every start, but loading a map is
# real work; after a clean shutdown every journal is truncated to its bare
# header by the last checkpoint, so the scan must load no maps at all
# (only the sidecar headers are read for validation).
# After a crash with journal records pending, the relation is opened and
# the counter in the completion LOG reflects it.
# ---------------------------------------------------------------------------
subtest 'recovery opens sidecars only for non-empty journals' => sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_empty_jrn');
    $node->init;
    $node->append_conf('postgresql.conf', "checkpoint_timeout = 30min");
    $node->start;
 
    if (!codec_built($node, 'lz4'))
    {
        plan skip_all =>
          'LZ4 support not built, skipping CFS empty-journal scan test';
    }
 
    $node->safe_psql('postgres',
        "CREATE TABLE gate_t (id int, payload text) WITH (algorithm = 'lz4')"
    );
    $node->safe_psql('postgres',
            "INSERT INTO gate_t SELECT g, repeat('g' || g, 80) "
          . "FROM generate_series(1, 200) g");
    $node->safe_psql('postgres', "CHECKPOINT");
 
    # Clean restart: the checkpoint truncated the journal, so the scan
    # must load no relation map at all (only the headers are read).
    $node->stop('fast');
    my $log_off = -s $node->logfile;
    $node->start;
    $node->log_check('clean restart opens no journals',
        $log_off, log_like => [qr/journals opened 0/]);
 
    # Crash with journal records pending (extension RESIZE records reach
    # the journal even when the pages themselves stay in the buffer
    # cache): the relation is opened and replayed.
    $node->safe_psql('postgres',
            "INSERT INTO gate_t SELECT g, repeat('g' || g, 80) "
          . "FROM generate_series(201, 400) g");
    $node->stop('immediate');
    $log_off = -s $node->logfile;
    $node->start;
    $node->log_check('crash with pending records opens the journal',
        $log_off, log_like => [qr/journals opened [1-9]\d*/]);
 
    is($node->safe_psql('postgres', "SELECT count(*) FROM gate_t"),
        '400', 'data is intact after the crash restart');
 
    $node->stop('fast');
};
 
# The checkpointer's VmRSS, in kB, from /proc.
sub vm_rss_kb
{
    my ($pid) = @_;
    my $status = PostgreSQL::Test::Utils::slurp_file("/proc/$pid/status");
 
    die "no VmRSS in /proc/$pid/status"
      unless $status =~ /^VmRSS:\s+(\d+) kB$/m;
    return int($1);
}
 
# ---------------------------------------------------------------------------
# The checkpoint's journal fold does not leak its reader buffer
#
# cfs_journal_fold() runs in the checkpointer - a long-lived process that
# holds no per-relation memory context a reset would reclaim - so every
# allocation the fold leaves behind accumulates across checkpoints.  Its
# chunked journal reader holds a 256 KiB buffer; a missing release leaks
# one per folded relation per checkpoint.  The checkpointer's VmRSS must
# stay flat across a series of forced checkpoints, each folding at least
# one journal record.
# ---------------------------------------------------------------------------
subtest 'checkpointer does not leak the journal fold reader' => sub {
    # The measurement reads /proc; skip on platforms without it.
    plan skip_all => 'requires procfs (/proc)'
      unless -r '/proc/self/status';
 
    my $node = PostgreSQL::Test::Cluster->new('cfs_fold_leak');
    $node->init;
    $node->append_conf('postgresql.conf', "checkpoint_timeout = 30min");
    $node->start;
 
    if (!codec_built($node, 'zstd'))
    {
        plan skip_all =>
          'zstd support not built, skipping CFS fold leak test';
    }
 
    $node->safe_psql('postgres',
        "CREATE TABLE leak_t (id int, data text) WITH (algorithm = 'zstd')");
    $node->safe_psql('postgres',
            "INSERT INTO leak_t SELECT g, repeat('x', 200) "
          . "FROM generate_series(1, 50) g");
 
    # Two warmup checkpoints settle the checkpointer's one-off allocations
    # before the baseline sample is taken.
    $node->safe_psql('postgres', "CHECKPOINT");
    $node->safe_psql('postgres', "CHECKPOINT");
 
    my $ckpt_pid = $node->safe_psql('postgres',
        "SELECT pid FROM pg_stat_activity WHERE backend_type = 'checkpointer'"
    );
    my $before = vm_rss_kb($ckpt_pid);
 
    # Sixty dirty checkpoints: each flushes the updated page, appends its
    # journal record and folds the journal.  A per-round leak of 256 KiB
    # would total ~15 MB, far above the noise margin below.
    for my $i (1 .. 60)
    {
        $node->safe_psql('postgres',
            "UPDATE leak_t SET data = repeat('y', 200) WHERE id = 1");
        $node->safe_psql('postgres', "CHECKPOINT");
    }
 
    my $after = vm_rss_kb($ckpt_pid);
 
    cmp_ok($after - $before,
        '<', 6144,
        'checkpointer RSS stays flat across 60 journal-folding checkpoints');
 
    $node->stop('fast');
};
 
# ---------------------------------------------------------------------------
# Unhealed map corruption found by a no-pool backend read is an ERROR, not
# a recovery-grade WARNING
#
# cfs_map_load() used its repair_torn_tail flag as the "am I the recovery
# scan" context of cfs_report_corruption(), but non-recovery callers pass
# repair=true as well: every full-map refresh under the append lock (the
# no-pool read path, nblocks, immedsync).  With the pool off, a map row
# corrupted on disk after the session's handle was opened produced only a
# WARNING when the post-checkpoint journal reset forced the full reload,
# and the read went on to serve a zero page for the block; an immedsync
# would silently snapshot the INVALID row.  The context is a separate flag
# now: only the startup recovery scan follows cfs_recovery_strict; every
# backend path escalates through cfs_checksum_failure.
#
# The stale-handle window lives inside one explicit transaction (smgr
# handles are released at transaction end), the 6 MB table cannot stay in
# the 1 MB buffer cache (so the second scan really reads through smgr),
# and the corruption lands after the checkpoint - its own full-handle open
# must not see the damaged row.
# ---------------------------------------------------------------------------
subtest 'no-pool read reports unhealed corruption as an error' => sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_nopool_corrupt');
    $node->init;
    $node->append_conf('postgresql.conf',
            "cfs_map_memory = 0\nshared_buffers = 1MB\n"
          . "checkpoint_timeout = 30min\nautovacuum = off");
    $node->start;
 
    if (!codec_built($node, 'lz4'))
    {
        plan skip_all =>
          'LZ4 support not built, skipping CFS no-pool corruption test';
    }
 
    # ~763 pages: the INSERT itself flushes pages through the CFS write
    # path (journal records exist) and no scan can hold the table in the
    # 1 MB buffer cache.
    $node->safe_psql('postgres',
        "CREATE TABLE noc_t (id int, payload text) WITH (algorithm = 'lz4'); "
          . "INSERT INTO noc_t SELECT g, repeat('n' || g, 300) "
          . "FROM generate_series(1, 4000) g;");
 
    my $a = $node->background_psql('postgres', timeout => 120);
    $a->query_until(qr/IN_TX/,
        "BEGIN;\nSELECT count(*) FROM noc_t;\n\\echo IN_TX\n");
 
    # The checkpoint folds the journal and resets it (incarnation bumped);
    # its own full-handle open happens before the corruption, so nothing
    # notices the damaged row yet.
    $node->safe_psql('postgres', "CHECKPOINT");
 
    # Flip one byte of block 0's row (row 0 starts right after the 8-byte
    # prologue): the entry CRC no longer matches, the row reads as INVALID.
    my $dd = $node->data_dir;
    my $path =
      $node->safe_psql('postgres', "SELECT pg_relation_filepath('noc_t')");
    my $cfsmap = "$dd/$path.cfsmap";
    {
        open my $fh, '+<:raw', $cfsmap or die "open $cfsmap: $!";
        seek($fh, 8, 0) or die "seek: $!";
        my $b;
        read($fh, $b, 1);
        seek($fh, 8, 0);
        print $fh chr(ord($b) ^ 0xFF);
        close($fh);
    }
    pass('flipped one byte of block 0 map row');
 
    # The second SELECT of the still-open transaction sees the journal
    # reset and does a full reload under the append lock (repair=true):
    # block 0 fails its CRC and the bare journal holds no covering record.
    # This must be the backend ERROR policy, never the recovery WARNING.
    my $log_off = -s $node->logfile;
    $a->query_until(qr/READ_DONE/,
        "SELECT count(*) FROM noc_t;\nCOMMIT;\n\\echo READ_DONE\n");
    $node->log_check(
        'no-pool read escalates unhealed corruption',
        $log_off,
        log_like => [qr/ERROR:  CFS: checksum or format corruption/],
        log_unlike => [qr/WARNING:  CFS: checksum or format corruption/]);
 
    $a->quit;
    $node->stop('fast');
};
 
 
# The generation watermark stamped in a .cfsjrn header, from its 16 bytes:
# magic u32, version u16, incarnation u16, max_generation u32, crc u32.
sub jrn_header_max_gen
{
    my ($path) = @_;
    my $conf = $Config{byteorder};
    my $fmt =
      ($conf =~ /^(1234|4321)/ || $conf eq '12345678')
      ? 'L<S<S<L<L<'
      : 'N n n N N';
 
    open my $fh, '<:raw', $path or die "open $path: $!";
    my $n = read($fh, my $b, 16);
    close($fh);
    die "short header in $path" unless $n == 16;
    my (undef, undef, undef, $gen, undef) = unpack($fmt, $b);
    return $gen;
}
 
# ---------------------------------------------------------------------------
# The journal generation watermark never regresses
#
# The watermark is a monotonic maximum of every issued
# generation: the allocator seeds from it after a metadata-slot eviction,
# so a stamp below an already-issued generation could hand that generation
# out again and defeat the (block, generation) replay idempotency.  The
# reset raises the stamp with the header it replaces, and the in-memory
# summary seeds from the journal header, so the stamp can no longer follow
# a shrunken map down.  The deterministic drop is constructed by shrinking
# the relation to zero valid rows (delete-all + VACUUM truncates in place,
# same relfilenode): no row survives to carry the high generations.  A
# whole-table TRUNCATE would not work - it starts a fresh relfilenode with
# its own journal.
# ---------------------------------------------------------------------------
subtest 'journal generation watermark never regresses' => sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_wm_delete');
    $node->init;
    $node->append_conf('postgresql.conf',
        "checkpoint_timeout = 30min\nautovacuum = off");
    $node->start;
 
    if (!codec_built($node, 'lz4'))
    {
        plan skip_all => 'LZ4 support not built, skipping CFS watermark test';
    }
 
    # Small payloads keep every row in the main fork (no TOAST), so the
    # watermark of 'wm_t' itself covers every generation the scenario
    # issues: ~25 heap pages, generations 1..N from the insert, more from
    # the rewrites below.
    $node->safe_psql('postgres',
        "CREATE TABLE wm_t (id int, payload text) WITH (algorithm = 'lz4'); "
          . "INSERT INTO wm_t SELECT g, repeat('w', 400) "
          . "FROM generate_series(1, 300) g;");
 
    # Set hint bits / the visibility map while the whole relation is still
    # low-generation, so the later vacuum has nothing left to write on the
    # surviving pages.
    $node->safe_psql('postgres', "VACUUM wm_t;");
 
    # Rewrite rounds grow the generations of the upper half well past the
    # lower half's.
    $node->safe_psql('postgres',
        "UPDATE wm_t SET payload = repeat('x', 400) WHERE id > 150;");
    $node->safe_psql('postgres',
        "UPDATE wm_t SET payload = repeat('y', 400) WHERE id > 150;");
    $node->safe_psql('postgres', "CHECKPOINT");
 
    my $dd = $node->data_dir;
    my $path =
      $node->safe_psql('postgres', "SELECT pg_relation_filepath('wm_t')");
    my $jrn = "$dd/$path.cfsjrn";
 
    my $w1 = jrn_header_max_gen($jrn);
    cmp_ok($w1, '>', 1, 'the first checkpoint stamps a real watermark');
 
    # Shrink the relation to ZERO valid rows: delete everything and let
    # VACUUM truncate in place (same relfilenode).  The rewrite noise of
    # the delete/vacuum itself only touches rows that the truncation then
    # removes, so after it no valid row is left to carry the high
    # generations - a summary-following-the-map stamp would drop to 0.
    # (A partial delete does NOT construct that state deterministically:
    # the vacuum dirties the new boundary page, whose row then re-raises
    # the summary on its own.)
    $node->safe_psql('postgres', "DELETE FROM wm_t;");
    $node->safe_psql('postgres', "VACUUM wm_t;");
    $node->safe_psql('postgres', "CHECKPOINT");
 
    cmp_ok(jrn_header_max_gen($jrn),
        '>=', $w1, 'the watermark does not regress after the shrink');
 
    # The relation stays fully usable on top of the preserved watermark.
    $node->safe_psql('postgres',
            "INSERT INTO wm_t SELECT g, repeat('z', 400) "
          . "FROM generate_series(1, 10) g;");
    is($node->safe_psql('postgres', 'SELECT count(*) FROM wm_t'),
        '10', 'the relation accepts new rows after the shrink');
    $node->safe_psql('postgres', "CHECKPOINT");
    cmp_ok(jrn_header_max_gen($jrn),
        '>=', $w1, 'the watermark still holds after the next checkpoint');
 
    $node->stop('fast');
};
 
# Flip one byte of a map row, 'field_off' bytes into its 24-byte CfsMapEntry:
# the row keeps its non-zero content but fails its entry_crc.  The .cfsmap
# prologue is 8 bytes; inside the entry physical_offset is at 0,
# compressed_size at 8, generation at 12 and entry_crc at 16.  The default 0
# damages a role field; 16 damages only the checksum, so the row is corrupt by
# its entry_crc alone.
sub flip_map_row_byte
{
    my ($cfsmap, $blocknum, $field_off) = @_;
    my $off = 8 + $blocknum * 24 + ($field_off // 0);
 
    open my $fh, '+<:raw', $cfsmap or die "open $cfsmap: $!";
    seek($fh, $off, 0) or die "seek: $!";
    my $b;
    read($fh, $b, 1);
    seek($fh, $off, 0);
    print $fh chr(ord($b) ^ 0xFF);
    close($fh);
}
 
# ---------------------------------------------------------------------------
# A pool-served corrupt map row is an error on EVERY read
#
# A row whose entry_crc fails and that no journal record covers must never
# be served as a zero page.  The pool path used to report the corruption
# once (through a handler that throws) but left the segment published and
# journal-synced: the FIRST reader of the block got an ERROR, every
# following one silently read a zeroed page.  The segment now stays
# unpublished while it holds an unhealed row, so each read re-detects the
# corruption and fails again.
# ---------------------------------------------------------------------------
subtest 'pool read of an unhealed map row is an error, repeatedly' => sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_pool_corrupt');
    $node->init;
    $node->append_conf('postgresql.conf',
        "checkpoint_timeout = 30min\nautovacuum = off");
    $node->start;
 
    if (!codec_built($node, 'lz4'))
    {
        plan skip_all =>
          'LZ4 support not built, skipping CFS pool corruption test';
    }
 
    $node->safe_psql('postgres',
        "CREATE TABLE pl_t (id int, payload text) WITH (algorithm = 'lz4'); "
          . "INSERT INTO pl_t SELECT g, repeat('p', 400) "
          . "FROM generate_series(1, 200) g; "
          . "VACUUM pl_t;");
    $node->safe_psql('postgres', "CHECKPOINT");
 
    # The journal is empty after the checkpoint, so nothing can heal the
    # corrupted row.  Restart so the scan really reads through CFS instead
    # of the warm shared buffers (the empty journal also means recovery
    # skips this relation - the corrupt row survives the restart).
    my $dd = $node->data_dir;
    my $path =
      $node->safe_psql('postgres', "SELECT pg_relation_filepath('pl_t')");
    flip_map_row_byte("$dd/$path.cfsmap", 0);
    pass('flipped one byte of the block 0 map row');
    $node->restart;
 
    # Each read must fail: the entry point raises the checksum-failure
    # ERROR; a returning count means the block came back as a zero page.
    for my $round (1, 2)
    {
        my ($ret, $stdout, $stderr) = $node->psql('postgres',
            "SET statement_timeout = '30s'; SELECT count(*) FROM pl_t;");
        isnt($ret, 0, "read $round of the corrupted block is an error");
        like(
            $stderr // '',
            qr/checksum or format corruption/,
            "read $round reports the corruption");
    }
 
    $node->stop('fast');
};
 
# ---------------------------------------------------------------------------
# The corruption report never leaks the append lock
#
# The unhealed-corruption report of the pool path throws (ERROR/PANIC per
# cfs_checksum_failure).  It used to fire inside the reader's SHARED
# append-lock section (the pool ensure/sync of a cache miss): the longjmp
# ran past the inline release and left the lock held - every writer of the
# relation then waited on it forever.  The corruption is now returned to
# the smgr entry point as a status code instead, and the ERROR is raised
# only after the lock is released, so a writer completes even though the
# reading session - which holds no lock anymore - stays connected after
# the error.
#
# The pool is sized to exactly one segment (cfs_map_memory = 1 MB), so
# reading the second table evicts the first table's segment and forces the
# corrupted reload on the next read.
# ---------------------------------------------------------------------------
subtest 'segment corruption report does not leak the append lock' => sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_seg_leak');
    $node->init;
    $node->append_conf('postgresql.conf',
            "cfs_map_memory = 1\nshared_buffers = 1MB\n"
          . "checkpoint_timeout = 30min\nautovacuum = off");
    $node->start;
 
    if (!codec_built($node, 'lz4'))
    {
        plan skip_all =>
          'LZ4 support not built, skipping CFS segment leak test';
    }
 
    # lk_a and lk_b: ~470 blocks each, cannot stay in the 1 MB buffer
    # cache, so their scans really read through smgr and the pool - and
    # reading lk_b evicts lk_a's segment from the one-slot pool.  The
    # VACUUMs set every hint/visibility bit BEFORE the checkpoint, so the
    # later scans write nothing through CFS and cannot heal the corrupted
    # row from the journal.
    $node->safe_psql('postgres',
            "CREATE TABLE lk_a (payload text) WITH (algorithm = 'lz4'); "
          . "INSERT INTO lk_a SELECT repeat('a' || g, 300) "
          . "FROM generate_series(1, 3000) g; "
          . "CREATE TABLE lk_b (payload text) WITH (algorithm = 'lz4'); "
          . "INSERT INTO lk_b SELECT repeat('b' || g, 300) "
          . "FROM generate_series(1, 3000) g; "
          . "VACUUM lk_a; VACUUM lk_b;");
    $node->safe_psql('postgres', "CHECKPOINT");
 
    my $dd = $node->data_dir;
    my $path_a =
      $node->safe_psql('postgres', "SELECT pg_relation_filepath('lk_a')");
 
    # Load lk_a's segment, then let lk_b's read take the only pool slot.
    $node->safe_psql('postgres', "SELECT count(*) FROM lk_a");
    $node->safe_psql('postgres', "SELECT count(*) FROM lk_b");
 
    # Corrupt lk_a's block 0 row on disk (after the checkpoint, so the
    # checkpointer's own full-map open never sees it).
    flip_map_row_byte("$dd/$path_a.cfsmap", 0);
 
    # The reading session must SURVIVE its ERROR: a backend that exits
    # releases its LWLocks, and the leak would be invisible.
    my $r3 = $node->background_psql(
        'postgres',
        timeout => 120,
        on_error_stop => 0);
    my $log_off = -s $node->logfile;
    $r3->query_until(qr/READ_SENT/,
        "SELECT count(*) FROM lk_a;\n\\echo READ_SENT\n");
    $node->log_check('segment reload reports unhealed corruption',
        $log_off,
        log_like => [qr/ERROR:  CFS: checksum or format corruption/]);
 
    # The session is still alive and holds NO lock: a writer of the same
    # relation must complete.  TRUNCATE is the probe: it takes the CFS
    # append lock exclusively without reading any heap page (an INSERT
    # would consult the FSM and could touch the corrupted block for its
    # own reason).  With the leaked lock it waits past the statement
    # timeout instead.
    my ($ret, $stdout, $stderr) =
      $node->psql('postgres', "SET statement_timeout = '3s'; TRUNCATE lk_a;");
    is($ret, 0, 'a writer completes while the corrupted reader is alive');
 
    $r3->quit;
    $node->stop('fast');
};
 
 
# ---------------------------------------------------------------------------
# Recovery does not launder unhealed corruption
#
# The startup fold rewrites exactly the rows its journal records name; it
# never scans the rest of the map.  A corrupt row that no journal record
# covers therefore survives the scan byte-identically - nothing replaces
# it with a fabricated INVALID - while the covered rows around it are
# legitimately folded and the journal is reset.  The damage is not
# reported by the scan itself anymore (the scan loads no map at startup,
# QDB-1515); it surfaces one step later, when WAL redo opens the map for
# the first time and fails loudly - the server does not come up until the
# relation is repaired, the same fail-loud contract as before.
# ---------------------------------------------------------------------------
subtest 'recovery does not launder unhealed corruption' => sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_recov_launder');
    $node->init;
    $node->append_conf('postgresql.conf',
            "checkpoint_timeout = 30min\nautovacuum = off\n"
          . "shared_buffers = 1MB");
    $node->start;
 
    if (!codec_built($node, 'lz4'))
    {
        plan skip_all =>
          'LZ4 support not built, skipping CFS recovery launder test';
    }
 
    # ~470 blocks: bigger than the buffer cache, so the UPDATE below
    # flushes its pages through CFS and the journal really holds records
    # when the crash happens.
    $node->safe_psql('postgres',
            "CREATE TABLE rc_t (id int, payload text) "
          . "WITH (algorithm = 'lz4'); "
          . "INSERT INTO rc_t SELECT g, repeat('r', 400) "
          . "FROM generate_series(1, 3000) g; VACUUM rc_t;");
    $node->safe_psql('postgres', "CHECKPOINT");
 
    # Journal records for the tail blocks only: crash-relevant pages
    # flushed by a cold full scan; block 0 stays untouched.
    $node->safe_psql('postgres',
        "UPDATE rc_t SET payload = repeat('s', 400) WHERE id > 2900;");
    $node->safe_psql('postgres', "SELECT count(*) FROM rc_t");
    $node->safe_psql('postgres', "SELECT count(*) FROM rc_t");
 
    my $dd = $node->data_dir;
    my $path =
      $node->safe_psql('postgres', "SELECT pg_relation_filepath('rc_t')");
    my $jrn = "$dd/$path.cfsjrn";
    my $map = "$dd/$path.cfsmap";
    cmp_ok(-s $jrn, '>', 16, 'the journal holds flushed records');
 
    # Corrupt block 0's row (flip a byte): non-zero content, bad
    # entry_crc, and no journal record covers it.
    flip_map_row_byte($map, 0);
 
    $node->stop('immediate');
    my $row_before = substr(PostgreSQL::Test::Utils::slurp_file($map), 8, 24);
 
    # QDB-1516 made the startup size path lazy (stat(.cfsmap) + journal
    # RESIZE records, no full map open), and the WAL redo of the flushed
    # updates does not read block 0, so the unhealed damage no longer
    # aborts the start: the server comes up, the corrupt row survives
    # byte-identically, the journal folds, and the damage still refuses
    # the first read instead of being laundered or served.
    $node->stop('fast');
    ok($node->start, 'server starts with an unhealed corrupt map row');
 
    # THE regression asserts: the corrupt row was not replaced by a
    # laundered INVALID (the fold rewrites only the rows the journal
    # names), and the covered rows were folded with the journal reset -
    # the scan did its full job around the damage.
    my $row_after = substr(PostgreSQL::Test::Utils::slurp_file($map), 8, 24);
    is($row_after, $row_before,
        'the corrupt map row survived the recovery scan byte-identically');
    cmp_ok(-s $jrn, '<=', 16,
        'the covered rows were folded and the journal reset');
 
    # The latent damage still surfaces loudly at the first read of the
    # block: the read refuses to decompress through the corrupted entry.
    my ($ret2, $stdout2, $stderr2) =
      $node->psql('postgres', "SELECT count(*) FROM rc_t");
    isnt($ret2, 0, 'first read fails on the unhealed corrupt row');
    like(
        $stderr2,
        qr/checksum or format corruption .* block 0/,
        'first-read corruption error names block 0');
};
 
 
# ---------------------------------------------------------------------------
# The write path accounts no dead space between checkpoints
#
# dead_bytes is a durable checkpoint stamp: the fold counts superseded
# rows, compaction resets the counters, and nothing on the write path
# touches them.  Between two checkpoints the published value must stay
# exactly zero even while the relation is being rewritten.
# ---------------------------------------------------------------------------
subtest 'dead_bytes stays zero between checkpoints' => sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_dead_between');
    $node->init;
    $node->append_conf('postgresql.conf',
        "checkpoint_timeout = 30min\nautovacuum = off");
    $node->start;
 
    if (!codec_built($node, 'lz4'))
    {
        plan skip_all => 'LZ4 support not built, skipping CFS dead-byte test';
    }
 
    $node->safe_psql(
        'postgres', q{
        CREATE TABLE db_t (g int, payload text) WITH (algorithm = 'lz4');
        INSERT INTO db_t
            SELECT g, repeat(md5(g::text), 20)
            FROM generate_series(1, 400) g;
        CHECKPOINT;
    });
 
    is( $node->safe_psql(
            'postgres',
            "SELECT dead_bytes FROM pg_stat_cfs WHERE relname = 'db_t'"),
        '0',
        'a fresh checkpoint publishes no dead space');
 
    $node->safe_psql('postgres',
        "UPDATE db_t SET payload = repeat(md5(g::text || 'x'), 20)");
 
    is( $node->safe_psql(
            'postgres',
            "SELECT dead_bytes FROM pg_stat_cfs WHERE relname = 'db_t'"),
        '0',
        'rewrites between checkpoints account nothing');
 
    $node->safe_psql('postgres', 'CHECKPOINT');
    cmp_ok(
        $node->safe_psql(
            'postgres',
            "SELECT dead_bytes FROM pg_stat_cfs WHERE relname = 'db_t'"),
        '>', 0,
        'the checkpoint publishes the accumulated dead space');
 
    $node->stop('fast');
};
 
# ---------------------------------------------------------------------------
# Durability order with fsync=on: after a checkpoint, an immediate stop
# must not lose anything the checkpoint reported durable.
# ---------------------------------------------------------------------------
subtest 'fsync=on crash after checkpoint keeps every row' => sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_fsync_on');
    $node->init;
    $node->append_conf('postgresql.conf',
        "fsync = on\ncheckpoint_timeout = 30min\nautovacuum = off");
    $node->start;
 
    if (!codec_built($node, 'lz4'))
    {
        plan skip_all => 'LZ4 support not built, skipping CFS fsync-on test';
    }
 
    $node->safe_psql(
        'postgres', q{
        CREATE TABLE fo_t (g int, payload text) WITH (algorithm = 'lz4');
        INSERT INTO fo_t
            SELECT g, repeat(md5(g::text), 20)
            FROM generate_series(1, 300) g;
    });
    $node->safe_psql(
        'postgres',
        "UPDATE fo_t SET payload = repeat(md5(g::text || 'd'), 20)
         WHERE g % 3 = 1");
    $node->safe_psql('postgres', 'CHECKPOINT');
 
    my $expect = $node->safe_psql('postgres',
        "SELECT md5(string_agg(md5(payload), '' ORDER BY g)) FROM fo_t");
 
    $node->stop('immediate');
    $node->start;
 
    is($node->safe_psql('postgres', 'SELECT count(*) FROM fo_t'),
        '300', 'all rows survive the immediate stop');
    is( $node->safe_psql(
            'postgres',
            "SELECT md5(string_agg(md5(payload), '' ORDER BY g)) FROM fo_t"),
        $expect,
        'checkpointed payloads are byte-identical after the crash');
 
    $node->stop('fast');
};
 
 
# ---------------------------------------------------------------------------
# A partial trailing .cfsmap row is a crash artifact, not damage
#
# A torn positional pwrite can leave the map file one byte short of a whole
# row.  The loader ignores it and the next snapshot rewrites the file, so
# pg_cfs_check must report clean, not an error.
# ---------------------------------------------------------------------------
subtest 'fsck ignores a partial trailing map row' => sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_map_partial');
    $node->init;
    $node->append_conf('postgresql.conf',
        "checkpoint_timeout = 30min\nautovacuum = off");
    $node->start;
 
    if (!codec_built($node, 'lz4'))
    {
        plan skip_all =>
          'LZ4 support not built, skipping CFS partial-map-row test';
    }
 
    $node->safe_psql(
        'postgres', q{
        CREATE TABLE partial_t (g int, payload text)
            WITH (algorithm = 'lz4');
        INSERT INTO partial_t
            SELECT g, repeat(md5(g::text), 10)
            FROM generate_series(1, 200) g;
        CHECKPOINT;
    });
    my $path =
      $node->safe_psql('postgres',
        "SELECT pg_relation_filepath('partial_t')");
    my $map = $node->data_dir . "/$path.cfsmap";
 
    $node->stop('fast');
    my $size = -s $map;
    truncate($map, $size - 1) or die "truncate $map: $!";
    $node->start;
 
    my ($ok, $errors) = split qr/\|/,
      $node->safe_psql('postgres',
        "SELECT ok, errors FROM pg_cfs_check('partial_t')");
    is($ok, 't', 'pg_cfs_check stays clean after a partial map row');
    is($errors, '0', 'the partial row is not counted as an error');
 
    $node->stop('fast');
};
 
# ---------------------------------------------------------------------------
# A 1-7 byte .cfsmap is a truncated prologue, not an empty map
#
# An empty map file is legal and means "no blocks yet"; a file that is
# shorter than its 8-byte header can only be a torn write or external
# damage.  Treating it as empty would replay the journal onto a blank map
# and silently lose every pre-checkpoint block, and the next snapshot save
# would overwrite the evidence.  The file and the journal must survive the
# failed open unchanged.
#
# cfs_map_memory = 0 forces the private-map load path, so the corruption is
# hit on the open of a fresh backend, not served from a shared pool segment.
# ---------------------------------------------------------------------------
subtest 'a short page map prologue is corruption, not an empty map' => sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_short_prologue');
    $node->init;
    $node->append_conf('postgresql.conf',
        "cfs_map_memory = 0\nautovacuum = off\ncheckpoint_timeout = 30min");
    $node->start;
 
    if (!codec_built($node, 'lz4'))
    {
        plan skip_all =>
          'LZ4 support not built, skipping CFS short-prologue test';
    }
 
    $node->safe_psql('postgres',
        "CREATE TABLE sp_t (id int) WITH (algorithm = 'lz4')");
    $node->safe_psql('postgres',
        "INSERT INTO sp_t SELECT generate_series(1, 100)");
    $node->safe_psql('postgres', 'CHECKPOINT');
 
    my $path =
      $node->safe_psql('postgres', "SELECT pg_relation_filepath('sp_t')");
    my $map = $node->data_dir . "/$path.cfsmap";
    my $jrn = $node->data_dir . "/$path.cfsjrn";
    truncate($map, 4) or die "truncate $map: $!";
    my $jrn_before = -s $jrn;
 
    my ($ret, $stdout, $stderr) =
      $node->psql('postgres', 'SELECT count(*) FROM sp_t');
    isnt($ret, 0, 'opening the relation fails on a short prologue');
    like($stderr, qr/checksum or format corruption/, 'the error names the map (centralised corruption report)');
    is(-s $map, 4, 'the short file is not overwritten');
    is(-s $jrn, $jrn_before, 'the journal is not reset');
    $node->stop('fast');
};
 
# ---------------------------------------------------------------------------
# A corrupt map row covered by a journal record is healable, not damage
#
# The checkpoint fold rewrites .cfsmap rows with lock-free positional pwrites
# while the journal record covering each block is still there (the journal is
# reset only after the map fsync).  A torn row therefore loads as INVALID and
# the journal replay heals it - the engine never reports damage.  pg_cfs_check
# must reach the same verdict: a corrupt row the journal covers is healed, not
# counted in crc_failures/errors.
#
# shared_buffers = 128kB forces the UPDATE's heap pages out through CFS, so
# the journal really holds an UPDATE record for block 0 when the row is
# damaged; checkpoint_timeout = 30min keeps a fold from racing the check.
# ---------------------------------------------------------------------------
subtest 'a corrupt row covered by the journal is healable' => sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_healable');
    $node->init;
    $node->append_conf('postgresql.conf',
        "shared_buffers = 128kB\nautovacuum = off\ncheckpoint_timeout = 30min"
    );
    $node->start;
 
    if (!codec_built($node, 'lz4'))
    {
        plan skip_all =>
          'LZ4 support not built, skipping CFS healable-row test';
    }
 
    $node->safe_psql('postgres',
        "CREATE TABLE heal_t (id int, payload text) WITH (algorithm = 'lz4')"
    );
    $node->safe_psql('postgres',
            "INSERT INTO heal_t SELECT g, repeat(md5(g::text), 40) "
          . "FROM generate_series(1, 300) g");
    $node->safe_psql('postgres', 'CHECKPOINT');
 
    # Flushed UPDATE records: the journal covers block 0 while the .cfsmap
    # row still holds the post-checkpoint version.
    $node->safe_psql('postgres',
        "UPDATE heal_t SET payload = repeat('x', 40)");
 
    my $dd = $node->data_dir;
    my $path =
      $node->safe_psql('postgres', "SELECT pg_relation_filepath('heal_t')");
    my $map = "$dd/$path.cfsmap";
    my $jrn = "$dd/$path.cfsjrn";
    cmp_ok(-s $jrn, '>', 16, 'the journal holds the UPDATE records');
    flip_map_row_byte($map, 0, 16);
 
    my ($ok, $errors, $msg) = split qr/\|/,
      $node->safe_psql('postgres',
        "SELECT ok, errors, details FROM pg_cfs_check('heal_t')");
    is($ok, 't', 'a covered corrupt row is not an error');
    is($errors, '0', 'no error is counted');
    like($msg, qr/healed_entries=[1-9]/, 'the healed row is reported');
 
    # Deep mode cross-checks the map against .cfp; the healed row must not
    # leak into that verdict.
    my ($deep_ok, $deep_errors) = split qr/\|/,
      $node->safe_psql('postgres',
        "SELECT ok, errors FROM pg_cfs_check('heal_t', true)");
    is($deep_ok, 't', 'the deep check stays clean on a healed row');
    is($deep_errors, '0', 'the deep check counts no error');
 
    $node->stop('fast');
};
 
# ---------------------------------------------------------------------------
# A corrupt map row without a covering journal record is damage
#
# The checkpoint after the last write truncates the journal, so nothing can
# heal block 0: the row's data exists nowhere else.  pg_cfs_check must keep
# reporting the corruption.
# ---------------------------------------------------------------------------
subtest 'a corrupt row without a covering record is an error' => sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_uncovered');
    $node->init;
    $node->append_conf('postgresql.conf',
        "autovacuum = off\ncheckpoint_timeout = 30min");
    $node->start;
 
    if (!codec_built($node, 'lz4'))
    {
        plan skip_all =>
          'LZ4 support not built, skipping CFS uncovered-row test';
    }
 
    $node->safe_psql('postgres',
        "CREATE TABLE heal_t (id int, payload text) WITH (algorithm = 'lz4')"
    );
    $node->safe_psql('postgres',
            "INSERT INTO heal_t SELECT g, repeat(md5(g::text), 40) "
          . "FROM generate_series(1, 300) g");
    $node->safe_psql('postgres', 'CHECKPOINT');
 
    my $dd = $node->data_dir;
    my $path =
      $node->safe_psql('postgres', "SELECT pg_relation_filepath('heal_t')");
    my $map = "$dd/$path.cfsmap";
    my $jrn = "$dd/$path.cfsjrn";
    ok(-e $jrn && -s _ <= 16,
        'the journal holds no records after the checkpoint');
    flip_map_row_byte($map, 0, 16);
 
    my ($ok, $errors) = split qr/\|/,
      $node->safe_psql('postgres',
        "SELECT ok, errors FROM pg_cfs_check('heal_t')");
    is($ok, 'f', 'an uncovered corrupt row is an error');
    cmp_ok($errors, '>', 0, 'the error is counted');
 
    $node->stop('fast');
};
 
# ---------------------------------------------------------------------------
# An unreadable journal size must not let a checkpoint reset the journal.
#
# The fold boundary IS the sampled journal size: when the stat fails (the
# fstat error class), silently clamping the boundary to the bare header
# would let phase 2 reset the journal without folding it - destroying
# records that were never proven durable in the map.  The checkpoint must
# instead fail the relation (the journal is preserved; the next
# checkpoint retries), the same contract the torn-tail classification
# already upholds.
#
# The failure is injected with the injection point cfs-fail-jrn-fstat,
# placed inside cfs_state_capture().
# ---------------------------------------------------------------------------
subtest
  'a checkpoint with an unreadable journal size preserves the journal' =>
  sub {
    if ($ENV{enable_injection_points} ne 'yes')
    {
        plan skip_all => 'Injection points not supported by this build';
    }
 
    my $node = PostgreSQL::Test::Cluster->new('cfs_jrn_stat');
    $node->init;
    $node->append_conf('postgresql.conf', "autovacuum = off\n");
    $node->append_conf('postgresql.conf', "checkpoint_timeout = 30min\n");
    $node->start;
 
    if (!$node->check_extension('injection_points'))
    {
        plan skip_all => 'Extension injection_points not installed';
    }
 
    $node->safe_psql(
        'postgres', q{
        CREATE TABLE jstat_t (id int, payload text) WITH (algorithm = 'lz4');
        INSERT INTO jstat_t
            SELECT g, repeat('s' || g, 80)
            FROM generate_series(1, 500) g;
        CHECKPOINT;
    });
    $node->safe_psql('postgres',
        "UPDATE jstat_t SET payload = repeat('u' || id, 80)");
 
    my $dd = $node->data_dir;
    my $path =
      $node->safe_psql('postgres', "SELECT pg_relation_filepath('jstat_t')");
    my $jrn = "$dd/$path.cfsjrn";
    ok(-s $jrn > 16,
        'the journal holds unfolded records before the checkpoint');
 
    $node->safe_psql('postgres', 'CREATE EXTENSION injection_points');
    $node->safe_psql('postgres',
        "SELECT injection_points_attach('cfs-fail-jrn-fstat', 'notice')");
 
    # The checkpoint must refuse the relation: the ERROR unwinds the
    # checkpointer's relation loop, and the CHECKPOINT command reports
    # the failed request.  Use the non-fatal psql() so the harness keeps
    # running; the journal is what matters - the reset never ran, so
    # every record survives untouched.
    my $log_off = -s $node->logfile;
    my ($ret, $stdout, $stderr) = $node->psql('postgres', 'CHECKPOINT');
    isnt($ret, 0, 'checkpoint with an unreadable journal size fails');
    ok( $node->log_contains(
            qr/CFS: could not determine the journal size/, $log_off),
        'the checkpoint reports the unreadable journal size');
    ok(-s $jrn > 16,
        'the journal is preserved when its size cannot be proven');
 
    $node->safe_psql('postgres',
        "SELECT injection_points_detach('cfs-fail-jrn-fstat')");
    $node->safe_psql('postgres', 'CHECKPOINT');
 
    is(-s $jrn, 16, 'the retry checkpoint folds and resets the journal');
    is($node->safe_psql('postgres', 'SELECT count(*) FROM jstat_t'),
        '500', 'the data is intact');
    is( $node->safe_psql(
            'postgres', "SELECT ok FROM pg_cfs_check('jstat_t', true)"),
        't',
        'pg_cfs_check is clean after the retry');
 
    $node->stop('fast');
  };
 
# ---------------------------------------------------------------------------
# A journal header already unreadable at the capture must fail the
# checkpoint, not skip it forever.
#
# The HEADER_STALE skip arm of phase 2 describes the window "the header was
# readable at the capture and became unreadable while phase 1 ran".  A
# header already torn at the capture is not that window: the incarnation
# cannot be compared, but the journal identity (dev/ino/size) is intact,
# so every checkpoint would fold the whole growing journal, phase 2 would
# skip the reset through the stale-header arm, the dirty mark would never
# clear and the journal would grow without converging - a silent
# degradation with no report louder than DEBUG1.  The checkpoint must
# instead fail the relation (a plain ERROR, the journal preserved; the
# next checkpoint retries), matching the signal every other consumer of
# the same state already raises (replay: ERROR, verify: ERROR).
#
# The corruption is injected by flipping the first header byte (the
# magic) of the on-disk journal between checkpoints; the original header
# is restored afterwards to prove the retry converges once the damage is
# repaired.
# ---------------------------------------------------------------------------
subtest 'a checkpoint with a corrupted journal header fails loudly' => sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_jrn_hdr');
    $node->init;
    $node->append_conf('postgresql.conf', "autovacuum = off\n");
    $node->append_conf('postgresql.conf', "checkpoint_timeout = 30min\n");
    $node->start;
 
    if (!codec_built($node, 'lz4'))
    {
        plan skip_all =>
          'LZ4 support not built, skipping CFS journal header test';
    }
 
    $node->safe_psql(
        'postgres', q{
        CREATE TABLE jhdr_t (id int, payload text) WITH (algorithm = 'lz4');
        INSERT INTO jhdr_t
            SELECT g, repeat('s' || g, 80)
            FROM generate_series(1, 500) g;
        CHECKPOINT;
    });
    $node->safe_psql('postgres',
        "UPDATE jhdr_t SET payload = repeat('u' || id, 80)");
 
    my $dd = $node->data_dir;
    my $path =
      $node->safe_psql('postgres', "SELECT pg_relation_filepath('jhdr_t')");
    my $jrn = "$dd/$path.cfsjrn";
    ok(-s $jrn > 16,
        'the journal holds unfolded records before the checkpoint');
 
    # Break the header in place: flip the magic byte, keep the records.
    my $orig_hdr;
    {
        open my $fh, '+<:raw', $jrn or die "open $jrn: $!";
        seek($fh, 0, 0) or die "seek: $!";
        read($fh, $orig_hdr, 16) == 16 or die "short header read";
        seek($fh, 0, 0) or die "seek: $!";
        print $fh chr(ord(substr($orig_hdr, 0, 1)) ^ 0xFF);
        close($fh) or die "close: $!";
    }
 
    # The checkpoint must refuse the relation: phase 1 raises before any
    # reset, so the header stays broken and the journal keeps every record
    # (its size may still grow: the buffer flush of the same checkpoint
    # legitimately appends the pending page records before the CFS phase
    # runs).  Use the non-fatal psql() so the harness keeps running.
    my $log_off = -s $node->logfile;
    my ($ret, $stdout, $stderr) = $node->psql('postgres', 'CHECKPOINT');
    isnt($ret, 0, 'checkpoint over a corrupted journal header fails');
    ok( $node->log_contains(
            qr/CFS: journal .* has an unreadable header/, $log_off),
        'the checkpoint reports the unreadable journal header');
    {
        open my $fh, '<:raw', $jrn or die "open $jrn: $!";
        seek($fh, 0, 0) or die "seek: $!";
        read($fh, my $now, 16) == 16 or die "short header read";
        close($fh) or die "close: $!";
        isnt(
            ord(substr($now, 0, 1)),
            ord(substr($orig_hdr, 0, 1)),
            'the failed checkpoint did not rewrite the journal header');
    }
    ok(-s $jrn > 16, 'the journal is preserved: the reset never ran');
 
    # Repair the header: the retry must converge - fold, reset, data intact.
    {
        open my $fh, '+<:raw', $jrn or die "open $jrn: $!";
        seek($fh, 0, 0) or die "seek: $!";
        print $fh $orig_hdr;
        close($fh) or die "close: $!";
    }
    $node->safe_psql('postgres', 'CHECKPOINT');
 
    is(-s $jrn, 16, 'the retry checkpoint folds and resets the journal');
    is($node->safe_psql('postgres', 'SELECT count(*) FROM jhdr_t'),
        '500', 'the data is intact');
    is( $node->safe_psql(
            'postgres', "SELECT ok FROM pg_cfs_check('jhdr_t', true)"),
        't',
        'pg_cfs_check is clean after the retry');
 
    $node->stop('fast');
};
 
# ---------------------------------------------------------------------------
# Startup folds journals row by row and never materializes the map
#
# After a crash with journal records pending, the startup scan must fold the
# journal into the .cfsmap in place (lazy handle, row-by-row rewrites) and
# reset the journal - never load the whole map into memory (the old path,
# whose cost tracked the table) and never rewrite a full snapshot.  With
# log_min_messages = debug1 this is observable in the scan's own log slice,
# between the "recovery init starting" and "recovery init complete" LOG
# lines: the slice must carry the fold reports and neither a "map loaded:"
# full-map load nor a "saving map snapshot:" rewrite.  (Outside that slice
# WAL redo may still open a full map through a cold nblocks slot - a
# pre-existing, out-of-scope path the scan does not own.)
# ---------------------------------------------------------------------------
subtest 'startup fold does not materialize the map' => sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_startup_fold');
    $node->init;
    $node->append_conf('postgresql.conf',
            "checkpoint_timeout = 30min\n"
          . "max_wal_size = 1GB\n"
          . "log_min_messages = debug1\n"
          . "autovacuum = off\n"
          . "shared_buffers = 128kB");
    $node->start;
 
    if (!codec_built($node, 'lz4'))
    {
        plan skip_all =>
          'LZ4 support not built, skipping CFS startup-fold test';
    }
 
    # A CFS table with a flushed baseline, then writes past the checkpoint:
    # the journal holds UPDATE/RESIZE records at the crash (the tiny
    # shared_buffers forces page evictions, so real UPDATE records reach it).
    $node->safe_psql('postgres',
        "CREATE TABLE fold_t (id int, payload text) WITH (algorithm = 'lz4')"
    );
    $node->safe_psql('postgres',
            "INSERT INTO fold_t SELECT g, repeat(md5(g::text), 50) "
          . "FROM generate_series(1, 500) g");
    $node->safe_psql('postgres', "CHECKPOINT");
    $node->safe_psql('postgres',
            "INSERT INTO fold_t SELECT g, repeat(md5(g::text), 50) "
          . "FROM generate_series(501, 700) g");
 
    my $dd = $node->data_dir;
    my $path =
      $node->safe_psql('postgres', "SELECT pg_relation_filepath('fold_t')");
    my $jrn = "$dd/$path.cfsjrn";
 
    # Crash before any checkpoint folds the journal.
    $node->stop('immediate');
    cmp_ok(-s $jrn, '>', 16, 'journal holds records at the crash');
 
    my $log_off = -s $node->logfile;
    ok($node->start, 'server starts after the crash');
 
    # The fold completed: the journal is reset to its bare header and the
    # data is intact (WAL redo re-applies whatever the crash window lost).
    ok(-s $jrn < 64, 'journal is truncated back to its bare header');
    is($node->safe_psql('postgres', 'SELECT count(*) FROM fold_t'),
        '700', 'all rows survive the crash restart');
 
    # The scan's own slice: everything the recovery scan logged between its
    # starting and completion LOG lines.
    my $log = PostgreSQL::Test::Utils::slurp_file($node->logfile, $log_off);
    ok($log =~ qr/CFS: recovery init starting(.*CFS: recovery init complete[^\n]*)/s,
        'the recovery scan starting/completion lines bracket the slice');
    my $slice = $1 // '';
    like($slice, qr/folded \d+ row\(s\)/,
        'the completion LOG reports folded rows');
    like($slice, qr/row\(s\) folded into the page map/,
        'the per-relation fold is logged at DEBUG1');
 
    # THE regression asserts, scoped to the scan's slice: no private
    # full-map load (the old path logged "map loaded:" at DEBUG1) and no
    # whole-file snapshot rewrite ("saving map snapshot:").
    unlike($slice, qr/map loaded:/,
        'the scan does not materialize the page map');
    unlike($slice, qr/saving map snapshot:/,
        'the scan does not rewrite a full map snapshot');
 
    $node->stop('fast');
};
 
# ---------------------------------------------------------------------------
# Mid-file torn journal record during startup
#
# A zeroed record in the middle of the journal (valid records still follow
# it) cannot be produced by a legal append: the records behind it are the
# only durable trace of their changes, so the startup fold must stop and
# preserve the journal instead of resetting it.  Non-strict mode keeps this
# a WARNING and the server comes up (the next restart repeats the fold);
# cfs_recovery_strict = on makes the same damage fatal to startup.
#
# The corruption flips a payload byte of the SECOND record (offset
# 16 + 48 + 16; CFS_JOURNAL_HEADER_SIZE is 16, a record is 48 bytes), so
# the fold first applies record one and then stops mid-file with one row
# already written - the exact "rows folded, journal kept" window the
# next restart must complete idempotently.
# ---------------------------------------------------------------------------
subtest 'mid-file torn journal record during startup' => sub {
    my $node = PostgreSQL::Test::Cluster->new('cfs_startup_torn');
    $node->init;
    $node->append_conf('postgresql.conf',
            "checkpoint_timeout = 30min\n"
          . "autovacuum = off\n"
          . "shared_buffers = 128kB");
    $node->start;
 
    if (!codec_built($node, 'lz4'))
    {
        plan skip_all =>
          'LZ4 support not built, skipping CFS startup torn-record test';
    }
 
    # Journal with real UPDATE records past the checkpoint (the tiny
    # shared_buffers evicts the rewritten pages through CFS).
    $node->safe_psql('postgres',
        "CREATE TABLE torn2_t (id int, payload text) WITH (algorithm = 'lz4')"
    );
    $node->safe_psql('postgres',
            "INSERT INTO torn2_t SELECT g, repeat(md5(g::text), 50) "
          . "FROM generate_series(1, 500) g");
    $node->safe_psql('postgres', "CHECKPOINT");
    $node->safe_psql('postgres',
            "INSERT INTO torn2_t SELECT g, repeat(md5(g::text), 50) "
          . "FROM generate_series(501, 700) g");
 
    my $dd = $node->data_dir;
    my $path =
      $node->safe_psql('postgres',
        "SELECT pg_relation_filepath('torn2_t')");
    my $jrn = "$dd/$path.cfsjrn";
 
    $node->stop('immediate');
    my $jrn_size = -s $jrn;
    ok($jrn_size > 512, 'journal holds many records at the crash');
 
    # Flip a byte of the second record: it fails validation while the
    # records behind it stay valid, so the fold classifies the stop as
    # mid-file damage (after folding the first record's row).
    flip_journal_byte($jrn, 16 + 48 + 16);
    pass('flipped a payload byte of the second journal record');
 
    # Non-strict (default): the scan engine's torn classification reports
    # the stop as a WARNING with the "recovery" role and the server comes
    # up; the journal is NOT truncated (WAL redo appends its own records at
    # EOF, so it may have grown - what matters is that the scan did not cut
    # it back).  Reads through the still-torn journal are deliberately not
    # probed here: the map is missing every row covered by a record behind
    # the torn one, so a read may legitimately ERROR - the loud, non-silent
    # behaviour the whole contract exists for (the repair below restores
    # and verifies the data).
    my $log_off = -s $node->logfile;
    ok($node->start, 'non-strict startup survives a mid-file torn record');
    $node->log_check('non-strict torn-record warning',
        $log_off,
        log_like =>
          [qr/WARNING:  CFS: stopping journal recovery at offset \d+ \(torn record\)/]
    );
    cmp_ok(-s $jrn, '>=', $jrn_size,
        'the journal is not truncated by the non-strict startup');
 
    # Strict: the same damage must refuse the startup - the engine routes
    # the mid-file report through the recovery channel, which is fatal
    # under cfs_recovery_strict.
    $node->stop('fast');
    $node->append_conf('postgresql.conf', "cfs_recovery_strict = on");
    $log_off = -s $node->logfile;
    my $started = $node->start(fail_ok => 1);
    ok(!$started, 'strict startup aborts on a mid-file torn record');
    $node->log_check('strict torn-record failure',
        $log_off,
        log_like =>
          [qr/checksum or format corruption/, qr/torn journal record at offset/]
    );
 
    # Back to non-strict, repair the byte and converge: the next startup
    # folds every record (the original ones and those WAL redo appended at
    # the restarts above), the journal resets and all 700 rows read back.
    $node->append_conf('postgresql.conf', "cfs_recovery_strict = off");
    ok($node->start, 'non-strict startup works again once strict is off');
    $node->stop('fast');
    flip_journal_byte($jrn, 16 + 48 + 16);
    ok($node->start, 'server starts after the repair');
    is($node->safe_psql('postgres', 'SELECT count(*) FROM torn2_t'),
        '700', 'every row is back after the repair restart');
    $node->safe_psql('postgres', 'CHECKPOINT');
    is(-s $jrn, 16, 'the repaired journal is folded and reset');
 
    $node->stop('fast');
};
 
done_testing();