pointbreak 0.10.0

Durable terminal code review for changes humans and coding agents collaborate on together
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
use std::collections::BTreeMap;
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::Duration;

use heed3::types::Bytes;
use heed3::{
    CompactionOption, Database, Env, EnvFlags, EnvOpenOptions, Error as HeedError, MdbError,
};
use serde::{Deserialize, Serialize};

use super::{
    IndependentContentStoreV1, LogicalCapabilityEpochV1, QUALIFICATION_LOGICAL_KEY_MAX_BYTES_V1,
    QualificationCreateOutcome, QualificationEntry, QualificationGeneratedWorkloadV1,
    QualificationInventoryV1, QualificationJournal, QualificationPerformanceInventoryStateV1,
    QualificationPerformanceInventoryV2, QualificationProcessOverlapEvidenceV1,
    QualificationProfile, QualificationProfileDescriptorV1, QualificationRecordKindV1,
    publish_completed_backup, qualification_generated_manifest_v1, qualification_generator_spec_v1,
    qualification_operation_schedule_v1, verify_completed_backup,
};
use crate::canonical_hash::{canonical_json_bytes, sha256_bytes_hex};

pub const QUALIFICATION_LMDB_PLAIN_PROFILE_ID_V1: &str = "qualification-lmdb-plain-v1";
pub const QUALIFICATION_LMDB_SMOKE_SCHEMA_V1: &str = "pointbreak.qualification-lmdb-smoke.v1";
pub const QUALIFICATION_LMDB_LIFECYCLE_SMOKE_SCHEMA_V1: &str =
    "pointbreak.qualification-lmdb-lifecycle-smoke.v1";
pub const QUALIFICATION_LMDB_LIFECYCLE_SMOKE_MODE_V1: &str = "--lmdb-lifecycle-smoke";
pub const QUALIFICATION_LMDB_LIFECYCLE_REPORT_MODE_V1: &str = "non_timing_lifecycle_receipts";
pub const LIFECYCLE_READER_RETENTION_BOUND_BYTES_V1: u64 = 16 * MIB;
pub const LIFECYCLE_POST_RELEASE_REUSE_BOUND_BYTES_V1: u64 = 2 * MIB;

const METADATA_SCHEMA_V1: &str = "pointbreak.qualification-lmdb-plain-metadata.v1";
const DATABASE_NAME_V1: &str = "journal-v1";
const JOURNAL_DIRECTORY_V1: &str = "journal";
const CONTENT_DIRECTORY_V1: &str = "content";
const RESIZE_LOCK_FILE_V1: &str = "pointbreak-lmdb-resize-v1.lock";
const LMDB_BACKUP_RECEIPT_SCHEMA_V1: &str = "pointbreak.qualification-lmdb-backup-receipt.v1";
const LMDB_BACKUP_DATABASE_FILE_V1: &str = "journal/data.mdb";
const LMDB_BACKUP_RECEIPT_FILE_V1: &str = "pointbreak-lmdb-receipt-v1.json";
const METADATA_KEY_V1: &[u8] = b"\x00metadata-v1";
const HEAD_KEY_V1: &[u8] = b"\x00head-v1";
const ENTRY_KEY_PREFIX_V1: u8 = 1;
const ENTRY_MAGIC_V1: &[u8; 4] = b"PBLJ";
const ENTRY_VERSION_V1: u8 = 1;
const HEAD_MAGIC_V1: &[u8; 4] = b"PBHD";
const HEAD_VERSION_V1: u8 = 1;
const MIB: u64 = 1024 * 1024;
static REPAIR_STAGING_SEQUENCE: AtomicU64 = AtomicU64::new(0);

type JournalDatabase = Database<Bytes, Bytes>;

#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LmdbMapPolicyV1 {
    pub initial_size_bytes: u64,
    pub growth_increment_bytes: u64,
    pub maximum_size_bytes: u64,
    pub resize_retry_limit: u32,
}

impl Default for LmdbMapPolicyV1 {
    fn default() -> Self {
        Self {
            initial_size_bytes: 16 * MIB,
            growth_increment_bytes: 64 * MIB,
            maximum_size_bytes: 256 * MIB,
            resize_retry_limit: 4,
        }
    }
}

impl LmdbMapPolicyV1 {
    fn validate(self) -> Result<(), String> {
        if self.initial_size_bytes == 0
            || self.growth_increment_bytes == 0
            || self.maximum_size_bytes < self.initial_size_bytes
        {
            return Err("plain LMDB map policy has invalid bounds".to_owned());
        }
        for (label, value) in [
            ("initial", self.initial_size_bytes),
            ("growth", self.growth_increment_bytes),
            ("maximum", self.maximum_size_bytes),
        ] {
            if value % 65_536 != 0 {
                return Err(format!(
                    "plain LMDB {label} map size must be a multiple of 65536 bytes"
                ));
            }
        }
        Ok(())
    }

    fn next_size(self, current: u64) -> Option<u64> {
        (current < self.maximum_size_bytes).then(|| {
            current
                .saturating_add(self.growth_increment_bytes)
                .min(self.maximum_size_bytes)
        })
    }

    fn admits_size(self, size: u64) -> bool {
        size >= self.initial_size_bytes && size <= self.maximum_size_bytes
    }

