hawdb 0.19.0

An embedded Rust graph database for local data-plane workloads
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
// Copyright 2026 Nowledge
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::search::{
    AdaptiveVectorSearchOptions, CompressedVectorSearchMode, SearchFallbackReasonCode,
    SearchLexicalProductionQualificationReport, SearchOutOfCoreConfig,
    SearchOutOfCoreHydrationOutput, SearchOutOfCoreMetrics, SearchOutOfCoreReader,
    SearchQueryOptions, SearchRangeReadConfig, VectorRecallProductionQualificationReport,
    VectorRecallValidationOptions, VectorRecallValidationReport, VectorSearchExecutionOptions,
    NOWLEDGE_SEARCH_PROJECTION_SCAN_FILTER_FIELDS,
};
use crate::search_projection_evidence::{
    nowledge_search_projection_evidence_json, nowledge_search_projection_shadow_evidence_json,
    NowledgeSearchProjectionEvidenceReport,
};
use crate::{
    cypher, BackgroundMaintenanceKind, BackgroundMaintenanceOptions, BackgroundMaintenanceSummary,
    BackgroundWorkHint, BackgroundWorkPlan, BoundedReadQueryOutput, Database, DatabaseConfig,
    DatabaseReadTransaction, GraphRagGeneratedQuery, GraphRagSchemaContext,
    GraphRagSchemaContextOptions, HawDBError, HawDBLightningBootstrapManifest,
    HawDBLightningInitialImportApplyReport, HawDBLightningInitialImportCheckpoint,
    HawDBLightningInitialImportCutoverCatchUpReport, HawDBLightningInitialImportDocumentIdentity,
    HawDBLightningInitialImportRecoveryReadinessReport, KnowledgeRetrievalOutput,
    KnowledgeRetrievalRequest, LocalQosPolicy, LocalQosState, NowledgeGraphStatement,
    PlanCacheLookup, QueryOutput, QueryStreamOptions, QueryStreamReport, ReadBudgetResource,
    ReadExecutionProfile, Result, ScheduledSearchProjectionCatchUpReport, SearchDocument,
    SearchIndex, SearchProjectionCatchUpReport, SearchProjectionChangeBatch,
    SearchProjectionChangefeedReadiness, SearchProjectionDelta, SearchProjectionDeltaReport,
    SearchProjectionFreshness, SearchProjectionGraphDeltaRequest, SearchProjectionProbeOptions,
    SearchProjectionRelationalDelta, SearchResultSet, StorageResourceProfileLimits,
    StorageResourceProfileReport, TelemetrySink, Value, STORAGE_RESOURCE_PROFILE_PROTOCOL,
};
use crate::{
    graph_route_readiness::NMEM_GRAPH_ROUTE_READINESS_PROTOCOL,
    nowledge_inventory::{
        background_maintenance_evidence_health, background_maintenance_summary_to_json,
        replacement_readiness_family_evidence_health, REQUIRED_NOWLEDGE_REPLACEMENT_QUERY_FAMILIES,
    },
    route_ownership::NowledgeMemRouteOwnershipReadinessReport,
    search_route_ownership::{
        NowledgeMemActiveSearchRouteOwnershipReadinessReport,
        NowledgeMemActiveSearchRouteReadinessReport,
        NowledgeMemSearchRouteOwnershipReadinessReport,
        NOWLEDGE_MEM_ACTIVE_SEARCH_ROUTE_READINESS_PROTOCOL,
        NOWLEDGE_MEM_SEARCH_ROUTE_OWNERSHIP_PROTOCOL, REQUIRED_NOWLEDGE_MEM_ACTIVE_SEARCH_ROUTES,
        REQUIRED_NOWLEDGE_MEM_SEARCH_ROUTES,
    },
    workload_fixtures::{
        NowledgeGraphRouteWorkloadFixtureReport, NOWLEDGE_GRAPH_ROUTE_WORKLOAD_FIXTURE_PROTOCOL,
    },
};
use hawdb_core::RuntimeTaskContext;
mod concurrent_owner;
mod incremental_search;
mod read_execution;
mod resident_read;
mod search_read;
use resident_read::ResidentProjectionRef;
mod handle;
mod registered_search;
use handle::*;
pub use handle::{NowledgeMemEmbeddedStoreHandle, NowledgeMemReadSnapshot};
use hawdb_optimizer::AdaptiveVectorBackendPolicy;
use hawdb_qos::{
    IoConcurrencyBudget, RuntimeGovernor, RuntimeGovernorConfig, RuntimeGovernorSnapshot,
    RuntimePermit, RuntimeWorkKind, RuntimeWorkPriority, RuntimeWorkRequest, StorageDeviceProfile,
    WorkPriority,
};
pub use hawdb_readiness::bounded_read_evidence::{
    nowledge_mem_bounded_read_evidence_json,
    nowledge_mem_bounded_read_evidence_json_with_route_readiness,
    nowledge_mem_bounded_read_evidence_json_with_routes, NowledgeMemGraphMode,
    NowledgeMemReadReport, NowledgeMemRouteReadinessSummary,
    NOWLEDGE_MEM_BOUNDED_READ_EVIDENCE_PROTOCOL, NOWLEDGE_MEM_READ_REPORT_PROTOCOL,
};
use hawdb_readiness::nowledge_mem_query_report::nowledge_mem_plan_cache_report;
pub use hawdb_readiness::nowledge_mem_query_report::{
    nowledge_mem_fast_path_classification, NowledgeMemFastPathClassification,
    NowledgeMemQueryApiBehavior, NowledgeMemQueryExecutionPath, NowledgeMemQueryOutput,
    NowledgeMemQueryOutputRowShape, NowledgeMemQueryReport, NowledgeMemQueryReportOptions,
    NOWLEDGE_MEM_QUERY_REPORT_PROTOCOL,
};
pub use hawdb_readiness::query_runtime_preflight::NowledgeQueryRuntimePreflightProbe;
use hawdb_readiness::query_runtime_preflight_report::{
    hawdb_error_class, nowledge_query_runtime_route_coverage,
    query_runtime_preflight_blocker_codes, query_runtime_probe_blocker_codes,
};
pub use hawdb_readiness::query_runtime_preflight_report::{
    NowledgeQueryRuntimePreflightProbeReport, NowledgeQueryRuntimePreflightRedactionSummary,
    NowledgeQueryRuntimePreflightReport,
};
pub use hawdb_readiness::slow_query::{
    NowledgeMemSlowQueryRecord, NowledgeMemSlowQueryReport, NOWLEDGE_MEM_SLOW_QUERY_REPORT_PROTOCOL,
};
pub use hawdb_readiness::{NowledgeMemReadinessAreaMap, NowledgeMemReadinessAreaSummary};
pub use incremental_search::NowledgeMemIncrementalSearchMaintenanceOptions;
pub use registered_search::{
    NowledgeMemDefinedSearchProjectionConsumer, NowledgeMemPreparedConsumerUpdate,
    NowledgeMemSearchProjectionConsumer,
};

#[cfg(test)]
mod slow_query_facade_tests {
    use super::*;
    use std::any::TypeId;

    #[test]
    fn facade_reexports_slow_query_contracts_without_conversion() {
        assert_eq!(
            TypeId::of::<NowledgeMemSlowQueryRecord>(),
            TypeId::of::<hawdb_readiness::slow_query::NowledgeMemSlowQueryRecord>(),
        );
        assert_eq!(
            TypeId::of::<NowledgeMemSlowQueryReport>(),
            TypeId::of::<hawdb_readiness::slow_query::NowledgeMemSlowQueryReport>(),
        );
        assert_eq!(
            NOWLEDGE_MEM_SLOW_QUERY_REPORT_PROTOCOL,
            hawdb_readiness::slow_query::NOWLEDGE_MEM_SLOW_QUERY_REPORT_PROTOCOL,
        );
    }
}
use hawdb_search::candidate_evidence::{
    advised_compressed_vector_search_mode, effective_search_candidate_mode,
    nowledge_mem_search_candidate_report, retrieval_projection_advisor_blocker_codes,
    retrieval_projection_advisor_json,
};
pub use hawdb_search::candidate_evidence::{
    nowledge_mem_search_candidate_shadow_evidence_json, NowledgeMemRetrievalProjectionAdvisor,
    NowledgeMemSearchCandidateFieldSummary, NowledgeMemSearchCandidateFilterPushdownEvidence,
    NowledgeMemSearchCandidateOutput, NowledgeMemSearchCandidateReadinessOptions,
    NowledgeMemSearchCandidateReadinessReport, NowledgeMemSearchCandidateReport,
    NowledgeMemSearchCandidateRequest, NowledgeMemSearchCandidateShadowAccumulator,
    NowledgeMemSearchCandidateShadowEvidence, NOWLEDGE_MEM_SEARCH_CANDIDATE_EVIDENCE_ROUTE,
    NOWLEDGE_MEM_SEARCH_CANDIDATE_EVIDENCE_SOURCE, NOWLEDGE_MEM_SEARCH_CANDIDATE_PRIMARY_ENGINE,
    NOWLEDGE_MEM_SEARCH_CANDIDATE_READINESS_PROTOCOL,
    NOWLEDGE_MEM_SEARCH_CANDIDATE_REPORT_PROTOCOL, NOWLEDGE_MEM_SEARCH_CANDIDATE_SHADOW_ENGINE,
    NOWLEDGE_MEM_SEARCH_CANDIDATE_SHADOW_EVIDENCE_PROTOCOL,
    NOWLEDGE_MEM_SEARCH_CANDIDATE_TRACE_EVIDENCE_SOURCE,
    NOWLEDGE_MEM_SEARCH_CANDIDATE_TRACE_PRIMARY_ENGINE,
    NOWLEDGE_MEM_SEARCH_CANDIDATE_TRACE_SHADOW_ENGINE,
};
use std::collections::{BTreeMap, BTreeSet};
use std::mem::size_of;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::Instant;

#[cfg(test)]
#[path = "nowledge_mem_app_read_snapshot_tests.rs"]
mod app_read_snapshot_tests;
#[cfg(test)]
mod candidate_facade_tests;

#[cfg(test)]
mod runtime_status_facade_tests {
    use super::{
        NowledgeMemCutoverControls, NowledgeMemCutoverControlsReport, NowledgeMemProductionStatus,
        NowledgeMemReadControl, NowledgeMemRuntimeStatus, NowledgeMemWorkControl,
    };
    use std::any::TypeId;

    #[test]
    fn root_facade_preserves_runtime_status_type_identity() {
        assert_eq!(
            TypeId::of::<NowledgeMemRuntimeStatus>(),
            TypeId::of::<hawdb_readiness::nowledge_mem_runtime_status::NowledgeMemRuntimeStatus>()
        );
        assert_eq!(
            TypeId::of::<NowledgeMemProductionStatus>(),
            TypeId::of::<hawdb_readiness::nowledge_mem_runtime_status::NowledgeMemProductionStatus>(
            )
        );
        assert_eq!(
            TypeId::of::<NowledgeMemReadControl>(),
            TypeId::of::<hawdb_readiness::nowledge_mem_cutover::NowledgeMemReadControl>()
        );
        assert_eq!(
            TypeId::of::<NowledgeMemWorkControl>(),
            TypeId::of::<hawdb_readiness::nowledge_mem_cutover::NowledgeMemWorkControl>()
        );
        assert_eq!(
            TypeId::of::<NowledgeMemCutoverControls>(),
            TypeId::of::<hawdb_readiness::nowledge_mem_cutover::NowledgeMemCutoverControls>()
        );
        assert_eq!(
            TypeId::of::<NowledgeMemCutoverControlsReport>(),
            TypeId::of::<hawdb_readiness::nowledge_mem_cutover::NowledgeMemCutoverControlsReport>()
        );
    }
}

pub use hawdb_readiness::nowledge_mem_serving_path::{
    NowledgeMemServingEntrypoint, NowledgeMemServingPathReadiness,
    NOWLEDGE_MEM_SERVING_PATH_READINESS_PROTOCOL,
};

const TYPED_CONTROL_STATEMENT_MEMORY_BYTES: u64 = 1024 * 1024;
const SEARCH_PROJECTION_CHANGEFEED_OPERATION_BYTES: usize = 1024;

pub fn nowledge_mem_graph_config(mode: NowledgeMemGraphMode) -> DatabaseConfig {
    nowledge_mem_graph_config_with_search_mode(mode, CompressedVectorSearchMode::Disabled)
}

pub fn nowledge_mem_graph_config_with_search_mode(
    mode: NowledgeMemGraphMode,
    compressed_vector_search_mode: CompressedVectorSearchMode,
) -> DatabaseConfig {
    DatabaseConfig {
        read_only: matches!(mode, NowledgeMemGraphMode::ShadowReadOnly),
        compressed_vector_search_mode,
        ..DatabaseConfig::default()
    }
}

fn default_nowledge_mem_runtime_governor(
    path: &Path,
    database_config: &DatabaseConfig,
) -> RuntimeGovernor {
    let storage_device = StorageDeviceProfile::detect(path);
    let mut governor_config = RuntimeGovernorConfig::shared_host();
    if let Some(max_payload_bytes) = database_config.max_read_result_payload_bytes {
        governor_config.result_budget_bytes = u64::try_from(max_payload_bytes).unwrap_or(u64::MAX);
    }
    RuntimeGovernor::detect(
        governor_config,
        IoConcurrencyBudget::shared_host_for_device(storage_device),
    )
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NowledgeMemOpenOptions {
    pub graph_path: PathBuf,
    pub search_projection_path: Option<PathBuf>,
    pub search_projection_open_mode: NowledgeMemSearchProjectionOpenMode,
    pub mode: NowledgeMemGraphMode,
    pub database_config: Option<DatabaseConfig>,
    pub compressed_vector_search_mode: CompressedVectorSearchMode,
    pub adaptive_vector_backend_policy: AdaptiveVectorBackendPolicy,
    pub retrieval_projection_advisor: NowledgeMemRetrievalProjectionAdvisor,
    pub search_range_read_config: Option<SearchRangeReadConfig>,
    pub system_schema_registries: Vec<crate::SystemSchemaRegistry>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NowledgeMemQualifiedOutOfCoreSearchOptions {
    pub config: SearchOutOfCoreConfig,
    pub qualification: SearchLexicalProductionQualificationReport,
    pub expected_identity: crate::ProductionQualificationIdentity,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NowledgeMemSearchProjectionOpenMode {
    FullResidencyMaintenance,
    IncrementalMaintenance(Box<NowledgeMemIncrementalSearchMaintenanceOptions>),
    QualifiedOutOfCore(Box<NowledgeMemQualifiedOutOfCoreSearchOptions>),
}

impl NowledgeMemSearchProjectionOpenMode {
    fn role(&self) -> NowledgeMemSearchProjectionRole {
        match self {
            Self::FullResidencyMaintenance => {
                NowledgeMemSearchProjectionRole::FullResidencyMaintenance
            }
            Self::IncrementalMaintenance(_) => {
                NowledgeMemSearchProjectionRole::IncrementalMaintenance
            }
            Self::QualifiedOutOfCore(_) => NowledgeMemSearchProjectionRole::QualifiedOutOfCore,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NowledgeMemSearchProjectionRole {
    FullResidencyMaintenance,
    IncrementalMaintenance,
    QualifiedOutOfCore,
}

impl NowledgeMemSearchProjectionRole {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::FullResidencyMaintenance => "full_residency_maintenance",
            Self::IncrementalMaintenance => "incremental_maintenance",
            Self::QualifiedOutOfCore => "qualified_out_of_core",
        }
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct NowledgeMemOpenDiagnosticOptions {
    pub include_local_paths: bool,
}

impl NowledgeMemOpenOptions {
    pub fn graph_only(graph_path: impl Into<PathBuf>, mode: NowledgeMemGraphMode) -> Self {
        Self {
            graph_path: graph_path.into(),
            search_projection_path: None,
            search_projection_open_mode:
                NowledgeMemSearchProjectionOpenMode::FullResidencyMaintenance,
            mode,
            database_config: None,
            compressed_vector_search_mode: CompressedVectorSearchMode::Disabled,
            adaptive_vector_backend_policy: AdaptiveVectorBackendPolicy::default(),
            retrieval_projection_advisor: NowledgeMemRetrievalProjectionAdvisor::default(),
            search_range_read_config: None,
            system_schema_registries: Vec::new(),
        }
    }

    pub fn with_search_projection(
        graph_path: impl Into<PathBuf>,
        search_projection_path: impl Into<PathBuf>,
        mode: NowledgeMemGraphMode,
    ) -> Self {
        Self {
            graph_path: graph_path.into(),
            search_projection_path: Some(search_projection_path.into()),
            search_projection_open_mode:
                NowledgeMemSearchProjectionOpenMode::FullResidencyMaintenance,
            mode,
            database_config: None,
            compressed_vector_search_mode: CompressedVectorSearchMode::Disabled,
            adaptive_vector_backend_policy: AdaptiveVectorBackendPolicy::default(),
            retrieval_projection_advisor: NowledgeMemRetrievalProjectionAdvisor::default(),
            search_range_read_config: None,
            system_schema_registries: Vec::new(),
        }
    }

    pub fn with_qualified_out_of_core_search_projection(
        graph_path: impl Into<PathBuf>,
        search_projection_path: impl Into<PathBuf>,
        mode: NowledgeMemGraphMode,
        qualified: NowledgeMemQualifiedOutOfCoreSearchOptions,
    ) -> Self {
        Self {
            graph_path: graph_path.into(),
            search_projection_path: Some(search_projection_path.into()),
            search_projection_open_mode: NowledgeMemSearchProjectionOpenMode::QualifiedOutOfCore(
                Box::new(qualified),
            ),
            mode,
            database_config: None,
            compressed_vector_search_mode: CompressedVectorSearchMode::Disabled,
            adaptive_vector_backend_policy: AdaptiveVectorBackendPolicy::default(),
            retrieval_projection_advisor: NowledgeMemRetrievalProjectionAdvisor::default(),
            search_range_read_config: None,
            system_schema_registries: Vec::new(),
        }
    }

    pub fn with_compressed_vector_search_mode(mut self, mode: CompressedVectorSearchMode) -> Self {
        self.compressed_vector_search_mode = mode;
        self
    }

    /// Overrides resource and storage policy while retaining facade-owned mode
    /// and vector-backend settings.
    /// An explicit namespace durability anchor also applies to the search
    /// projection and must contain both paths. The host must already guarantee
    /// the anchor's namespace durability.
    pub fn with_database_config(mut self, config: DatabaseConfig) -> Self {
        self.database_config = Some(config);
        self
    }

    /// Registers application-owned system schemas that must be current before
    /// the embedded store is returned to its host.
    pub fn with_system_schema_registry(mut self, registry: crate::SystemSchemaRegistry) -> Self {
        self.system_schema_registries.push(registry);
        self
    }

    pub fn with_adaptive_vector_backend_policy(
        mut self,
        policy: AdaptiveVectorBackendPolicy,
    ) -> Self {
        self.adaptive_vector_backend_policy = policy;
        self
    }

    pub fn with_retrieval_projection_advisor(
        mut self,
        advisor: NowledgeMemRetrievalProjectionAdvisor,
    ) -> Self {
        self.retrieval_projection_advisor = advisor;
        self
    }

    pub fn with_search_range_read_config(mut self, config: SearchRangeReadConfig) -> Self {
        self.search_range_read_config = Some(config);
        self
    }

    fn effective_compressed_vector_search_mode(&self) -> CompressedVectorSearchMode {
        advised_compressed_vector_search_mode(
            self.compressed_vector_search_mode,
            &self.retrieval_projection_advisor,
        )
    }

    fn effective_database_config(&self) -> DatabaseConfig {
        let mut config = self.database_config.clone().unwrap_or_default();
        config.read_only = matches!(self.mode, NowledgeMemGraphMode::ShadowReadOnly);
        config.compressed_vector_search_mode = self.effective_compressed_vector_search_mode();
        config.adaptive_vector_backend_policy = self.adaptive_vector_backend_policy;
        config
    }

    fn validate(&self) -> Result<()> {
        match (
            self.search_projection_path.as_ref(),
            &self.search_projection_open_mode,
        ) {
            (None, NowledgeMemSearchProjectionOpenMode::IncrementalMaintenance(_)) => {
                return Err(HawDBError::Semantic(
                    "incremental search maintenance requires search_projection_path".into(),
                ));
            }
            (Some(_), NowledgeMemSearchProjectionOpenMode::IncrementalMaintenance(options)) => {
                options.validate()?;
                if self.search_range_read_config.is_some() {
                    return Err(HawDBError::Semantic(
                        "incremental search maintenance uses its typed reader configuration".into(),
                    ));
                }
            }
            (None, NowledgeMemSearchProjectionOpenMode::QualifiedOutOfCore(_)) => {
                return Err(HawDBError::Semantic(
                    "qualified out-of-core search requires search_projection_path".to_string(),
                ));
            }
            (Some(_), NowledgeMemSearchProjectionOpenMode::QualifiedOutOfCore(qualified)) => {
                qualified.expected_identity.validate()?;
                if self.search_range_read_config.is_some() {
                    return Err(HawDBError::Semantic(
                        "search_range_read_config applies only to the full-residency maintenance projection"
                            .to_string(),
                    ));
                }
            }
            _ => {}
        }
        if self.search_projection_path.is_none() && self.search_range_read_config.is_some() {
            return Err(HawDBError::Semantic(
                "search_range_read_config requires search_projection_path".to_string(),
            ));
        }
        let mut schema_owners = BTreeSet::new();
        for registry in &self.system_schema_registries {
            if !schema_owners.insert(registry.owner()) {
                return Err(HawDBError::Semantic(format!(
                    "system schema owner {} is registered more than once",
                    registry.owner()
                )));
            }
        }
        Ok(())
    }

    pub fn sanitized_report(&self) -> NowledgeMemOpenReport {
        let effective_compressed_vector_search_mode =
            self.effective_compressed_vector_search_mode();
        NowledgeMemOpenReport {
            protocol: NOWLEDGE_MEM_OPEN_REPORT_PROTOCOL.to_string(),
            mode: self.mode,
            graph_configured: true,
            search_projection_configured: self.search_projection_path.is_some(),
            search_projection_role: self
                .search_projection_path
                .as_ref()
                .map(|_| self.search_projection_open_mode.role()),
            compressed_vector_search_mode: effective_compressed_vector_search_mode,
            requested_compressed_vector_search_mode: self.compressed_vector_search_mode,
            adaptive_vector_backend_policy: self.adaptive_vector_backend_policy,
            retrieval_projection_advisor: self.retrieval_projection_advisor.clone(),
            retrieval_projection_advisor_blocker_codes: if self.compressed_vector_search_mode
                == effective_compressed_vector_search_mode
            {
                Vec::new()
            } else {
                retrieval_projection_advisor_blocker_codes(&self.retrieval_projection_advisor)
            },
            graph_opened: false,
            search_projection_opened: false,
            search_production_qualification_bound: false,
            system_schema_upgrades: Vec::new(),
        }
    }

    pub fn diagnostic_report_json(
        &self,
        options: NowledgeMemOpenDiagnosticOptions,
    ) -> serde_json::Value {
        let mut report = self.sanitized_report().json();
        if let Some(object) = report.as_object_mut() {
            object.insert(
                "debug_local_paths_included".to_string(),
                serde_json::Value::Bool(options.include_local_paths),
            );
            object.insert(
                "local_paths_redacted".to_string(),
                serde_json::Value::Bool(!options.include_local_paths),
            );
            if options.include_local_paths {
                object.insert(
                    "graph_path".to_string(),
                    serde_json::Value::String(self.graph_path.to_string_lossy().into_owned()),
                );
                object.insert(
                    "search_projection_path".to_string(),
                    self.search_projection_path
                        .as_ref()
                        .map(|path| serde_json::Value::String(path.to_string_lossy().into_owned()))
                        .unwrap_or(serde_json::Value::Null),
                );
            }
        }
        report
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NowledgeMemOpenReport {
    pub protocol: String,
    pub mode: NowledgeMemGraphMode,
    pub graph_configured: bool,
    pub search_projection_configured: bool,
    pub search_projection_role: Option<NowledgeMemSearchProjectionRole>,
    pub compressed_vector_search_mode: CompressedVectorSearchMode,
    pub requested_compressed_vector_search_mode: CompressedVectorSearchMode,
    pub adaptive_vector_backend_policy: AdaptiveVectorBackendPolicy,
    pub retrieval_projection_advisor: NowledgeMemRetrievalProjectionAdvisor,
    pub retrieval_projection_advisor_blocker_codes: Vec<String>,
    pub graph_opened: bool,
    pub search_projection_opened: bool,
    pub search_production_qualification_bound: bool,
    pub system_schema_upgrades: Vec<crate::SystemSchemaUpgradeReport>,
}

impl NowledgeMemOpenReport {
    pub fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "protocol": self.protocol,
            "mode": self.mode.as_str(),
            "graph_configured": self.graph_configured,
            "search_projection_configured": self.search_projection_configured,
            "search_projection_role": self.search_projection_role.map(NowledgeMemSearchProjectionRole::as_str),
            "compressed_vector_search_mode": self.compressed_vector_search_mode.as_str(),
            "requested_compressed_vector_search_mode": self.requested_compressed_vector_search_mode.as_str(),
            "adaptive_vector_backend_policy": {
                "flat_scan_max_documents": self.adaptive_vector_backend_policy.flat_scan_max_documents,
                "high_filter_selectivity_per_million": self.adaptive_vector_backend_policy.high_filter_selectivity_per_million,
                "flat_scan_memory_budget_bytes": self.adaptive_vector_backend_policy.flat_scan_memory_budget_bytes,
            },
            "retrieval_projection_advisor": retrieval_projection_advisor_json(&self.retrieval_projection_advisor),
            "retrieval_projection_advisor_blocker_codes": self.retrieval_projection_advisor_blocker_codes,
            "graph_opened": self.graph_opened,
            "search_projection_opened": self.search_projection_opened,
            "search_production_qualification_bound": self.search_production_qualification_bound,
            "system_schema_upgrades": self.system_schema_upgrades.iter().map(|upgrade| serde_json::json!({
                "owner": upgrade.owner,
                "previous_version": upgrade.previous_version,
                "current_version": upgrade.current_version,
                "applied_versions": upgrade.applied_versions,
                "commit_epoch_before": upgrade.commit_epoch_before,
                "commit_epoch_after": upgrade.commit_epoch_after,
            })).collect::<Vec<_>>(),
        })
    }
}

pub use hawdb_readiness::nowledge_mem_runtime_status::{
    NowledgeMemProductionStatus, NowledgeMemRuntimeStatus, NOWLEDGE_MEM_PRODUCTION_STATUS_PROTOCOL,
    NOWLEDGE_MEM_RUNTIME_STATUS_PROTOCOL,
};

pub use hawdb_readiness::nowledge_mem_cutover::{
    NowledgeMemCutoverControls, NowledgeMemCutoverControlsReport, NowledgeMemReadControl,
    NowledgeMemWorkControl,
};

pub use hawdb_nowledge_contracts::{
    NowledgeMemReadSnapshotBudget, NowledgeMemReadSnapshotReport,
    NowledgeMemStorageLifecycleActionKind, NowledgeMemStorageLifecycleDecision,
    NowledgeMemStorageRecoveryReport, NOWLEDGE_MEM_READ_SNAPSHOT_REPORT_PROTOCOL,
    NOWLEDGE_MEM_STORAGE_LIFECYCLE_DECISION_PROTOCOL,
};

#[cfg(test)]
mod storage_lifecycle_facade_tests {
    use super::*;
    use std::any::TypeId;

    #[test]
    fn facade_reexports_storage_lifecycle_contracts_without_conversion() {
        assert_eq!(
            TypeId::of::<NowledgeMemStorageRecoveryReport>(),
            TypeId::of::<hawdb_nowledge_contracts::NowledgeMemStorageRecoveryReport>(),
        );
        assert_eq!(
            TypeId::of::<NowledgeMemStorageLifecycleDecision>(),
            TypeId::of::<hawdb_nowledge_contracts::NowledgeMemStorageLifecycleDecision>(),
        );
        assert_eq!(
            TypeId::of::<NowledgeMemStorageLifecycleActionKind>(),
            TypeId::of::<hawdb_nowledge_contracts::NowledgeMemStorageLifecycleActionKind>(),
        );
    }

    #[test]
    fn facade_reexports_read_snapshot_contracts_without_conversion() {
        assert_eq!(
            TypeId::of::<NowledgeMemReadSnapshotBudget>(),
            TypeId::of::<hawdb_nowledge_contracts::NowledgeMemReadSnapshotBudget>(),
        );
        assert_eq!(
            TypeId::of::<NowledgeMemReadSnapshotReport>(),
            TypeId::of::<hawdb_nowledge_contracts::NowledgeMemReadSnapshotReport>(),
        );
        assert_eq!(
            NOWLEDGE_MEM_READ_SNAPSHOT_REPORT_PROTOCOL,
            hawdb_nowledge_contracts::NOWLEDGE_MEM_READ_SNAPSHOT_REPORT_PROTOCOL,
        );
    }
}

pub use hawdb_readiness::source_mutation::{
    nowledge_mem_source_mutation_dual_write_evidence_all_ready,
    nowledge_mem_source_mutation_dual_write_readiness,
    nowledge_mem_source_mutation_family_requirements, NowledgeMemSourceMutationDualWriteEvidence,
    NowledgeMemSourceMutationDualWriteReadinessReport, NowledgeMemSourceMutationFamilyRequirement,
    NOWLEDGE_MEM_SOURCE_MUTATION_DUAL_WRITE_READINESS_PROTOCOL,
    NOWLEDGE_MEM_SOURCE_MUTATION_FAMILY_CONTENT_REFRESH_REPARSE,
    NOWLEDGE_MEM_SOURCE_MUTATION_FAMILY_GRAPH_DELETE,
    NOWLEDGE_MEM_SOURCE_MUTATION_FAMILY_INDEXED_TRANSITION,
    NOWLEDGE_MEM_SOURCE_MUTATION_FAMILY_INGEST_CREATE,
    NOWLEDGE_MEM_SOURCE_MUTATION_FAMILY_LIFECYCLE,
    NOWLEDGE_MEM_SOURCE_MUTATION_FAMILY_PATCH_DELETE,
    NOWLEDGE_MEM_SOURCE_MUTATION_FAMILY_REVISION_EDGES,
    NOWLEDGE_MEM_SOURCE_MUTATION_FAMILY_SEARCH_PROJECTION_EFFECTS,
    REQUIRED_NOWLEDGE_MEM_SOURCE_MUTATION_FAMILIES,
};

pub const NOWLEDGE_MEM_OPEN_REPORT_PROTOCOL: &str = "hawdb-nowledge-mem-open-report";
pub use hawdb_readiness::previous_wrapper_preflight::{
    NOWLEDGE_MEM_CUTOVER_CONTROLS_PROTOCOL, NOWLEDGE_MEM_LIBRARY_READINESS_PROTOCOL,
    NOWLEDGE_MEM_OPERATIONS_READINESS_PROTOCOL, NOWLEDGE_QUERY_RUNTIME_PREFLIGHT_PROTOCOL,
};
pub const NOWLEDGE_MEM_RETRIEVAL_REPORT_PROTOCOL: &str = "hawdb-nowledge-mem-retrieval-report";
pub const NOWLEDGE_MEM_READINESS_DASHBOARD_PROTOCOL: &str =
    "hawdb-nowledge-mem-readiness-dashboard-v1";
pub use hawdb_route_ownership::graph::{
    nowledge_mem_graph_read_route_catalog_digest, nowledge_mem_graph_read_route_spec,
    nowledge_mem_graph_read_route_spec_json, nowledge_mem_graph_read_route_specs_json,
    nowledge_mem_required_query_families_for_route, NowledgeMemGraphReadRouteEvidenceKind,
    NowledgeMemGraphReadRouteOwner, NowledgeMemGraphReadRouteSpec,
    NOWLEDGE_MEM_GRAPH_READ_ROUTE_CATALOG_VERSION, NOWLEDGE_MEM_GRAPH_READ_ROUTE_SPECS,
    NOWLEDGE_MEM_SEARCH_ROUTE, REQUIRED_NOWLEDGE_MEM_BOUNDED_READ_ROUTES,
};

pub const DEFAULT_NOWLEDGE_MEM_READ_MAX_ROWS: usize = 512;
pub const DEFAULT_NOWLEDGE_MEM_READ_MAX_ESTIMATED_PAYLOAD_BYTES: usize = 4 * 1024 * 1024;

#[derive(Debug)]
pub struct NowledgeMemGraph {
    db: Database,
    mode: NowledgeMemGraphMode,
    runtime_governor: RuntimeGovernor,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NowledgeMemReadOptions {
    pub max_rows: Option<usize>,
    pub max_estimated_payload_bytes: Option<usize>,
}

impl Default for NowledgeMemReadOptions {
    fn default() -> Self {
        Self {
            max_rows: Some(DEFAULT_NOWLEDGE_MEM_READ_MAX_ROWS),
            max_estimated_payload_bytes: Some(
                DEFAULT_NOWLEDGE_MEM_READ_MAX_ESTIMATED_PAYLOAD_BYTES,
            ),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NowledgeMemReadOutput {
    pub output: QueryOutput,
    pub report: NowledgeMemReadReport,
}

#[derive(Debug, Clone, Default, PartialEq)]
pub struct NowledgeMemReadinessOptions {
    pub bounded_read_probe: Option<NowledgeGraphStatement>,
    pub bounded_read_evidence: Option<serde_json::Value>,
    pub covered_routes: Vec<String>,
    pub graph_route_readiness: Option<NowledgeMemRouteReadinessSummary>,
    pub search_route_ownership: Option<NowledgeMemSearchRouteOwnershipReadinessReport>,
    pub active_search_route_ownership: Option<NowledgeMemActiveSearchRouteOwnershipReadinessReport>,
    pub active_search_route_readiness: Option<NowledgeMemActiveSearchRouteReadinessReport>,
    pub replacement_readiness_by_query_family: Option<serde_json::Value>,
    pub read_options: NowledgeMemReadOptions,
    pub search_projection_evidence: Option<serde_json::Value>,
    pub search_projection_probe_options: SearchProjectionProbeOptions,
    pub primary_search_projection_probe: Option<serde_json::Value>,
    pub search_projection_shadow_evidence: Option<serde_json::Value>,
    pub search_candidate_shadow_evidence: Option<serde_json::Value>,
    pub workload_fixture_evidence: Option<NowledgeGraphRouteWorkloadFixtureReport>,
    pub production_resource_profile: Option<StorageResourceProfileReport>,
    pub qos_policy: LocalQosPolicy,
    pub qos_state: LocalQosState,
    pub background_maintenance_options: BackgroundMaintenanceOptions,
}

#[derive(Debug, Clone, PartialEq)]
pub struct NowledgeMemLibraryReadinessReport {
    pub protocol: String,
    pub present: bool,
    pub ready: bool,
    pub mode: NowledgeMemGraphMode,
    pub redaction: NowledgeMemReadinessRedactionSummary,
    pub production_path: NowledgeMemLibraryProductionPathSummary,
    pub blocker_codes: Vec<String>,
    pub readiness_by_area: NowledgeMemReadinessAreaMap,
    pub ready_area_count: usize,
    pub blocked_area_count: usize,
    pub graph_open: bool,
    pub graph_read_only: bool,
    pub graph_route_readiness: serde_json::Value,
    pub search_route_ownership: serde_json::Value,
    pub active_search_route_ownership: serde_json::Value,
    pub active_search_route_readiness: serde_json::Value,
    pub bounded_read_evidence: serde_json::Value,
    pub storage_recovery: serde_json::Value,
    pub background_maintenance: serde_json::Value,
    pub query_family_evidence: serde_json::Value,
    pub search_projection_evidence: serde_json::Value,
    pub search_projection_shadow_evidence: serde_json::Value,
    pub search_candidate_shadow_evidence: serde_json::Value,
    pub workload_fixture_evidence: serde_json::Value,
    pub production_resource_profile: serde_json::Value,
}

impl NowledgeMemLibraryReadinessReport {
    pub fn areas(&self) -> Vec<NowledgeMemReadinessAreaSummary> {
        self.readiness_by_area.areas()
    }

    pub fn json(&self) -> serde_json::Value {
        let areas = self.areas();
        serde_json::json!({
            "protocol": self.protocol,
            "present": self.present,
            "ready": self.ready,
            "mode": self.mode.as_str(),
            "redaction": self.redaction.json(),
            "production_path": self.production_path.json(),
            "blocker_codes": self.blocker_codes,
            "readiness_by_area": self.readiness_by_area.json(),
            "areas": areas.iter().map(NowledgeMemReadinessAreaSummary::json).collect::<Vec<_>>(),
            "ready_area_count": self.ready_area_count,
            "blocked_area_count": self.blocked_area_count,
            "graph": {
                "open": self.graph_open,
                "mode": self.mode.as_str(),
                "read_only": self.graph_read_only,
            },
            "graph_route_readiness": self.graph_route_readiness,
            "search_route_ownership": self.search_route_ownership,
            "active_search_route_ownership": self.active_search_route_ownership,
            "active_search_route_readiness": self.active_search_route_readiness,
            "bounded_read_evidence": self.bounded_read_evidence,
            "storage_recovery": self.storage_recovery,
            "background_maintenance": self.background_maintenance,
            "query_family_evidence": self.query_family_evidence,
            "search_projection_evidence": self.search_projection_evidence,
            "search_projection_shadow_evidence": self.search_projection_shadow_evidence,
            "search_candidate_shadow_evidence": self.search_candidate_shadow_evidence,
            "workload_fixture_evidence": self.workload_fixture_evidence,
            "production_resource_profile": self.production_resource_profile,
        })
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NowledgeMemLibraryProductionPathSummary {
    pub in_process: bool,
    pub cli_required: bool,
    pub env_control_plane_required: bool,
    pub spawned_helper_required: bool,
}

impl Default for NowledgeMemLibraryProductionPathSummary {
    fn default() -> Self {
        Self {
            in_process: true,
            cli_required: false,
            env_control_plane_required: false,
            spawned_helper_required: false,
        }
    }
}

impl NowledgeMemLibraryProductionPathSummary {
    pub fn ready(&self) -> bool {
        self.in_process
            && !self.cli_required
            && !self.env_control_plane_required
            && !self.spawned_helper_required
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "ready": self.ready(),
            "in_process": self.in_process,
            "cli_required": self.cli_required,
            "env_control_plane_required": self.env_control_plane_required,
            "spawned_helper_required": self.spawned_helper_required,
        })
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct NowledgeMemReadinessRedactionSummary {
    pub query_text_copied: bool,
    pub parameters_copied: bool,
    pub local_paths_copied: bool,
}

impl NowledgeMemReadinessRedactionSummary {
    pub fn ready(&self) -> bool {
        !self.query_text_copied && !self.parameters_copied && !self.local_paths_copied
    }

    fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "ready": self.ready(),
            "query_text_copied": self.query_text_copied,
            "parameters_copied": self.parameters_copied,
            "local_paths_copied": self.local_paths_copied,
        })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NowledgeMemReadinessDashboard {
    pub protocol: String,
    pub ready: bool,
    pub mode: NowledgeMemGraphMode,
    pub area_count: usize,
    pub ready_area_count: usize,
    pub blocked_area_count: usize,
    pub blocker_codes: Vec<String>,
    pub areas: Vec<NowledgeMemReadinessAreaSummary>,
    pub storage_lifecycle_action: NowledgeMemStorageLifecycleActionKind,
    pub storage_lifecycle_ready: bool,
    pub slow_query_ready: bool,
    pub slow_query_record_count: usize,
}

impl NowledgeMemReadinessDashboard {
    fn from_reports(
        library: &NowledgeMemLibraryReadinessReport,
        storage_lifecycle: &NowledgeMemStorageLifecycleDecision,
        slow_query: &NowledgeMemSlowQueryReport,
    ) -> Self {
        let areas = nowledge_mem_readiness_dashboard_areas(library, slow_query);
        let blocked_area_count = areas.iter().filter(|area| !area.ready).count();
        let ready_area_count = areas.len().saturating_sub(blocked_area_count);

        Self {
            protocol: NOWLEDGE_MEM_READINESS_DASHBOARD_PROTOCOL.to_string(),
            ready: library.ready && slow_query.ready,
            mode: library.mode,
            area_count: areas.len(),
            ready_area_count,
            blocked_area_count,
            blocker_codes: library.blocker_codes.clone(),
            areas,
            storage_lifecycle_action: storage_lifecycle.action,
            storage_lifecycle_ready: storage_lifecycle.ready_for_mem_lifecycle,
            slow_query_ready: slow_query.ready,
            slow_query_record_count: slow_query.record_count,
        }
    }

    pub fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "protocol": self.protocol,
            "ready": self.ready,
            "mode": self.mode.as_str(),
            "area_count": self.area_count,
            "ready_area_count": self.ready_area_count,
            "blocked_area_count": self.blocked_area_count,
            "blocker_codes": self.blocker_codes,
            "areas": self.areas.iter().map(NowledgeMemReadinessAreaSummary::json).collect::<Vec<_>>(),
            "storage_lifecycle": {
                "ready": self.storage_lifecycle_ready,
                "action": self.storage_lifecycle_action.as_str(),
            },
            "slow_query": {
                "ready": self.slow_query_ready,
                "record_count": self.slow_query_record_count,
            },
            "redaction": {
                "query_text_copied": false,
                "parameters_copied": false,
                "local_paths_copied": false
            },
        })
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct NowledgeMemOperationsReadinessReport {
    pub protocol: String,
    pub present: bool,
    pub ready: bool,
    pub mode: NowledgeMemGraphMode,
    pub graph_open: bool,
    pub graph_read_only: bool,
    pub search_projection_open: bool,
    pub graph_commit_epoch: u64,
    pub projection_commit_lag: u64,
    pub projection_stale: bool,
    pub storage_lifecycle_action: NowledgeMemStorageLifecycleActionKind,
    pub storage_lifecycle_ready: bool,
    pub storage_recovery_ready: bool,
    pub slow_query_ready: bool,
    pub background_maintenance_ready: bool,
    pub blocker_codes: Vec<String>,
    pub runtime_status: NowledgeMemRuntimeStatus,
    pub storage_lifecycle_decision: NowledgeMemStorageLifecycleDecision,
    pub storage_recovery: NowledgeMemStorageRecoveryReport,
    pub slow_query: NowledgeMemSlowQueryReport,
    pub background_maintenance: NowledgeMemBackgroundMaintenanceReport,
}

impl NowledgeMemOperationsReadinessReport {
    fn from_reports(
        mode: NowledgeMemGraphMode,
        graph_read_only: bool,
        runtime_status: NowledgeMemRuntimeStatus,
        storage_recovery: NowledgeMemStorageRecoveryReport,
        slow_query: NowledgeMemSlowQueryReport,
        background_maintenance: NowledgeMemBackgroundMaintenanceReport,
    ) -> Self {
        let search_projection_open = runtime_status.projection_freshness.is_some();
        let projection_commit_lag = runtime_status.projection_commit_lag();
        let projection_stale = search_projection_open && runtime_status.projection_stale();
        let storage_lifecycle_decision =
            NowledgeMemStorageLifecycleDecision::from_storage_recovery(storage_recovery.clone());
        let mut blocker_codes = Vec::new();
        if !storage_lifecycle_decision.ready_for_mem_lifecycle {
            blocker_codes.push("storage_recovery_not_ready".to_string());
            blocker_codes.extend(
                storage_lifecycle_decision
                    .blocker_codes
                    .iter()
                    .map(|code| format!("storage_lifecycle.{code}")),
            );
        }
        if !slow_query.ready {
            blocker_codes.push("slow_query_report_not_ready".to_string());
        }
        if !background_maintenance.ready {
            blocker_codes.push("background_maintenance_not_ready".to_string());
        }
        if search_projection_open && projection_stale {
            blocker_codes.push("search_projection_stale".to_string());
        }

        Self {
            protocol: NOWLEDGE_MEM_OPERATIONS_READINESS_PROTOCOL.to_string(),
            present: true,
            ready: blocker_codes.is_empty(),
            mode,
            graph_open: true,
            graph_read_only,
            search_projection_open,
            graph_commit_epoch: runtime_status.graph_commit_epoch,
            projection_commit_lag,
            projection_stale,
            storage_lifecycle_action: storage_lifecycle_decision.action,
            storage_lifecycle_ready: storage_lifecycle_decision.ready_for_mem_lifecycle,
            storage_recovery_ready: storage_recovery.ready,
            slow_query_ready: slow_query.ready,
            background_maintenance_ready: background_maintenance.ready,
            blocker_codes,
            runtime_status,
            storage_lifecycle_decision,
            storage_recovery,
            slow_query,
            background_maintenance,
        }
    }

    pub fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "protocol": self.protocol,
            "present": self.present,
            "ready": self.ready,
            "mode": self.mode.as_str(),
            "graph": {
                "open": self.graph_open,
                "read_only": self.graph_read_only,
                "commit_epoch": self.graph_commit_epoch,
            },
            "search_projection": {
                "open": self.search_projection_open,
                "commit_lag": self.projection_commit_lag,
                "stale": self.projection_stale,
            },
            "storage_lifecycle": {
                "ready": self.storage_lifecycle_ready,
                "action": self.storage_lifecycle_action.as_str(),
            },
            "readiness": {
                "storage_lifecycle_ready": self.storage_lifecycle_ready,
                "storage_recovery_ready": self.storage_recovery_ready,
                "slow_query_ready": self.slow_query_ready,
                "background_maintenance_ready": self.background_maintenance_ready,
            },
            "blocker_codes": self.blocker_codes,
            "runtime_status": self.runtime_status.json(),
            "storage_lifecycle_decision": self.storage_lifecycle_decision.json(),
            "storage_recovery": self.storage_recovery.json(),
            "slow_query": self.slow_query.json(),
            "background_maintenance": self.background_maintenance.json(),
            "redaction": {
                "query_text_copied": false,
                "parameters_copied": false,
                "local_paths_copied": false,
            },
        })
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct NowledgeMemBackgroundMaintenanceReport {
    pub protocol: String,
    pub present: bool,
    pub ready: bool,
    pub total_candidates: usize,
    pub admitted_count: usize,
    pub deferred_count: usize,
    pub rejected_count: usize,
    pub total_estimated_operations: usize,
    pub admitted_estimated_operations: usize,
    pub deferred_estimated_operations: usize,
    pub rejected_estimated_operations: usize,
    pub executable_search_projection_graph_delta_count: usize,
    pub admitted_search_projection_graph_delta_count: usize,
    pub deferred_search_projection_graph_delta_count: usize,
    pub rejected_search_projection_graph_delta_count: usize,
    pub executable_search_projection_graph_delta_operations: usize,
    pub admitted_search_projection_graph_delta_operations: usize,
    pub max_search_projection_graph_delta_complete_through_graph_commit_epoch: Option<u64>,
    pub foreground_admission_probe_ready: Option<bool>,
    pub foreground_admission_probe_admission_name: Option<String>,
    pub memory_pressure_ready: Option<bool>,
    pub memory_budget_bytes: Option<u64>,
    pub estimated_memory_bytes: Option<u64>,
    pub slow_query_ready: Option<bool>,
    pub slow_query_record_count: Option<u64>,
    pub slow_query_capacity: Option<u64>,
    pub slow_query_redaction_ready: Option<bool>,
    pub top_admitted_kind: Option<BackgroundMaintenanceKind>,
    pub top_admitted_name: Option<String>,
    pub ranked_count: u64,
    pub foreground_ranked_count: u64,
    pub unknown_admission_count: u64,
    pub blocker_codes: Vec<String>,
    summary: serde_json::Value,
}

impl NowledgeMemBackgroundMaintenanceReport {
    pub fn from_summary(summary: &BackgroundMaintenanceSummary) -> Self {
        Self::from_summary_with_slow_query(summary, None)
    }

    fn from_summary_with_slow_query(
        summary: &BackgroundMaintenanceSummary,
        slow_query: Option<&NowledgeMemSlowQueryReport>,
    ) -> Self {
        let mut json = background_maintenance_summary_to_json(summary);
        if let Some(object) = json.as_object_mut() {
            object.insert(
                "protocol".to_string(),
                serde_json::Value::String("hawdb-background-maintenance-report".to_string()),
            );
            if let Some(slow_query) = slow_query {
                object.insert(
                    "slow_query".to_string(),
                    background_maintenance_slow_query_json(slow_query),
                );
                object.insert(
                    "slow_query_ready".to_string(),
                    serde_json::Value::Bool(slow_query.ready),
                );
                object.insert(
                    "slow_query_record_count".to_string(),
                    serde_json::json!(slow_query.record_count),
                );
                object.insert(
                    "slow_query_capacity".to_string(),
                    serde_json::json!(slow_query.capacity),
                );
            }
        }
        let health = background_maintenance_evidence_health(Some(&json), true);

        Self {
            protocol: "hawdb-background-maintenance-report".to_string(),
            present: true,
            ready: health.ready,
            total_candidates: summary.total_candidates,
            admitted_count: summary.admitted_count,
            deferred_count: summary.deferred_count,
            rejected_count: summary.rejected_count,
            total_estimated_operations: summary.total_estimated_operations,
            admitted_estimated_operations: summary.admitted_estimated_operations,
            deferred_estimated_operations: summary.deferred_estimated_operations,
            rejected_estimated_operations: summary.rejected_estimated_operations,
            executable_search_projection_graph_delta_count: summary
                .executable_search_projection_graph_delta_count,
            admitted_search_projection_graph_delta_count: summary
                .admitted_search_projection_graph_delta_count,
            deferred_search_projection_graph_delta_count: summary
                .deferred_search_projection_graph_delta_count,
            rejected_search_projection_graph_delta_count: summary
                .rejected_search_projection_graph_delta_count,
            executable_search_projection_graph_delta_operations: summary
                .executable_search_projection_graph_delta_operations,
            admitted_search_projection_graph_delta_operations: summary
                .admitted_search_projection_graph_delta_operations,
            max_search_projection_graph_delta_complete_through_graph_commit_epoch: summary
                .max_search_projection_graph_delta_complete_through_graph_commit_epoch,
            foreground_admission_probe_ready: health.foreground_admission_probe_ready,
            foreground_admission_probe_admission_name: health
                .foreground_admission_probe_admission_name,
            memory_pressure_ready: health.memory_pressure_ready,
            memory_budget_bytes: health.memory_budget_bytes,
            estimated_memory_bytes: health.estimated_memory_bytes,
            slow_query_ready: health.slow_query_ready,
            slow_query_record_count: health.slow_query_record_count,
            slow_query_capacity: health.slow_query_capacity,
            slow_query_redaction_ready: health.slow_query_redaction_ready,
            top_admitted_kind: summary.top_admitted_kind,
            top_admitted_name: summary.top_admitted_name.clone(),
            ranked_count: health.ranked_count.unwrap_or_default(),
            foreground_ranked_count: health.foreground_ranked_count,
            unknown_admission_count: health.unknown_admission_count,
            blocker_codes: health.blocker_codes,
            summary: json,
        }
    }

    pub fn json(&self) -> serde_json::Value {
        self.summary.clone()
    }
}

fn background_maintenance_slow_query_json(
    slow_query: &NowledgeMemSlowQueryReport,
) -> serde_json::Value {
    serde_json::json!({
        "protocol": slow_query.protocol,
        "ready": slow_query.ready,
        "capacity": slow_query.capacity,
        "record_count": slow_query.record_count,
        "latest_sequence": slow_query.latest_sequence,
        "max_elapsed_micros": slow_query.max_elapsed_micros,
        "redaction": {
            "query_text_copied": false,
            "parameters_copied": false,
            "local_paths_copied": false,
        },
    })
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NowledgeMemRetrievalReport {
    pub protocol: String,
    pub mode: NowledgeMemGraphMode,
    pub compressed_vector_search_mode: CompressedVectorSearchMode,
    pub graph_commit_epoch: u64,
    pub projection_source_graph_commit_epoch: Option<u64>,
    pub projection_commit_lag: u64,
    pub projection_stale: bool,
    pub search_document_count: usize,
    pub search_filtered_document_count: usize,
    pub search_total_hits: usize,
    pub candidate_count: usize,
    pub candidate_total_count: usize,
    pub evidence_count: usize,
    pub graph_seed_count: usize,
    pub graph_context_path_count: usize,
    pub search_backend: Option<String>,
    pub vector_backend: Option<String>,
    pub text_backend: Option<String>,
    pub search_fallback_reason_codes: Vec<String>,
    pub retriever_fallback_reason_codes: Vec<String>,
    pub knowledge_fallback_reason_codes: Vec<String>,
    pub truncation_reason_codes: Vec<String>,
    pub warning_count: usize,
    pub warnings: Vec<String>,
}

impl NowledgeMemRetrievalReport {
    pub fn json(&self) -> serde_json::Value {
        serde_json::json!({
            "protocol": self.protocol,
            "mode": self.mode.as_str(),
            "compressed_vector_search_mode": self.compressed_vector_search_mode.as_str(),
            "graph_commit_epoch": self.graph_commit_epoch,
            "projection_source_graph_commit_epoch": self.projection_source_graph_commit_epoch,
            "projection_commit_lag": self.projection_commit_lag,
            "projection_stale": self.projection_stale,
            "search_document_count": self.search_document_count,
            "search_filtered_document_count": self.search_filtered_document_count,
            "search_total_hits": self.search_total_hits,
            "candidate_count": self.candidate_count,
            "candidate_total_count": self.candidate_total_count,
            "evidence_count": self.evidence_count,
            "graph_seed_count": self.graph_seed_count,
            "graph_context_path_count": self.graph_context_path_count,
            "search_backend": self.search_backend,
            "vector_backend": self.vector_backend,
            "text_backend": self.text_backend,
            "search_fallback_reason_codes": self.search_fallback_reason_codes,
            "retriever_fallback_reason_codes": self.retriever_fallback_reason_codes,
            "knowledge_fallback_reason_codes": self.knowledge_fallback_reason_codes,
            "truncation_reason_codes": self.truncation_reason_codes,
            "warning_count": self.warning_count,
            "warnings": self.warnings,
        })
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct NowledgeMemRetrievalOutput {
    pub output: KnowledgeRetrievalOutput,
    pub report: NowledgeMemRetrievalReport,
    pub out_of_core_search_metrics: Option<SearchOutOfCoreMetrics>,
}

impl NowledgeMemGraph {
    pub fn open(path: impl AsRef<Path>, mode: NowledgeMemGraphMode) -> Result<Self> {
        let path = path.as_ref();
        Self::open_with_config(path, nowledge_mem_graph_config(mode))
    }

    pub fn open_with_config(path: impl AsRef<Path>, config: DatabaseConfig) -> Result<Self> {
        let path = path.as_ref();
        let runtime_governor = default_nowledge_mem_runtime_governor(path, &config);
        Self::open_with_config_and_runtime_governor(path, config, runtime_governor)
    }

    pub fn open_with_config_and_runtime_governor(
        path: impl AsRef<Path>,
        config: DatabaseConfig,
        runtime_governor: RuntimeGovernor,
    ) -> Result<Self> {
        let mode = if config.read_only {
            NowledgeMemGraphMode::ShadowReadOnly
        } else {
            NowledgeMemGraphMode::WritableCutover
        };
        let mut db = Database::open_with_config(path, config)?;
        db.set_runtime_governor(runtime_governor.clone());
        Ok(Self {
            db,
            mode,
            runtime_governor,
        })
    }

    pub fn from_database(db: Database, mode: NowledgeMemGraphMode) -> Self {
        let runtime_governor = default_nowledge_mem_runtime_governor(Path::new("."), db.config());
        Self::from_database_with_runtime_governor(db, mode, runtime_governor)
    }

    pub fn from_database_with_runtime_governor(
        mut db: Database,
        mode: NowledgeMemGraphMode,
        runtime_governor: RuntimeGovernor,
    ) -> Self {
        db.set_runtime_governor(runtime_governor.clone());
        Self {
            db,
            mode,
            runtime_governor,
        }
    }

    pub fn mode(&self) -> NowledgeMemGraphMode {
        self.mode
    }

    pub fn database(&self) -> &Database {
        &self.db
    }

    pub fn database_mut(&mut self) -> &mut Database {
        &mut self.db
    }

    pub fn runtime_governor(&self) -> &RuntimeGovernor {
        &self.runtime_governor
    }

    pub fn runtime_governor_snapshot(&self) -> RuntimeGovernorSnapshot {
        self.runtime_governor.snapshot()
    }

    pub fn refresh_runtime_resources(&self) -> bool {
        self.runtime_governor.refresh_from_host()
    }

    pub fn into_database(self) -> Database {
        self.db
    }

    pub fn query(&mut self, cypher: &str) -> Result<QueryOutput> {
        self.query_with_params(cypher, &BTreeMap::new())
    }

    pub fn query_with_report(&mut self, cypher: &str) -> Result<NowledgeMemQueryOutput> {
        self.query_with_params_with_report(cypher, &BTreeMap::new())
    }

    pub fn query_with_report_options(
        &mut self,
        cypher: &str,
        options: NowledgeMemQueryReportOptions,
    ) -> Result<NowledgeMemQueryOutput> {
        self.query_with_params_with_report_options(cypher, &BTreeMap::new(), options)
    }

    pub fn query_with_params(
        &mut self,
        cypher: &str,
        parameters: &BTreeMap<String, Value>,
    ) -> Result<QueryOutput> {
        Ok(self
            .query_with_params_with_report(cypher, parameters)?
            .output)
    }

    pub fn query_with_params_with_report(
        &mut self,
        cypher: &str,
        parameters: &BTreeMap<String, Value>,
    ) -> Result<NowledgeMemQueryOutput> {
        self.query_with_params_with_report_options(
            cypher,
            parameters,
            NowledgeMemQueryReportOptions::default(),
        )
    }

    pub fn query_with_params_with_report_options(
        &mut self,
        cypher: &str,
        parameters: &BTreeMap<String, Value>,
        options: NowledgeMemQueryReportOptions,
    ) -> Result<NowledgeMemQueryOutput> {
        let mut external = crate::executor::NoExternalReadOperator;
        self.query_with_params_with_report_options_and_external(
            cypher,
            parameters,
            options,
            &mut external,
        )
    }

    pub fn query_with_params_with_report_options_context(
        &mut self,
        cypher: &str,
        parameters: &BTreeMap<String, Value>,
        options: NowledgeMemQueryReportOptions,
        task_context: &RuntimeTaskContext,
    ) -> Result<NowledgeMemQueryOutput> {
        let mut external = crate::executor::NoExternalReadOperator;
        self.query_with_params_with_report_options_and_external_context(
            cypher,
            parameters,
            options,
            &mut external,
            task_context,
        )
    }

    fn query_with_params_with_report_options_and_external(
        &mut self,
        cypher: &str,
        parameters: &BTreeMap<String, Value>,
        options: NowledgeMemQueryReportOptions,
        external: &mut dyn crate::executor::ExternalReadOperator,
    ) -> Result<NowledgeMemQueryOutput> {
        self.query_with_params_with_report_options_and_external_context(
            cypher,
            parameters,
            options,
            external,
            &RuntimeTaskContext::default(),
        )
    }

    fn query_with_params_with_report_options_and_external_context(
        &mut self,
        cypher: &str,
        parameters: &BTreeMap<String, Value>,
        options: NowledgeMemQueryReportOptions,
        external: &mut dyn crate::executor::ExternalReadOperator,
        task_context: &RuntimeTaskContext,
    ) -> Result<NowledgeMemQueryOutput> {
        self.query_request_with_report_and_external(
            crate::QueryRequest::new(cypher)
                .with_params(parameters)
                .with_task_context(task_context),
            options,
            external,
        )
    }

    pub(crate) fn query_request_with_report(
        &mut self,
        request: crate::QueryRequest<'_>,
        options: NowledgeMemQueryReportOptions,
    ) -> Result<NowledgeMemQueryOutput> {
        self.query_request_with_report_and_external(
            request,
            options,
            &mut crate::executor::NoExternalReadOperator,
        )
    }

    fn query_request_with_report_and_external(
        &mut self,
        request: crate::QueryRequest<'_>,
        options: NowledgeMemQueryReportOptions,
        external: &mut dyn crate::executor::ExternalReadOperator,
    ) -> Result<NowledgeMemQueryOutput> {
        let default_context = RuntimeTaskContext::default();
        let task_context = request.task_context.unwrap_or(&default_context);
        let empty = BTreeMap::new();
        let parameters = request.parameters.unwrap_or(&empty);
        let cypher = request.cypher;
        self.check_runtime_context(task_context)?;
        let (permit, prepared) = self.admit_materialized_query(cypher, parameters)?;
        let is_mutation = prepared.admission().is_mutation;
        let execution_task_context = permit.bind_task_context(task_context.clone());
        let started = Instant::now();
        let result = self.db.query_prepared_request_with_trace_and_external(
            prepared,
            request.with_task_context(&execution_task_context),
            options.capture_physical_plan,
            external,
        );
        self.record_runtime_cancellation(result.as_ref().err(), task_context);
        let (output, execution_trace) = result?;
        if !is_mutation {
            self.check_runtime_context(task_context)?;
        }
        let elapsed_micros = started.elapsed().as_micros();
        let report = nowledge_mem_query_report(NowledgeMemQueryReportInput {
            mode: self.mode,
            statement: &execution_trace.statement,
            trace: execution_trace.optimizer_trace.as_ref(),
            plan_cache_lookup: execution_trace.plan_cache_lookup,
            execution_profile: execution_trace.execution_profile.as_ref(),
            output: &output,
            options,
            elapsed_micros,
        });
        Ok(NowledgeMemQueryOutput { output, report })
    }

    fn admit_materialized_query(
        &self,
        cypher: &str,
        parameters: &BTreeMap<String, Value>,
    ) -> Result<(RuntimePermit, crate::api::PreparedRuntimeQuery)> {
        let prepared = self.prepare_admitted_query(cypher, parameters)?;
        let admission = prepared.admission();
        let result_budget = read_execution::materialized_result_budget(
            self.db.config(),
            &self.runtime_governor,
            admission.is_mutation,
        )?;
        let request = admission
            .runtime_work_request_for_snapshot(result_budget, self.runtime_governor.snapshot())
            .with_retained_memory_bytes(prepared.planning_memory_bytes());
        read_execution::admit_reusable_prepared(prepared, &self.runtime_governor, request, || {
            self.db
                .prepare_runtime_query(cypher.to_string(), parameters)
        })
    }

    fn prepare_admitted_query(
        &self,
        cypher: &str,
        parameters: &BTreeMap<String, Value>,
    ) -> Result<crate::api::PreparedRuntimeQuery> {
        let request = crate::api::runtime_planning_request(
            cypher.len(),
            hawdb_qos::RuntimeWorkPriority::Foreground,
        );
        let permit = self.try_admit_runtime(request)?;
        let prepared = self
            .db
            .prepare_runtime_query(cypher.to_string(), parameters)?;
        Ok(prepared.with_planning_memory(
            permit
                .into_retained_memory()
                .expect("control work owns a fixed memory reservation"),
        ))
    }

    fn admit_streaming_query(
        &self,
        cypher: &str,
        parameters: &BTreeMap<String, Value>,
        result_memory_bytes: u64,
    ) -> Result<(RuntimePermit, crate::api::PreparedRuntimeQuery)> {
        let prepared = self.prepare_admitted_query(cypher, parameters)?;
        let admission = prepared.admission();
        if admission.is_mutation {
            return Err(HawDBError::Execution(
                "admitted streaming query must be read-only".to_string(),
            ));
        }
        let request = admission
            .runtime_work_request_for_snapshot(
                result_memory_bytes,
                self.runtime_governor.snapshot(),
            )
            .with_retained_memory_bytes(prepared.planning_memory_bytes());
        read_execution::admit_reusable_prepared(prepared, &self.runtime_governor, request, || {
            self.db
                .prepare_runtime_query(cypher.to_string(), parameters)
        })
    }

    fn try_admit_runtime(&self, request: hawdb_qos::RuntimeWorkRequest) -> Result<RuntimePermit> {
        try_admit_runtime(&self.runtime_governor, request)
    }

    fn admitted_streaming_result_bytes(&self, options: &NowledgeMemReadOptions) -> Result<usize> {
        read_execution::admitted_result_bytes(self.db.config(), &self.runtime_governor, options)
    }

    fn check_runtime_context(&self, task_context: &RuntimeTaskContext) -> Result<()> {
        task_context.checkpoint().map_err(|reason| {
            self.runtime_governor.record_cancellation(reason);
            HawDBError::Execution(format!("runtime task {reason}"))
        })
    }

    fn record_runtime_cancellation(
        &self,
        error: Option<&HawDBError>,
        task_context: &RuntimeTaskContext,
    ) {
        if error.is_some()
            && let Err(reason) = task_context.checkpoint()
        {
            self.runtime_governor.record_cancellation(reason);
        }
    }

    pub fn slow_query_report(&self) -> NowledgeMemSlowQueryReport {
        let config = self.db.config();
        NowledgeMemSlowQueryReport::from_summaries(
            self.mode,
            config.slow_query_log_capacity,
            config.slow_query_log_threshold_micros,
            self.db.slow_query_log_snapshot(),
        )
    }

    pub fn slow_query_report_json(&self) -> serde_json::Value {
        self.slow_query_report().json()
    }

    pub fn read_query(&self, cypher: &str) -> Result<NowledgeMemReadOutput> {
        self.read_query_with_params(cypher, &BTreeMap::new(), &NowledgeMemReadOptions::default())
    }

    pub fn read_query_with_options(
        &self,
        cypher: &str,
        options: &NowledgeMemReadOptions,
    ) -> Result<NowledgeMemReadOutput> {
        self.read_query_with_params(cypher, &BTreeMap::new(), options)
    }

    pub fn read_query_with_params(
        &self,
        cypher: &str,
        parameters: &BTreeMap<String, Value>,
        options: &NowledgeMemReadOptions,
    ) -> Result<NowledgeMemReadOutput> {
        let mut output = self
            .read_query_with_params_streaming_collect(cypher, parameters, options)
            .map_err(|error| legacy_nowledge_mem_read_error(error, options))?;
        output.report.streaming = false;
        Ok(output)
    }

    pub fn read_query_with_params_streaming(
        &self,
        cypher: &str,
        parameters: &BTreeMap<String, Value>,
        options: &NowledgeMemReadOptions,
        consumer: impl FnMut(BTreeMap<String, Value>) -> Result<()>,
    ) -> Result<QueryStreamReport> {
        self.read_query_with_params_streaming_context(
            cypher,
            parameters,
            options,
            &RuntimeTaskContext::default(),
            consumer,
        )
    }

    pub fn read_query_with_params_streaming_context(
        &self,
        cypher: &str,
        parameters: &BTreeMap<String, Value>,
        options: &NowledgeMemReadOptions,
        task_context: &RuntimeTaskContext,
        consumer: impl FnMut(BTreeMap<String, Value>) -> Result<()>,
    ) -> Result<QueryStreamReport> {
        self.check_runtime_context(task_context)?;
        let max_payload_bytes = self.admitted_streaming_result_bytes(options)?;
        let (permit, prepared) = self.admit_streaming_query(
            cypher,
            parameters,
            read_execution::result_memory_budget(self.db.config(), &self.runtime_governor),
        )?;
        let execution_task_context = permit.bind_task_context(task_context.clone());
        let result = self
            .db
            .begin_read_transaction()?
            .query_prepared_with_params_streaming_context(
                prepared,
                parameters,
                QueryStreamOptions {
                    max_rows: options.max_rows,
                    max_payload_bytes: Some(max_payload_bytes),
                },
                crate::executor::StreamDelivery::Validated,
                &execution_task_context,
                consumer,
            );
        self.record_runtime_cancellation(result.as_ref().err(), task_context);
        result
    }

    /// Collects compact owned rows with the same limits as streaming reads.
    /// No result becomes observable before complete execution and validation.
    pub fn read_query_with_params_streaming_collect(
        &self,
        cypher: &str,
        parameters: &BTreeMap<String, Value>,
        options: &NowledgeMemReadOptions,
    ) -> Result<NowledgeMemReadOutput> {
        let max_payload_bytes = self.admitted_streaming_result_bytes(options)?;
        let (permit, prepared) = self.admit_streaming_query(
            cypher,
            parameters,
            read_execution::result_memory_budget(self.db.config(), &self.runtime_governor),
        )?;
        let task_context = permit.bind_task_context(RuntimeTaskContext::default());
        let bounded = self
            .db
            .begin_read_transaction()?
            .query_prepared_with_params_profiled_context(
                prepared,
                parameters,
                QueryStreamOptions {
                    max_rows: options.max_rows,
                    max_payload_bytes: Some(max_payload_bytes),
                },
                &task_context,
            )?;
        let mut output = bounded_nowledge_mem_read_output(self.mode, bounded, options)?;
        output.report.streaming = true;
        Ok(output)
    }

    pub fn graph_rag_schema_context(
        &self,
        options: GraphRagSchemaContextOptions,
    ) -> Result<GraphRagSchemaContext> {
        self.db.graph_rag_schema_context(options)
    }

    pub fn read_generated_graph_rag(
        &self,
        query: &GraphRagGeneratedQuery,
        parameters: &BTreeMap<String, Value>,
        options: &NowledgeMemReadOptions,
    ) -> Result<NowledgeMemReadOutput> {
        query
            .validate_parameters(parameters)
            .map_err(|error| HawDBError::Semantic(error.to_string()))?;
        let max_payload_bytes = self.admitted_streaming_result_bytes(options)?;
        let (permit, prepared) = self.admit_streaming_query(
            query.cypher(),
            parameters,
            read_execution::result_memory_budget(self.db.config(), &self.runtime_governor),
        )?;
        let context = permit.bind_task_context(RuntimeTaskContext::default());
        let mut read = self.db.begin_read_transaction_with_context(&context)?;
        read.validate_generated_graph_rag(query, parameters)?;
        let bounded = read.query_prepared_with_params_profiled_context(
            prepared,
            parameters,
            QueryStreamOptions {
                max_rows: options.max_rows,
                max_payload_bytes: Some(max_payload_bytes),
            },
            &context,
        )?;
        bounded_nowledge_mem_read_output(self.mode, bounded, options)
    }
}

#[derive(Debug)]
pub struct NowledgeMemSearchProjection {
    index: SearchIndex,
}

#[derive(Debug)]
pub struct NowledgeMemOutOfCoreSearchProjection {
    reader: Arc<SearchOutOfCoreReader>,
    maintenance: Option<(PathBuf, NowledgeMemIncrementalSearchMaintenanceOptions)>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct NowledgeMemOutOfCoreSearchCandidateOutput {
    pub result: SearchResultSet,
    pub report: NowledgeMemSearchCandidateReport,
    pub metrics: SearchOutOfCoreMetrics,
}

#[derive(Debug, Clone, PartialEq)]
pub struct NowledgeMemSearchHydrationOutput {
    pub documents: Vec<SearchDocument>,
    pub out_of_core_metrics: Option<SearchOutOfCoreMetrics>,
}

impl From<NowledgeMemOutOfCoreSearchCandidateOutput> for NowledgeMemSearchCandidateOutput {
    fn from(output: NowledgeMemOutOfCoreSearchCandidateOutput) -> Self {
        Self {
            result: output.result,
            report: output.report,
            out_of_core_metrics: Some(output.metrics),
        }
    }
}

impl NowledgeMemOutOfCoreSearchProjection {
    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
        Ok(Self {
            reader: Arc::new(SearchOutOfCoreReader::open(path)?),
            maintenance: None,
        })
    }

    pub fn open_with_config(path: impl AsRef<Path>, config: SearchOutOfCoreConfig) -> Result<Self> {
        Ok(Self {
            reader: Arc::new(SearchOutOfCoreReader::open_with_config(path, config)?),
            maintenance: None,
        })
    }

    pub fn open_production(
        path: impl AsRef<Path>,
        qualification: &SearchLexicalProductionQualificationReport,
        expected_identity: &crate::ProductionQualificationIdentity,
    ) -> Result<Self> {
        let projection = Self::open(path)?;
        projection.validate_lexical_production_qualification(qualification, expected_identity)?;
        Ok(projection)
    }

    pub fn open_production_with_config(
        path: impl AsRef<Path>,
        config: SearchOutOfCoreConfig,
        qualification: &SearchLexicalProductionQualificationReport,
        expected_identity: &crate::ProductionQualificationIdentity,
    ) -> Result<Self> {
        let projection = Self::open_with_config(path, config)?;
        projection.validate_lexical_production_qualification(qualification, expected_identity)?;
        Ok(projection)
    }

    pub fn validate_lexical_production_qualification(
        &self,
        qualification: &SearchLexicalProductionQualificationReport,
        expected_identity: &crate::ProductionQualificationIdentity,
    ) -> Result<()> {
        qualification.validate_for_projection_and_release(
            &self.reader.production_qualification_identity(),
            expected_identity,
        )
    }

    pub fn reader(&self) -> &SearchOutOfCoreReader {
        &self.reader
    }

    fn read_snapshot(&self) -> Self {
        Self {
            reader: Arc::clone(&self.reader),
            maintenance: None,
        }
    }

    pub fn freshness(&self) -> SearchProjectionFreshness {
        self.reader.projection_freshness()
    }

    fn runtime_admission_memory_bytes(
        &self,
        working_memory_bytes: u64,
        result_budget_bytes: u64,
    ) -> u64 {
        let config = self.reader.config();
        working_memory_bytes
            .saturating_add(config.max_vector_search_working_bytes.get() as u64)
            .saturating_add(config.max_uncompressed_segment_bytes.get())
            .saturating_add(config.max_candidate_block_bytes.get())
            .saturating_add(config.max_hydrated_bytes.get().min(result_budget_bytes))
            .saturating_add(config.max_matched_span_bytes.get())
    }

    pub fn hydrate_documents(
        &self,
        document_ids: &[String],
    ) -> Result<SearchOutOfCoreHydrationOutput> {
        self.reader.hydrate_documents(document_ids)
    }

    pub fn search_candidates(
        &self,
        request: &NowledgeMemSearchCandidateRequest,
    ) -> Result<SearchResultSet> {
        Ok(self.search_candidates_with_report(request)?.result)
    }

    pub fn search_candidates_with_report(
        &self,
        request: &NowledgeMemSearchCandidateRequest,
    ) -> Result<NowledgeMemOutOfCoreSearchCandidateOutput> {
        self.search_candidates_with_report_context(request, VectorSearchExecutionOptions::default())
    }

    pub fn search_candidates_with_report_context(
        &self,
        request: &NowledgeMemSearchCandidateRequest,
        vector_execution_options: VectorSearchExecutionOptions<'_>,
    ) -> Result<NowledgeMemOutOfCoreSearchCandidateOutput> {
        let effective_compressed_vector_search_mode = effective_search_candidate_mode(request);
        let output = self
            .reader
            .search_with_options_compressed_vector_projection_execution_options(
                &request.query_text,
                request.query_embedding.as_deref(),
                request.mode,
                SearchQueryOptions {
                    limit: request.limit,
                    offset: request.offset,
                    rank_window: request.rank_window,
                    fusion_weights: request.fusion_weights,
                    metadata_filters: request.metadata_filters.clone(),
                    policy_epoch: None,
                },
                effective_compressed_vector_search_mode,
                vector_execution_options,
            )?;
        let report = nowledge_mem_search_candidate_report(
            request,
            effective_compressed_vector_search_mode,
            &output.result,
        );
        Ok(NowledgeMemOutOfCoreSearchCandidateOutput {
            result: output.result,
            report,
            metrics: output.metrics,
        })
    }
}

impl NowledgeMemSearchProjection {
    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
        Ok(Self {
            index: SearchIndex::open(path)?,
        })
    }

    pub fn from_index(index: SearchIndex) -> Self {
        Self { index }
    }

    pub fn set_range_read_config(&mut self, config: SearchRangeReadConfig) {
        self.index.set_range_read_config(config);
    }

    pub fn index(&self) -> &SearchIndex {
        &self.index
    }

    pub fn index_mut(&mut self) -> &mut SearchIndex {
        &mut self.index
    }

    pub fn set_telemetry_sink(&mut self, telemetry: Option<Arc<dyn TelemetrySink>>) {
        self.index.set_telemetry_sink(telemetry);
    }

    pub fn into_index(self) -> SearchIndex {
        self.index
    }

    pub fn probe_json(&self, options: SearchProjectionProbeOptions) -> serde_json::Value {
        self.index.nowledge_search_projection_probe_json(options)
    }

    pub fn evidence_json(&self, options: SearchProjectionProbeOptions) -> serde_json::Value {
        nowledge_search_projection_evidence_json(&self.probe_json(options))
    }

    pub fn evidence_report(
        &self,
        options: SearchProjectionProbeOptions,
    ) -> NowledgeSearchProjectionEvidenceReport {
        NowledgeSearchProjectionEvidenceReport::from_probe(&self.probe_json(options))
    }

    pub fn validate_sampled_vector_recall(
        &self,
        options: VectorRecallValidationOptions,
    ) -> VectorRecallValidationReport {
        self.index.validate_sampled_vector_recall(options)
    }

    pub fn qualify_sampled_vector_recall_for_production(
        &self,
        options: VectorRecallValidationOptions,
        evidence_binding: crate::ProductionEvidenceBinding,
        expected_identity: crate::ProductionQualificationIdentity,
    ) -> VectorRecallProductionQualificationReport {
        self.index.qualify_sampled_vector_recall_for_production(
            options,
            evidence_binding,
            expected_identity,
        )
    }

    pub fn shadow_evidence_json(
        &self,
        primary_probe: &serde_json::Value,
        options: SearchProjectionProbeOptions,
    ) -> serde_json::Value {
        nowledge_search_projection_shadow_evidence_json(primary_probe, &self.probe_json(options))
    }

    pub fn freshness(&self) -> SearchProjectionFreshness {
        self.index.projection_freshness()
    }

    pub fn search_candidates(
        &self,
        request: &NowledgeMemSearchCandidateRequest,
    ) -> Result<SearchResultSet> {
        self.search_candidates_with_report(request)
            .map(|output| output.result)
    }

    pub fn search_candidates_with_report(
        &self,
        request: &NowledgeMemSearchCandidateRequest,
    ) -> Result<NowledgeMemSearchCandidateOutput> {
        let effective_compressed_vector_search_mode = effective_search_candidate_mode(request);
        let result = self.index.search_with_options_adaptive_vector_projection(
            &request.query_text,
            request.query_embedding.as_deref(),
            request.mode,
            SearchQueryOptions {
                limit: request.limit,
                offset: request.offset,
                rank_window: request.rank_window,
                fusion_weights: request.fusion_weights,
                metadata_filters: request.metadata_filters.clone(),
                policy_epoch: None,
            },
            AdaptiveVectorSearchOptions {
                compression_mode: effective_compressed_vector_search_mode,
                backend_policy: request.adaptive_vector_backend_policy,
                recall_validation_probe: request.recall_validation_probe,
            },
        )?;
        let report = nowledge_mem_search_candidate_report(
            request,
            effective_compressed_vector_search_mode,
            &result,
        );
        Ok(NowledgeMemSearchCandidateOutput {
            result,
            report,
            out_of_core_metrics: None,
        })
    }

    pub fn try_search_candidates_with_report(
        &self,
        request: &NowledgeMemSearchCandidateRequest,
    ) -> Result<NowledgeMemSearchCandidateOutput> {
        self.try_search_candidates_with_report_context(
            request,
            VectorSearchExecutionOptions::default(),
        )
    }

    pub fn try_search_candidates_with_report_context(
        &self,
        request: &NowledgeMemSearchCandidateRequest,
        vector_execution_options: VectorSearchExecutionOptions<'_>,
    ) -> Result<NowledgeMemSearchCandidateOutput> {
        let effective_compressed_vector_search_mode = effective_search_candidate_mode(request);
        let result = self
            .index
            .try_search_with_options_adaptive_vector_projection_context(
                &request.query_text,
                request.query_embedding.as_deref(),
                request.mode,
                SearchQueryOptions {
                    limit: request.limit,
                    offset: request.offset,
                    rank_window: request.rank_window,
                    fusion_weights: request.fusion_weights,
                    metadata_filters: request.metadata_filters.clone(),
                    policy_epoch: None,
                },
                AdaptiveVectorSearchOptions {
                    compression_mode: effective_compressed_vector_search_mode,
                    backend_policy: request.adaptive_vector_backend_policy,
                    recall_validation_probe: request.recall_validation_probe,
                },
                vector_execution_options,
            )?;
        let report = nowledge_mem_search_candidate_report(
            request,
            effective_compressed_vector_search_mode,
            &result,
        );
        Ok(NowledgeMemSearchCandidateOutput {
            result,
            report,
            out_of_core_metrics: None,
        })
    }

    pub fn search_candidate_readiness(
        &self,
        request: &NowledgeMemSearchCandidateRequest,
        options: &NowledgeMemSearchCandidateReadinessOptions,
    ) -> Result<NowledgeMemSearchCandidateReadinessReport> {
        self.search_candidates_with_report(request)
            .map(|output| output.readiness_report(options))
    }

    pub fn search_candidate_shadow_evidence<I, S>(
        &self,
        request: &NowledgeMemSearchCandidateRequest,
        primary_candidate_ids: I,
    ) -> Result<NowledgeMemSearchCandidateShadowEvidence>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let output = self.search_candidates_with_report(request)?;
        let mut accumulator = NowledgeMemSearchCandidateShadowAccumulator::new();
        accumulator.record_search_candidate_output(primary_candidate_ids, &output);
        Ok(accumulator.evidence())
    }

    pub fn search_candidate_shadow_evidence_json<I, S>(
        &self,
        request: &NowledgeMemSearchCandidateRequest,
        primary_candidate_ids: I,
    ) -> Result<serde_json::Value>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        self.search_candidate_shadow_evidence(request, primary_candidate_ids)
            .map(|evidence| evidence.json())
    }
}

struct SearchProjectionExternalReadOperator<'a> {
    projection: Option<ResidentProjectionRef<'a>>,
    out_of_core_projection: Option<&'a NowledgeMemOutOfCoreSearchProjection>,
    vector_seed_execution_count: usize,
}

impl SearchProjectionExternalReadOperator<'_> {
    fn execute_text_seed_mode(
        &self,
        request: crate::executor::TextSeedExecutionRequest<'_>,
        complete: bool,
    ) -> Result<crate::executor::TextSeedExecutionOutput> {
        request.resources.checkpoint()?;
        let mut output = if complete {
            crate::executor::TextSeedExecutionOutput::new_complete(
                request.result_account,
                request.resources.result,
            )
        } else {
            crate::executor::TextSeedExecutionOutput::new(
                request.result_account,
                request.resources.result,
            )
        }?;
        if let (Some(projection), None) = (self.projection, self.out_of_core_projection) {
            let default_task = RuntimeTaskContext::default();
            let task = request.resources.task_context.unwrap_or(&default_task);
            let scored = if complete {
                projection.complete_text_seed_scores_with_context(
                    request.query_text,
                    request.metadata_filters,
                    request.resources.result.max_rows,
                    request.working_account,
                    task,
                )
            } else {
                projection.text_seed_scores_with_context(
                    request.query_text,
                    request.metadata_filters,
                    request.resources.result.max_rows,
                    request.working_account,
                    task,
                )
            }?;
            output = output.with_source_report(crate::executor::TextSeedSourceReport {
                corpus_documents: Some(scored.corpus_document_count),
                matching_documents: Some(scored.matching_document_count),
                ..Default::default()
            });
            if complete {
                for (id, score) in scored.scores() {
                    request.resources.checkpoint()?;
                    let document = projection.document(id).ok_or_else(|| {
                        HawDBError::Storage(format!("text seed document {id} is missing"))
                    })?;
                    output.push(
                        id,
                        document.metadata.get("external_id").map(String::as_str),
                        *score,
                    )?;
                }
                request.resources.checkpoint()?;
                return output.finish_complete();
            }
            let ranked_bytes = scored
                .scores()
                .len()
                .checked_mul(std::mem::size_of::<(&String, &f64)>())
                .ok_or_else(|| HawDBError::Execution("text seed rank size overflow".into()))?;
            let _ranked_memory = request.working_account.reserve(ranked_bytes)?;
            let mut ranked = scored.scores().iter().collect::<Vec<_>>();
            ranked.sort_unstable_by(|(left_id, left_score), (right_id, right_score)| {
                right_score
                    .total_cmp(left_score)
                    .then_with(|| left_id.cmp(right_id))
            });
            for (id, score) in ranked {
                request.resources.checkpoint()?;
                let document = projection.document(id).ok_or_else(|| {
                    HawDBError::Storage(format!("text seed document {id} is missing"))
                })?;
                output.push(
                    id,
                    document.metadata.get("external_id").map(String::as_str),
                    *score,
                )?;
            }
            return Ok(output);
        }
        if let (None, Some(projection)) = (self.projection, self.out_of_core_projection) {
            let default_task = RuntimeTaskContext::default();
            let task = request.resources.task_context.unwrap_or(&default_task);
            let scored = if complete {
                projection
                    .reader()
                    .complete_text_seed_scores_with_metadata_filters(
                        request.query_text,
                        request.metadata_filters,
                        request.resources.result.max_rows,
                        request.working_account,
                        task,
                    )
            } else {
                projection.reader().text_seed_scores_with_metadata_filters(
                    request.query_text,
                    request.metadata_filters,
                    request.resources.result.max_rows,
                    request.working_account,
                    task,
                )
            }?;
            output = output.with_source_report(crate::executor::TextSeedSourceReport {
                generation: Some(scored.report.generation),
                source_commit_epoch: scored.report.source_graph_commit_epoch,
                corpus_documents: Some(scored.report.corpus_document_count),
                matching_documents: Some(scored.report.matching_document_count),
                postings_visited: Some(scored.report.postings_visited),
                bytes_read: Some(scored.report.bytes_read),
                document_bytes_read: Some(scored.report.document_bytes_read),
            });
            if complete {
                for (id, score) in scored.scores() {
                    request.resources.checkpoint()?;
                    output.push(id, scored.external_id(id), *score)?;
                }
                request.resources.checkpoint()?;
                return output.finish_complete();
            }
            let ranked_bytes = scored
                .scores()
                .len()
                .checked_mul(std::mem::size_of::<(&String, &f64)>())
                .ok_or_else(|| HawDBError::Execution("text seed rank size overflow".into()))?;
            let _ranked_memory = request.working_account.reserve(ranked_bytes)?;
            let mut ranked = scored.scores().iter().collect::<Vec<_>>();
            ranked.sort_unstable_by(|(left_id, left_score), (right_id, right_score)| {
                right_score
                    .total_cmp(left_score)
                    .then_with(|| left_id.cmp(right_id))
            });
            for (id, score) in ranked {
                request.resources.checkpoint()?;
                output.push(id, scored.external_id(id), *score)?;
            }
            return Ok(output);
        }
        if self.projection.is_some() {
            return Err(HawDBError::Storage(
                "nowledge mem search projection ownership is ambiguous".to_string(),
            ));
        }
        Err(missing_search_projection_error())
    }
}

impl crate::executor::ExternalReadOperator for SearchProjectionExternalReadOperator<'_> {
    fn execute_complete_text_seed(
        &mut self,
        request: crate::executor::TextSeedExecutionRequest<'_>,
    ) -> Result<crate::executor::TextSeedExecutionOutput> {
        self.execute_text_seed_mode(request, true)
    }

    fn execute_text_seed(
        &mut self,
        request: crate::executor::TextSeedExecutionRequest<'_>,
    ) -> Result<crate::executor::TextSeedExecutionOutput> {
        self.execute_text_seed_mode(request, false)
    }

    fn execute_vector_seed(
        &mut self,
        request: crate::executor::VectorSeedExecutionRequest<'_>,
    ) -> Result<crate::executor::VectorSeedExecutionOutput> {
        request.resources.checkpoint()?;
        let top_k = vector_plan_top_k(request.vector_plan)?.min(request.resources.result.max_rows);
        let search_request =
            NowledgeMemSearchCandidateRequest::vector(request.embedding.to_vec(), top_k)
                .with_metadata_filters(request.metadata_filters.clone());
        let vector_execution_options = VectorSearchExecutionOptions::bounded(
            request.resources.max_parallelism,
            request.resources.max_working_memory_bytes.get(),
            request.resources.task_context,
        );
        let output = match (self.projection, self.out_of_core_projection) {
            (Some(projection), None) => projection.try_search_candidates_with_report_context(
                &search_request,
                vector_execution_options,
            )?,
            (None, Some(projection)) => projection
                .search_candidates_with_report_context(&search_request, vector_execution_options)?
                .into(),
            (None, None) => return Err(missing_search_projection_error()),
            (Some(_), Some(_)) => {
                return Err(HawDBError::Storage(
                    "nowledge mem search projection ownership is ambiguous".to_string(),
                ));
            }
        };
        let retriever = output
            .result
            .retrievers
            .iter()
            .find(|retriever| retriever.name == "vector")
            .ok_or_else(|| {
                HawDBError::Execution(
                    "vector search did not produce a vector retriever report".to_string(),
                )
            })?;
        let candidate_score_source = vector_score_source(&retriever.candidate_score_source)?;
        let execution_output = crate::executor::VectorSeedExecutionOutput {
            rows: output
                .result
                .hits
                .into_iter()
                .map(|hit| crate::executor::VectorSeedExecutionRow {
                    id: hit.id,
                    external_id: hit.external_id,
                    score: hit.vector_score,
                })
                .collect(),
            report: hawdb_executor::VectorExecutionReport {
                backend: vector_execution_backend(candidate_score_source),
                compression_mode: vector_compression_mode(
                    output.report.compressed_vector_search_mode,
                ),
                candidate_source: vector_plan_candidate_source(request.vector_plan)?,
                backend_selection_reason: retriever.backend_selection_reason,
                estimated_raw_vector_bytes: retriever.estimated_raw_vector_bytes,
                filter_selectivity_per_million: retriever.filter_selectivity_per_million,
                candidate_score_source,
                final_score_source: vector_score_source(&retriever.final_score_source)?,
                generated_candidate_count: retriever.generated_candidate_count,
                descriptor_pruned_count: retriever.descriptor_pruned_count,
                scalar_filtered_count: retriever.scalar_filtered_count,
                residual_filtered_count: retriever.residual_filtered_count,
                candidate_scan_rounds: retriever.candidate_scan_rounds,
                reranked_candidate_count: retriever.reranked_candidate_count,
                returned_count: retriever.candidate_count,
                raw_vector_bytes_read: retriever.raw_vector_bytes_read,
                candidate_scan_metrics: retriever.candidate_scan_kernel.as_ref().map(|kernel| {
                    hawdb_executor::VectorCandidateScanMetrics {
                        kernel: kernel.clone(),
                        worker_count: retriever.candidate_scan_worker_count,
                        segment_count: retriever.candidate_scan_segment_count,
                        scanned_segment_count: retriever.candidate_scan_scanned_segment_count,
                        scored_document_count: retriever.candidate_scan_scored_document_count,
                        filtered_document_count: retriever.candidate_scan_filtered_document_count,
                        scanned_block_count: retriever.candidate_scan_scanned_block_count,
                        skipped_block_count: retriever.candidate_scan_skipped_block_count,
                        adaptive_exact_scan_count: retriever
                            .candidate_scan_adaptive_exact_scan_count,
                        payload_bytes_read: retriever.candidate_scan_payload_bytes_read,
                        admitted_working_bytes: retriever.candidate_scan_admitted_working_bytes,
                    }
                }),
                index_covered_document_count: Some(retriever.index_covered_document_count),
                index_candidate_document_count: Some(retriever.index_candidate_document_count),
                index_coverage_complete: Some(retriever.index_coverage_complete),
                fallback_reason_codes: retriever
                    .fallback_reason_codes
                    .iter()
                    .filter_map(|code| vector_fallback_reason_code(*code))
                    .collect(),
            },
        };
        execution_output.validate_result_budget(request.resources.result)?;
        request.resources.checkpoint()?;
        self.vector_seed_execution_count = self
            .vector_seed_execution_count
            .checked_add(1)
            .ok_or_else(|| {
                HawDBError::Execution(
                    "bounded external vector seed execution count overflowed".to_string(),
                )
            })?;
        Ok(execution_output)
    }
}

fn vector_plan_top_k(plan: &hawdb_plan_cypher::VectorPhysicalPlan) -> Result<usize> {
    match plan {
        hawdb_plan_cypher::VectorPhysicalPlan::TopK { limit, .. } => Ok(*limit),
        _ => Err(HawDBError::Execution(
            "vector seed physical plan is missing TopK".to_string(),
        )),
    }
}

fn vector_plan_candidate_source(
    plan: &hawdb_plan_cypher::VectorPhysicalPlan,
) -> Result<hawdb_plan_cypher::VectorCandidateSource> {
    match plan {
        hawdb_plan_cypher::VectorPhysicalPlan::VectorCandidateScan { source, .. } => Ok(*source),
        hawdb_plan_cypher::VectorPhysicalPlan::ResidualFilter { input, .. }
        | hawdb_plan_cypher::VectorPhysicalPlan::RawVectorRerank { input, .. }
        | hawdb_plan_cypher::VectorPhysicalPlan::TopK { input, .. } => {
            vector_plan_candidate_source(input)
        }
        hawdb_plan_cypher::VectorPhysicalPlan::Filter { .. } => Err(HawDBError::Execution(
            "vector seed physical plan is missing VectorCandidateScan".to_string(),
        )),
    }
}

fn vector_score_source(value: &str) -> Result<hawdb_executor::VectorScoreSource> {
    match value {
        "unavailable" | "none" => Ok(hawdb_executor::VectorScoreSource::Unavailable),
        "raw_vector" => Ok(hawdb_executor::VectorScoreSource::RawVector),
        "ann_approximate" | "graph_distance" => {
            Ok(hawdb_executor::VectorScoreSource::AnnApproximate)
        }
        "quantized_approximate" | "quantized_projection" => {
            Ok(hawdb_executor::VectorScoreSource::QuantizedApproximate)
        }
        _ => Err(HawDBError::Execution(
            "vector search returned an unsupported score source".to_string(),
        )),
    }
}

fn vector_execution_backend(
    score_source: hawdb_executor::VectorScoreSource,
) -> hawdb_executor::VectorExecutionBackend {
    match score_source {
        hawdb_executor::VectorScoreSource::Unavailable => {
            hawdb_executor::VectorExecutionBackend::Unavailable
        }
        hawdb_executor::VectorScoreSource::RawVector => {
            hawdb_executor::VectorExecutionBackend::ScalarFlat
        }
        hawdb_executor::VectorScoreSource::AnnApproximate => {
            hawdb_executor::VectorExecutionBackend::AnnProjection
        }
        hawdb_executor::VectorScoreSource::QuantizedApproximate => {
            hawdb_executor::VectorExecutionBackend::QuantizedProjection
        }
    }
}

fn vector_compression_mode(
    mode: CompressedVectorSearchMode,
) -> hawdb_executor::VectorCompressionMode {
    match mode {
        CompressedVectorSearchMode::Disabled => hawdb_executor::VectorCompressionMode::Disabled,
        CompressedVectorSearchMode::Preferred => hawdb_executor::VectorCompressionMode::Preferred,
        CompressedVectorSearchMode::Required => hawdb_executor::VectorCompressionMode::Required,
    }
}

fn vector_fallback_reason_code(
    code: SearchFallbackReasonCode,
) -> Option<hawdb_executor::VectorFallbackReasonCode> {
    match code {
        SearchFallbackReasonCode::VectorDimensionMismatch => {
            Some(hawdb_executor::VectorFallbackReasonCode::VectorDimensionMismatch)
        }
        SearchFallbackReasonCode::VectorIndexEmpty => {
            Some(hawdb_executor::VectorFallbackReasonCode::VectorIndexEmpty)
        }
        SearchFallbackReasonCode::CompressedVectorProjectionUnavailable => {
            Some(hawdb_executor::VectorFallbackReasonCode::CompressedVectorProjectionUnavailable)
        }
        SearchFallbackReasonCode::CompressedVectorBudgetExceeded => {
            Some(hawdb_executor::VectorFallbackReasonCode::CompressedVectorBudgetExceeded)
        }
        SearchFallbackReasonCode::DiskAnnCacheBudgetExceeded => {
            Some(hawdb_executor::VectorFallbackReasonCode::DiskAnnCacheBudgetExceeded)
        }
        SearchFallbackReasonCode::QueryEmbeddingMissing => {
            Some(hawdb_executor::VectorFallbackReasonCode::QueryEmbeddingMissing)
        }
        SearchFallbackReasonCode::TextQueryEmpty => None,
    }
}

#[derive(Debug)]
pub struct NowledgeMemEmbeddedStore {
    graph: NowledgeMemGraph,
    search_projection: Option<NowledgeMemSearchProjection>,
    out_of_core_search_projection: Option<NowledgeMemOutOfCoreSearchProjection>,
    retrieval_projection_advisor: NowledgeMemRetrievalProjectionAdvisor,
}

impl crate::DatabasePublicationState for NowledgeMemEmbeddedStore {
    fn database(&self) -> &crate::Database {
        self.graph.database()
    }
}

fn search_document_payload_bytes(document: &SearchDocument) -> usize {
    let embedding_bytes = document.embedding.as_ref().map_or(0, |embedding| {
        embedding.len().saturating_mul(size_of::<f32>())
    });
    let metadata_bytes = document
        .metadata
        .iter()
        .fold(0usize, |total, (key, value)| {
            total.saturating_add(key.len()).saturating_add(value.len())
        });
    size_of::<SearchDocument>()
        .saturating_add(document.id.len())
        .saturating_add(document.title.len())
        .saturating_add(document.content.len())
        .saturating_add(embedding_bytes)
        .saturating_add(metadata_bytes)
}

impl NowledgeMemEmbeddedStore {
    pub fn new(
        graph: NowledgeMemGraph,
        mut search_projection: Option<NowledgeMemSearchProjection>,
    ) -> Self {
        if let Some(projection) = search_projection.as_mut() {
            let mut range_read_config = projection.index().range_read_config();
            range_read_config.io_depth = range_read_config
                .io_depth
                .min(graph.runtime_governor_snapshot().limits.foreground_io_depth);
            projection.set_range_read_config(range_read_config);
        }
        Self {
            graph,
            search_projection,
            out_of_core_search_projection: None,
            retrieval_projection_advisor: NowledgeMemRetrievalProjectionAdvisor::default(),
        }
    }

    fn new_with_out_of_core_search(
        graph: NowledgeMemGraph,
        out_of_core_search_projection: NowledgeMemOutOfCoreSearchProjection,
        retrieval_projection_advisor: NowledgeMemRetrievalProjectionAdvisor,
    ) -> Self {
        Self {
            graph,
            search_projection: None,
            out_of_core_search_projection: Some(out_of_core_search_projection),
            retrieval_projection_advisor,
        }
    }

    pub fn open_with_options(
        options: NowledgeMemOpenOptions,
    ) -> Result<(Self, NowledgeMemOpenReport)> {
        let graph_config = options.effective_database_config();
        let runtime_governor =
            default_nowledge_mem_runtime_governor(&options.graph_path, &graph_config);
        Self::open_with_options_and_runtime_governor(options, runtime_governor)
    }

    pub fn open_with_options_and_runtime_governor(
        options: NowledgeMemOpenOptions,
        runtime_governor: RuntimeGovernor,
    ) -> Result<(Self, NowledgeMemOpenReport)> {
        options.validate()?;
        let mut report = options.sanitized_report();
        let graph_config = options.effective_database_config();
        let namespace_anchor = graph_config.namespace_durability_anchor.clone();
        let mut graph = NowledgeMemGraph::open_with_config_and_runtime_governor(
            &options.graph_path,
            graph_config,
            runtime_governor,
        )?;
        // Project metadata can open without recovering main's data runtime.
        // Readiness requires data admission before any host schema mutation.
        graph.database().commit_epoch()?;
        for registry in &options.system_schema_registries {
            report.system_schema_upgrades.push(
                graph
                    .database_mut()
                    .apply_system_schema_registry(registry)?,
            );
        }
        report.graph_opened = true;
        let default_search_range_read_config = SearchRangeReadConfig {
            io_depth: graph.runtime_governor_snapshot().limits.foreground_io_depth,
            ..SearchRangeReadConfig::default()
        };
        let Some(path) = options.search_projection_path.as_ref() else {
            return Ok((Self::new(graph, None), report));
        };
        // A sibling search projection is a separate descriptor domain. Admit
        // the same explicit host boundary before its internal component opens;
        // the returned index/reader retains that domain after this guard drops.
        // Reader modes must not create or synchronize an absent projection.
        let create_search = matches!(
            &options.search_projection_open_mode,
            NowledgeMemSearchProjectionOpenMode::FullResidencyMaintenance
        );
        let _search_namespace = namespace_anchor
            .as_deref()
            .map(|anchor| {
                hawdb_storage::file_descriptors::ProjectFileDescriptors::acquire_component_with_namespace_anchor(
                    path,
                    create_search,
                    anchor,
                )
            })
            .transpose()?;
        match &options.search_projection_open_mode {
            NowledgeMemSearchProjectionOpenMode::FullResidencyMaintenance => {
                let mut projection = NowledgeMemSearchProjection::open(path)?;
                projection.set_range_read_config(
                    options
                        .search_range_read_config
                        .unwrap_or(default_search_range_read_config),
                );
                report.search_projection_opened = true;
                Ok((Self::new(graph, Some(projection)), report))
            }
            NowledgeMemSearchProjectionOpenMode::IncrementalMaintenance(maintenance) => {
                let projection = NowledgeMemOutOfCoreSearchProjection::open_incremental(
                    path,
                    (**maintenance).clone(),
                )?;
                report.search_projection_opened = true;
                Ok((
                    Self::new_with_out_of_core_search(
                        graph,
                        projection,
                        options.retrieval_projection_advisor.clone(),
                    ),
                    report,
                ))
            }
            NowledgeMemSearchProjectionOpenMode::QualifiedOutOfCore(qualified) => {
                let graph_commit_epoch = graph.database().commit_epoch()?;
                if graph_commit_epoch != qualified.expected_identity.canonical_graph_commit_epoch {
                    return Err(HawDBError::Storage(format!(
                        "qualified out-of-core search expected canonical graph commit epoch {}, opened graph is at {graph_commit_epoch}",
                        qualified.expected_identity.canonical_graph_commit_epoch
                    )));
                }
                let projection = NowledgeMemOutOfCoreSearchProjection::open_production_with_config(
                    path,
                    qualified.config.clone(),
                    &qualified.qualification,
                    &qualified.expected_identity,
                )?;
                report.search_projection_opened = true;
                report.search_production_qualification_bound = true;
                Ok((
                    Self::new_with_out_of_core_search(
                        graph,
                        projection,
                        options.retrieval_projection_advisor.clone(),
                    ),
                    report,
                ))
            }
        }
    }

    pub fn graph(&self) -> &NowledgeMemGraph {
        &self.graph
    }

    pub fn graph_mut(&mut self) -> &mut NowledgeMemGraph {
        &mut self.graph
    }

    pub fn runtime_governor_snapshot(&self) -> RuntimeGovernorSnapshot {
        self.graph.runtime_governor_snapshot()
    }

    pub fn refresh_runtime_resources(&self) -> bool {
        self.graph.refresh_runtime_resources()
    }

    pub fn search_projection(&self) -> Option<&NowledgeMemSearchProjection> {
        self.search_projection.as_ref()
    }

    pub fn search_projection_mut(&mut self) -> Option<&mut NowledgeMemSearchProjection> {
        self.search_projection.as_mut()
    }

    pub fn out_of_core_search_projection(&self) -> Option<&NowledgeMemOutOfCoreSearchProjection> {
        self.out_of_core_search_projection.as_ref()
    }

    /// Applies a projection delta and checkpoints it before acknowledging
    /// success to the host. A checkpoint failure is returned to the caller,
    /// leaving the host free to retry its idempotent batch.
    pub fn apply_search_projection_delta_and_checkpoint(
        &mut self,
        delta: SearchProjectionDelta,
    ) -> Result<SearchProjectionDeltaReport> {
        if self.incremental_search_enabled() {
            let permit =
                self.admit_incremental_search_maintenance(search_projection_delta_bytes(&delta))?;
            return self.apply_incremental_search_delta(
                delta,
                permit.bind_task_context(RuntimeTaskContext::default()),
            );
        }
        let projection = require_search_projection_mut(&mut self.search_projection)?;
        let report = projection.index_mut().apply_projection_delta(delta)?;
        projection.index().checkpoint()?;
        Ok(report)
    }

    pub fn apply_initial_import_projection_delta_and_checkpoint(
        &mut self,
        delta: SearchProjectionDelta,
        import_source_graph_commit_epoch: u64,
    ) -> Result<SearchProjectionDeltaReport> {
        // The frozen legacy source epoch is provenance only. The database import
        // created a new local WAL history, so the projection cursor must be
        // stamped from that local history before it is made durable.
        let local_graph_commit_epoch = self.graph.database().commit_epoch()?;
        let projection = require_search_projection_mut(&mut self.search_projection)?;
        projection
            .index()
            .validate_import_source_graph_commit_epoch(import_source_graph_commit_epoch)?;
        let report = projection
            .index_mut()
            .apply_projection_delta(SearchProjectionDelta {
                source_graph_commit_epoch: Some(local_graph_commit_epoch),
                ..delta
            })?;
        projection
            .index_mut()
            .record_import_source_graph_commit_epoch(import_source_graph_commit_epoch)?;
        projection.index().checkpoint()?;
        Ok(report)
    }

    pub fn set_telemetry_sink(&mut self, telemetry: Option<Arc<dyn TelemetrySink>>) {
        self.graph
            .database_mut()
            .set_telemetry_sink(telemetry.clone());
        if let Some(search_projection) = &mut self.search_projection {
            search_projection.set_telemetry_sink(telemetry);
        }
    }

    pub fn storage_recovery_report(&self) -> Result<NowledgeMemStorageRecoveryReport> {
        Ok({
            NowledgeMemStorageRecoveryReport::from_storage_report(
                &self.graph.database().storage_recovery_report()?,
            )
        })
    }

    pub fn storage_recovery_report_json(&self) -> Result<serde_json::Value> {
        Ok(self.storage_recovery_report()?.json())
    }

    pub fn production_resource_profile(
        &self,
        statement: &NowledgeGraphStatement,
        limits: StorageResourceProfileLimits,
        evidence_binding: crate::ProductionEvidenceBinding,
        expected_identity: crate::ProductionQualificationIdentity,
    ) -> Result<StorageResourceProfileReport> {
        self.graph
            .database()
            .storage_resource_profile_for_production(
                &statement.cypher,
                &statement.parameters,
                limits,
                evidence_binding,
                expected_identity,
            )
    }

    pub fn storage_lifecycle_decision(&self) -> Result<NowledgeMemStorageLifecycleDecision> {
        Ok({
            NowledgeMemStorageLifecycleDecision::from_storage_recovery(
                self.storage_recovery_report()?,
            )
        })
    }

    pub fn storage_lifecycle_decision_json(&self) -> Result<serde_json::Value> {
        Ok(self.storage_lifecycle_decision()?.json())
    }

    pub fn runtime_status(&self) -> Result<NowledgeMemRuntimeStatus> {
        Ok({
            let graph_commit_epoch = self.graph.database().commit_epoch()?;
            NowledgeMemRuntimeStatus {
                protocol: NOWLEDGE_MEM_RUNTIME_STATUS_PROTOCOL.to_string(),
                graph_commit_epoch,
                changefeed: self
                    .graph
                    .database()
                    .search_projection_changefeed_status()?,
                projection_freshness: self.search_projection_freshness(),
                file_descriptors: self.graph.database().file_descriptor_metrics(),
            }
        })
    }

    pub fn production_status(
        &self,
        route_ownership: Option<&NowledgeMemRouteOwnershipReadinessReport>,
    ) -> Result<NowledgeMemProductionStatus> {
        Ok({
            NowledgeMemProductionStatus::from_runtime(
                self.graph.mode(),
                self.graph.database().config().read_only,
                self.runtime_status()?,
                route_ownership.cloned(),
            )
        })
    }

    pub fn production_status_json(
        &self,
        route_ownership: Option<&NowledgeMemRouteOwnershipReadinessReport>,
    ) -> Result<serde_json::Value> {
        Ok(self.production_status(route_ownership)?.json())
    }

    pub fn cutover_controls_report(
        &self,
        controls: NowledgeMemCutoverControls,
        route_ownership: Option<&NowledgeMemRouteOwnershipReadinessReport>,
    ) -> Result<NowledgeMemCutoverControlsReport> {
        Ok({
            self.cutover_controls_report_with_initial_import_cutover_catch_up(
                controls,
                route_ownership,
                None,
            )?
        })
    }

    pub fn cutover_controls_report_with_initial_import_cutover_catch_up(
        &self,
        controls: NowledgeMemCutoverControls,
        route_ownership: Option<&NowledgeMemRouteOwnershipReadinessReport>,
        initial_import_cutover_catch_up: Option<&HawDBLightningInitialImportCutoverCatchUpReport>,
    ) -> Result<NowledgeMemCutoverControlsReport> {
        Ok({
            NowledgeMemCutoverControlsReport::from_production_status(
                controls,
                self.production_status(route_ownership)?,
                initial_import_cutover_catch_up.is_some_and(|report| report.ready),
            )
        })
    }

    pub fn cutover_controls_report_with_initial_import_recovery(
        &self,
        controls: NowledgeMemCutoverControls,
        route_ownership: Option<&NowledgeMemRouteOwnershipReadinessReport>,
        initial_import_recovery: Option<&HawDBLightningInitialImportRecoveryReadinessReport>,
    ) -> Result<NowledgeMemCutoverControlsReport> {
        Ok({
            let recovery_ready = initial_import_recovery.is_some_and(|report| {
                report.ready
                    && report.startup.readiness.ready_for_cutover
                    && report
                        .startup
                        .cutover_catch_up
                        .as_ref()
                        .is_some_and(|catch_up| catch_up.ready)
            });
            let mut report = NowledgeMemCutoverControlsReport::from_production_status(
                controls,
                self.production_status(route_ownership)?,
                recovery_ready,
            );
            if report.initial_import_enabled && !recovery_ready {
                report.ready = false;
                report
                    .blocker_codes
                    .push("initial_import_recovery_not_ready".to_string());
                report.blocker_codes.sort();
                report.blocker_codes.dedup();
            }
            report
        })
    }

    pub fn cutover_controls_report_json(
        &self,
        controls: NowledgeMemCutoverControls,
        route_ownership: Option<&NowledgeMemRouteOwnershipReadinessReport>,
    ) -> Result<serde_json::Value> {
        Ok({
            self.cutover_controls_report(controls, route_ownership)?
                .json()
        })
    }

    pub fn cutover_controls_report_json_with_initial_import_cutover_catch_up(
        &self,
        controls: NowledgeMemCutoverControls,
        route_ownership: Option<&NowledgeMemRouteOwnershipReadinessReport>,
        initial_import_cutover_catch_up: Option<&HawDBLightningInitialImportCutoverCatchUpReport>,
    ) -> Result<serde_json::Value> {
        Ok({
            self.cutover_controls_report_with_initial_import_cutover_catch_up(
                controls,
                route_ownership,
                initial_import_cutover_catch_up,
            )?
            .json()
        })
    }

    pub fn build_search_projection_graph_delta_request_from_freshness(
        &self,
        max_operations: Option<usize>,
    ) -> Result<Option<SearchProjectionGraphDeltaRequest>> {
        let search_projection = self.require_search_projection()?;
        self.graph
            .database()
            .build_search_projection_graph_delta_request_from_freshness(
                search_projection.index(),
                max_operations,
            )
    }

    pub fn search_projection_changefeed_readiness(
        &self,
        require_restart_recoverable: bool,
        max_operations: Option<usize>,
    ) -> Result<SearchProjectionChangefeedReadiness> {
        if self.incremental_search_enabled() {
            let freshness = self.search_projection_freshness().ok_or_else(|| {
                HawDBError::Storage("incremental search reader is detached".into())
            })?;
            return Ok(self
                .graph
                .database()
                .search_projection_changefeed_status()?
                .readiness_after(
                    freshness.source_graph_commit_epoch,
                    freshness.durable_source_graph_commit_epoch,
                    require_restart_recoverable,
                    max_operations,
                ));
        }
        let search_projection = self.require_search_projection()?;
        self.graph
            .database()
            .search_projection_changefeed_readiness(
                search_projection.index(),
                require_restart_recoverable,
                max_operations,
            )
    }

    pub fn search_projection_graph_delta_background_work_plan(
        &self,
        request: &SearchProjectionGraphDeltaRequest,
        hint: BackgroundWorkHint,
    ) -> Result<Option<BackgroundWorkPlan>> {
        let Some(search_projection) = self.search_projection.as_ref() else {
            return Ok(None);
        };
        self.graph
            .database()
            .search_projection_graph_delta_freshness_background_work_plan(
                search_projection.index(),
                request,
                hint,
            )
    }

    pub fn apply_search_projection_graph_delta(
        &mut self,
        request: SearchProjectionGraphDeltaRequest,
    ) -> Result<SearchProjectionDeltaReport> {
        let Self {
            graph,
            search_projection,
            ..
        } = self;
        let search_projection = require_search_projection_mut(search_projection)?;
        graph
            .database()
            .apply_search_projection_graph_delta(search_projection.index_mut(), request)
    }

    pub fn catch_up_search_projection(
        &mut self,
        max_operations_per_batch: usize,
        max_batches: usize,
    ) -> Result<SearchProjectionCatchUpReport> {
        let Self {
            graph,
            search_projection,
            ..
        } = self;
        let search_projection = require_search_projection_mut(search_projection)?;
        graph.database().catch_up_search_projection(
            search_projection.index_mut(),
            max_operations_per_batch,
            max_batches,
        )
    }

    pub fn catch_up_search_projection_with_relational<F>(
        &mut self,
        max_operations_per_batch: usize,
        max_batches: usize,
        relational_hydrator: F,
    ) -> Result<SearchProjectionCatchUpReport>
    where
        F: FnMut(
            &mut DatabaseReadTransaction,
            &SearchProjectionChangeBatch,
        ) -> Result<SearchProjectionRelationalDelta>,
    {
        let Self {
            graph,
            search_projection,
            ..
        } = self;
        let search_projection = require_search_projection_mut(search_projection)?;
        graph.database().catch_up_search_projection_with_relational(
            search_projection.index_mut(),
            max_operations_per_batch,
            max_batches,
            relational_hydrator,
        )
    }

    pub fn catch_up_search_projection_with_batch_hydrator<F>(
        &mut self,
        max_change_operations_per_batch: usize,
        max_projection_operations_per_batch: usize,
        max_batches: usize,
        batch_hydrator: F,
    ) -> Result<SearchProjectionCatchUpReport>
    where
        F: FnMut(
            &mut DatabaseReadTransaction,
            &SearchProjectionChangeBatch,
        ) -> Result<SearchProjectionRelationalDelta>,
    {
        if self.incremental_search_enabled() {
            let operations = max_change_operations_per_batch
                .max(max_projection_operations_per_batch)
                .saturating_mul(max_batches);
            let permit = self.admit_incremental_search_maintenance(
                operations.saturating_mul(SEARCH_PROJECTION_CHANGEFEED_OPERATION_BYTES),
            )?;
            return self.catch_up_incremental_search_with_batch_hydrator(
                max_change_operations_per_batch,
                max_projection_operations_per_batch,
                max_batches,
                batch_hydrator,
                permit.bind_task_context(RuntimeTaskContext::default()),
            );
        }
        let Self {
            graph,
            search_projection,
            ..
        } = self;
        let search_projection = require_search_projection_mut(search_projection)?;
        graph
            .database()
            .catch_up_search_projection_with_batch_hydrator(
                search_projection.index_mut(),
                max_change_operations_per_batch,
                max_projection_operations_per_batch,
                max_batches,
                batch_hydrator,
            )
    }

    pub fn catch_up_search_projection_scheduled(
        &mut self,
        max_operations_per_batch: usize,
        max_batches: usize,
    ) -> Result<ScheduledSearchProjectionCatchUpReport> {
        let Self {
            graph,
            search_projection,
            ..
        } = self;
        let search_projection = require_search_projection_mut(search_projection)?;
        graph.database().catch_up_search_projection_scheduled(
            search_projection.index_mut(),
            max_operations_per_batch,
            max_batches,
        )
    }

    pub fn apply_scheduled_background_search_projection_graph_delta(
        &mut self,
        request: SearchProjectionGraphDeltaRequest,
    ) -> Result<SearchProjectionDeltaReport> {
        let Self {
            graph,
            search_projection,
            ..
        } = self;
        let search_projection = require_search_projection_mut(search_projection)?;
        graph
            .database()
            .apply_scheduled_background_search_projection_graph_delta(
                search_projection.index_mut(),
                request,
            )
    }

    pub fn search_projection_probe_json(
        &self,
        options: SearchProjectionProbeOptions,
    ) -> Result<serde_json::Value> {
        Ok(self.require_search_projection()?.probe_json(options))
    }

    pub fn search_projection_evidence_json(
        &self,
        options: SearchProjectionProbeOptions,
    ) -> Result<serde_json::Value> {
        Ok(self.require_search_projection()?.evidence_json(options))
    }

    pub fn search_projection_evidence_report(
        &self,
        options: SearchProjectionProbeOptions,
    ) -> Result<NowledgeSearchProjectionEvidenceReport> {
        Ok(self.require_search_projection()?.evidence_report(options))
    }

    pub fn validate_sampled_vector_recall(
        &self,
        options: VectorRecallValidationOptions,
    ) -> Result<VectorRecallValidationReport> {
        Ok(self
            .require_search_projection()?
            .validate_sampled_vector_recall(options))
    }

    pub fn qualify_sampled_vector_recall_for_production(
        &self,
        options: VectorRecallValidationOptions,
        evidence_binding: crate::ProductionEvidenceBinding,
        expected_identity: crate::ProductionQualificationIdentity,
    ) -> Result<VectorRecallProductionQualificationReport> {
        Ok(self
            .require_search_projection()?
            .qualify_sampled_vector_recall_for_production(
                options,
                evidence_binding,
                expected_identity,
            ))
    }

    pub fn search_projection_shadow_evidence_json(
        &self,
        primary_probe: &serde_json::Value,
        options: SearchProjectionProbeOptions,
    ) -> Result<serde_json::Value> {
        Ok(self
            .require_search_projection()?
            .shadow_evidence_json(primary_probe, options))
    }

    pub fn search_candidates(
        &self,
        request: &NowledgeMemSearchCandidateRequest,
    ) -> Result<NowledgeMemSearchCandidateOutput> {
        match (
            self.search_projection.as_ref(),
            self.out_of_core_search_projection.as_ref(),
        ) {
            (Some(projection), None) => projection.try_search_candidates_with_report(request),
            (None, Some(projection)) => {
                Ok(projection.search_candidates_with_report(request)?.into())
            }
            (None, None) => Err(missing_search_projection_error()),
            (Some(_), Some(_)) => Err(ambiguous_search_projection_error()),
        }
    }

    pub fn search_candidate_readiness(
        &self,
        request: &NowledgeMemSearchCandidateRequest,
        options: &NowledgeMemSearchCandidateReadinessOptions,
    ) -> Result<NowledgeMemSearchCandidateReadinessReport> {
        Ok(self.search_candidates(request)?.readiness_report(options))
    }

    pub fn search_candidate_shadow_evidence_json<I, S>(
        &self,
        request: &NowledgeMemSearchCandidateRequest,
        primary_candidate_ids: I,
    ) -> Result<serde_json::Value>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        self.require_search_projection()?
            .search_candidate_shadow_evidence_json(request, primary_candidate_ids)
    }

    pub fn retrieve_knowledge(
        &self,
        request: &KnowledgeRetrievalRequest,
    ) -> Result<KnowledgeRetrievalOutput> {
        Ok(self.retrieve_knowledge_with_report(request)?.output)
    }

    pub fn retrieve_knowledge_with_report(
        &self,
        request: &KnowledgeRetrievalRequest,
    ) -> Result<NowledgeMemRetrievalOutput> {
        let (output, out_of_core_search_metrics) = match (
            self.search_projection.as_ref(),
            self.out_of_core_search_projection.as_ref(),
        ) {
            (Some(search_projection), None) => (
                self.graph
                    .database()
                    .try_retrieve_knowledge(search_projection.index(), request)?,
                None,
            ),
            (None, Some(search_projection)) => {
                let search = search_projection
                    .search_candidates_with_report(&self.search_request_for_retrieval(request))?;
                let output = self.graph.database().try_retrieve_knowledge_from_search(
                    search.result,
                    search_projection.freshness(),
                    request,
                )?;
                (output, Some(search.metrics))
            }
            (None, None) => return Err(missing_search_projection_error()),
            (Some(_), Some(_)) => return Err(ambiguous_search_projection_error()),
        };
        let report = nowledge_mem_retrieval_report(
            self.graph.mode(),
            self.graph.database().config().compressed_vector_search_mode,
            &output,
        );
        Ok(NowledgeMemRetrievalOutput {
            output,
            report,
            out_of_core_search_metrics,
        })
    }

    pub fn read_query(&self, cypher: &str) -> Result<NowledgeMemReadOutput> {
        self.graph.read_query(cypher)
    }

    pub fn query_with_report(&mut self, cypher: &str) -> Result<NowledgeMemQueryOutput> {
        self.query_with_params_with_report_options(
            cypher,
            &BTreeMap::new(),
            NowledgeMemQueryReportOptions::default(),
        )
    }

    pub fn query_with_report_options(
        &mut self,
        cypher: &str,
        options: NowledgeMemQueryReportOptions,
    ) -> Result<NowledgeMemQueryOutput> {
        self.query_with_params_with_report_options(cypher, &BTreeMap::new(), options)
    }

    pub fn query_with_params_with_report(
        &mut self,
        cypher: &str,
        parameters: &BTreeMap<String, Value>,
    ) -> Result<NowledgeMemQueryOutput> {
        self.query_with_params_with_report_options(
            cypher,
            parameters,
            NowledgeMemQueryReportOptions::default(),
        )
    }

    pub fn query_with_params_with_report_options(
        &mut self,
        cypher: &str,
        parameters: &BTreeMap<String, Value>,
        options: NowledgeMemQueryReportOptions,
    ) -> Result<NowledgeMemQueryOutput> {
        let Self {
            graph,
            search_projection,
            out_of_core_search_projection,
            ..
        } = self;
        let mut external = SearchProjectionExternalReadOperator {
            projection: search_projection.as_ref().map(ResidentProjectionRef::Live),
            out_of_core_projection: out_of_core_search_projection.as_ref(),
            vector_seed_execution_count: 0,
        };
        graph.query_with_params_with_report_options_and_external(
            cypher,
            parameters,
            options,
            &mut external,
        )
    }

    pub fn query_with_params_with_report_options_context(
        &mut self,
        cypher: &str,
        parameters: &BTreeMap<String, Value>,
        options: NowledgeMemQueryReportOptions,
        task_context: &RuntimeTaskContext,
    ) -> Result<NowledgeMemQueryOutput> {
        let Self {
            graph,
            search_projection,
            out_of_core_search_projection,
            ..
        } = self;
        let mut external = SearchProjectionExternalReadOperator {
            projection: search_projection.as_ref().map(ResidentProjectionRef::Live),
            out_of_core_projection: out_of_core_search_projection.as_ref(),
            vector_seed_execution_count: 0,
        };
        graph.query_with_params_with_report_options_and_external_context(
            cypher,
            parameters,
            options,
            &mut external,
            task_context,
        )
    }

    pub fn query_runtime_preflight(
        &mut self,
        probes: &[NowledgeQueryRuntimePreflightProbe],
    ) -> NowledgeQueryRuntimePreflightReport {
        nowledge_query_runtime_preflight_report(self.graph.database_mut(), probes)
    }

    pub fn query_runtime_preflight_json(
        &mut self,
        probes: &[NowledgeQueryRuntimePreflightProbe],
    ) -> serde_json::Value {
        self.query_runtime_preflight(probes).json()
    }

    pub fn slow_query_report(&self) -> NowledgeMemSlowQueryReport {
        self.graph.slow_query_report()
    }

    pub fn slow_query_report_json(&self) -> serde_json::Value {
        self.slow_query_report().json()
    }

    pub fn read_query_with_options(
        &self,
        cypher: &str,
        options: &NowledgeMemReadOptions,
    ) -> Result<NowledgeMemReadOutput> {
        self.graph.read_query_with_options(cypher, options)
    }

    pub fn read_query_with_params(
        &self,
        cypher: &str,
        parameters: &BTreeMap<String, Value>,
        options: &NowledgeMemReadOptions,
    ) -> Result<NowledgeMemReadOutput> {
        self.graph
            .read_query_with_params(cypher, parameters, options)
    }

    pub fn read_query_with_params_streaming(
        &self,
        cypher: &str,
        parameters: &BTreeMap<String, Value>,
        options: &NowledgeMemReadOptions,
        consumer: impl FnMut(BTreeMap<String, Value>) -> Result<()>,
    ) -> Result<QueryStreamReport> {
        self.graph
            .read_query_with_params_streaming(cypher, parameters, options, consumer)
    }

    pub fn read_query_with_params_streaming_context(
        &self,
        cypher: &str,
        parameters: &BTreeMap<String, Value>,
        options: &NowledgeMemReadOptions,
        task_context: &RuntimeTaskContext,
        consumer: impl FnMut(BTreeMap<String, Value>) -> Result<()>,
    ) -> Result<QueryStreamReport> {
        self.graph.read_query_with_params_streaming_context(
            cypher,
            parameters,
            options,
            task_context,
            consumer,
        )
    }

    pub fn read_query_with_params_streaming_collect(
        &self,
        cypher: &str,
        parameters: &BTreeMap<String, Value>,
        options: &NowledgeMemReadOptions,
    ) -> Result<NowledgeMemReadOutput> {
        self.graph
            .read_query_with_params_streaming_collect(cypher, parameters, options)
    }

    pub fn graph_rag_schema_context(
        &self,
        options: GraphRagSchemaContextOptions,
    ) -> Result<GraphRagSchemaContext> {
        self.graph.graph_rag_schema_context(options)
    }

    pub fn read_generated_graph_rag(
        &self,
        query: &GraphRagGeneratedQuery,
        parameters: &BTreeMap<String, Value>,
        options: &NowledgeMemReadOptions,
    ) -> Result<NowledgeMemReadOutput> {
        self.graph
            .read_generated_graph_rag(query, parameters, options)
    }
}
impl NowledgeMemEmbeddedStore {
    pub fn background_maintenance_summary(
        &self,
        policy: &LocalQosPolicy,
        state: &LocalQosState,
        options: BackgroundMaintenanceOptions,
    ) -> Result<BackgroundMaintenanceSummary> {
        Ok({
            self.graph.database().background_maintenance_summary(
                self.search_projection
                    .as_ref()
                    .map(NowledgeMemSearchProjection::index),
                policy,
                state,
                options,
            )?
        })
    }

    pub fn background_maintenance_report(
        &self,
        policy: &LocalQosPolicy,
        state: &LocalQosState,
        options: BackgroundMaintenanceOptions,
    ) -> Result<NowledgeMemBackgroundMaintenanceReport> {
        Ok({
            let summary = self.background_maintenance_summary(policy, state, options)?;
            let slow_query = self.slow_query_report();
            NowledgeMemBackgroundMaintenanceReport::from_summary_with_slow_query(
                &summary,
                Some(&slow_query),
            )
        })
    }

    pub fn background_maintenance_report_json(
        &self,
        policy: &LocalQosPolicy,
        state: &LocalQosState,
        options: BackgroundMaintenanceOptions,
    ) -> Result<serde_json::Value> {
        Ok({
            self.background_maintenance_report(policy, state, options)?
                .json()
        })
    }

    pub fn library_readiness_json(
        &self,
        options: &NowledgeMemReadinessOptions,
    ) -> Result<serde_json::Value> {
        Ok(self.library_readiness(options)?.json())
    }

    pub fn library_readiness(
        &self,
        options: &NowledgeMemReadinessOptions,
    ) -> Result<NowledgeMemLibraryReadinessReport> {
        Ok({
            let bounded_read_evidence = options
                .bounded_read_evidence
                .clone()
                .unwrap_or_else(|| self.bounded_read_probe_evidence_json(options));
            let storage_recovery = self.storage_recovery_report_json()?;
            let background_maintenance = self.background_maintenance_report_json(
                &options.qos_policy,
                &options.qos_state,
                options.background_maintenance_options.clone(),
            )?;
            let query_family_evidence = query_family_replacement_evidence_json(
                options.replacement_readiness_by_query_family.as_ref(),
            );
            let graph_route_readiness =
                nowledge_mem_graph_route_readiness_json(options.graph_route_readiness.as_ref());
            let search_route_ownership = options
                .search_route_ownership
                .as_ref()
                .map(NowledgeMemSearchRouteOwnershipReadinessReport::json)
                .unwrap_or_else(missing_search_route_ownership_json);
            let active_search_route_ownership = options
                .active_search_route_ownership
                .as_ref()
                .map(NowledgeMemActiveSearchRouteOwnershipReadinessReport::json)
                .unwrap_or_else(missing_active_search_route_ownership_json);
            let active_search_route_readiness = options
                .active_search_route_readiness
                .as_ref()
                .map(NowledgeMemActiveSearchRouteReadinessReport::json)
                .unwrap_or_else(missing_active_search_route_readiness_json);
            let search_projection_evidence = options
                .search_projection_evidence
                .clone()
                .unwrap_or_else(|| {
                    self.search_projection_evidence_json(
                        options.search_projection_probe_options.clone(),
                    )
                    .unwrap_or_else(|_| missing_search_projection_evidence_json())
                });
            let search_projection_shadow_evidence = options
                .search_projection_shadow_evidence
                .clone()
                .unwrap_or_else(|| {
                    options
                        .primary_search_projection_probe
                        .as_ref()
                        .map(|primary_probe| {
                            self.search_projection_shadow_evidence_json(
                                primary_probe,
                                options.search_projection_probe_options.clone(),
                            )
                            .unwrap_or_else(|_| missing_search_projection_shadow_evidence_json())
                        })
                        .unwrap_or_else(missing_primary_search_projection_probe_json)
                });
            let search_candidate_shadow_evidence = options
                .search_candidate_shadow_evidence
                .clone()
                .unwrap_or_else(missing_search_candidate_shadow_evidence_json);
            let workload_fixture_evidence = options
                .workload_fixture_evidence
                .as_ref()
                .map(NowledgeGraphRouteWorkloadFixtureReport::json)
                .unwrap_or_else(missing_workload_fixture_evidence_json);
            let production_resource_profile = options
                .production_resource_profile
                .as_ref()
                .map(StorageResourceProfileReport::json)
                .unwrap_or_else(missing_production_resource_profile_json);
            let assessment =
                hawdb_readiness::library_readiness::assess_nowledge_mem_library_readiness(
                    &hawdb_readiness::library_readiness::NowledgeMemLibraryReadinessEvidence {
                        bounded_read_evidence: &bounded_read_evidence,
                        storage_recovery: &storage_recovery,
                        background_maintenance: &background_maintenance,
                        query_family_evidence: &query_family_evidence,
                        graph_route_readiness: &graph_route_readiness,
                        search_route_ownership: &search_route_ownership,
                        active_search_route_ownership: &active_search_route_ownership,
                        active_search_route_readiness: &active_search_route_readiness,
                        search_projection_evidence: &search_projection_evidence,
                        search_projection_shadow_evidence: &search_projection_shadow_evidence,
                        search_candidate_shadow_evidence: &search_candidate_shadow_evidence,
                        workload_fixture_evidence: &workload_fixture_evidence,
                        production_resource_profile: &production_resource_profile,
                    },
                );
            let readiness_by_area = assessment.readiness_by_area;
            let areas = readiness_by_area.areas();
            let ready_area_count = areas.iter().filter(|area| area.ready).count();
            let blocked_area_count = areas.len().saturating_sub(ready_area_count);
            let blocker_codes = assessment.blocker_codes;
            let ready = blocker_codes.is_empty();
            NowledgeMemLibraryReadinessReport {
                protocol: NOWLEDGE_MEM_LIBRARY_READINESS_PROTOCOL.to_string(),
                present: true,
                ready,
                mode: self.graph.mode(),
                redaction: NowledgeMemReadinessRedactionSummary::default(),
                production_path: NowledgeMemLibraryProductionPathSummary::default(),
                blocker_codes,
                readiness_by_area,
                ready_area_count,
                blocked_area_count,
                graph_open: true,
                graph_read_only: self.graph.database().config().read_only,
                graph_route_readiness,
                search_route_ownership,
                active_search_route_ownership,
                active_search_route_readiness,
                bounded_read_evidence,
                storage_recovery,
                background_maintenance,
                query_family_evidence,
                search_projection_evidence,
                search_projection_shadow_evidence,
                search_candidate_shadow_evidence,
                workload_fixture_evidence,
                production_resource_profile,
            }
        })
    }

    pub fn readiness_dashboard(
        &self,
        options: &NowledgeMemReadinessOptions,
    ) -> Result<NowledgeMemReadinessDashboard> {
        Ok({
            let library = self.library_readiness(options)?;
            let storage_lifecycle = self.storage_lifecycle_decision()?;
            let slow_query = self.slow_query_report();
            NowledgeMemReadinessDashboard::from_reports(&library, &storage_lifecycle, &slow_query)
        })
    }

    pub fn readiness_dashboard_json(
        &self,
        options: &NowledgeMemReadinessOptions,
    ) -> Result<serde_json::Value> {
        Ok(self.readiness_dashboard(options)?.json())
    }

    pub fn operations_readiness(
        &self,
        options: &NowledgeMemReadinessOptions,
    ) -> Result<NowledgeMemOperationsReadinessReport> {
        Ok({
            let runtime_status = self.runtime_status()?;
            let storage_recovery = self.storage_recovery_report()?;
            let slow_query = self.slow_query_report();
            let background_maintenance = self.background_maintenance_report(
                &options.qos_policy,
                &options.qos_state,
                options.background_maintenance_options.clone(),
            )?;
            NowledgeMemOperationsReadinessReport::from_reports(
                self.graph.mode(),
                self.graph.database().config().read_only,
                runtime_status,
                storage_recovery,
                slow_query,
                background_maintenance,
            )
        })
    }

    pub fn operations_readiness_json(
        &self,
        options: &NowledgeMemReadinessOptions,
    ) -> Result<serde_json::Value> {
        Ok(self.operations_readiness(options)?.json())
    }

    fn bounded_read_probe_evidence_json(
        &self,
        options: &NowledgeMemReadinessOptions,
    ) -> serde_json::Value {
        let Some(probe) = options.bounded_read_probe.as_ref() else {
            return serde_json::json!({
                "protocol": NOWLEDGE_MEM_BOUNDED_READ_EVIDENCE_PROTOCOL,
                "present": false,
                "ready": false,
                "blocker_codes": ["bounded_read_probe_missing"],
            });
        };
        match self.read_query_with_params(&probe.cypher, &probe.parameters, &options.read_options) {
            Ok(read) => nowledge_mem_bounded_read_evidence_json_with_route_readiness(
                &read.report,
                &options.covered_routes,
                options.graph_route_readiness.as_ref(),
            ),
            Err(_) => serde_json::json!({
                "protocol": NOWLEDGE_MEM_BOUNDED_READ_EVIDENCE_PROTOCOL,
                "present": true,
                "ready": false,
                "blocker_codes": ["bounded_read_probe_failed"],
            }),
        }
    }

    fn search_projection_freshness(&self) -> Option<SearchProjectionFreshness> {
        match (
            self.search_projection.as_ref(),
            self.out_of_core_search_projection.as_ref(),
        ) {
            (Some(projection), None) => Some(projection.freshness()),
            (None, Some(projection)) => Some(projection.freshness()),
            _ => None,
        }
    }

    fn external_seed_io_slots(&self) -> usize {
        self.search_projection
            .as_ref()
            .map_or(0, |projection| {
                projection.index().range_read_config().io_depth.get()
            })
            .max(usize::from(self.out_of_core_search_projection.is_some()))
    }

    fn search_request_for_retrieval(
        &self,
        request: &KnowledgeRetrievalRequest,
    ) -> NowledgeMemSearchCandidateRequest {
        search_read::retrieval_request(
            self.graph.database().config(),
            &self.retrieval_projection_advisor,
            request,
        )
    }

    fn require_search_projection(&self) -> Result<&NowledgeMemSearchProjection> {
        self.search_projection
            .as_ref()
            .ok_or_else(missing_search_projection_error)
    }
}

fn missing_search_projection_error() -> HawDBError {
    HawDBError::Storage("nowledge mem search projection is not configured".to_string())
}

fn ambiguous_search_projection_error() -> HawDBError {
    HawDBError::Storage("nowledge mem search projection ownership is ambiguous".to_string())
}

fn require_search_projection_mut(
    search_projection: &mut Option<NowledgeMemSearchProjection>,
) -> Result<&mut NowledgeMemSearchProjection> {
    search_projection
        .as_mut()
        .ok_or_else(missing_search_projection_error)
}

struct NowledgeMemQueryReportInput<'a> {
    mode: NowledgeMemGraphMode,
    statement: &'a cypher::Statement,
    trace: Option<&'a crate::optimizer::OptimizerTrace>,
    plan_cache_lookup: Option<PlanCacheLookup>,
    execution_profile: Option<&'a ReadExecutionProfile>,
    output: &'a QueryOutput,
    options: NowledgeMemQueryReportOptions,
    elapsed_micros: u128,
}

fn nowledge_mem_query_report(input: NowledgeMemQueryReportInput<'_>) -> NowledgeMemQueryReport {
    let statement_kind = crate::api::statement_kind(
        hawdb_cypher::read_route::query_statement_body(input.statement),
    );
    let decision = nowledge_mem_fast_path_classification(input.statement);
    hawdb_readiness::nowledge_mem_query_report::nowledge_mem_query_report(
        hawdb_readiness::nowledge_mem_query_report::NowledgeMemQueryReportInput {
            mode: input.mode,
            statement_kind,
            statement: input.statement,
            execution_path: decision.execution_path,
            fast_path_reason: decision.fast_path_reason,
            physical_plan_captured: input.trace.is_some(),
            physical_operator_counts: input
                .trace
                .map(|trace| trace.selected_plan_operator_counts.clone())
                .unwrap_or_default(),
            optimizer_decision_count: input
                .trace
                .map(|trace| trace.decisions.len())
                .unwrap_or_default(),
            optimizer_rule_event_count: input
                .trace
                .map(|trace| trace.rule_events.len())
                .unwrap_or_default(),
            plan_cache_lookup: input.plan_cache_lookup,
            execution_profile: input.execution_profile,
            output: input.output,
            options: input.options,
            elapsed_micros: input.elapsed_micros,
        },
    )
}

fn nowledge_query_runtime_preflight_report(
    db: &mut Database,
    probes: &[NowledgeQueryRuntimePreflightProbe],
) -> NowledgeQueryRuntimePreflightReport {
    let route_coverage = nowledge_query_runtime_route_coverage(probes);
    let probe_reports = probes
        .iter()
        .map(|probe| nowledge_query_runtime_probe_report(db, probe))
        .collect::<Vec<_>>();
    let passed_probe_count = probe_reports.iter().filter(|probe| probe.ready).count();
    let failed_probe_count = probe_reports.len().saturating_sub(passed_probe_count);
    let blocker_codes =
        query_runtime_preflight_blocker_codes(probes.len(), failed_probe_count, &route_coverage);

    NowledgeQueryRuntimePreflightReport {
        protocol: NOWLEDGE_QUERY_RUNTIME_PREFLIGHT_PROTOCOL.to_string(),
        ready: blocker_codes.is_empty(),
        database_opened: true,
        redaction: NowledgeQueryRuntimePreflightRedactionSummary::default(),
        probe_count: probes.len(),
        passed_probe_count,
        failed_probe_count,
        required_route_count: route_coverage.required_route_count,
        covered_route_count: route_coverage.covered_route_count,
        covered_routes: route_coverage.covered_routes,
        missing_required_routes: route_coverage.missing_required_routes,
        required_routes_covered: route_coverage.required_routes_covered,
        unknown_routes: route_coverage.unknown_routes,
        duplicate_routes: route_coverage.duplicate_routes,
        route_catalog_version: NOWLEDGE_MEM_GRAPH_READ_ROUTE_CATALOG_VERSION.to_string(),
        route_catalog_digest: nowledge_mem_graph_read_route_catalog_digest(),
        route_coverage_ready: route_coverage.ready,
        route_coverage_blocker_codes: route_coverage.blocker_codes,
        blocker_codes,
        probes: probe_reports,
    }
}

fn nowledge_query_runtime_probe_report(
    db: &mut Database,
    probe: &NowledgeQueryRuntimePreflightProbe,
) -> NowledgeQueryRuntimePreflightProbeReport {
    match db.explain_analyze_query_with_params(&probe.cypher, &probe.parameters) {
        Ok(output) => {
            let scan_pruning_report_count = output.execution_profile.scan_pruning_reports.len();
            let pruned_scan_count = output
                .execution_profile
                .scan_pruning_reports
                .iter()
                .filter(|report| report.pruned)
                .count();
            let output_row_count = output.output.rows.len();
            let blocker_codes = query_runtime_probe_blocker_codes(
                probe,
                scan_pruning_report_count,
                pruned_scan_count,
                output_row_count,
            );
            let plan_cache_lookup = output.plan_cache_lookup;
            let plan_cache = nowledge_mem_plan_cache_report(Some(plan_cache_lookup));
            NowledgeQueryRuntimePreflightProbeReport {
                name: probe.name.clone(),
                route: probe.route.clone(),
                query_family: probe.query_family.clone(),
                ready: blocker_codes.is_empty(),
                success: true,
                output_row_count,
                selected_plan_fingerprint: Some(output.trace.selected_plan_fingerprint),
                search_mode: Some(output.trace.search_mode.as_str().to_string()),
                selected_plan_operator_counts: output.trace.selected_plan_operator_counts,
                selected_plan_class_counts: output.trace.selected_plan_class_counts,
                optimizer_decision_count: output.trace.decisions.len(),
                optimizer_rule_event_count: output.trace.rule_events.len(),
                plan_cache_lookup: Some(plan_cache_lookup.as_str().to_string()),
                plan_cache_bypass_reason: plan_cache_lookup
                    .bypass_reason()
                    .map(|reason| reason.as_str().to_string()),
                plan_cache_cacheable: plan_cache.cacheable,
                plan_cache_hit: plan_cache.hit,
                plan_cache_miss: plan_cache.miss,
                plan_cache_bypassed: plan_cache.bypassed,
                work_priority: Some(output.work_request.priority.as_str().to_string()),
                work_class: Some(output.work_request.class.as_str().to_string()),
                estimated_operations: Some(output.work_request.estimated_operations),
                max_rows: output.execution_profile.max_rows,
                detection_row_cap: output.execution_profile.detection_row_cap,
                row_limit_enforced_before_output: output
                    .execution_profile
                    .row_limit_enforced_before_output,
                operator_row_cap_enabled: output.execution_profile.operator_row_cap_enabled,
                blocking_operator_kinds: output.execution_profile.blocking_operator_kinds,
                scan_pruning_reports: output.execution_profile.scan_pruning_reports,
                pruned_scan_count,
                error_class: None,
                blocker_codes,
            }
        }
        Err(error) => NowledgeQueryRuntimePreflightProbeReport {
            name: probe.name.clone(),
            route: probe.route.clone(),
            query_family: probe.query_family.clone(),
            ready: false,
            success: false,
            output_row_count: 0,
            selected_plan_fingerprint: None,
            search_mode: None,
            selected_plan_operator_counts: BTreeMap::new(),
            selected_plan_class_counts: BTreeMap::new(),
            optimizer_decision_count: 0,
            optimizer_rule_event_count: 0,
            plan_cache_lookup: None,
            plan_cache_bypass_reason: None,
            plan_cache_cacheable: false,
            plan_cache_hit: false,
            plan_cache_miss: false,
            plan_cache_bypassed: false,
            work_priority: None,
            work_class: None,
            estimated_operations: None,
            max_rows: None,
            detection_row_cap: None,
            row_limit_enforced_before_output: false,
            operator_row_cap_enabled: false,
            blocking_operator_kinds: Vec::new(),
            scan_pruning_reports: Vec::new(),
            pruned_scan_count: 0,
            error_class: Some(hawdb_error_class(&error).to_string()),
            blocker_codes: vec!["query_runtime_failed".to_string()],
        },
    }
}

fn missing_search_projection_evidence_json() -> serde_json::Value {
    serde_json::json!({
        "protocol": "hawdb-nowledge-search-projection-evidence",
        "present": false,
        "ready": false,
        "blocker_codes": ["search_projection_not_configured"],
    })
}

fn missing_search_projection_shadow_evidence_json() -> serde_json::Value {
    serde_json::json!({
        "protocol": "hawdb-nowledge-search-projection-shadow-evidence",
        "present": false,
        "ready": false,
        "blocker_codes": ["search_projection_not_configured"],
    })
}

fn missing_primary_search_projection_probe_json() -> serde_json::Value {
    serde_json::json!({
        "protocol": "hawdb-nowledge-search-projection-shadow-evidence",
        "present": false,
        "ready": false,
        "blocker_codes": ["primary_search_projection_probe_missing"],
    })
}

fn missing_search_candidate_shadow_evidence_json() -> serde_json::Value {
    serde_json::json!({
        "protocol": NOWLEDGE_MEM_SEARCH_CANDIDATE_SHADOW_EVIDENCE_PROTOCOL,
        "route": NOWLEDGE_MEM_SEARCH_CANDIDATE_EVIDENCE_ROUTE,
        "evidence_source": NOWLEDGE_MEM_SEARCH_CANDIDATE_EVIDENCE_SOURCE,
        "present": false,
        "ready": false,
        "candidate_primary_engine": NOWLEDGE_MEM_SEARCH_CANDIDATE_PRIMARY_ENGINE,
        "request_count": null,
        "primary_candidate_count": null,
        "shadow_candidate_count": null,
        "matched_candidate_count": null,
        "primary_only_candidate_count": null,
        "candidate_identity": {
            "ready": false,
            "parity": false,
        },
        "filter_pushdown_ready": false,
        "filter_pushdown": {
            "ready": false,
            "required_fields": NOWLEDGE_SEARCH_PROJECTION_SCAN_FILTER_FIELDS,
            "missing_required_fields": NOWLEDGE_SEARCH_PROJECTION_SCAN_FILTER_FIELDS,
            "field_summary_count": 0,
            "field_summaries": [],
            "blocker_codes": ["search_candidate_shadow_evidence_missing"],
        },
        "blocker_codes": ["search_candidate_shadow_evidence_missing"],
    })
}

fn missing_workload_fixture_evidence_json() -> serde_json::Value {
    serde_json::json!({
        "protocol": NOWLEDGE_GRAPH_ROUTE_WORKLOAD_FIXTURE_PROTOCOL,
        "present": false,
        "ready": false,
        "route_count": null,
        "query_count": null,
        "failed_query_count": null,
        "bounded_expansion_probe_count": null,
        "failed_bounded_expansion_probe_count": null,
        "search_metadata_probe_count": null,
        "failed_search_metadata_probe_count": null,
        "blocker_codes": ["workload_fixture_evidence_missing"],
    })
}

fn missing_production_resource_profile_json() -> serde_json::Value {
    serde_json::json!({
        "protocol": STORAGE_RESOURCE_PROFILE_PROTOCOL,
        "protocol_version": 2,
        "present": false,
        "resource_ready": false,
        "ready": false,
        "blocker_codes": ["production_resource_profile_missing"],
    })
}

fn query_family_replacement_evidence_json(
    replacement_readiness_by_query_family: Option<&serde_json::Value>,
) -> serde_json::Value {
    let Some(families) =
        query_family_replacement_readiness_array(replacement_readiness_by_query_family)
    else {
        return serde_json::json!({
            "protocol": "hawdb-nowledge-query-family-evidence-v1",
            "present": false,
            "ready": false,
            "required_query_families": REQUIRED_NOWLEDGE_REPLACEMENT_QUERY_FAMILIES,
            "missing_required_query_families": REQUIRED_NOWLEDGE_REPLACEMENT_QUERY_FAMILIES,
            "blocker_codes": ["query_family_evidence_missing"],
        });
    };
    let health = replacement_readiness_family_evidence_health(Some(families));
    let blocker_codes = query_family_replacement_blocker_codes(&health);
    serde_json::json!({
        "protocol": "hawdb-nowledge-query-family-evidence-v1",
        "present": health.present,
        "ready": health.ready,
        "min_replacement_readiness_per_million": health.min_replacement_readiness_per_million,
        "invalid_family_count": health.invalid_family_count,
        "blocked_query_families": health.blocked_query_families,
        "required_query_families": REQUIRED_NOWLEDGE_REPLACEMENT_QUERY_FAMILIES,
        "missing_required_query_families": health.missing_required_query_families,
        "blocker_codes": blocker_codes,
        "blockers": health.blockers,
        "replacement_readiness_by_query_family": families,
    })
}

fn query_family_replacement_readiness_array(
    value: Option<&serde_json::Value>,
) -> Option<&serde_json::Value> {
    let value = value?;
    if value.is_array() {
        return Some(value);
    }
    value
        .get("replacement_readiness_by_query_family")
        .filter(|families| families.is_array())
}

fn query_family_replacement_blocker_codes(
    health: &crate::nowledge_inventory::ReplacementReadinessFamilyEvidenceHealth,
) -> Vec<&'static str> {
    let mut blockers = Vec::new();
    if health.invalid_family_count > 0 {
        blockers.push("invalid_family_entries");
    }
    if !health.blocked_query_families.is_empty() {
        blockers.push("blocked_query_families");
    }
    if !health.missing_required_query_families.is_empty() {
        blockers.push("missing_required_query_families");
    }
    blockers
}

fn nowledge_mem_graph_route_readiness_json(
    route_readiness: Option<&NowledgeMemRouteReadinessSummary>,
) -> serde_json::Value {
    let Some(summary) = route_readiness else {
        return serde_json::json!({
            "protocol": NMEM_GRAPH_ROUTE_READINESS_PROTOCOL,
            "present": false,
            "ready": false,
            "required_route_count": REQUIRED_NOWLEDGE_MEM_BOUNDED_READ_ROUTES.len(),
            "primary_ready_route_count": 0,
            "primary_ready_routes": [],
            "missing_required_routes": REQUIRED_NOWLEDGE_MEM_BOUNDED_READ_ROUTES,
            "route_catalog_version": NOWLEDGE_MEM_GRAPH_READ_ROUTE_CATALOG_VERSION,
            "route_catalog_digest": nowledge_mem_graph_read_route_catalog_digest(),
            "route_primary_ready": null,
            "route_query_plan_evidence_ready": null,
            "route_query_profile_evidence_ready": null,
            "route_query_api_behavior_evidence_ready": null,
            "relationship_property_pruning_required_count": null,
            "relationship_property_pruning_report_count": null,
            "route_relationship_property_pruning_evidence_ready": null,
            "blocker_codes": ["graph_route_readiness_missing"],
        });
    };

    let missing_required_routes =
        hawdb_readiness::bounded_read_evidence::missing_nowledge_mem_bounded_read_routes(
            &summary.primary_ready_routes,
        );
    let relationship_property_pruning_count_matches = summary
        .relationship_property_pruning_required_count
        == summary.relationship_property_pruning_report_count;
    let mut blocker_codes = Vec::new();
    if !summary.route_primary_ready || !missing_required_routes.is_empty() {
        blocker_codes.push("route_primary_not_ready");
    }
    if !summary.route_query_plan_evidence_ready {
        blocker_codes.push("route_query_plan_evidence_not_ready");
    }
    if !summary.route_query_profile_evidence_ready {
        blocker_codes.push("route_query_profile_evidence_not_ready");
    }
    if !summary.route_query_api_behavior_evidence_ready {
        blocker_codes.push("route_query_api_behavior_evidence_not_ready");
    }
    if !summary.route_relationship_property_pruning_evidence_ready
        || !relationship_property_pruning_count_matches
    {
        blocker_codes.push("route_relationship_property_pruning_not_ready");
    }

    serde_json::json!({
        "protocol": NMEM_GRAPH_ROUTE_READINESS_PROTOCOL,
        "present": true,
        "ready": blocker_codes.is_empty(),
        "required_route_count": REQUIRED_NOWLEDGE_MEM_BOUNDED_READ_ROUTES.len(),
        "primary_ready_route_count": summary.primary_ready_routes.len(),
        "primary_ready_routes": summary.primary_ready_routes,
        "missing_required_routes": missing_required_routes,
        "route_catalog_version": NOWLEDGE_MEM_GRAPH_READ_ROUTE_CATALOG_VERSION,
        "route_catalog_digest": nowledge_mem_graph_read_route_catalog_digest(),
        "route_primary_ready": summary.route_primary_ready,
        "route_query_plan_evidence_ready": summary.route_query_plan_evidence_ready,
        "route_query_profile_evidence_ready": summary.route_query_profile_evidence_ready,
        "route_query_api_behavior_evidence_ready": summary.route_query_api_behavior_evidence_ready,
        "relationship_property_pruning_required_count": summary.relationship_property_pruning_required_count,
        "relationship_property_pruning_report_count": summary.relationship_property_pruning_report_count,
        "route_relationship_property_pruning_evidence_ready": summary.route_relationship_property_pruning_evidence_ready,
        "blocker_codes": blocker_codes,
    })
}

fn missing_search_route_ownership_json() -> serde_json::Value {
    serde_json::json!({
        "protocol": NOWLEDGE_MEM_SEARCH_ROUTE_OWNERSHIP_PROTOCOL,
        "ready": false,
        "production_cutover_ready": false,
        "require_all_hawdb": true,
        "required_route_count": REQUIRED_NOWLEDGE_MEM_SEARCH_ROUTES.len(),
        "explicit_route_count": 0,
        "hawdb_route_count": 0,
        "lancedb_route_count": 0,
        "routes": [],
        "hawdb_routes": [],
        "lancedb_routes": [],
        "missing_required_routes": REQUIRED_NOWLEDGE_MEM_SEARCH_ROUTES,
        "unknown_routes": [],
        "duplicate_routes": [],
        "conflicting_routes": [],
        "blocker_codes": ["search_route_ownership_missing"],
    })
}

fn missing_active_search_route_ownership_json() -> serde_json::Value {
    serde_json::json!({
        "protocol": NOWLEDGE_MEM_SEARCH_ROUTE_OWNERSHIP_PROTOCOL,
        "ready": false,
        "production_cutover_ready": false,
        "require_all_hawdb": true,
        "required_route_count": REQUIRED_NOWLEDGE_MEM_ACTIVE_SEARCH_ROUTES.len(),
        "explicit_route_count": 0,
        "hawdb_route_count": 0,
        "lancedb_route_count": 0,
        "routes": [],
        "hawdb_routes": [],
        "lancedb_routes": [],
        "missing_required_routes": REQUIRED_NOWLEDGE_MEM_ACTIVE_SEARCH_ROUTES,
        "unknown_routes": [],
        "duplicate_routes": [],
        "invalid_projection_routes": [],
        "blocker_codes": ["active_search_route_ownership_missing"],
    })
}

fn missing_active_search_route_readiness_json() -> serde_json::Value {
    serde_json::json!({
        "protocol": NOWLEDGE_MEM_ACTIVE_SEARCH_ROUTE_READINESS_PROTOCOL,
        "ready": false,
        "production_cutover_ready": false,
        "require_all_hawdb": true,
        "required_route_count": REQUIRED_NOWLEDGE_MEM_ACTIVE_SEARCH_ROUTES.len(),
        "evidence_route_count": 0,
        "ready_route_count": 0,
        "hawdb_route_count": 0,
        "lancedb_handle_required_route_count": 0,
        "routes": [],
        "ready_routes": [],
        "missing_required_routes": REQUIRED_NOWLEDGE_MEM_ACTIVE_SEARCH_ROUTES,
        "unknown_routes": [],
        "duplicate_routes": [],
        "invalid_projection_routes": [],
        "non_hawdb_routes": [],
        "lancedb_handle_required_routes": [],
        "candidate_not_ready_routes": [],
        "candidate_identity_not_ready_routes": [],
        "metadata_pushdown_not_ready_routes": [],
        "ranking_not_ready_routes": [],
        "fail_soft_not_ready_routes": [],
        "blocker_codes": ["active_search_route_readiness_missing"],
    })
}

fn nowledge_mem_readiness_dashboard_areas(
    library: &NowledgeMemLibraryReadinessReport,
    slow_query: &NowledgeMemSlowQueryReport,
) -> Vec<NowledgeMemReadinessAreaSummary> {
    let mut areas = library.areas();
    areas.push(NowledgeMemReadinessAreaSummary {
        name: "slow_query".to_string(),
        ready: slow_query.ready,
        blocker_codes: if slow_query.ready {
            Vec::new()
        } else {
            vec!["slow_query_report_not_ready".to_string()]
        },
    });
    areas
}

fn nowledge_mem_retrieval_report(
    mode: NowledgeMemGraphMode,
    compressed_vector_search_mode: CompressedVectorSearchMode,
    output: &KnowledgeRetrievalOutput,
) -> NowledgeMemRetrievalReport {
    let vector_backend = output
        .search
        .retrievers
        .iter()
        .find(|retriever| retriever.name == "vector")
        .map(|retriever| retriever.backend.clone());
    let text_backend = output
        .search
        .retrievers
        .iter()
        .find(|retriever| retriever.name == "text")
        .map(|retriever| retriever.backend.clone());
    let search_backend = vector_backend
        .clone()
        .or_else(|| text_backend.clone())
        .or_else(|| {
            output
                .search
                .retrievers
                .first()
                .map(|retriever| retriever.backend.clone())
        });
    let knowledge_fallback_reason_codes = output
        .diagnostics
        .graph_context_fallback_reason_codes
        .iter()
        .map(|code| code.as_str().to_string())
        .collect::<Vec<_>>();
    let retriever_fallback_reason_codes = output
        .retrievers
        .iter()
        .flat_map(|retriever| retriever.fallback_reason_codes.iter())
        .map(|code| code.as_str().to_string())
        .collect::<Vec<_>>();
    let truncation_reason_codes = output
        .diagnostics
        .search_truncation_reason_codes
        .iter()
        .map(|code| code.as_str().to_string())
        .chain(
            output
                .diagnostics
                .graph_seed_truncation_reason_codes
                .iter()
                .map(|code| code.as_str().to_string()),
        )
        .chain(
            output
                .diagnostics
                .graph_context_truncation_reason_codes
                .iter()
                .map(|code| code.as_str().to_string()),
        )
        .chain(
            output
                .diagnostics
                .candidate_truncation_reason_codes
                .iter()
                .map(|code| code.as_str().to_string()),
        )
        .collect::<Vec<_>>();
    NowledgeMemRetrievalReport {
        protocol: NOWLEDGE_MEM_RETRIEVAL_REPORT_PROTOCOL.to_string(),
        mode,
        compressed_vector_search_mode,
        graph_commit_epoch: output.graph_commit_epoch,
        projection_source_graph_commit_epoch: output.projection_freshness.source_graph_commit_epoch,
        projection_commit_lag: output.diagnostics.projection_commit_lag,
        projection_stale: output.diagnostics.projection_stale,
        search_document_count: output.search.document_count,
        search_filtered_document_count: output.search.filtered_document_count,
        search_total_hits: output.search.total_hits,
        candidate_count: output.candidates.len(),
        candidate_total_count: output.diagnostics.candidate_total_count,
        evidence_count: output.evidence.len(),
        graph_seed_count: output.graph_seeds.len(),
        graph_context_path_count: output.graph_context_paths.len(),
        search_backend,
        vector_backend,
        text_backend,
        search_fallback_reason_codes: output
            .diagnostics
            .search_fallback_reason_codes
            .iter()
            .map(|code| code.as_str().to_string())
            .collect(),
        retriever_fallback_reason_codes,
        knowledge_fallback_reason_codes,
        truncation_reason_codes,
        warning_count: output.diagnostics.warnings.len(),
        warnings: output.diagnostics.warnings.clone(),
    }
}

fn nowledge_mem_read_report(
    mode: NowledgeMemGraphMode,
    output: &QueryOutput,
    options: &NowledgeMemReadOptions,
    execution_profile: &ReadExecutionProfile,
) -> NowledgeMemReadReport {
    let estimated_payload_bytes = estimate_query_output_payload_bytes(output);
    NowledgeMemReadReport {
        protocol: NOWLEDGE_MEM_READ_REPORT_PROTOCOL.to_string(),
        mode,
        row_count: output.rows.len(),
        max_rows: options.max_rows,
        execution_row_cap: execution_profile.detection_row_cap,
        estimated_payload_bytes,
        max_estimated_payload_bytes: options.max_estimated_payload_bytes,
        row_budget_exceeded: options
            .max_rows
            .is_some_and(|max_rows| output.rows.len() > max_rows),
        payload_budget_exceeded: options
            .max_estimated_payload_bytes
            .is_some_and(|max_bytes| estimated_payload_bytes > max_bytes),
        row_limit_enforced_before_output: execution_profile.row_limit_enforced_before_output,
        operator_row_cap_enabled: execution_profile.operator_row_cap_enabled,
        blocking_operator_count: execution_profile.blocking_operator_count(),
        blocking_operator_kinds: execution_profile.blocking_operator_kinds.clone(),
        blocking_operator_memory_reports: execution_profile
            .blocking_operator_memory_reports
            .clone(),
        intermediate_rows: execution_profile.pipeline_memory_report.intermediate_rows,
        intermediate_payload_bytes: execution_profile
            .pipeline_memory_report
            .intermediate_payload_bytes,
        output_payload_bytes: execution_profile
            .pipeline_memory_report
            .output_payload_bytes,
        steady_resident_bytes: execution_profile
            .pipeline_memory_report
            .steady_resident_bytes,
        peak_resident_bytes: execution_profile.pipeline_memory_report.peak_resident_bytes,
        total_page_faults: execution_profile.pipeline_memory_report.total_page_faults,
        minor_page_faults: execution_profile.pipeline_memory_report.minor_page_faults,
        major_page_faults: execution_profile.pipeline_memory_report.major_page_faults,
        streaming: false,
    }
}

fn bounded_nowledge_mem_read_output(
    mode: NowledgeMemGraphMode,
    bounded: BoundedReadQueryOutput,
    options: &NowledgeMemReadOptions,
) -> Result<NowledgeMemReadOutput> {
    let report =
        nowledge_mem_read_report(mode, &bounded.output, options, &bounded.execution_profile);
    if report.row_budget_exceeded {
        return Err(HawDBError::read_budget_exceeded(
            ReadBudgetResource::Rows,
            report.max_rows.unwrap_or_default(),
            format!(
                "nowledge mem read query returned {} rows, exceeding max_rows {}",
                report.row_count,
                report.max_rows.unwrap_or_default()
            ),
        ));
    }
    if report.payload_budget_exceeded {
        return Err(HawDBError::read_budget_exceeded(ReadBudgetResource::PayloadBytes, report.max_estimated_payload_bytes.unwrap_or_default(), format!(
            "nowledge mem read query estimated {} payload bytes, exceeding max_estimated_payload_bytes {}",
            report.estimated_payload_bytes,
            report.max_estimated_payload_bytes.unwrap_or_default()
        )));
    }
    Ok(NowledgeMemReadOutput {
        output: bounded.output,
        report,
    })
}

fn legacy_nowledge_mem_read_error(
    error: HawDBError,
    options: &NowledgeMemReadOptions,
) -> HawDBError {
    let Some(max_payload_bytes) = options.max_estimated_payload_bytes else {
        return error;
    };
    if matches!(
        &error,
        HawDBError::ReadBudgetExceeded(cause)
            if cause.resource == ReadBudgetResource::PayloadBytes && cause.limit == max_payload_bytes
    ) {
        return HawDBError::read_budget_exceeded(ReadBudgetResource::PayloadBytes, max_payload_bytes, format!(
            "nowledge mem read query payload exceeding max_estimated_payload_bytes {max_payload_bytes}"
        ));
    }
    error
}

fn estimate_query_output_payload_bytes(output: &QueryOutput) -> usize {
    output
        .rows
        .iter()
        .map(|row| {
            row.iter()
                .map(|(key, value)| key.len() + estimate_value_payload_bytes(value))
                .sum::<usize>()
        })
        .sum()
}

fn estimate_value_payload_bytes(value: &Value) -> usize {
    match value {
        Value::Null => 0,
        Value::Bool(_) => 1,
        Value::Int(_) | Value::Float(_) => std::mem::size_of::<i64>(),
        Value::String(value) => value.len(),
        Value::Binary(value) => value.len(),
        Value::Vector(value) => value.encoded().len(),
        Value::Uuid(_) => 16,
        Value::List(values) => values.iter().map(estimate_value_payload_bytes).sum(),
        Value::Map(values) => values
            .iter()
            .map(|(key, value)| key.len() + estimate_value_payload_bytes(value))
            .sum(),
    }
}

#[cfg(test)]
mod tests;