    #[cfg(test)]
    fn test_resize_policy() -> Self {
        Self {
            initial_size_bytes: MIB,
            growth_increment_bytes: MIB,
            maximum_size_bytes: 8 * MIB,
            resize_retry_limit: 7,
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct LmdbProfileMetadataV1 {
    schema: String,
    profile_id: String,
    map_policy: LmdbMapPolicyV1,
}

impl LmdbProfileMetadataV1 {
    fn expected(map_policy: LmdbMapPolicyV1) -> Self {
        Self {
            schema: METADATA_SCHEMA_V1.to_owned(),
            profile_id: QUALIFICATION_LMDB_PLAIN_PROFILE_ID_V1.to_owned(),
            map_policy,
        }
    }

    fn encode(&self) -> Result<Vec<u8>, String> {
        let value = serde_json::to_value(self)
            .map_err(|error| format!("plain LMDB metadata serialization failed: {error}"))?;
        canonical_json_bytes(&value)
            .map_err(|error| format!("plain LMDB metadata canonicalization failed: {error}"))
    }

    fn decode(bytes: &[u8]) -> Result<Self, String> {
        serde_json::from_slice(bytes)
            .map_err(|error| format!("plain LMDB metadata is invalid: {error}"))
    }

    fn validate(&self, expected_policy: LmdbMapPolicyV1) -> Result<(), String> {
        if self.schema != METADATA_SCHEMA_V1 {
            return Err(format!(
                "unsupported plain LMDB metadata schema {}",
                self.schema
            ));
        }
        if self.profile_id != QUALIFICATION_LMDB_PLAIN_PROFILE_ID_V1 {
            return Err(format!(
                "stale or incompatible plain LMDB profile identity {}",
                self.profile_id
            ));
        }
        if self.map_policy != expected_policy {
            return Err("plain LMDB profile uses an incompatible fixed map policy".to_owned());
        }
        Ok(())
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct QualificationLmdbSmokeV1 {
    pub schema: &'static str,
    pub mode: &'static str,
    pub profile_id: String,
    pub map_policy: LmdbMapPolicyV1,
    pub workload: QualificationGeneratedWorkloadV1,
    pub manifest_sha256: String,
    pub records: u64,
    pub head_marker: u64,
    pub receipts_exact: bool,
}

#[derive(Debug)]
pub struct LmdbQualificationJournal {
    root: PathBuf,
    environment: Env<heed3::WithoutTls>,
    database: JournalDatabase,
    map_policy: LmdbMapPolicyV1,
    transaction_gate: Mutex<()>,
    active_pinned_readers: Arc<AtomicUsize>,
}

#[derive(Debug)]
pub struct LmdbQualificationProfile {
    descriptor: QualificationProfileDescriptorV1,
    journal: LmdbQualificationJournal,
    content: IndependentContentStoreV1,
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct LmdbExactReceiptV1 {
    pub profile_id: String,
    pub map_policy: LmdbMapPolicyV1,
    pub head_marker: u64,
    pub journal_records: u64,
    pub journal_logical_bytes: u64,
    pub journal_receipt_sha256: String,
    pub content_records: u64,
    pub content_logical_bytes: u64,
    pub content_receipt_sha256: String,
}

pub struct LmdbPinnedReaderV1 {
    transaction: Option<heed3::RoTxn<'static, heed3::WithoutTls>>,
    database: JournalDatabase,
    map_policy: LmdbMapPolicyV1,
    content: IndependentContentStoreV1,
    active_pinned_readers: Arc<AtomicUsize>,
}

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum LmdbCarrierClassV1 {
    Database,
    Lock,
    ResizeLock,
    IndependentContent,
    Copy,
    Temporary,
    Obsolete,
    Pinned,
    Repair,
    Sidecar,
}

impl LmdbCarrierClassV1 {
    pub const ALL: [Self; 10] = [
        Self::Database,
        Self::Lock,
        Self::ResizeLock,
        Self::IndependentContent,
        Self::Copy,
        Self::Temporary,
        Self::Obsolete,
        Self::Pinned,
        Self::Repair,
        Self::Sidecar,
    ];

    fn as_str(self) -> &'static str {
        match self {
            Self::Database => "database",
            Self::Lock => "lock",
            Self::ResizeLock => "resize_lock",
            Self::IndependentContent => "independent_content",
            Self::Copy => "copy",
            Self::Temporary => "temporary",
            Self::Obsolete => "obsolete",
            Self::Pinned => "pinned",
            Self::Repair => "repair",
            Self::Sidecar => "sidecar",
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct QualificationLmdbCarrierClassInventoryV1 {
    pub class: LmdbCarrierClassV1,
    pub carrier_count: u64,
    pub carrier_set_sha256: String,
    pub encoded_bytes: u64,
    pub allocated_bytes: u64,
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct QualificationLmdbSanitizedInventoryV1 {
    pub carrier_classes: Vec<LmdbCarrierClassV1>,
    pub class_inventories: Vec<QualificationLmdbCarrierClassInventoryV1>,
    pub inventory: QualificationPerformanceInventoryV2,
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct QualificationLmdbReaderLifecycleV1 {
    pub pinned_receipt: LmdbExactReceiptV1,
    pub latest_receipt: LmdbExactReceiptV1,
    pub process_overlap: QualificationProcessOverlapEvidenceV1,
    pub stale_readers_cleared: u64,
    pub live_reader_preserved: bool,
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct QualificationLmdbRetentionLifecycleV1 {
    pub steady_allocated_bytes: u64,
    pub retained_allocated_bytes: u64,
    pub reused_allocated_bytes: u64,
    pub retention_bound_bytes: u64,
    pub post_release_reuse_bound_bytes: u64,
    pub within_predeclared_bounds: bool,
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct QualificationLmdbCopyLifecycleV1 {
    pub copied_receipt: LmdbExactReceiptV1,
    pub source_before_receipt: LmdbExactReceiptV1,
    pub source_after_receipt: LmdbExactReceiptV1,
    pub exact_coherent_prefix: bool,
    pub process_overlap: QualificationProcessOverlapEvidenceV1,
    pub completion_marker_last: bool,
    pub interrupted_backup_rejected: bool,
    pub interrupted_retry_rejected: bool,
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct QualificationLmdbRestoreRepairLifecycleV1 {
    pub restored_receipt: LmdbExactReceiptV1,
    pub repaired_receipt: LmdbExactReceiptV1,
    pub backup_preserved: bool,
    pub source_preserved: bool,
    pub restore_inventory_identity_exact: bool,
    pub repair_inventory_identity_exact: bool,
    pub corrupt_truth_rejected: bool,
    pub incomplete_destination_rejected: bool,
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct QualificationLmdbInventorySnapshotV1 {
    pub state: QualificationPerformanceInventoryStateV1,
    pub inventory: QualificationPerformanceInventoryV2,
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct QualificationLmdbWindowsLifecycleV1 {
    pub required: bool,
    pub replacement_blocked_while_open: bool,
    pub replacement_succeeded_after_close: bool,
    pub reopened_exact: bool,
    pub interrupted_copy_cleaned: bool,
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct QualificationLmdbLifecycleSmokeV1 {
    pub schema: &'static str,
    pub mode: &'static str,
    pub profile_id: String,
    pub map_policy: LmdbMapPolicyV1,
    pub workload: QualificationGeneratedWorkloadV1,
    pub workload_manifest_sha256: String,
    pub reader: QualificationLmdbReaderLifecycleV1,
    pub retention: QualificationLmdbRetentionLifecycleV1,
    pub copy: QualificationLmdbCopyLifecycleV1,
    pub restore_repair: QualificationLmdbRestoreRepairLifecycleV1,
    pub inventory: QualificationLmdbSanitizedInventoryV1,
    pub inventory_snapshots: Vec<QualificationLmdbInventorySnapshotV1>,
    pub native_allocation_excludes_virtual_map: bool,
    pub windows: QualificationLmdbWindowsLifecycleV1,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct LmdbLifecycleChildRequestV1 {
    source_root: PathBuf,
    destination: Option<PathBuf>,
    barrier_root: Option<PathBuf>,
    participant: String,
    result_path: PathBuf,
    operation: LmdbLifecycleChildOperationV1,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(tag = "operation", rename_all = "snake_case")]
enum LmdbLifecycleChildOperationV1 {
    PinnedReader,
    HoldPinnedReader,
    CreateCohort { records: Vec<LmdbLifecycleRecordV1> },
    OnlineCopy,
    InterruptedCopy,
    Restore,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct LmdbLifecycleRecordV1 {
    logical_key: String,
    decoded_bytes: Vec<u8>,
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct LmdbBackupReceiptV1 {
    schema: String,
    exact: LmdbExactReceiptV1,
}

#[derive(Clone, Debug)]
struct LmdbCarrierV1 {
    class: LmdbCarrierClassV1,
    relative_path: String,
    encoded_sha256: String,
    encoded_bytes: u64,
    allocated_bytes: u64,
}

struct LmdbLifecycleInventoryRoots<'a> {
    source: &'a Path,
    backup: &'a Path,
    interrupted: &'a Path,
    restored: &'a Path,
    repair_backup: &'a Path,
    repair_restored: &'a Path,
    retention: &'a Path,
    corrupt: &'a Path,
}

struct RepairStagingDirectory {
    path: PathBuf,
}

impl RepairStagingDirectory {
    fn create(parent: &Path) -> Result<Self, String> {
        for _ in 0..64 {
            let sequence = REPAIR_STAGING_SEQUENCE.fetch_add(1, Ordering::Relaxed);
            let path = parent.join(format!(
                ".pointbreak-lmdb-repair-{}-{sequence}",
                std::process::id()
            ));
            match fs::create_dir(&path) {
                Ok(()) => return Ok(Self { path }),
                Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
                Err(error) => {
                    return Err(format!(
                        "plain LMDB repair staging creation failed: {error}"
                    ));
                }
            }
        }
        Err("plain LMDB repair could not allocate a fresh staging directory".to_owned())
    }

    fn path(&self) -> &Path {
        &self.path
    }
}

impl Drop for RepairStagingDirectory {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.path);
    }
}

impl LmdbQualificationProfile {
    pub fn open(root: &Path) -> Result<Self, String> {
        Self::open_with_policy(root, LmdbMapPolicyV1::default())
    }

    pub fn open_with_policy(root: &Path, map_policy: LmdbMapPolicyV1) -> Result<Self, String> {
        map_policy.validate()?;
        fs::create_dir_all(root)
            .map_err(|error| format!("plain LMDB profile root creation failed: {error}"))?;
        let journal_root = root.join(JOURNAL_DIRECTORY_V1);
        fs::create_dir_all(&journal_root)
            .map_err(|error| format!("plain LMDB journal root creation failed: {error}"))?;
        let map_size = usize::try_from(map_policy.initial_size_bytes)
            .map_err(|_| "plain LMDB initial map size exceeds this platform".to_owned())?;
        let mut options = EnvOpenOptions::new().read_txn_without_tls();
        options.map_size(map_size).max_dbs(1);
        // SAFETY: the profile owns this stable directory for the environment's
        // lifetime. Reopens in other processes use the same fixed policy.
        let environment = unsafe { options.open(&journal_root) }
            .map_err(|error| format!("plain LMDB environment open failed: {error}"))?;
        let database = initialize_database(&environment, map_policy)?;
        let journal = LmdbQualificationJournal {
            root: root.to_path_buf(),
            environment,
            database,
            map_policy,
            transaction_gate: Mutex::new(()),
            active_pinned_readers: Arc::new(AtomicUsize::new(0)),
        };
        journal.validate_current_map_size()?;
        let content = IndependentContentStoreV1::open(&root.join(CONTENT_DIRECTORY_V1))
            .map_err(|error| error.to_string())?;
        Ok(Self {
            descriptor: QualificationProfileDescriptorV1 {
                physical_profile_id: QUALIFICATION_LMDB_PLAIN_PROFILE_ID_V1.to_owned(),
                logical_capabilities: LogicalCapabilityEpochV1::foundation(),
            },
            journal,
            content,
        })
    }

    pub fn current_map_size_bytes(&self) -> u64 {
        self.journal.environment.info().map_size as u64
    }

    pub fn pin_reader(&self) -> Result<LmdbPinnedReaderV1, String> {
        let _gate = self.journal.gate()?;
        let transaction = self
            .journal
            .environment
            .clone()
            .static_read_txn()
            .map_err(|error| format!("plain LMDB pinned read transaction failed: {error}"))?;
        self.journal
            .active_pinned_readers
            .fetch_add(1, Ordering::SeqCst);
        Ok(LmdbPinnedReaderV1 {
            transaction: Some(transaction),
            database: self.journal.database,
            map_policy: self.journal.map_policy,
            content: self.content.clone(),
            active_pinned_readers: Arc::clone(&self.journal.active_pinned_readers),
        })
    }

    pub fn clear_stale_readers(&self) -> Result<usize, String> {
        self.journal
            .environment
            .clear_stale_readers()
            .map_err(|error| format!("plain LMDB stale reader cleanup failed: {error}"))
    }

    pub fn exact_receipt(&self) -> Result<LmdbExactReceiptV1, String> {
        let _gate = self.journal.gate()?;
        self.journal.read_transaction(|transaction| {
            exact_receipt_from_transaction(
                self.journal.database,
                transaction,
                self.journal.map_policy,
                &self.content,
            )
        })
    }

    pub fn sanitized_inventory(&self) -> Result<QualificationLmdbSanitizedInventoryV1, String> {
        let carriers = collect_active_lmdb_carriers(&self.journal.root)?;
        sanitized_inventory_from_carriers(&carriers, self.inventory()?)
    }

    pub fn repair_to(&self, destination: &Path) -> Result<(), String> {
        if destination
            .try_exists()
            .map_err(|error| format!("plain LMDB repair destination check failed: {error}"))?
        {
            return Err("plain LMDB repair destination already exists".to_owned());
        }
        let source_receipt = self.exact_receipt()?;
        let entries = self.journal.list()?;
        let parent = destination.parent().ok_or_else(|| {
            "plain LMDB repair destination must have a parent directory".to_owned()
        })?;
        fs::create_dir_all(parent)
            .map_err(|error| format!("plain LMDB repair parent creation failed: {error}"))?;
        let staging = RepairStagingDirectory::create(parent)?;
        let repaired = LmdbQualificationProfile::open(staging.path())?;
        for entry in entries {
            if repaired
                .journal()
                .create_once(&entry.logical_key, &entry.decoded_bytes)?
                != QualificationCreateOutcome::Created
            {
                return Err("plain LMDB repair replay encountered existing truth".to_owned());
            }
        }
        copy_directory_contents(self.content.root(), repaired.content.root())?;
        if repaired.exact_receipt()? != source_receipt {
            return Err("plain LMDB repaired truth receipt does not match the source".to_owned());
        }
        repaired.backup_to(destination)?;
        verify_lmdb_backup_receipt(destination, &self.descriptor, Some(&source_receipt))?;
        Ok(())
    }

    fn backup_to_with_hook(
        &self,
        destination: &Path,
        after_database_copy: impl FnOnce() -> Result<(), String>,
    ) -> Result<(), String> {
        let mut after_database_copy = Some(after_database_copy);
        publish_completed_backup(destination, &self.descriptor, |backup_root| {
            let journal_root = backup_root.join(JOURNAL_DIRECTORY_V1);
            fs::create_dir_all(&journal_root)
                .map_err(|error| format!("plain LMDB backup journal creation failed: {error}"))?;
            let database_path = backup_root.join(LMDB_BACKUP_DATABASE_FILE_V1);
            let database_file = self
                .journal
                .environment
                .copy_to_path(&database_path, CompactionOption::Disabled)
                .map_err(|error| format!("plain LMDB online copy failed: {error}"))?;
            database_file
                .sync_all()
                .map_err(|error| format!("plain LMDB online copy sync failed: {error}"))?;
            after_database_copy
                .take()
                .expect("database-copy hook is called once")()?;
            copy_directory_contents(self.content.root(), &backup_root.join(CONTENT_DIRECTORY_V1))?;
            let exact = exact_receipt_from_candidate(backup_root, self.journal.map_policy)?;
            write_canonical_new(
                &backup_root.join(LMDB_BACKUP_RECEIPT_FILE_V1),
                &LmdbBackupReceiptV1 {
                    schema: LMDB_BACKUP_RECEIPT_SCHEMA_V1.to_owned(),
                    exact,
                },
            )
        })
        .map(|_| ())
        .map_err(|error| error.to_string())
    }

    fn backup_to_after_copy_barrier(
        &self,
        destination: &Path,
        barrier_root: &Path,
        participant: &str,
    ) -> Result<(), String> {
        self.backup_to_with_hook(destination, || {
            let participant =
                super::QualificationProcessBarrierParticipantV1::join(barrier_root, participant)
                    .map_err(|error| error.to_string())?;
            participant
                .wait_for_release(std::time::Duration::from_secs(20))
                .map_err(|error| error.to_string())?;
            participant.complete().map_err(|error| error.to_string())
        })
    }
}

impl LmdbPinnedReaderV1 {
    fn transaction(&self) -> Result<&heed3::RoTxn<'static, heed3::WithoutTls>, String> {
        self.transaction
            .as_ref()
            .ok_or_else(|| "plain LMDB pinned reader is closed".to_owned())
    }

    pub fn head_marker(&self) -> Result<u64, String> {
        head_from_transaction(self.database, self.transaction()?)
    }

    pub fn exact_receipt(&self) -> Result<LmdbExactReceiptV1, String> {
        exact_receipt_from_transaction(
            self.database,
            self.transaction()?,
            self.map_policy,
            &self.content,
        )
    }
}

impl Drop for LmdbPinnedReaderV1 {
    fn drop(&mut self) {
        self.transaction.take();
        self.active_pinned_readers.fetch_sub(1, Ordering::SeqCst);
    }
}

fn initialize_database(
    environment: &Env<heed3::WithoutTls>,
    map_policy: LmdbMapPolicyV1,
) -> Result<JournalDatabase, String> {
    let mut refreshes = 0;
    loop {
        let mut transaction = match environment.write_txn() {
            Ok(transaction) => transaction,
            Err(error) if is_map_resized(&error) && refreshes < map_policy.resize_retry_limit => {
                refresh_environment_map(environment)?;
                refreshes += 1;
                continue;
            }
            Err(error) => return Err(format!("plain LMDB initialization failed: {error}")),
        };
        let database: JournalDatabase = environment
            .create_database(&mut transaction, Some(DATABASE_NAME_V1))
            .map_err(|error| format!("plain LMDB journal database open failed: {error}"))?;
        let expected = LmdbProfileMetadataV1::expected(map_policy);
        match database
            .get(&transaction, METADATA_KEY_V1)
            .map_err(|error| format!("plain LMDB metadata read failed: {error}"))?
        {
            Some(bytes) => LmdbProfileMetadataV1::decode(bytes)?.validate(map_policy)?,
            None => {
                if database.len(&transaction).map_err(|error| {
                    format!("plain LMDB initialization inspection failed: {error}")
                })? != 0
                {
                    return Err("plain LMDB journal contains entries without metadata".to_owned());
                }
                database
                    .put(&mut transaction, METADATA_KEY_V1, &expected.encode()?)
                    .map_err(|error| format!("plain LMDB metadata write failed: {error}"))?;
                database
                    .put(&mut transaction, HEAD_KEY_V1, &encode_head(0))
                    .map_err(|error| format!("plain LMDB head initialization failed: {error}"))?;
            }
        }
        let head = database
            .get(&transaction, HEAD_KEY_V1)
            .map_err(|error| format!("plain LMDB head read failed: {error}"))?
            .ok_or_else(|| "plain LMDB journal metadata omitted the head marker".to_owned())?;
        decode_head(head)?;
        transaction
            .commit()
            .map_err(|error| format!("plain LMDB initialization commit failed: {error}"))?;
        return Ok(database);
    }
}

impl LmdbQualificationJournal {
    fn gate(&self) -> Result<MutexGuard<'_, ()>, String> {
        self.transaction_gate
            .lock()
            .map_err(|_| "plain LMDB transaction gate is poisoned".to_owned())
    }

    fn validate_current_map_size(&self) -> Result<(), String> {
        let size = self.environment.info().map_size as u64;
        if !self.map_policy.admits_size(size) {
            return Err(format!(
                "plain LMDB environment map size {size} is outside the fixed policy"
            ));
        }
        Ok(())
    }

    fn refresh_map(&self) -> Result<(), String> {
        self.ensure_no_pinned_readers("refresh")?;
        with_resize_lock(&self.root, || refresh_environment_map(&self.environment))?;
        self.validate_current_map_size()
    }

    fn grow_map(&self) -> Result<(), String> {
        self.ensure_no_pinned_readers("resize")?;
        with_resize_lock(&self.root, || {
            let current = self.environment.info().map_size as u64;
            if !self.map_policy.admits_size(current) {
                return Err(format!(
                    "plain LMDB environment map size {current} is outside the fixed policy"
                ));
            }
            let Some(next) = self.map_policy.next_size(current) else {
                return Err(format!(
                    "plain LMDB map full at fixed ceiling {current} bytes"
                ));
            };
            let next = usize::try_from(next)
                .map_err(|_| "plain LMDB map ceiling exceeds this platform".to_owned())?;
            // SAFETY: every operation in this process holds transaction_gate,
            // so no local transaction is active; the file lock serializes
            // cross-process resize decisions.
            unsafe { self.environment.resize(next) }
                .map_err(|error| format!("plain LMDB map resize failed: {error}"))
        })
    }

    fn ensure_no_pinned_readers(&self, operation: &str) -> Result<(), String> {
        if self.active_pinned_readers.load(Ordering::SeqCst) != 0 {
            return Err(format!(
                "plain LMDB map {operation} is blocked by a live pinned reader"
            ));
        }
        Ok(())
    }

    fn read_transaction<T>(
        &self,
        mut operation: impl FnMut(&heed3::RoTxn<'_, heed3::WithoutTls>) -> Result<T, String>,
    ) -> Result<T, String> {
        for refresh in 0..=self.map_policy.resize_retry_limit {
            match self.environment.read_txn() {
                Ok(transaction) => return operation(&transaction),
                Err(error)
                    if is_map_resized(&error) && refresh < self.map_policy.resize_retry_limit =>
                {
                    self.refresh_map()?;
                }
                Err(error) => return Err(format!("plain LMDB read transaction failed: {error}")),
            }
        }
        Err("plain LMDB read transaction exceeded the map refresh retry limit".to_owned())
    }

    fn list_in_transaction(
        &self,
        transaction: &heed3::RoTxn<'_, heed3::WithoutTls>,
    ) -> Result<Vec<QualificationEntry>, String> {
        list_from_transaction(self.database, transaction)
    }

    fn head_in_transaction(
        &self,
        transaction: &heed3::RoTxn<'_, heed3::WithoutTls>,
    ) -> Result<u64, String> {
        head_from_transaction(self.database, transaction)
    }
}

impl QualificationJournal for LmdbQualificationJournal {
    fn create_once(
        &self,
        logical_key: &str,
        decoded_bytes: &[u8],
    ) -> Result<QualificationCreateOutcome, String> {
        validate_logical_key(logical_key)?;
        let key = encode_entry_key(logical_key);
        let envelope = encode_entry(decoded_bytes)?;
        let _gate = self.gate()?;
        let mut resizes = 0;
        let mut refreshes = 0;
        loop {
            let mut transaction = match self.environment.write_txn() {
                Ok(transaction) => transaction,
                Err(error)
                    if is_map_resized(&error) && refreshes < self.map_policy.resize_retry_limit =>
                {
                    self.refresh_map()?;
                    refreshes += 1;
                    continue;
                }
                Err(error) => return Err(format!("plain LMDB write transaction failed: {error}")),
            };
            let existing = match self.database.get(&transaction, &key) {
                Ok(existing) => existing,
                Err(error) => {
                    return Err(format!("plain LMDB existing-value read failed: {error}"));
                }
            };
            if let Some(existing) = existing {
                let existing = decode_entry(logical_key, existing)?;
                return if existing.decoded_bytes == decoded_bytes {
                    Ok(QualificationCreateOutcome::AlreadyExists)
                } else {
                    Err(format!(
                        "plain LMDB create conflict for logical key {logical_key}"
                    ))
                };
            }
            let head = self
                .database
                .get(&transaction, HEAD_KEY_V1)
                .map_err(|error| format!("plain LMDB head read failed: {error}"))?
                .ok_or_else(|| "plain LMDB head marker is missing".to_owned())?;
            let next_head = decode_head(head)?
                .checked_add(1)
                .ok_or_else(|| "plain LMDB head marker overflow".to_owned())?;
            let attempt = self
                .database
                .put(&mut transaction, &key, &envelope)
                .and_then(|()| {
                    self.database
                        .put(&mut transaction, HEAD_KEY_V1, &encode_head(next_head))
                })
                .and_then(|()| transaction.commit());
            match attempt {
                Ok(()) => return Ok(QualificationCreateOutcome::Created),
                Err(error) if is_map_full(&error) => {
                    if resizes >= self.map_policy.resize_retry_limit {
                        return Err(format!(
                            "plain LMDB map full after {resizes} bounded resize attempts"
                        ));
                    }
                    self.grow_map()?;
                    resizes += 1;
                }
                Err(error)
                    if is_map_resized(&error) && refreshes < self.map_policy.resize_retry_limit =>
                {
                    self.refresh_map()?;
                    refreshes += 1;
                }
                Err(error) if is_map_resized(&error) => {
                    return Err(format!(
                        "plain LMDB write exceeded the map refresh retry limit: {error}"
                    ));
                }
                Err(error) => return Err(format!("plain LMDB durable commit failed: {error}")),
            }
        }
    }

    fn read(&self, logical_key: &str) -> Result<Option<QualificationEntry>, String> {
        validate_logical_key(logical_key)?;
        let key = encode_entry_key(logical_key);
        let _gate = self.gate()?;
        self.read_transaction(|transaction| {
            self.database
                .get(transaction, &key)
                .map_err(|error| format!("plain LMDB keyed read failed: {error}"))?
                .map(|bytes| decode_entry(logical_key, bytes))
                .transpose()
        })
    }

    fn list(&self) -> Result<Vec<QualificationEntry>, String> {
        let _gate = self.gate()?;
        self.read_transaction(|transaction| self.list_in_transaction(transaction))
    }

    fn head_marker(&self) -> Result<u64, String> {
        let _gate = self.gate()?;
        self.read_transaction(|transaction| self.head_in_transaction(transaction))
    }

    fn integrity_check(&self) -> Result<(), String> {
        let _gate = self.gate()?;
        self.read_transaction(|transaction| {
            let entries = self.list_in_transaction(transaction)?;
            let head = self.head_in_transaction(transaction)?;
            if entries.len() as u64 != head {
                return Err(format!(
                    "plain LMDB head marker {head} does not match {} entries",
                    entries.len()
                ));
            }
            Ok(())
        })
    }
}

fn list_from_transaction(
    database: JournalDatabase,
    transaction: &heed3::RoTxn<'_, heed3::WithoutTls>,
) -> Result<Vec<QualificationEntry>, String> {
    let mut entries = Vec::new();
    let iterator = database
        .iter(transaction)
        .map_err(|error| format!("plain LMDB replay cursor failed: {error}"))?;
    for result in iterator {
        let (key, value) = result.map_err(|error| format!("plain LMDB replay failed: {error}"))?;
        if key == METADATA_KEY_V1 || key == HEAD_KEY_V1 {
            continue;
        }
        let logical_key = decode_entry_key(key)?;
        entries.push(decode_entry(&logical_key, value)?);
    }
    Ok(entries)
}

fn head_from_transaction(
    database: JournalDatabase,
    transaction: &heed3::RoTxn<'_, heed3::WithoutTls>,
) -> Result<u64, String> {
    let bytes = database
        .get(transaction, HEAD_KEY_V1)
        .map_err(|error| format!("plain LMDB head read failed: {error}"))?
        .ok_or_else(|| "plain LMDB head marker is missing".to_owned())?;
    decode_head(bytes)
}

fn exact_receipt_from_transaction(
    database: JournalDatabase,
    transaction: &heed3::RoTxn<'_, heed3::WithoutTls>,
    map_policy: LmdbMapPolicyV1,
    content: &IndependentContentStoreV1,
) -> Result<LmdbExactReceiptV1, String> {
    let metadata = database
        .get(transaction, METADATA_KEY_V1)
        .map_err(|error| format!("plain LMDB metadata read failed: {error}"))?
        .ok_or_else(|| "plain LMDB profile metadata is missing".to_owned())?;
    LmdbProfileMetadataV1::decode(metadata)?.validate(map_policy)?;
    let entries = list_from_transaction(database, transaction)?;
    let head_marker = head_from_transaction(database, transaction)?;
    if entries.len() as u64 != head_marker {
        return Err(format!(
            "plain LMDB head marker {head_marker} does not match {} entries",
            entries.len()
        ));
    }
    let content_entries = content.list().map_err(|error| error.to_string())?;
    Ok(LmdbExactReceiptV1 {
        profile_id: QUALIFICATION_LMDB_PLAIN_PROFILE_ID_V1.to_owned(),
        map_policy,
        head_marker,
        journal_records: entries.len() as u64,
        journal_logical_bytes: logical_bytes(&entries)?,
        journal_receipt_sha256: entry_set_sha256(&entries)?,
        content_records: content_entries.len() as u64,
        content_logical_bytes: logical_bytes(&content_entries)?,
        content_receipt_sha256: entry_set_sha256(&content_entries)?,
    })
}

fn logical_bytes(entries: &[QualificationEntry]) -> Result<u64, String> {
    entries.iter().try_fold(0_u64, |total, entry| {
        total
            .checked_add(entry.decoded_bytes.len() as u64)
            .ok_or_else(|| "plain LMDB receipt byte count overflow".to_owned())
    })
}

fn entry_set_sha256(entries: &[QualificationEntry]) -> Result<String, String> {
    let values = entries
        .iter()
        .map(|entry| {
            serde_json::json!({
                "logicalKey": entry.logical_key,
                "decodedSha256": entry.decoded_sha256,
                "decodedBytes": entry.decoded_bytes.len(),
            })
        })
        .collect::<Vec<_>>();
    let bytes = canonical_json_bytes(&serde_json::Value::Array(values))
        .map_err(|error| format!("plain LMDB receipt canonicalization failed: {error}"))?;
    Ok(sha256_bytes_hex(&bytes))
}

fn exact_receipt_from_candidate(
    root: &Path,
    map_policy: LmdbMapPolicyV1,
) -> Result<LmdbExactReceiptV1, String> {
    let mut options = EnvOpenOptions::new().read_txn_without_tls();
    options.max_dbs(1);
    // SAFETY: completed or in-progress candidate carriers are immutable while
    // this read-only, lock-free inspection is active.
    unsafe { options.flags(EnvFlags::READ_ONLY | EnvFlags::NO_LOCK) };
    // SAFETY: the candidate journal directory remains stable for this bounded
    // read and is not modified through this environment handle.
    let environment = unsafe { options.open(root.join(JOURNAL_DIRECTORY_V1)) }
        .map_err(|error| format!("plain LMDB backup candidate open failed: {error}"))?;
    let transaction = environment
        .read_txn()
        .map_err(|error| format!("plain LMDB backup candidate read failed: {error}"))?;
    let database: JournalDatabase = environment
        .open_database(&transaction, Some(DATABASE_NAME_V1))
        .map_err(|error| format!("plain LMDB backup database open failed: {error}"))?
        .ok_or_else(|| "plain LMDB backup omitted the journal database".to_owned())?;
    let content = IndependentContentStoreV1::open(&root.join(CONTENT_DIRECTORY_V1))
        .map_err(|error| error.to_string())?;
    exact_receipt_from_transaction(database, &transaction, map_policy, &content)
}

fn verify_lmdb_backup_receipt(
    backup_root: &Path,
    descriptor: &QualificationProfileDescriptorV1,
    expected: Option<&LmdbExactReceiptV1>,
) -> Result<LmdbExactReceiptV1, String> {
    verify_completed_backup(backup_root, descriptor).map_err(|error| error.to_string())?;
    let receipt_path = backup_root.join(LMDB_BACKUP_RECEIPT_FILE_V1);
    let receipt: LmdbBackupReceiptV1 = serde_json::from_slice(
        &fs::read(&receipt_path)
            .map_err(|error| format!("plain LMDB backup receipt read failed: {error}"))?,
    )
    .map_err(|error| format!("plain LMDB backup receipt is invalid: {error}"))?;
    if receipt.schema != LMDB_BACKUP_RECEIPT_SCHEMA_V1 {
        return Err(format!(
            "unsupported plain LMDB backup receipt schema {}",
            receipt.schema
        ));
    }
    receipt.exact.map_policy.validate()?;
    let actual = exact_receipt_from_candidate(backup_root, receipt.exact.map_policy)?;
    if actual != receipt.exact {
        return Err("plain LMDB backup receipt does not match its candidate carriers".to_owned());
    }
    if expected.is_some_and(|expected| expected != &actual) {
        return Err("plain LMDB backup receipt does not match the expected truth".to_owned());
    }
    Ok(actual)
}

pub fn restore_completed_lmdb_backup_v1(
    backup_root: &Path,
    destination: &Path,
) -> Result<LmdbExactReceiptV1, String> {
    let descriptor = QualificationProfileDescriptorV1 {
        physical_profile_id: QUALIFICATION_LMDB_PLAIN_PROFILE_ID_V1.to_owned(),
        logical_capabilities: LogicalCapabilityEpochV1::foundation(),
    };
    let expected = verify_lmdb_backup_receipt(backup_root, &descriptor, None)?;
    if destination
        .try_exists()
        .map_err(|error| format!("plain LMDB restore destination check failed: {error}"))?
    {
        return Err("plain LMDB restore destination already exists".to_owned());
    }
    fs::create_dir_all(destination.join(JOURNAL_DIRECTORY_V1))
        .map_err(|error| format!("plain LMDB restore journal creation failed: {error}"))?;
    copy_file_synced(
        &backup_root.join(LMDB_BACKUP_DATABASE_FILE_V1),
        &destination.join(LMDB_BACKUP_DATABASE_FILE_V1),
    )?;
    copy_directory_contents(
        &backup_root.join(CONTENT_DIRECTORY_V1),
        &destination.join(CONTENT_DIRECTORY_V1),
    )?;
    copy_file_synced(
        &backup_root.join(LMDB_BACKUP_RECEIPT_FILE_V1),
        &destination.join(LMDB_BACKUP_RECEIPT_FILE_V1),
    )?;
    let actual = exact_receipt_from_candidate(destination, expected.map_policy)?;
    if actual != expected {
        return Err("plain LMDB restored truth does not match the completed backup".to_owned());
    }
    Ok(actual)
}

fn write_canonical_new(path: &Path, value: &impl Serialize) -> Result<(), String> {
    let value = serde_json::to_value(value)
        .map_err(|error| format!("plain LMDB sidecar serialization failed: {error}"))?;
    let bytes = canonical_json_bytes(&value)
        .map_err(|error| format!("plain LMDB sidecar canonicalization failed: {error}"))?;
    let mut file = OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(path)
        .map_err(|error| format!("plain LMDB sidecar creation failed: {error}"))?;
    file.write_all(&bytes)
        .and_then(|()| file.sync_all())
        .map_err(|error| format!("plain LMDB sidecar write failed: {error}"))
}

fn copy_directory_contents(source: &Path, destination: &Path) -> Result<(), String> {
    fs::create_dir_all(destination)
        .map_err(|error| format!("plain LMDB copy directory creation failed: {error}"))?;
    let mut entries = fs::read_dir(source)
        .map_err(|error| format!("plain LMDB copy directory read failed: {error}"))?
        .collect::<Result<Vec<_>, _>>()
        .map_err(|error| format!("plain LMDB copy directory entry failed: {error}"))?;
    entries.sort_by_key(|entry| entry.file_name());
    for entry in entries {
        let file_type = entry
            .file_type()
            .map_err(|error| format!("plain LMDB copy carrier inspection failed: {error}"))?;
        let target = destination.join(entry.file_name());
        if file_type.is_dir() {
            copy_directory_contents(&entry.path(), &target)?;
        } else if file_type.is_file() {
            copy_file_synced(&entry.path(), &target)?;
        } else {
            return Err("plain LMDB copy rejected a non-file carrier".to_owned());
        }
    }
    Ok(())
}

fn copy_file_synced(source: &Path, destination: &Path) -> Result<(), String> {
    if destination
        .try_exists()
        .map_err(|error| format!("plain LMDB copy destination check failed: {error}"))?
    {
        return Err(format!(
            "plain LMDB copy destination already exists: {}",
            destination.display()
        ));
    }
    fs::copy(source, destination)
        .map_err(|error| format!("plain LMDB carrier copy failed: {error}"))?;
    OpenOptions::new()
        .write(true)
        .open(destination)
        .and_then(|file| file.sync_all())
        .map_err(|error| format!("plain LMDB copied carrier sync failed: {error}"))
}

fn collect_active_lmdb_carriers(root: &Path) -> Result<Vec<LmdbCarrierV1>, String> {
    let mut carriers = Vec::new();
    collect_carriers_recursive(root, root, &mut carriers, &classify_active_carrier)?;
    carriers.sort_by(|left, right| {
        left.relative_path
            .as_bytes()
            .cmp(right.relative_path.as_bytes())
    });
    Ok(carriers)
}

fn collect_carriers_recursive(
    root: &Path,
    directory: &Path,
    carriers: &mut Vec<LmdbCarrierV1>,
    classify: &impl Fn(&str) -> Result<LmdbCarrierClassV1, String>,
) -> Result<(), String> {
    let mut entries = fs::read_dir(directory)
        .map_err(|error| format!("plain LMDB inventory directory read failed: {error}"))?
        .collect::<Result<Vec<_>, _>>()
        .map_err(|error| format!("plain LMDB inventory directory entry failed: {error}"))?;
    entries.sort_by_key(|entry| entry.file_name());
    for entry in entries {
        let path = entry.path();
        let file_type = entry
            .file_type()
            .map_err(|error| format!("plain LMDB inventory carrier inspection failed: {error}"))?;
        if file_type.is_dir() {
            collect_carriers_recursive(root, &path, carriers, classify)?;
            continue;
        }
        if !file_type.is_file() {
            return Err(format!(
                "plain LMDB inventory rejected non-file carrier {}",
                path.display()
            ));
        }
        let relative_path = path
            .strip_prefix(root)
            .map_err(|_| "plain LMDB inventory carrier escaped its root".to_owned())?
            .to_string_lossy()
            .replace('\\', "/");
        let metadata = fs::metadata(&path)
            .map_err(|error| format!("plain LMDB inventory metadata read failed: {error}"))?;
        carriers.push(LmdbCarrierV1 {
            class: classify(&relative_path)?,
            relative_path,
            encoded_sha256: sha256_bytes_hex(
                &fs::read(&path).map_err(|error| {
                    format!("plain LMDB inventory carrier read failed: {error}")
                })?,
            ),
            encoded_bytes: metadata.len(),
            allocated_bytes: super::fault::native_file_allocation(&path, &metadata)?,
        });
    }
    Ok(())
}

fn classify_active_carrier(relative_path: &str) -> Result<LmdbCarrierClassV1, String> {
    match relative_path {
        "journal/data.mdb" => Ok(LmdbCarrierClassV1::Database),
        "journal/lock.mdb" => Ok(LmdbCarrierClassV1::Lock),
        RESIZE_LOCK_FILE_V1 => Ok(LmdbCarrierClassV1::ResizeLock),
        LMDB_BACKUP_RECEIPT_FILE_V1 => Ok(LmdbCarrierClassV1::Sidecar),
        path if path.starts_with("content/") => Ok(LmdbCarrierClassV1::IndependentContent),
        other => Err(format!(
            "plain LMDB inventory found an unclassified carrier {other}"
        )),
    }
}

fn inventory_from_carriers(
    carriers: &[LmdbCarrierV1],
    logical_bytes: u64,
) -> Result<QualificationInventoryV1, String> {
    if carriers.is_empty() {
        return Err("plain LMDB inventory is empty".to_owned());
    }
    let mut encoded_bytes = 0_u64;
    let mut allocated_bytes = 0_u64;
    let mut names = Vec::with_capacity(carriers.len());
    for carrier in carriers {
        encoded_bytes = encoded_bytes
            .checked_add(carrier.encoded_bytes)
            .ok_or_else(|| "plain LMDB inventory encoded byte count overflow".to_owned())?;
        allocated_bytes = allocated_bytes
            .checked_add(carrier.allocated_bytes)
            .ok_or_else(|| "plain LMDB inventory allocation byte count overflow".to_owned())?;
        names.push(format!(
            "{}:{}",
            carrier.class.as_str(),
            carrier.relative_path
        ));
    }
    names.sort_by(|left, right| left.as_bytes().cmp(right.as_bytes()));
    Ok(QualificationInventoryV1 {
        carriers: names,
        logical_bytes,
        encoded_bytes,
        allocated_bytes,
        high_water_bytes: allocated_bytes,
    })
}

fn sanitized_inventory_from_carriers(
    carriers: &[LmdbCarrierV1],
    inventory: QualificationInventoryV1,
) -> Result<QualificationLmdbSanitizedInventoryV1, String> {
    let mut by_class = BTreeMap::<LmdbCarrierClassV1, Vec<&LmdbCarrierV1>>::new();
    for carrier in carriers {
        by_class.entry(carrier.class).or_default().push(carrier);
    }
    let carrier_classes = LmdbCarrierClassV1::ALL.to_vec();
    let class_inventories = LmdbCarrierClassV1::ALL
        .into_iter()
        .map(|class| {
            let carriers = by_class.remove(&class).unwrap_or_default();
            let encoded_bytes = carriers.iter().try_fold(0_u64, |total, carrier| {
                total
                    .checked_add(carrier.encoded_bytes)
                    .ok_or_else(|| "plain LMDB class inventory byte count overflow".to_owned())
            })?;
            let allocated_bytes = carriers.iter().try_fold(0_u64, |total, carrier| {
                total
                    .checked_add(carrier.allocated_bytes)
                    .ok_or_else(|| "plain LMDB class inventory allocation overflow".to_owned())
            })?;
            let identities = carriers
                .iter()
                .map(|carrier| {
                    serde_json::json!({
                        "relativePath": carrier.relative_path,
                        "encodedSha256": carrier.encoded_sha256,
                        "encodedBytes": carrier.encoded_bytes,
                    })
                })
                .collect::<Vec<_>>();
            let identity = canonical_json_bytes(
                &serde_json::to_value(identities).map_err(|error| error.to_string())?,
            )
            .map_err(|error| error.to_string())?;
            Ok(QualificationLmdbCarrierClassInventoryV1 {
                class,
                carrier_count: carriers.len() as u64,
                carrier_set_sha256: sha256_bytes_hex(&identity),
                encoded_bytes,
                allocated_bytes,
            })
        })
        .collect::<Result<Vec<_>, String>>()?;
    Ok(QualificationLmdbSanitizedInventoryV1 {
        carrier_classes,
        class_inventories,
        inventory: QualificationPerformanceInventoryV2::from_inventory(&inventory)?,
    })
}

pub fn run_qualification_lmdb_lifecycle_child_v1(request_path: &Path) -> Result<(), String> {
    let request: LmdbLifecycleChildRequestV1 = serde_json::from_slice(
        &fs::read(request_path)
            .map_err(|error| format!("plain LMDB lifecycle child request read failed: {error}"))?,
    )
    .map_err(|error| format!("plain LMDB lifecycle child request is invalid: {error}"))?;
    match request.operation.clone() {
        LmdbLifecycleChildOperationV1::Restore => {
            let destination = request
                .destination
                .as_deref()
                .ok_or_else(|| "plain LMDB restore child omitted its destination".to_owned())?;
            let receipt = restore_completed_lmdb_backup_v1(&request.source_root, destination)?;
            let restored = LmdbQualificationProfile::open(destination)?;
            if restored.exact_receipt()? != receipt {
                return Err("plain LMDB fresh-process restore receipt drifted on open".to_owned());
            }
            write_canonical_new(&request.result_path, &receipt)
        }
        LmdbLifecycleChildOperationV1::PinnedReader
        | LmdbLifecycleChildOperationV1::HoldPinnedReader => {
            let profile = LmdbQualificationProfile::open(&request.source_root)?;
            let pinned = profile.pin_reader()?;
            let participant = join_lifecycle_participant(&request)?;
            participant.wait_for_release(Duration::from_secs(300))?;
            let receipt = pinned.exact_receipt()?;
            write_canonical_new(&request.result_path, &receipt)?;
            participant.complete()
        }
        LmdbLifecycleChildOperationV1::InterruptedCopy => {
            let profile = LmdbQualificationProfile::open(&request.source_root)?;
            profile.backup_to_after_copy_barrier(
                request
                    .destination
                    .as_deref()
                    .ok_or_else(|| "plain LMDB copy child omitted its destination".to_owned())?,
                request
                    .barrier_root
                    .as_deref()
                    .ok_or_else(|| "plain LMDB copy child omitted its barrier".to_owned())?,
                &request.participant,
            )
        }
        operation => {
            let profile = LmdbQualificationProfile::open(&request.source_root)?;
            let participant = join_lifecycle_participant(&request)?;
            participant.wait_for_release(Duration::from_secs(300))?;
            let receipt = match operation {
                LmdbLifecycleChildOperationV1::CreateCohort { records } => {
                    for record in records {
                        if profile
                            .journal()
                            .create_once(&record.logical_key, &record.decoded_bytes)?
                            != QualificationCreateOutcome::Created
                        {
                            return Err(format!(
                                "plain LMDB lifecycle writer found existing key {}",
                                record.logical_key
                            ));
                        }
                    }
                    profile.exact_receipt()?
                }
                LmdbLifecycleChildOperationV1::OnlineCopy => {
                    let destination = request.destination.as_deref().ok_or_else(|| {
                        "plain LMDB copy child omitted its destination".to_owned()
                    })?;
                    profile.backup_to(destination)?;
                    verify_lmdb_backup_receipt(destination, &profile.descriptor, None)?
                }
                _ => unreachable!("early lifecycle child operations returned above"),
            };
            write_canonical_new(&request.result_path, &receipt)?;
            participant.complete()
        }
    }
}

fn join_lifecycle_participant(
    request: &LmdbLifecycleChildRequestV1,
) -> Result<super::QualificationProcessBarrierParticipantV1, String> {
    super::QualificationProcessBarrierParticipantV1::join(
        request
            .barrier_root
            .as_deref()
            .ok_or_else(|| "plain LMDB lifecycle child omitted its barrier".to_owned())?,
        &request.participant,
    )
}

fn spawn_lmdb_lifecycle_child(
    executable: &Path,
    requests_root: &Path,
    label: &str,
    request: &LmdbLifecycleChildRequestV1,
) -> Result<Child, String> {
    fs::create_dir_all(requests_root)
        .map_err(|error| format!("plain LMDB lifecycle request root creation failed: {error}"))?;
    let request_path = requests_root.join(format!("{label}.json"));
    write_canonical_new(&request_path, request)?;
    Command::new(executable)
        .arg("--lmdb-lifecycle-child")
        .arg(request_path)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(|error| format!("failed to spawn plain LMDB lifecycle child {label}: {error}"))
}

fn read_lmdb_lifecycle_receipt(path: &Path) -> Result<LmdbExactReceiptV1, String> {
    serde_json::from_slice(
        &fs::read(path)
            .map_err(|error| format!("plain LMDB lifecycle child result read failed: {error}"))?,
    )
    .map_err(|error| format!("plain LMDB lifecycle child result is invalid: {error}"))
}

fn terminate_lmdb_lifecycle_child(child: &mut Child) -> Result<(), String> {
    child
        .kill()
        .map_err(|error| format!("plain LMDB lifecycle child termination failed: {error}"))?;
    let status = child
        .wait()
        .map_err(|error| format!("plain LMDB lifecycle child wait failed: {error}"))?;
    if status.success() {
        return Err("plain LMDB lifecycle child exited successfully before termination".to_owned());
    }
    Ok(())
}

pub fn run_qualification_lmdb_lifecycle_smoke_v1(
    executable: &Path,
    root: &Path,
) -> Result<QualificationLmdbLifecycleSmokeV1, String> {
    fs::create_dir_all(root)
        .map_err(|error| format!("plain LMDB lifecycle root creation failed: {error}"))?;
    let requests_root = root.join("orchestration").join("requests");
    let results_root = root.join("orchestration").join("results");
    fs::create_dir_all(&results_root)
        .map_err(|error| format!("plain LMDB lifecycle result root creation failed: {error}"))?;
    let source_root = root.join("source");
    let profile = LmdbQualificationProfile::open(&source_root)?;
    profile.put_content_once(
        "sha256:3000000000000000000000000000000000000000000000000000000000000000",
        QualificationRecordKindV1::ObjectArtifact,
        b"plain-lmdb-lifecycle-content",
    )?;
    let spec = qualification_generator_spec_v1(QualificationGeneratedWorkloadV1::G0);
    let manifest = qualification_generated_manifest_v1(&spec).map_err(|error| error.to_string())?;
    let split = manifest.records.len() / 2;
    for record in &manifest.records[..split] {
        if profile
            .journal()
            .create_once(&record.logical_key, &record.decoded_bytes)?
            != QualificationCreateOutcome::Created
        {
            return Err("plain LMDB lifecycle seed cohort was not created once".to_owned());
        }
    }

    let reader_barrier_root = root.join("orchestration").join("reader-barrier");
    fs::create_dir_all(&reader_barrier_root)
        .map_err(|error| format!("plain LMDB reader barrier root creation failed: {error}"))?;
    let reader_barrier = super::QualificationProcessBarrierV1::create(
        &reader_barrier_root,
        &["pinned-reader", "later-writer"],
    )?;
    let pinned_result = results_root.join("pinned-reader.json");
    let writer_result = results_root.join("later-writer.json");
    let mut pinned_child = spawn_lmdb_lifecycle_child(
        executable,
        &requests_root,
        "pinned-reader",
        &LmdbLifecycleChildRequestV1 {
            source_root: source_root.clone(),
            destination: None,
            barrier_root: Some(reader_barrier_root.clone()),
            participant: "pinned-reader".to_owned(),
            result_path: pinned_result.clone(),
            operation: LmdbLifecycleChildOperationV1::PinnedReader,
        },
    )?;
    let mut writer_child = spawn_lmdb_lifecycle_child(
        executable,
        &requests_root,
        "later-writer",
        &LmdbLifecycleChildRequestV1 {
            source_root: source_root.clone(),
            destination: None,
            barrier_root: Some(reader_barrier_root.clone()),
            participant: "later-writer".to_owned(),
            result_path: writer_result,
            operation: LmdbLifecycleChildOperationV1::CreateCohort {
                records: manifest.records[split..]
                    .iter()
                    .map(|record| LmdbLifecycleRecordV1 {
                        logical_key: record.logical_key.clone(),
                        decoded_bytes: record.decoded_bytes.clone(),
                    })
                    .collect(),
            },
        },
    )?;
    reader_barrier.wait_until_ready(Duration::from_secs(30))?;
    reader_barrier.release()?;
    super::fault::wait_child(&mut pinned_child, Duration::from_secs(60))?;
    super::fault::wait_child(&mut writer_child, Duration::from_secs(60))?;
    let reader_overlap = reader_barrier.evidence()?;
    let pinned_receipt = read_lmdb_lifecycle_receipt(&pinned_result)?;
    let latest_receipt = profile.exact_receipt()?;
    if pinned_receipt.head_marker != split as u64
        || latest_receipt.head_marker != manifest.records.len() as u64
        || pinned_receipt == latest_receipt
    {
        return Err(
            "plain LMDB pinned-reader lifecycle receipts are not stable and current".to_owned(),
        );
    }

    let retention_root = root.join("retention");
    let retention_profile = LmdbQualificationProfile::open(&retention_root)?;
    populate_lifecycle_range(&retention_profile, "seed", 0..32, 512)?;
    let steady_allocated_bytes = retention_profile.inventory()?.allocated_bytes;
    let retained_reader = retention_profile.pin_reader()?;
    populate_lifecycle_range(&retention_profile, "retained", 0..128, 4096)?;
    let retained_allocated_bytes = retention_profile.inventory()?.allocated_bytes;
    drop(retained_reader);
    populate_lifecycle_range(&retention_profile, "reuse", 0..128, 512)?;
    let reused_allocated_bytes = retention_profile.inventory()?.allocated_bytes;
    let within_predeclared_bounds = reused_allocated_bytes
        <= LIFECYCLE_READER_RETENTION_BOUND_BYTES_V1
        && reused_allocated_bytes.saturating_sub(retained_allocated_bytes)
            <= LIFECYCLE_POST_RELEASE_REUSE_BOUND_BYTES_V1;
    if !within_predeclared_bounds {
        return Err(format!(
            "plain LMDB reader retention exceeded its predeclared native-allocation bounds: steady={steady_allocated_bytes}, retained={retained_allocated_bytes}, reused={reused_allocated_bytes}"
        ));
    }

    let live_reader = profile.pin_reader()?;
    let live_receipt = live_reader.exact_receipt()?;
    let stale_barrier_root = root.join("orchestration").join("stale-reader-barrier");
    fs::create_dir_all(&stale_barrier_root)
        .map_err(|error| format!("plain LMDB stale-reader barrier creation failed: {error}"))?;
    let stale_barrier =
        super::QualificationProcessBarrierV1::create(&stale_barrier_root, &["stale-reader"])?;
    let mut stale_child = spawn_lmdb_lifecycle_child(
        executable,
        &requests_root,
        "stale-reader",
        &LmdbLifecycleChildRequestV1 {
            source_root: source_root.clone(),
            destination: None,
            barrier_root: Some(stale_barrier_root),
            participant: "stale-reader".to_owned(),
            result_path: results_root.join("stale-reader.json"),
            operation: LmdbLifecycleChildOperationV1::HoldPinnedReader,
        },
    )?;
    stale_barrier.wait_until_ready(Duration::from_secs(30))?;
    terminate_lmdb_lifecycle_child(&mut stale_child)?;
    let stale_readers_cleared = profile.clear_stale_readers()? as u64;
    drop(stale_child);
    let live_reader_preserved = live_reader.exact_receipt()? == live_receipt;
    drop(live_reader);
    if stale_readers_cleared == 0 || !live_reader_preserved || profile.clear_stale_readers()? != 0 {
        return Err("plain LMDB stale-reader cleanup did not preserve the live reader".to_owned());
    }

    let copy_before = profile.exact_receipt()?;
    let copy_barrier_root = root.join("orchestration").join("copy-barrier");
    fs::create_dir_all(&copy_barrier_root)
        .map_err(|error| format!("plain LMDB copy barrier root creation failed: {error}"))?;
    let copy_barrier = super::QualificationProcessBarrierV1::create(
        &copy_barrier_root,
        &["online-copy", "copy-writer"],
    )?;
    let backup_root = root.join("backup");
    let copy_result = results_root.join("online-copy.json");
    let mut copy_child = spawn_lmdb_lifecycle_child(
        executable,
        &requests_root,
        "online-copy",
        &LmdbLifecycleChildRequestV1 {
            source_root: source_root.clone(),
            destination: Some(backup_root.clone()),
            barrier_root: Some(copy_barrier_root.clone()),
            participant: "online-copy".to_owned(),
            result_path: copy_result.clone(),
            operation: LmdbLifecycleChildOperationV1::OnlineCopy,
        },
    )?;
    let mut copy_writer_child = spawn_lmdb_lifecycle_child(
        executable,
        &requests_root,
        "copy-writer",
        &LmdbLifecycleChildRequestV1 {
            source_root: source_root.clone(),
            destination: None,
            barrier_root: Some(copy_barrier_root),
            participant: "copy-writer".to_owned(),
            result_path: results_root.join("copy-writer.json"),
            operation: LmdbLifecycleChildOperationV1::CreateCohort {
                records: vec![LmdbLifecycleRecordV1 {
                    logical_key: "journal/lifecycle-copy-writer".to_owned(),
                    decoded_bytes: b"later-writer-cohort".to_vec(),
                }],
            },
        },
    )?;
    copy_barrier.wait_until_ready(Duration::from_secs(30))?;
    copy_barrier.release()?;
    super::fault::wait_child(&mut copy_child, Duration::from_secs(60))?;
    super::fault::wait_child(&mut copy_writer_child, Duration::from_secs(60))?;
    let copy_overlap = copy_barrier.evidence()?;
    let copied_receipt = read_lmdb_lifecycle_receipt(&copy_result)?;
    let copy_after = profile.exact_receipt()?;
    let exact_coherent_prefix = copied_receipt == copy_before || copied_receipt == copy_after;
    if !exact_coherent_prefix {
        return Err("plain LMDB online copy is not an exact coherent cohort prefix".to_owned());
    }
    let completed_manifest = verify_completed_backup(&backup_root, &profile.descriptor)
        .map_err(|error| error.to_string())?;
    let completion_marker_last = backup_root.join(super::BACKUP_COMPLETION_FILE_V1).is_file()
        && backup_root.join(super::BACKUP_MANIFEST_FILE_V1).is_file()
        && !completed_manifest.carriers.iter().any(|carrier| {
            carrier.relative_path == super::BACKUP_COMPLETION_FILE_V1
                || carrier.relative_path == super::BACKUP_MANIFEST_FILE_V1
        });
    if !completion_marker_last {
        return Err("plain LMDB completion marker publication order is invalid".to_owned());
    }

    let interrupted_root = root.join("interrupted");
    let interrupted_barrier_root = root.join("orchestration").join("interrupted-barrier");
    fs::create_dir_all(&interrupted_barrier_root).map_err(|error| {
        format!("plain LMDB interrupted-copy barrier root creation failed: {error}")
    })?;
    let interrupted_barrier =
        super::QualificationProcessBarrierV1::create(&interrupted_barrier_root, &["copy"])?;
    let mut interrupted_child = spawn_lmdb_lifecycle_child(
        executable,
        &requests_root,
        "interrupted-copy",
        &LmdbLifecycleChildRequestV1 {
            source_root: source_root.clone(),
            destination: Some(interrupted_root.clone()),
            barrier_root: Some(interrupted_barrier_root),
            participant: "copy".to_owned(),
            result_path: results_root.join("interrupted-copy.json"),
            operation: LmdbLifecycleChildOperationV1::InterruptedCopy,
        },
    )?;
    interrupted_barrier.wait_until_ready(Duration::from_secs(30))?;
    terminate_lmdb_lifecycle_child(&mut interrupted_child)?;
    let interrupted_backup_rejected =
        verify_completed_backup(&interrupted_root, &profile.descriptor).is_err();
    let interrupted_retry_rejected = profile.backup_to(&interrupted_root).is_err();
    if !interrupted_backup_rejected || !interrupted_retry_rejected {
        return Err("plain LMDB interrupted backup was reinterpreted as complete".to_owned());
    }

    let backup_before_restore = tree_carrier_receipt(&backup_root, false)?;
    let restored_root = root.join("restored");
    let restored_result = results_root.join("restored.json");
    let mut restore_child = spawn_lmdb_lifecycle_child(
        executable,
        &requests_root,
        "fresh-restore",
        &LmdbLifecycleChildRequestV1 {
            source_root: backup_root.clone(),
            destination: Some(restored_root.clone()),
            barrier_root: None,
            participant: "restore".to_owned(),
            result_path: restored_result.clone(),
            operation: LmdbLifecycleChildOperationV1::Restore,
        },
    )?;
    super::fault::wait_child(&mut restore_child, Duration::from_secs(60))?;
    let restored_receipt = read_lmdb_lifecycle_receipt(&restored_result)?;
    let backup_preserved = tree_carrier_receipt(&backup_root, false)? == backup_before_restore;
    let restore_inventory_identity_exact =
        truth_carrier_identity(&backup_root)? == truth_carrier_identity(&restored_root)?;
    if restored_receipt != copied_receipt || !backup_preserved || !restore_inventory_identity_exact
    {
        return Err("plain LMDB fresh-process restore was not exact and read-only".to_owned());
    }

    with_resize_lock(&source_root, || Ok(()))?;
    let source_before_repair = tree_carrier_receipt(&source_root, true)?;
    let repair_backup_root = root.join("repair-backup");
    profile.repair_to(&repair_backup_root)?;
    let source_preserved = tree_carrier_receipt(&source_root, true)? == source_before_repair;
    let repair_root = root.join("repair-restored");
    let repaired_receipt = restore_completed_lmdb_backup_v1(&repair_backup_root, &repair_root)?;
    let repair_inventory_identity_exact =
        truth_carrier_identity(&repair_backup_root)? == truth_carrier_identity(&repair_root)?;
    if repaired_receipt != copy_after || !source_preserved || !repair_inventory_identity_exact {
        return Err("plain LMDB fresh-copy repair did not preserve exact source truth".to_owned());
    }
    let corrupt_root = root.join("corrupt-source");
    fs::create_dir_all(corrupt_root.join(JOURNAL_DIRECTORY_V1))
        .map_err(|error| format!("plain LMDB corrupt fixture creation failed: {error}"))?;
    copy_file_synced(
        &backup_root.join(LMDB_BACKUP_DATABASE_FILE_V1),
        &corrupt_root.join(JOURNAL_DIRECTORY_V1).join("data.mdb"),
    )?;
    OpenOptions::new()
        .write(true)
        .open(corrupt_root.join(JOURNAL_DIRECTORY_V1).join("data.mdb"))
        .and_then(|file| file.set_len(1024))
        .map_err(|error| format!("plain LMDB corrupt fixture truncation failed: {error}"))?;
    let corrupt_truth_rejected = LmdbQualificationProfile::open(&corrupt_root).is_err();
    let incomplete_repair_root = root.join("incomplete-repair");
    fs::create_dir(&incomplete_repair_root)
        .map_err(|error| format!("plain LMDB incomplete repair fixture failed: {error}"))?;
    let incomplete_destination_rejected = profile.repair_to(&incomplete_repair_root).is_err();
    if !corrupt_truth_rejected || !incomplete_destination_rejected {
        return Err(
            "plain LMDB repair admitted corrupt truth or an incomplete destination".to_owned(),
        );
    }

    let source_inventory = profile.inventory()?;
    let steady_inventory = QualificationPerformanceInventoryV2::from_inventory(&source_inventory)?;
    let native_allocation_excludes_virtual_map =
        source_inventory.allocated_bytes < profile.current_map_size_bytes();
    if !native_allocation_excludes_virtual_map {
        return Err(
            "plain LMDB inventory counted virtual map reservation as allocation".to_owned(),
        );
    }
    let inventory = collect_lifecycle_inventory(
        LmdbLifecycleInventoryRoots {
            source: &source_root,
            backup: &backup_root,
            interrupted: &interrupted_root,
            restored: &restored_root,
            repair_backup: &repair_backup_root,
            repair_restored: &repair_root,
            retention: &retention_root,
            corrupt: &corrupt_root,
        },
        source_inventory.logical_bytes,
    )?;
    if inventory.carrier_classes != LmdbCarrierClassV1::ALL {
        return Err("plain LMDB lifecycle inventory omitted an owned carrier class".to_owned());
    }

    drop(retention_profile);
    let interrupted_copy_cleaned = fs::remove_dir_all(&interrupted_root).is_ok()
        && !interrupted_root.try_exists().map_err(|error| {
            format!("plain LMDB interrupted-copy cleanup check failed: {error}")
        })?;
    if !interrupted_copy_cleaned {
        return Err("plain LMDB interrupted-copy carriers could not be cleaned".to_owned());
    }
    drop(profile);
    let reopened_profile = LmdbQualificationProfile::open(&source_root)?;
    let reopened_inventory =
        QualificationPerformanceInventoryV2::from_inventory(&reopened_profile.inventory()?)?;
    drop(reopened_profile);
    let windows = exercise_windows_lmdb_lifecycle(&backup_root, root, interrupted_copy_cleaned)?;
    let inventory_snapshots = vec![
        QualificationLmdbInventorySnapshotV1 {
            state: QualificationPerformanceInventoryStateV1::Steady,
            inventory: steady_inventory,
        },
        QualificationLmdbInventorySnapshotV1 {
            state: QualificationPerformanceInventoryStateV1::Reopened,
            inventory: reopened_inventory,
        },
        QualificationLmdbInventorySnapshotV1 {
            state: QualificationPerformanceInventoryStateV1::HighWater,
            inventory: inventory.inventory.clone(),
        },
    ];

    Ok(QualificationLmdbLifecycleSmokeV1 {
        schema: QUALIFICATION_LMDB_LIFECYCLE_SMOKE_SCHEMA_V1,
        mode: QUALIFICATION_LMDB_LIFECYCLE_REPORT_MODE_V1,
        profile_id: QUALIFICATION_LMDB_PLAIN_PROFILE_ID_V1.to_owned(),
        map_policy: LmdbMapPolicyV1::default(),
        workload: QualificationGeneratedWorkloadV1::G0,
        workload_manifest_sha256: manifest.manifest_sha256,
        reader: QualificationLmdbReaderLifecycleV1 {
            pinned_receipt,
            latest_receipt,
            process_overlap: reader_overlap,
            stale_readers_cleared,
            live_reader_preserved,
        },
        retention: QualificationLmdbRetentionLifecycleV1 {
            steady_allocated_bytes,
            retained_allocated_bytes,
            reused_allocated_bytes,
            retention_bound_bytes: LIFECYCLE_READER_RETENTION_BOUND_BYTES_V1,
            post_release_reuse_bound_bytes: LIFECYCLE_POST_RELEASE_REUSE_BOUND_BYTES_V1,
            within_predeclared_bounds,
        },
        copy: QualificationLmdbCopyLifecycleV1 {
            copied_receipt,
            source_before_receipt: copy_before,
            source_after_receipt: copy_after,
            exact_coherent_prefix,
            process_overlap: copy_overlap,
            completion_marker_last,
            interrupted_backup_rejected,
            interrupted_retry_rejected,
        },
        restore_repair: QualificationLmdbRestoreRepairLifecycleV1 {
            restored_receipt,
            repaired_receipt,
            backup_preserved,
            source_preserved,
            restore_inventory_identity_exact,
            repair_inventory_identity_exact,
            corrupt_truth_rejected,
            incomplete_destination_rejected,
        },
        inventory,
        inventory_snapshots,
        native_allocation_excludes_virtual_map,
        windows,
    })
}

fn populate_lifecycle_range(
    profile: &LmdbQualificationProfile,
    prefix: &str,
    range: std::ops::Range<u64>,
    value_bytes: usize,
) -> Result<(), String> {
    for index in range {
        let outcome = profile.journal().create_once(
            &format!("journal/{prefix}-{index:04}"),
            &vec![(index % 251) as u8; value_bytes],
        )?;
        if outcome != QualificationCreateOutcome::Created {
            return Err(format!(
                "plain LMDB lifecycle record {prefix}-{index:04} was not created once"
            ));
        }
    }
    Ok(())
}

fn tree_carrier_receipt(root: &Path, exclude_lock: bool) -> Result<String, String> {
    fn visit(
        root: &Path,
        directory: &Path,
        exclude_lock: bool,
        carriers: &mut Vec<serde_json::Value>,
    ) -> Result<(), String> {
        let mut entries = fs::read_dir(directory)
            .map_err(|error| format!("plain LMDB receipt directory read failed: {error}"))?
            .collect::<Result<Vec<_>, _>>()
            .map_err(|error| format!("plain LMDB receipt directory entry failed: {error}"))?;
        entries.sort_by_key(|entry| entry.file_name());
        for entry in entries {
            let path = entry.path();
            let file_type = entry.file_type().map_err(|error| {
                format!("plain LMDB receipt carrier inspection failed: {error}")
            })?;
            if file_type.is_dir() {
                visit(root, &path, exclude_lock, carriers)?;
                continue;
            }
            if !file_type.is_file() {
                return Err("plain LMDB receipt rejected a non-file carrier".to_owned());
            }
            let relative = path
                .strip_prefix(root)
                .map_err(|_| "plain LMDB receipt carrier escaped its root".to_owned())?
                .to_string_lossy()
                .replace('\\', "/");
            if exclude_lock && relative == "journal/lock.mdb" {
                continue;
            }
            carriers.push(serde_json::json!({
                "relativePath": relative,
                "encodedSha256": sha256_bytes_hex(
                    &fs::read(&path)
                        .map_err(|error| format!("plain LMDB receipt carrier read failed: {error}"))?
                ),
            }));
        }
        Ok(())
    }

    let mut carriers = Vec::new();
    visit(root, root, exclude_lock, &mut carriers)?;
    let canonical =
        canonical_json_bytes(&serde_json::to_value(carriers).map_err(|error| error.to_string())?)
            .map_err(|error| error.to_string())?;
    Ok(sha256_bytes_hex(&canonical))
}

fn truth_carrier_identity(root: &Path) -> Result<String, String> {
    fn add_file(
        root: &Path,
        path: &Path,
        carriers: &mut Vec<serde_json::Value>,
    ) -> Result<(), String> {
        let relative = path
            .strip_prefix(root)
            .map_err(|_| "plain LMDB truth carrier escaped its root".to_owned())?
            .to_string_lossy()
            .replace('\\', "/");
        let bytes = fs::read(path)
            .map_err(|error| format!("plain LMDB truth carrier read failed: {error}"))?;
        carriers.push(serde_json::json!({
            "relativePath": relative,
            "encodedBytes": bytes.len(),
            "encodedSha256": sha256_bytes_hex(&bytes),
        }));
        Ok(())
    }

    fn visit_content(
        root: &Path,
        directory: &Path,
        carriers: &mut Vec<serde_json::Value>,
    ) -> Result<(), String> {
        let mut entries = fs::read_dir(directory)
            .map_err(|error| format!("plain LMDB truth content read failed: {error}"))?
            .collect::<Result<Vec<_>, _>>()
            .map_err(|error| format!("plain LMDB truth content entry failed: {error}"))?;
        entries.sort_by_key(|entry| entry.file_name());
        for entry in entries {
            let file_type = entry
                .file_type()
                .map_err(|error| format!("plain LMDB truth carrier inspection failed: {error}"))?;
            if file_type.is_dir() {
                visit_content(root, &entry.path(), carriers)?;
            } else if file_type.is_file() {
                add_file(root, &entry.path(), carriers)?;
            } else {
                return Err("plain LMDB truth identity rejected a non-file carrier".to_owned());
            }
        }
        Ok(())
    }

    let mut carriers = Vec::new();
    add_file(
        root,
        &root.join(LMDB_BACKUP_DATABASE_FILE_V1),
        &mut carriers,
    )?;
    visit_content(root, &root.join(CONTENT_DIRECTORY_V1), &mut carriers)?;
    carriers.sort_by(|left, right| {
        left["relativePath"]
            .as_str()
            .cmp(&right["relativePath"].as_str())
    });
    let canonical = canonical_json_bytes(&serde_json::Value::Array(carriers))
        .map_err(|error| error.to_string())?;
    Ok(sha256_bytes_hex(&canonical))
}

fn collect_lifecycle_inventory(
    roots: LmdbLifecycleInventoryRoots<'_>,
    logical_bytes: u64,
) -> Result<QualificationLmdbSanitizedInventoryV1, String> {
    let mut carriers = collect_active_lmdb_carriers(roots.source)?;
    prefix_carrier_paths(&mut carriers, "source");
    append_role_carriers(&mut carriers, "backup", roots.backup, |path| {
        if matches!(
            path,
            LMDB_BACKUP_RECEIPT_FILE_V1
                | super::BACKUP_MANIFEST_FILE_V1
                | super::BACKUP_COMPLETION_FILE_V1
        ) {
            Ok(LmdbCarrierClassV1::Sidecar)
        } else {
            Ok(LmdbCarrierClassV1::Copy)
        }
    })?;
    append_role_carriers(&mut carriers, "interrupted", roots.interrupted, |_| {
        Ok(LmdbCarrierClassV1::Temporary)
    })?;
    append_role_carriers(&mut carriers, "restored", roots.restored, |_| {
        Ok(LmdbCarrierClassV1::Copy)
    })?;
    append_role_carriers(&mut carriers, "repair-backup", roots.repair_backup, |_| {
        Ok(LmdbCarrierClassV1::Repair)
    })?;
    append_role_carriers(
        &mut carriers,
        "repair-restored",
        roots.repair_restored,
        |_| Ok(LmdbCarrierClassV1::Repair),
    )?;
    append_role_carriers(&mut carriers, "retention", roots.retention, |_| {
        Ok(LmdbCarrierClassV1::Obsolete)
    })?;
    append_role_carriers(&mut carriers, "corrupt", roots.corrupt, |_| {
        Ok(LmdbCarrierClassV1::Obsolete)
    })?;
    carriers.sort_by(|left, right| {
        left.relative_path
            .as_bytes()
            .cmp(right.relative_path.as_bytes())
    });
    let aggregate = inventory_from_carriers(&carriers, logical_bytes)?;
    sanitized_inventory_from_carriers(&carriers, aggregate)
}

fn append_role_carriers(
    carriers: &mut Vec<LmdbCarrierV1>,
    role: &str,
    root: &Path,
    classify: impl Fn(&str) -> Result<LmdbCarrierClassV1, String>,
) -> Result<(), String> {
    let mut role_carriers = Vec::new();
    collect_carriers_recursive(root, root, &mut role_carriers, &classify)?;
    prefix_carrier_paths(&mut role_carriers, role);
    carriers.extend(role_carriers);
    Ok(())
}

fn prefix_carrier_paths(carriers: &mut [LmdbCarrierV1], role: &str) {
    for carrier in carriers {
        carrier.relative_path = format!("{role}/{}", carrier.relative_path);
    }
}

#[cfg(not(windows))]
fn exercise_windows_lmdb_lifecycle(
    _backup_root: &Path,
    _workspace_root: &Path,
    interrupted_copy_cleaned: bool,
) -> Result<QualificationLmdbWindowsLifecycleV1, String> {
    Ok(QualificationLmdbWindowsLifecycleV1 {
        required: false,
        replacement_blocked_while_open: false,
        replacement_succeeded_after_close: false,
        reopened_exact: false,
        interrupted_copy_cleaned,
    })
}

#[cfg(windows)]
fn exercise_windows_lmdb_lifecycle(
    backup_root: &Path,
    workspace_root: &Path,
    interrupted_copy_cleaned: bool,
) -> Result<QualificationLmdbWindowsLifecycleV1, String> {
    let open_root = workspace_root.join("windows-open-handle");
    let expected = restore_completed_lmdb_backup_v1(backup_root, &open_root)?;
    let profile = LmdbQualificationProfile::open(&open_root)?;
    let journal_root = open_root.join(JOURNAL_DIRECTORY_V1);
    let database_path = journal_root.join("data.mdb");
    let replacement_path = journal_root.join("replacement.mdb");
    copy_file_synced(
        &backup_root.join(LMDB_BACKUP_DATABASE_FILE_V1),
        &replacement_path,
    )?;
    let replacement_blocked_while_open = fs::remove_file(&database_path).is_err();
    let closing = heed3::env_closing_event(&journal_root)
        .ok_or_else(|| "plain LMDB Windows closing event is unavailable".to_owned())?;
    drop(profile);
    closing.wait();
    if database_path.exists() {
        fs::remove_file(&database_path).map_err(|error| {
            format!("plain LMDB Windows closed carrier removal failed: {error}")
        })?;
    }
    let replacement_succeeded_after_close = fs::rename(&replacement_path, &database_path).is_ok();
    let reopened_exact = replacement_succeeded_after_close
        && LmdbQualificationProfile::open(&open_root)
            .and_then(|profile| profile.exact_receipt())
            .is_ok_and(|receipt| receipt == expected);
    if !replacement_blocked_while_open
        || !replacement_succeeded_after_close
        || !reopened_exact
        || !interrupted_copy_cleaned
    {
        return Err("plain LMDB Windows handle lifecycle proof failed".to_owned());
    }
    Ok(QualificationLmdbWindowsLifecycleV1 {
        required: true,
        replacement_blocked_while_open,
        replacement_succeeded_after_close,
        reopened_exact,
        interrupted_copy_cleaned,
    })
}

impl QualificationProfile for LmdbQualificationProfile {
    fn descriptor(&self) -> Result<QualificationProfileDescriptorV1, String> {
        Ok(self.descriptor.clone())
    }

    fn journal(&self) -> &dyn QualificationJournal {
        &self.journal
    }

    fn put_content_once(
        &self,
        content_key: &str,
        record_kind: QualificationRecordKindV1,
        decoded_bytes: &[u8],
    ) -> Result<QualificationCreateOutcome, String> {
        self.content
            .put_once(content_key, record_kind, decoded_bytes)
            .map_err(|error| error.to_string())
    }

    fn read_content(&self, content_key: &str) -> Result<Option<QualificationEntry>, String> {
        self.content
            .read(content_key)
            .map_err(|error| error.to_string())
    }

    fn remove_content(&self, content_key: &str) -> Result<bool, String> {
        self.content
            .remove(content_key)
            .map_err(|error| error.to_string())
    }

    fn backup_to(&self, destination: &Path) -> Result<(), String> {
        self.backup_to_with_hook(destination, || Ok(()))
    }

    fn verify_restore(&self, restored_root: &Path) -> Result<(), String> {
        verify_lmdb_backup_receipt(restored_root, &self.descriptor, None).map(|_| ())
    }

    fn inventory(&self) -> Result<QualificationInventoryV1, String> {
        let carriers = collect_active_lmdb_carriers(&self.journal.root)?;
        let logical_bytes = self
            .journal
            .list()?
            .into_iter()
            .chain(self.content.list().map_err(|error| error.to_string())?)
            .try_fold(0_u64, |total, entry| {
                total
                    .checked_add(entry.decoded_bytes.len() as u64)
                    .ok_or_else(|| "plain LMDB inventory logical byte count overflow".to_owned())
            })?;
        inventory_from_carriers(&carriers, logical_bytes)
    }
}

pub fn run_qualification_lmdb_smoke_v1(root: &Path) -> Result<QualificationLmdbSmokeV1, String> {
    let map_policy = LmdbMapPolicyV1::default();
    let profile = LmdbQualificationProfile::open_with_policy(root, map_policy)?;
    let spec = qualification_generator_spec_v1(QualificationGeneratedWorkloadV1::G0);
    let manifest = qualification_generated_manifest_v1(&spec).map_err(|error| error.to_string())?;
    for record in &manifest.records {
        if profile
            .journal()
            .create_once(&record.logical_key, &record.decoded_bytes)?
            != QualificationCreateOutcome::Created
        {
            return Err("plain LMDB smoke encountered a pre-existing generated record".to_owned());
        }
    }
    let listed = profile.journal().list()?;
    let receipts_exact = listed.len() == manifest.records.len()
        && listed.iter().zip(&manifest.records).all(|(entry, record)| {
            entry.logical_key == record.logical_key
                && entry.decoded_sha256 == record.decoded_sha256
                && entry.decoded_bytes == record.decoded_bytes
        });
    if !receipts_exact {
        return Err("plain LMDB smoke replay receipts are not exact".to_owned());
    }
    let schedule = qualification_operation_schedule_v1(&spec).map_err(|error| error.to_string())?;
    for scheduled in schedule.keyed_reads {
        let actual = profile.journal().read(&scheduled.logical_key)?;
        if matches!(
            scheduled.class,
            super::QualificationKeyedReadClassV1::Absent
        ) != actual.is_none()
        {
            return Err(format!(
                "plain LMDB smoke scheduled read {:?} returned the wrong presence",
                scheduled.class
            ));
        }
    }
    profile.journal().integrity_check()?;
    Ok(QualificationLmdbSmokeV1 {
        schema: QUALIFICATION_LMDB_SMOKE_SCHEMA_V1,
        mode: "non_timing_semantic_receipts",
        profile_id: QUALIFICATION_LMDB_PLAIN_PROFILE_ID_V1.to_owned(),
        map_policy,
        workload: QualificationGeneratedWorkloadV1::G0,
        manifest_sha256: manifest.manifest_sha256,
        records: listed.len() as u64,
        head_marker: profile.journal().head_marker()?,
        receipts_exact,
    })
}

fn validate_logical_key(logical_key: &str) -> Result<(), String> {
    if logical_key.is_empty() {
        return Err("plain LMDB logical key must not be empty".to_owned());
    }
    if logical_key.len() > QUALIFICATION_LOGICAL_KEY_MAX_BYTES_V1 {
        return Err(format!(
            "plain LMDB logical key exceeds the public {}-byte contract",
            QUALIFICATION_LOGICAL_KEY_MAX_BYTES_V1
        ));
    }
    Ok(())
}

fn encode_entry_key(logical_key: &str) -> Vec<u8> {
    let mut key = Vec::with_capacity(logical_key.len() + 1);
    key.push(ENTRY_KEY_PREFIX_V1);
    key.extend_from_slice(logical_key.as_bytes());
    key
}

fn decode_entry_key(key: &[u8]) -> Result<String, String> {
    let Some((&prefix, logical_key)) = key.split_first() else {
        return Err("plain LMDB journal contains an empty key".to_owned());
    };
    if prefix != ENTRY_KEY_PREFIX_V1 {
        return Err("plain LMDB journal contains an unknown internal key".to_owned());
    }
    let logical_key = std::str::from_utf8(logical_key)
        .map_err(|_| "plain LMDB journal key is not UTF-8".to_owned())?;
    validate_logical_key(logical_key)?;
    Ok(logical_key.to_owned())
}

fn encode_entry(decoded_bytes: &[u8]) -> Result<Vec<u8>, String> {
    let decoded_len = u64::try_from(decoded_bytes.len())
        .map_err(|_| "plain LMDB entry length exceeds u64".to_owned())?;
    let hash = sha256_bytes_hex(decoded_bytes);
    let mut envelope = Vec::with_capacity(4 + 1 + 8 + 64 + decoded_bytes.len());
    envelope.extend_from_slice(ENTRY_MAGIC_V1);
    envelope.push(ENTRY_VERSION_V1);
    envelope.extend_from_slice(&decoded_len.to_be_bytes());
    envelope.extend_from_slice(hash.as_bytes());
    envelope.extend_from_slice(decoded_bytes);
    Ok(envelope)
}

fn decode_entry(logical_key: &str, envelope: &[u8]) -> Result<QualificationEntry, String> {
    const HEADER_LEN: usize = 4 + 1 + 8 + 64;
    if envelope.len() < HEADER_LEN
        || &envelope[..4] != ENTRY_MAGIC_V1
        || envelope[4] != ENTRY_VERSION_V1
    {
        return Err(format!(
            "plain LMDB value for {logical_key} has an invalid envelope"
        ));
    }
    let decoded_len = u64::from_be_bytes(
        envelope[5..13]
            .try_into()
            .expect("entry length slice has eight bytes"),
    );
    let decoded_bytes = &envelope[HEADER_LEN..];
    if decoded_len != decoded_bytes.len() as u64 {
        return Err(format!(
            "plain LMDB value for {logical_key} has a mismatched decoded length"
        ));
    }
    let stored_hash = std::str::from_utf8(&envelope[13..HEADER_LEN])
        .map_err(|_| format!("plain LMDB value for {logical_key} has a non-text hash"))?;
    let actual_hash = sha256_bytes_hex(decoded_bytes);
    if stored_hash != actual_hash {
        return Err(format!(
            "plain LMDB value for {logical_key} has decoded hash {actual_hash}, expected {stored_hash}"
        ));
    }
    Ok(QualificationEntry {
        logical_key: logical_key.to_owned(),
        decoded_sha256: actual_hash,
        decoded_bytes: decoded_bytes.to_vec(),
    })
}

fn encode_head(head: u64) -> [u8; 13] {
    let mut encoded = [0_u8; 13];
    encoded[..4].copy_from_slice(HEAD_MAGIC_V1);
    encoded[4] = HEAD_VERSION_V1;
    encoded[5..].copy_from_slice(&head.to_be_bytes());
    encoded
}

fn decode_head(encoded: &[u8]) -> Result<u64, String> {
    if encoded.len() != 13 || &encoded[..4] != HEAD_MAGIC_V1 || encoded[4] != HEAD_VERSION_V1 {
        return Err("plain LMDB head marker has an invalid envelope".to_owned());
    }
    Ok(u64::from_be_bytes(
        encoded[5..]
            .try_into()
            .expect("head marker slice has eight bytes"),
    ))
}

fn is_map_full(error: &HeedError) -> bool {
    matches!(error, HeedError::Mdb(MdbError::MapFull))
}

fn is_map_resized(error: &HeedError) -> bool {
    matches!(error, HeedError::Mdb(MdbError::MapResized))
}

fn refresh_environment_map(environment: &Env<heed3::WithoutTls>) -> Result<(), String> {
    // SAFETY: callers serialize all local transactions before adopting the
    // map size persisted by another process.
    unsafe { environment.resize(0) }
        .map_err(|error| format!("plain LMDB map refresh failed: {error}"))
}

fn with_resize_lock<T>(
    root: &Path,
    operation: impl FnOnce() -> Result<T, String>,
) -> Result<T, String> {
    let path = root.join(RESIZE_LOCK_FILE_V1);
    let file = OpenOptions::new()
        .create(true)
        .read(true)
        .write(true)
        .truncate(false)
        .open(&path)
        .map_err(|error| format!("plain LMDB resize lock open failed: {error}"))?;
    file.lock()
        .map_err(|error| format!("plain LMDB resize lock failed: {error}"))?;
    let result = operation();
    let unlock = file
        .unlock()
        .map_err(|error| format!("plain LMDB resize unlock failed: {error}"));
    match (result, unlock) {
        (Ok(value), Ok(())) => Ok(value),
        (Err(error), _) | (Ok(_), Err(error)) => Err(error),
    }
}

#[cfg(test)]
fn overwrite_raw_journal_value_for_test(
    root: &Path,
    logical_key: &str,
    value: &[u8],
) -> Result<(), String> {
    mutate_raw_database_for_test(root, |database, transaction| {
        database
            .put(transaction, &encode_entry_key(logical_key), value)
            .map_err(|error| error.to_string())
    })
}

#[cfg(test)]
fn overwrite_profile_id_for_test(root: &Path, profile_id: &str) -> Result<(), String> {
    mutate_raw_database_for_test(root, |database, transaction| {
        let bytes = database
            .get(transaction, METADATA_KEY_V1)
            .map_err(|error| error.to_string())?
            .ok_or_else(|| "test metadata missing".to_owned())?;
        let mut metadata = LmdbProfileMetadataV1::decode(bytes)?;
        metadata.profile_id = profile_id.to_owned();
        database
            .put(transaction, METADATA_KEY_V1, &metadata.encode()?)
            .map_err(|error| error.to_string())
    })
}

#[cfg(test)]
fn mutate_raw_database_for_test(
    root: &Path,
    mutation: impl FnOnce(&JournalDatabase, &mut heed3::RwTxn<'_>) -> Result<(), String>,
) -> Result<(), String> {
    let mut options = EnvOpenOptions::new();
    options
        .map_size(LmdbMapPolicyV1::default().initial_size_bytes as usize)
        .max_dbs(1);
    // SAFETY: tests call this only after dropping the profile handle.
    let environment = unsafe { options.open(root.join(JOURNAL_DIRECTORY_V1)) }
        .map_err(|error| error.to_string())?;
    let mut transaction = environment.write_txn().map_err(|error| error.to_string())?;
    let database: JournalDatabase = environment
        .create_database(&mut transaction, Some(DATABASE_NAME_V1))
        .map_err(|error| error.to_string())?;
    mutation(&database, &mut transaction)?;
    transaction.commit().map_err(|error| error.to_string())?;
    environment.prepare_for_closing().wait();
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::fs;
    use std::path::{Path, PathBuf};
    use std::process::{Child, Command};
    use std::time::Duration;

    use super::*;
    use crate::bench_support::foundation::{
        BACKUP_COMPLETION_FILE_V1, BACKUP_MANIFEST_FILE_V1, QualificationCreateOutcome,
        QualificationGeneratedWorkloadV1, QualificationKeyedReadClassV1,
        QualificationProcessBarrierParticipantV1, QualificationProcessBarrierV1,
        qualification_generated_manifest_v1, qualification_generator_spec_v1,
        qualification_operation_schedule_v1,
    };

    const CHILD_TEST: &str =
        "bench_support::foundation::lmdb::tests::lmdb_process_child_entrypoint";

    fn spawn_child(
        action: &str,
        root: &Path,
        key: &str,
        bytes: &[u8],
        result: &Path,
        barrier: Option<(&Path, &str)>,
    ) -> Child {
        let mut command = Command::new(std::env::current_exe().expect("current test executable"));
        command
            .args(["--exact", CHILD_TEST, "--nocapture"])
            .env("POINTBREAK_LMDB_CHILD_ACTION", action)
            .env("POINTBREAK_LMDB_CHILD_ROOT", root)
            .env("POINTBREAK_LMDB_CHILD_KEY", key)
            .env(
                "POINTBREAK_LMDB_CHILD_BYTES",
                String::from_utf8_lossy(bytes).as_ref(),
            )
            .env("POINTBREAK_LMDB_CHILD_RESULT", result);
        if let Some((barrier_root, participant)) = barrier {
            command
                .env("POINTBREAK_LMDB_CHILD_BARRIER", barrier_root)
                .env("POINTBREAK_LMDB_CHILD_PARTICIPANT", participant);
        }
        command.spawn().expect("spawn LMDB process child")
    }

    fn wait_success(mut child: Child) {
        let status = child.wait().expect("wait for LMDB process child");
        assert!(status.success(), "LMDB process child failed: {status}");
    }

    fn child_result(path: &Path) -> String {
        std::fs::read_to_string(path).expect("read child result")
    }

    fn populate_records(
        profile: &LmdbQualificationProfile,
        prefix: &str,
        range: std::ops::Range<u64>,
        value_bytes: usize,
    ) {
        for index in range {
            assert_eq!(
                profile
                    .journal()
                    .create_once(
                        &format!("journal/{prefix}-{index:04}"),
                        &vec![(index % 251) as u8; value_bytes],
                    )
                    .expect("create lifecycle record"),
                QualificationCreateOutcome::Created
            );
        }
    }

    fn tree_receipt(root: &Path) -> String {
        fn visit(root: &Path, directory: &Path, carriers: &mut Vec<(String, String)>) {
            let mut entries = fs::read_dir(directory)
                .expect("read receipt directory")
                .collect::<Result<Vec<_>, _>>()
                .expect("collect receipt directory");
            entries.sort_by_key(|entry| entry.file_name());
            for entry in entries {
                let path = entry.path();
                if entry.file_type().expect("receipt file type").is_dir() {
                    visit(root, &path, carriers);
                } else {
                    let relative = path
                        .strip_prefix(root)
                        .expect("receipt relative path")
                        .to_string_lossy()
                        .replace('\\', "/");
                    carriers.push((
                        relative,
                        sha256_bytes_hex(&fs::read(path).expect("read receipt carrier")),
                    ));
                }
            }
        }

        let mut carriers = Vec::new();
        visit(root, root, &mut carriers);
        sha256_bytes_hex(&canonical_json_bytes(&serde_json::to_value(carriers).unwrap()).unwrap())
    }

    #[test]
    fn lmdb_process_child_entrypoint() {
        let Some(action) = std::env::var_os("POINTBREAK_LMDB_CHILD_ACTION") else {
            return;
        };
        let root = PathBuf::from(std::env::var_os("POINTBREAK_LMDB_CHILD_ROOT").unwrap());
        let key = std::env::var("POINTBREAK_LMDB_CHILD_KEY").unwrap();
        let bytes = std::env::var("POINTBREAK_LMDB_CHILD_BYTES")
            .unwrap()
            .into_bytes();
        let result = PathBuf::from(std::env::var_os("POINTBREAK_LMDB_CHILD_RESULT").unwrap());
        if action == "restore" {
            let destination = PathBuf::from(&key);
            restore_completed_lmdb_backup_v1(&root, &destination).expect("restore LMDB backup");
            let restored = LmdbQualificationProfile::open(&destination)
                .expect("open restored LMDB profile in child");
            fs::write(
                result,
                serde_json::to_vec(&restored.exact_receipt().expect("restored receipt")).unwrap(),
            )
            .expect("write restored receipt");
            return;
        }
        let profile = if action.to_string_lossy().starts_with("refresh_") {
            LmdbQualificationProfile::open_with_policy(&root, LmdbMapPolicyV1::test_resize_policy())
        } else {
            LmdbQualificationProfile::open(&root)
        }
        .expect("open child LMDB profile");
        if action == "pin_wait" {
            let pinned = profile.pin_reader().expect("pin LMDB reader");
            let participant = QualificationProcessBarrierParticipantV1::join(
                std::env::var_os("POINTBREAK_LMDB_CHILD_BARRIER").unwrap(),
                &std::env::var("POINTBREAK_LMDB_CHILD_PARTICIPANT").unwrap(),
            )
            .expect("join pinned-reader barrier");
            participant
                .wait_for_release(Duration::from_secs(20))
                .expect("wait for pinned-reader release");
            fs::write(
                result,
                serde_json::to_vec(&pinned.exact_receipt().expect("pinned receipt")).unwrap(),
            )
            .expect("write pinned receipt");
            participant
                .complete()
                .expect("complete pinned-reader barrier");
            return;
        }
        if action == "interrupt_backup" {
            profile
                .backup_to_after_copy_barrier(
                    &result,
                    Path::new(&std::env::var_os("POINTBREAK_LMDB_CHILD_BARRIER").unwrap()),
                    &std::env::var("POINTBREAK_LMDB_CHILD_PARTICIPANT").unwrap(),
                )
                .expect("interrupted backup should be killed at barrier");
            panic!("interrupted backup unexpectedly passed its copy barrier");
        }
        let participant = std::env::var_os("POINTBREAK_LMDB_CHILD_BARRIER").map(|barrier| {
            QualificationProcessBarrierParticipantV1::join(
                barrier,
                &std::env::var("POINTBREAK_LMDB_CHILD_PARTICIPANT").unwrap(),
            )
            .expect("join LMDB child barrier")
        });
        if let Some(participant) = &participant {
            participant
                .wait_for_release(Duration::from_secs(20))
                .expect("wait for LMDB child release");
        }
        if action == "backup" {
            profile.backup_to(&result).expect("online LMDB backup");
            if let Some(participant) = participant {
                participant.complete().expect("complete LMDB child barrier");
            }
            return;
        }
        let output = match action.to_string_lossy().as_ref() {
            "create" | "refresh_write" => profile
                .journal()
                .create_once(&key, &bytes)
                .map(|outcome| format!("{outcome:?}"))
                .unwrap_or_else(|error| format!("error:{error}")),
            "read" | "refresh_read" => profile
                .journal()
                .read(&key)
                .map(|entry| {
                    entry
                        .map(|entry| String::from_utf8(entry.decoded_bytes).unwrap())
                        .unwrap_or_else(|| "absent".to_owned())
                })
                .unwrap_or_else(|error| format!("error:{error}")),
            other => panic!("unknown child action {other}"),
        };
        std::fs::write(&result, output).expect("write child result");
        if let Some(participant) = participant {
            participant.complete().expect("complete LMDB child barrier");
        }
    }

    #[test]
    fn create_once_retry_and_commit_acknowledgement_survive_fresh_processes() {
        let root = tempfile::tempdir().expect("LMDB process root");
        let results = tempfile::tempdir().expect("LMDB process results");

        let created = results.path().join("created");
        wait_success(spawn_child(
            "create",
            root.path(),
            "journal/key",
            b"value",
            &created,
            None,
        ));
        assert_eq!(child_result(&created), "Created");

        let reopened = results.path().join("reopened");
        wait_success(spawn_child(
            "read",
            root.path(),
            "journal/key",
            b"",
            &reopened,
            None,
        ));
        assert_eq!(child_result(&reopened), "value");

        let exact_retry = results.path().join("exact-retry");
        wait_success(spawn_child(
            "create",
            root.path(),
            "journal/key",
            b"value",
            &exact_retry,
            None,
        ));
        assert_eq!(child_result(&exact_retry), "AlreadyExists");

        let divergent_retry = results.path().join("divergent-retry");
        wait_success(spawn_child(
            "create",
            root.path(),
            "journal/key",
            b"different",
            &divergent_retry,
            None,
        ));
        assert!(child_result(&divergent_retry).starts_with("error:"));

        let profile = LmdbQualificationProfile::open(root.path()).expect("reopen profile");
        assert_eq!(profile.journal().head_marker().unwrap(), 1);
    }

    #[test]
    fn synchronized_independent_writers_have_exactly_one_winner() {
        let root = tempfile::tempdir().expect("LMDB race root");
        let results = tempfile::tempdir().expect("LMDB race results");
        let barrier_root = results.path().join("barrier");
        std::fs::create_dir(&barrier_root).expect("create writer barrier root");
        let barrier =
            QualificationProcessBarrierV1::create(&barrier_root, &["writer-a", "writer-b"])
                .expect("create writer barrier");
        let first_result = results.path().join("writer-a");
        let second_result = results.path().join("writer-b");
        let first = spawn_child(
            "create",
            root.path(),
            "journal/race",
            b"same",
            &first_result,
            Some((&barrier_root, "writer-a")),
        );
        let second = spawn_child(
            "create",
            root.path(),
            "journal/race",
            b"same",
            &second_result,
            Some((&barrier_root, "writer-b")),
        );
        barrier
            .wait_until_ready(Duration::from_secs(20))
            .expect("both writers ready");
        barrier.release().expect("release writers");
        wait_success(first);
        wait_success(second);
        barrier
            .evidence()
            .expect("race evidence")
            .validate_overlap()
            .unwrap();

        let mut outcomes = [child_result(&first_result), child_result(&second_result)];
        outcomes.sort();
        assert_eq!(outcomes, ["AlreadyExists", "Created"]);
        let profile = LmdbQualificationProfile::open(root.path()).expect("reopen race profile");
        assert_eq!(profile.journal().head_marker().unwrap(), 1);
    }

    #[test]
    fn replay_reads_hashes_and_head_marker_are_exact_and_deterministic() {
        let root = tempfile::tempdir().expect("LMDB semantic root");
        let profile = LmdbQualificationProfile::open(root.path()).expect("open LMDB profile");
        let spec = qualification_generator_spec_v1(QualificationGeneratedWorkloadV1::G0);
        let manifest = qualification_generated_manifest_v1(&spec).expect("generate G0");
        for record in manifest.records.iter().rev() {
            assert_eq!(
                profile
                    .journal()
                    .create_once(&record.logical_key, &record.decoded_bytes)
                    .unwrap(),
                QualificationCreateOutcome::Created
            );
        }
        let listed = profile.journal().list().expect("list LMDB journal");
        assert_eq!(listed.len(), manifest.records.len());
        assert!(
            listed
                .windows(2)
                .all(|pair| pair[0].logical_key < pair[1].logical_key)
        );
        assert!(listed.iter().all(|entry| {
            crate::canonical_hash::sha256_bytes_hex(&entry.decoded_bytes) == entry.decoded_sha256
        }));
        assert_eq!(
            profile.journal().head_marker().unwrap(),
            manifest.records.len() as u64
        );

        let schedule = qualification_operation_schedule_v1(&spec).expect("G0 schedule");
        for read in schedule.keyed_reads {
            let entry = profile
                .journal()
                .read(&read.logical_key)
                .expect("scheduled read");
            match read.class {
                QualificationKeyedReadClassV1::Absent => assert!(entry.is_none()),
                _ => assert!(entry.is_some()),
            }
        }
        profile
            .journal()
            .integrity_check()
            .expect("integrity check");
    }

    #[test]
    fn invalid_envelope_and_stale_metadata_fail_without_partial_truth() {
        let root = tempfile::tempdir().expect("LMDB corruption root");
        let profile = LmdbQualificationProfile::open(root.path()).expect("open LMDB profile");
        profile
            .journal()
            .create_once("journal/a", b"valid")
            .unwrap();
        drop(profile);

        overwrite_raw_journal_value_for_test(root.path(), "journal/z", b"invalid-envelope")
            .expect("inject invalid envelope");
        let profile = LmdbQualificationProfile::open(root.path()).expect("reopen corrupt profile");
        assert!(profile.journal().list().is_err());
        drop(profile);

        overwrite_profile_id_for_test(root.path(), "qualification-lmdb-plain-stale")
            .expect("inject stale profile identity");
        assert!(LmdbQualificationProfile::open(root.path()).is_err());
    }

    #[test]
    fn map_full_aborts_without_acknowledging_a_partial_write() {
        let root = tempfile::tempdir().expect("LMDB map-full root");
        let policy = LmdbMapPolicyV1 {
            initial_size_bytes: 1_048_576,
            growth_increment_bytes: 1_048_576,
            maximum_size_bytes: 1_048_576,
            resize_retry_limit: 0,
        };
        let profile =
            LmdbQualificationProfile::open_with_policy(root.path(), policy).expect("small profile");
        let error = profile
            .journal()
            .create_once("journal/too-large", &vec![0x5a; 2 * 1_048_576])
            .unwrap_err();
        assert!(error.contains("map full"));
        drop(profile);

        let reopened = LmdbQualificationProfile::open_with_policy(root.path(), policy).unwrap();
        assert_eq!(reopened.journal().head_marker().unwrap(), 0);
        assert!(
            reopened
                .journal()
                .read("journal/too-large")
                .unwrap()
                .is_none()
        );
    }

    #[test]
    fn bounded_resize_refreshes_already_open_reader_and_writer_processes() {
        let root = tempfile::tempdir().expect("LMDB resize root");
        let results = tempfile::tempdir().expect("LMDB resize results");
        let policy = LmdbMapPolicyV1::test_resize_policy();
        let profile = LmdbQualificationProfile::open_with_policy(root.path(), policy)
            .expect("resize profile");
        profile
            .journal()
            .create_once("journal/seed", b"seed")
            .unwrap();

        let barrier_root = results.path().join("barrier");
        std::fs::create_dir(&barrier_root).expect("create refresh barrier root");
        let barrier = QualificationProcessBarrierV1::create(&barrier_root, &["reader", "writer"])
            .expect("create refresh barrier");
        let reader_result = results.path().join("reader");
        let writer_result = results.path().join("writer");
        let reader = spawn_child(
            "refresh_read",
            root.path(),
            "journal/grown",
            b"",
            &reader_result,
            Some((&barrier_root, "reader")),
        );
        let writer = spawn_child(
            "refresh_write",
            root.path(),
            "journal/after-resize",
            b"writer",
            &writer_result,
            Some((&barrier_root, "writer")),
        );
        barrier.wait_until_ready(Duration::from_secs(20)).unwrap();
        profile
            .journal()
            .create_once("journal/grown", &vec![0x33; 2 * 1_048_576])
            .expect("grow map");
        assert!(profile.current_map_size_bytes() > policy.initial_size_bytes);
        assert!(profile.current_map_size_bytes() <= policy.maximum_size_bytes);
        barrier.release().unwrap();
        wait_success(reader);
        wait_success(writer);
        assert_eq!(child_result(&reader_result).len(), 2 * 1_048_576);
        assert_eq!(child_result(&writer_result), "Created");
        assert!(
            profile
                .journal()
                .read("journal/after-resize")
                .unwrap()
                .is_some()
        );
    }

    #[test]
    fn profile_open_rejects_an_incompatible_fixed_map_policy() {
        let root = tempfile::tempdir().expect("LMDB policy root");
        let profile = LmdbQualificationProfile::open(root.path()).expect("default policy profile");
        drop(profile);
        let mut incompatible = LmdbMapPolicyV1::default();
        incompatible.maximum_size_bytes += incompatible.growth_increment_bytes;

        assert!(LmdbQualificationProfile::open_with_policy(root.path(), incompatible).is_err());
    }

    #[test]
    fn content_stays_independent_across_completed_backup_and_restore() {
        let root = tempfile::tempdir().expect("LMDB content root");
        let profile = LmdbQualificationProfile::open(root.path()).expect("LMDB profile");
        let key = "sha256:0000000000000000000000000000000000000000000000000000000000000001";

        assert_eq!(
            profile
                .put_content_once(
                    key,
                    crate::bench_support::foundation::QualificationRecordKindV1::ObjectArtifact,
                    b"object",
                )
                .unwrap(),
            QualificationCreateOutcome::Created
        );
        assert_eq!(
            profile.read_content(key).unwrap().unwrap().decoded_bytes,
            b"object"
        );
        assert_eq!(profile.journal().head_marker().unwrap(), 0);
        assert!(root.path().join("content").is_dir());
        let backup = root.path().join("backup");
        profile
            .backup_to(&backup)
            .expect("backup independent content");
        profile
            .verify_restore(&backup)
            .expect("verify completed backup");
        let restored_root = root.path().join("restored");
        restore_completed_lmdb_backup_v1(&backup, &restored_root)
            .expect("restore independent content");
        let restored =
            LmdbQualificationProfile::open(&restored_root).expect("open restored profile");
        assert_eq!(
            restored.read_content(key).unwrap().unwrap().decoded_bytes,
            b"object"
        );
        assert_eq!(restored.journal().head_marker().unwrap(), 0);
    }

    #[test]
    fn pinned_reader_keeps_a_stable_snapshot_while_later_writers_commit() {
        let root = tempfile::tempdir().expect("LMDB pinned-reader root");
        let profile = LmdbQualificationProfile::open(root.path()).expect("open LMDB profile");
        populate_records(&profile, "before-pin", 0..8, 128);
        let expected = profile.exact_receipt().expect("pre-pin receipt");
        let pinned = profile.pin_reader().expect("pin reader snapshot");

        populate_records(&profile, "after-pin", 0..8, 128);

        assert_eq!(pinned.exact_receipt().unwrap(), expected);
        assert_eq!(pinned.head_marker().unwrap(), 8);
        assert_eq!(profile.journal().head_marker().unwrap(), 16);
        assert_ne!(profile.exact_receipt().unwrap(), expected);
    }

    #[test]
    fn reader_retention_has_a_predeclared_bound_and_reuses_pages_after_release() {
        let root = tempfile::tempdir().expect("LMDB retention root");
        let profile = LmdbQualificationProfile::open(root.path()).expect("open LMDB profile");
        populate_records(&profile, "seed", 0..32, 512);
        let steady = profile.inventory().unwrap().allocated_bytes;
        let pinned = profile.pin_reader().expect("pin retention reader");
        populate_records(&profile, "retained", 0..128, 4096);
        let retained = profile.inventory().unwrap().allocated_bytes;
        assert!(retained >= steady);
        drop(pinned);
        populate_records(&profile, "reuse", 0..128, 512);
        let reused = profile.inventory().unwrap().allocated_bytes;

        assert!(
            reused <= LIFECYCLE_READER_RETENTION_BOUND_BYTES_V1,
            "native allocation {reused} exceeded the predeclared {}-byte bound",
            LIFECYCLE_READER_RETENTION_BOUND_BYTES_V1
        );
        assert!(
            reused.saturating_sub(retained) <= LIFECYCLE_POST_RELEASE_REUSE_BOUND_BYTES_V1,
            "ordinary post-release commits grew by {} bytes",
            reused.saturating_sub(retained)
        );
    }

    #[test]
    fn stale_reader_cleanup_clears_dead_slots_without_evicting_a_live_reader() {
        let root = tempfile::tempdir().expect("LMDB stale-reader root");
        let results = tempfile::tempdir().expect("LMDB stale-reader results");
        let profile = LmdbQualificationProfile::open(root.path()).expect("open LMDB profile");
        populate_records(&profile, "stable", 0..4, 64);
        let live = profile.pin_reader().expect("pin live reader");
        let expected = live.exact_receipt().unwrap();

        let barrier_root = results.path().join("barrier");
        fs::create_dir(&barrier_root).expect("create stale-reader barrier root");
        let barrier = QualificationProcessBarrierV1::create(&barrier_root, &["stale-reader"])
            .expect("create stale-reader barrier");
        let mut stale = spawn_child(
            "pin_wait",
            root.path(),
            "unused",
            b"",
            &results.path().join("stale-result"),
            Some((&barrier_root, "stale-reader")),
        );
        barrier
            .wait_until_ready(Duration::from_secs(20))
            .expect("stale reader pinned");
        stale.kill().expect("terminate stale reader process");
        assert!(!stale.wait().expect("wait for stale reader").success());

        assert!(profile.clear_stale_readers().expect("clear stale readers") >= 1);
        drop(stale);
        assert_eq!(live.exact_receipt().unwrap(), expected);
        assert_eq!(profile.clear_stale_readers().unwrap(), 0);
    }

    #[test]
    fn online_copy_overlapping_a_writer_restores_one_exact_coherent_prefix() {
        let root = tempfile::tempdir().expect("LMDB online-copy root");
        let results = tempfile::tempdir().expect("LMDB online-copy results");
        let profile = LmdbQualificationProfile::open(root.path()).expect("open LMDB profile");
        populate_records(&profile, "prefix", 0..32, 1024);
        let before = profile.exact_receipt().unwrap();

        let barrier_root = results.path().join("barrier");
        fs::create_dir(&barrier_root).expect("create copy barrier root");
        let barrier = QualificationProcessBarrierV1::create(&barrier_root, &["copy", "writer"])
            .expect("create copy barrier");
        let backup = results.path().join("completed-backup");
        let writer_result = results.path().join("writer-result");
        let copy = spawn_child(
            "backup",
            root.path(),
            "unused",
            b"",
            &backup,
            Some((&barrier_root, "copy")),
        );
        let writer = spawn_child(
            "create",
            root.path(),
            "journal/later-writer",
            b"later",
            &writer_result,
            Some((&barrier_root, "writer")),
        );
        barrier.wait_until_ready(Duration::from_secs(20)).unwrap();
        barrier.release().unwrap();
        wait_success(copy);
        wait_success(writer);
        barrier.evidence().unwrap().validate_overlap().unwrap();
        let after = profile.exact_receipt().unwrap();

        let restored_root = results.path().join("restored-prefix");
        restore_completed_lmdb_backup_v1(&backup, &restored_root).unwrap();
        let restored = LmdbQualificationProfile::open(&restored_root).unwrap();
        let restored_receipt = restored.exact_receipt().unwrap();
        assert!(restored_receipt == before || restored_receipt == after);
        restored.journal().integrity_check().unwrap();
    }

    #[test]
    fn backup_publishes_candidate_and_content_before_the_completion_marker() {
        let root = tempfile::tempdir().expect("LMDB publication root");
        let profile = LmdbQualificationProfile::open(root.path()).expect("open LMDB profile");
        populate_records(&profile, "backup", 0..4, 64);
        profile
            .put_content_once(
                "sha256:1000000000000000000000000000000000000000000000000000000000000000",
                QualificationRecordKindV1::NoteBody,
                b"independent",
            )
            .unwrap();
        let backup = root.path().join("completed");
        profile
            .backup_to(&backup)
            .expect("publish completed backup");
        let manifest = verify_completed_backup(&backup, &profile.descriptor().unwrap()).unwrap();

        assert!(backup.join(BACKUP_COMPLETION_FILE_V1).is_file());
        assert!(backup.join(BACKUP_MANIFEST_FILE_V1).is_file());
        assert!(
            manifest
                .carriers
                .iter()
                .any(|carrier| carrier.relative_path == LMDB_BACKUP_DATABASE_FILE_V1)
        );
        assert!(
            manifest
                .carriers
                .iter()
                .any(|carrier| carrier.relative_path.starts_with("content/"))
        );
        assert!(
            manifest
                .carriers
                .iter()
                .any(|carrier| carrier.relative_path == LMDB_BACKUP_RECEIPT_FILE_V1)
        );
    }

    #[test]
    fn interrupted_backup_is_incomplete_and_retry_does_not_reinterpret_it() {
        let root = tempfile::tempdir().expect("LMDB interrupted-copy root");
        let results = tempfile::tempdir().expect("LMDB interrupted-copy results");
        let profile = LmdbQualificationProfile::open(root.path()).expect("open LMDB profile");
        populate_records(&profile, "interrupt", 0..32, 2048);
        let barrier_root = results.path().join("barrier");
        fs::create_dir(&barrier_root).expect("create interruption barrier root");
        let barrier = QualificationProcessBarrierV1::create(&barrier_root, &["copy"])
            .expect("create interruption barrier");
        let destination = results.path().join("interrupted");
        let mut child = spawn_child(
            "interrupt_backup",
            root.path(),
            "unused",
            b"",
            &destination,
            Some((&barrier_root, "copy")),
        );
        barrier.wait_until_ready(Duration::from_secs(20)).unwrap();
        child.kill().expect("terminate interrupted copy");
        assert!(!child.wait().expect("wait interrupted copy").success());

        assert!(!destination.join(BACKUP_COMPLETION_FILE_V1).exists());
        assert!(verify_completed_backup(&destination, &profile.descriptor().unwrap()).is_err());
        assert!(profile.backup_to(&destination).is_err());
    }

    #[test]
    fn exact_restore_runs_in_a_fresh_process_without_mutating_the_backup() {
        let root = tempfile::tempdir().expect("LMDB fresh-restore root");
        let results = tempfile::tempdir().expect("LMDB fresh-restore results");
        let profile = LmdbQualificationProfile::open(root.path()).expect("open LMDB profile");
        populate_records(&profile, "restore", 0..12, 256);
        let expected = profile.exact_receipt().unwrap();
        let backup = results.path().join("backup");
        profile.backup_to(&backup).unwrap();
        let backup_before = tree_receipt(&backup);
        let restored_root = results.path().join("restored");
        let receipt_path = results.path().join("restored-receipt.json");

        wait_success(spawn_child(
            "restore",
            &backup,
            restored_root.to_string_lossy().as_ref(),
            b"",
            &receipt_path,
            None,
        ));
        let actual: LmdbExactReceiptV1 =
            serde_json::from_slice(&fs::read(receipt_path).unwrap()).unwrap();
        assert_eq!(actual, expected);
        assert_eq!(
            truth_carrier_identity(&backup).unwrap(),
            truth_carrier_identity(&restored_root).unwrap()
        );
        assert_eq!(tree_receipt(&backup), backup_before);
    }

    #[test]
    fn fresh_copy_repair_preserves_source_and_rejects_corrupt_or_incomplete_truth() {
        let root = tempfile::tempdir().expect("LMDB repair root");
        let results = tempfile::tempdir().expect("LMDB repair results");
        let profile = LmdbQualificationProfile::open(root.path()).expect("open LMDB profile");
        populate_records(&profile, "repair", 0..8, 128);
        let expected = profile.exact_receipt().unwrap();
        let source_before = tree_receipt(root.path());
        let repaired_backup = results.path().join("repaired-backup");

        profile
            .repair_to(&repaired_backup)
            .expect("fresh-copy repair");
        assert_eq!(tree_receipt(root.path()), source_before);
        let repaired_root = results.path().join("repaired-root");
        restore_completed_lmdb_backup_v1(&repaired_backup, &repaired_root).unwrap();
        assert_eq!(
            LmdbQualificationProfile::open(&repaired_root)
                .unwrap()
                .exact_receipt()
                .unwrap(),
            expected
        );
        assert_eq!(
            truth_carrier_identity(&repaired_backup).unwrap(),
            truth_carrier_identity(&repaired_root).unwrap()
        );

        drop(profile);
        overwrite_raw_journal_value_for_test(root.path(), "journal/corrupt", b"bad").unwrap();
        let corrupt = LmdbQualificationProfile::open(root.path()).unwrap();
        assert!(
            corrupt
                .repair_to(&results.path().join("corrupt-output"))
                .is_err()
        );
        let incomplete = results.path().join("incomplete-output");
        fs::create_dir(&incomplete).unwrap();
        fs::write(incomplete.join("partial"), b"partial").unwrap();
        assert!(corrupt.repair_to(&incomplete).is_err());
    }

    #[test]
    fn inventory_classifies_all_owned_carriers_and_excludes_virtual_map_reservation() {
        let root = tempfile::tempdir().expect("LMDB inventory root");
        let profile = LmdbQualificationProfile::open(root.path()).expect("open LMDB profile");
        populate_records(&profile, "inventory", 0..4, 64);
        profile
            .journal
            .refresh_map()
            .expect("materialize resize lock");
        profile
            .put_content_once(
                "sha256:2000000000000000000000000000000000000000000000000000000000000000",
                QualificationRecordKindV1::ObjectArtifact,
                b"content",
            )
            .unwrap();
        let inventory = profile.inventory().expect("native LMDB inventory");
        let sanitized = profile.sanitized_inventory().expect("sanitized inventory");

        assert_eq!(LmdbCarrierClassV1::ALL.len(), 10);
        assert!(
            sanitized
                .carrier_classes
                .contains(&LmdbCarrierClassV1::Database)
        );
        assert!(
            sanitized
                .carrier_classes
                .contains(&LmdbCarrierClassV1::Lock)
        );
        assert!(
            sanitized
                .carrier_classes
                .contains(&LmdbCarrierClassV1::ResizeLock)
        );
        assert!(
            sanitized
                .carrier_classes
                .contains(&LmdbCarrierClassV1::IndependentContent)
        );
        assert!(inventory.allocated_bytes < profile.current_map_size_bytes());
        assert_eq!(inventory.high_water_bytes, inventory.allocated_bytes);
        assert_eq!(
            sanitized
                .class_inventories
                .iter()
                .find(|class| class.class == LmdbCarrierClassV1::Pinned)
                .expect("pinned class remains explicit")
                .carrier_count,
            0
        );
        let json = serde_json::to_string(&sanitized).unwrap();
        assert!(!json.contains(root.path().to_string_lossy().as_ref()));
        assert!(!json.contains("data.mdb"));
        assert!(!json.contains("lock.mdb"));
    }

    #[test]
    fn lifecycle_schema_mode_and_carrier_names_are_frozen() {
        assert_eq!(
            QUALIFICATION_LMDB_LIFECYCLE_SMOKE_SCHEMA_V1,
            "pointbreak.qualification-lmdb-lifecycle-smoke.v1"
        );
        assert_eq!(
            QUALIFICATION_LMDB_LIFECYCLE_SMOKE_MODE_V1,
            "--lmdb-lifecycle-smoke"
        );
        assert_eq!(
            QUALIFICATION_LMDB_LIFECYCLE_REPORT_MODE_V1,
            "non_timing_lifecycle_receipts"
        );
        assert_eq!(
            serde_json::to_value(LmdbCarrierClassV1::ALL).unwrap(),
            serde_json::json!([
                "database",
                "lock",
                "resize_lock",
                "independent_content",
                "copy",
                "temporary",
                "obsolete",
                "pinned",
                "repair",
                "sidecar"
            ])
        );
    }

    #[cfg(windows)]
    #[test]
    fn windows_open_handles_block_replacement_then_allow_reopen_and_cleanup() {
        let root = tempfile::tempdir().expect("LMDB Windows lifecycle root");
        let source = LmdbQualificationProfile::open(&root.path().join("source"))
            .expect("open LMDB source profile");
        populate_records(&source, "windows", 0..4, 64);
        let backup = root.path().join("backup");
        source.backup_to(&backup).expect("create online backup");
        let open_root = root.path().join("open");
        let expected = restore_completed_lmdb_backup_v1(&backup, &open_root).unwrap();
        let profile = LmdbQualificationProfile::open(&open_root).expect("open restored profile");
        let database = open_root.join(JOURNAL_DIRECTORY_V1).join("data.mdb");
        let replacement = open_root.join(JOURNAL_DIRECTORY_V1).join("replacement.mdb");
        copy_file_synced(&backup.join(LMDB_BACKUP_DATABASE_FILE_V1), &replacement)
            .expect("copy offline replacement carrier");
        assert!(fs::remove_file(&database).is_err());
        let closing = heed3::env_closing_event(open_root.join(JOURNAL_DIRECTORY_V1)).unwrap();
        drop(profile);
        closing.wait();
        fs::remove_file(&database).expect("remove after handles close");
        fs::rename(&replacement, &database).expect("install replacement after handles close");
        let reopened = LmdbQualificationProfile::open(&open_root).expect("reopen after replace");
        assert_eq!(reopened.exact_receipt().unwrap(), expected);
    }

    #[test]
    fn g0_smoke_is_non_timing_and_uses_the_plain_profile_identity() {
        let root = tempfile::tempdir().expect("LMDB smoke root");
        let report = run_qualification_lmdb_smoke_v1(root.path()).expect("LMDB G0 smoke");

        assert_eq!(report.schema, "pointbreak.qualification-lmdb-smoke.v1");
        assert_eq!(report.mode, "non_timing_semantic_receipts");
        assert_eq!(report.profile_id, QUALIFICATION_LMDB_PLAIN_PROFILE_ID_V1);
        assert_eq!(report.workload, QualificationGeneratedWorkloadV1::G0);
        assert_eq!(report.records, 128);
        assert_eq!(report.head_marker, 128);
        assert!(report.receipts_exact);
    }
}