weftgraph 0.1.0

Graph Storage gear: typed, multi-tenant knowledge graph with search and traversal over a pluggable store
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
//! An in-memory `GraphStoreV1`, the conformance suite's second
//! implementation.
//!
//! It exists so the trait's obligations are asserted against something other
//! than the code that motivated them: a change to the contract that only the
//! `PostgreSQL` store can satisfy fails here. It is deliberately simple —
//! correctness of the *obligations*, not of a database.

use std::collections::{BTreeMap, BTreeSet};
use std::sync::Mutex;

use async_trait::async_trait;
use graph_storage_sdk::models::{
    AdjacencyEntry, AdjacencySide, AdmissionBasis, ComponentReadiness, DeleteOutcome,
    DeleteRequest, EdgeKey, EdgeView, ElementEnvelope, GraphRevision, GtsTypeId, IngestOutcome,
    IngestRequest, ItemError, ItemFamily, ItemOutcome, NodeId, NodeKey, NodeRow, NodeView,
    OnExisting, Page, ProjectionRequest, ReadSnapshot, ReadinessState, RegisteredType,
    SchemaDiagnostic, SearchMode, SearchRequest, SearchResponse, SourceNamespaceOwner,
    StoreCapabilities, Subject, TopologyPage, TopologyRequest, TypeChange, TypeChangeState,
    TypeIdSet, TypeOutcome, TypeQuery, TypeRecord, TypeRegistration, TypeRegistrationOptions,
};
use graph_storage_sdk::plugin_api::{
    EmbeddingPlan, EmbeddingState, GraphStoreError, GraphStoreV1, StoreCtx, VectorArm,
};
use time::OffsetDateTime;
use uuid::Uuid;

use crate::domain::embedding::{PlannedVector, StoredVector, VectorOutcome, decide_vector};
use crate::domain::tally::IngestTally;
use crate::domain::{evolution, identity, ontology, ownership, projection};

#[derive(Clone)]
struct FakeNode {
    id: i64,
    key: String,
    type_id: String,
    name: Option<String>,
    /// The searchable text, composed by the *same* function the built-in
    /// store composes it with. The fake used to match on the name alone, so
    /// a type declaring `full_text_search` paths was searchable on one
    /// implementation and not the other — and the suite could not see it,
    /// because no case searched for text that lived in a payload.
    search_text: String,
    payload: Option<serde_json::Value>,
    /// The real vector, not a flag: the fake serves an actual cosine arm, so
    /// the acceptance test -- a document retrieved by its own text -- runs
    /// against both implementations rather than only the one with a database.
    embedding: Option<Vec<f32>>,
    /// `None` marks a vector that must not rank: absent, or stale.
    embedding_epoch: Option<i64>,
    embedding_input_hash: Option<String>,
    version: i64,
    deleted: bool,
    /// The audit envelope's storage. The fake tracks it for real rather than
    /// reporting a constant: an envelope only one implementation fills in is
    /// an envelope the conformance suite cannot see -- the same lesson the
    /// endpoint-constraint episode taught earlier in this prototype.
    audit: FakeAudit,
}

#[derive(Clone)]
struct FakeEdge {
    key: String,
    type_id: String,
    src: i64,
    dst: i64,
    discriminator: Option<String>,
    payload: Option<serde_json::Value>,
    deleted: bool,
    /// The scope whose declared snapshot this edge belongs to, as
    /// `(attribute, value)`, when a scoped batch wrote it.
    ///
    /// A replacement converges on edges by *ownership*, not by where their
    /// endpoints happen to be: an edge between two nodes of this scope may
    /// have been declared by a different producer under a different scope,
    /// and endpoint membership cannot tell the two apart. `None` means no
    /// scope has declared this edge, and a replacement leaves it alone
    /// unless one of its endpoints is departing.
    scope: Option<(String, String)>,
    audit: FakeAudit,
}

/// What `fr-audit-envelope` asks a store to remember per element: the last
/// writer of each of the three verbs, and when.
#[derive(Clone)]
struct FakeAudit {
    created_at: OffsetDateTime,
    created_by: Subject,
    updated_at: OffsetDateTime,
    updated_by: Subject,
    deleted_at: Option<OffsetDateTime>,
    deleted_by: Option<Subject>,
}

impl FakeAudit {
    fn created(subject: &Subject) -> Self {
        let now = OffsetDateTime::now_utc();
        Self {
            created_at: now,
            created_by: subject.clone(),
            updated_at: now,
            updated_by: subject.clone(),
            deleted_at: None,
            deleted_by: None,
        }
    }

    fn updated(&mut self, subject: &Subject) {
        self.updated_at = OffsetDateTime::now_utc();
        self.updated_by = subject.clone();
        self.deleted_at = None;
        self.deleted_by = None;
    }

    fn tombstoned(&mut self, subject: &Subject) {
        self.deleted_at = Some(OffsetDateTime::now_utc());
        self.deleted_by = Some(subject.clone());
    }

    fn envelope(&self, key: String, tenant_id: Uuid, revision: GraphRevision) -> ElementEnvelope {
        ElementEnvelope {
            tenant_id,
            key,
            created_at: self.created_at,
            created_by: self.created_by.clone(),
            updated_at: self.updated_at,
            updated_by: self.updated_by.clone(),
            deleted_at: self.deleted_at,
            deleted_by: self.deleted_by.clone(),
            graph_revision: revision,
        }
    }
}

#[derive(Clone)]
struct Receipt {
    request_hash: String,
    epoch: i64,
    outcome: IngestOutcome,
}

/// One scope's fence: who owns it, the highest generation it has accepted,
/// and the content hash that generation carried. The owner is here because
/// the scope's canonical identity includes it (Concurrent Ingest Protocol,
/// rule 3) — a boundary only one implementation carries is a boundary the
/// conformance suite cannot see.
#[derive(Clone)]
struct FakeScope {
    owner_producer: String,
    generation: i64,
    request_hash: String,
}

#[derive(Default)]
struct Tenant {
    types: BTreeMap<String, TypeRecord>,
    /// Source namespace -> the producer principal bound to it. The fake
    /// carries the ownership boundary for the same reason it carries the
    /// others: a boundary only one implementation enforces is a boundary the
    /// conformance suite cannot see.
    namespaces: BTreeMap<String, SourceNamespaceOwner>,
    /// The resolved `index` kinds per registered type, what the projection
    /// admits payload paths against (mirrors `gts_type.effective_traits`'s
    /// `index_kinds` on the built-in store).
    index_kinds: BTreeMap<String, BTreeMap<String, ontology::ScalarKind>>,
    nodes: Vec<FakeNode>,
    edges: Vec<FakeEdge>,
    revision: i64,
    /// Keyed by `(producer principal, idempotency key)`: the key is
    /// tenant- and producer-scoped, so two producers choosing the same
    /// string are two logical requests.
    receipts: BTreeMap<(String, String), Receipt>,
    scopes: BTreeMap<(String, String), FakeScope>,
    /// Snapshots taken by `begin_read`: a full copy, which is what makes this
    /// implementation able to honour the one-snapshot obligation the
    /// `PostgreSQL` store currently cannot.
    snapshots: BTreeMap<Uuid, Box<TenantData>>,
}

#[derive(Clone, Default)]
struct TenantData {
    nodes: Vec<FakeNode>,
    edges: Vec<FakeEdge>,
    revision: i64,
}

pub struct FakeGraphStore {
    epoch: i64,
    tenants: Mutex<BTreeMap<Uuid, Tenant>>,
    /// Internal ids are unique across the whole store, not per tenant, like
    /// the `PostgreSQL` sequence they stand in for. Per-tenant counters would
    /// hand two tenants the same id, and a case that hydrates by a foreign id
    /// -- the surface where a missing tenant predicate does not show up as a
    /// key collision -- would then be asserting nothing.
    next_id: std::sync::atomic::AtomicI64,
    /// Longest admitted derivation chain, in segments; the platform posture
    /// (3) unless a test raises it, exactly like `ontology_max_chain_depth`.
    max_chain_depth: usize,
    /// Report `snapshots = false`, and refuse to hand one out.
    declines_snapshots: bool,
    /// How much each revision read advances the answer, standing in for a
    /// tenant being written to by somebody else.
    drift_per_revision_read: i64,
    /// How many revision reads have happened, so the drift accumulates.
    revision_reads: std::sync::atomic::AtomicI64,
    /// Rows handed back by `hydrate_nodes`, across every call. Read by tests
    /// that bound how much a read fetches, which nothing about the answer
    /// itself can show.
    rows_hydrated: std::sync::atomic::AtomicU64,
    /// Calls to `hydrate_nodes`: a read that hydrates in pieces is bounded
    /// in round trips as well as in rows.
    hydrate_calls: std::sync::atomic::AtomicU64,
    /// What `node_types` answers: the types, `Unsupported` as a store that
    /// never implemented the optional method would, or a failure.
    node_types_answer: NodeTypesAnswer,
}

/// The three things `node_types` can answer, so a test can see the service
/// take each of them apart.
#[derive(Clone, Copy, Debug)]
enum NodeTypesAnswer {
    Typed,
    Unsupported,
    Failing,
}

impl Default for FakeGraphStore {
    fn default() -> Self {
        Self::new()
    }
}

impl FakeGraphStore {
    #[must_use]
    pub fn new() -> Self {
        Self {
            epoch: 1,
            tenants: Mutex::new(BTreeMap::new()),
            next_id: std::sync::atomic::AtomicI64::new(0),
            max_chain_depth: 3,
            declines_snapshots: false,
            drift_per_revision_read: 0,
            revision_reads: std::sync::atomic::AtomicI64::new(0),
            rows_hydrated: std::sync::atomic::AtomicU64::new(0),
            hydrate_calls: std::sync::atomic::AtomicU64::new(0),
            node_types_answer: NodeTypesAnswer::Typed,
        }
    }

    /// A store that never implemented `node_types`: the trait's default,
    /// `Unsupported`, which a filtered read has to work without.
    #[must_use]
    pub fn without_node_types() -> Self {
        Self {
            node_types_answer: NodeTypesAnswer::Unsupported,
            ..Self::new()
        }
    }

    /// A store whose `node_types` fails outright, which is not the same
    /// thing as one that cannot say.
    #[must_use]
    pub fn failing_node_types() -> Self {
        Self {
            node_types_answer: NodeTypesAnswer::Failing,
            ..Self::new()
        }
    }

    /// How many times `hydrate_nodes` has been called so far.
    #[must_use]
    pub fn hydrate_calls(&self) -> u64 {
        self.hydrate_calls
            .load(std::sync::atomic::Ordering::Relaxed)
    }

    /// How many rows `hydrate_nodes` has returned so far.
    #[must_use]
    pub fn rows_hydrated(&self) -> u64 {
        self.rows_hydrated
            .load(std::sync::atomic::Ordering::Relaxed)
    }

    /// A store shaped like the built-in one: it declares `snapshots = false`
    /// and means it.
    ///
    /// The fake honours the snapshot obligation, which is exactly why it
    /// could not catch a service that ignored the declaration -- the handle
    /// worked, so nothing downstream noticed it was being asked for under
    /// false pretences. `drift` makes each revision read answer that many
    /// higher, standing in for a tenant being written to while a walk runs:
    /// forcing that interleaving for real is a race, and a race is not a
    /// test.
    #[must_use]
    pub fn declining_snapshots(drift: i64) -> Self {
        Self {
            declines_snapshots: true,
            drift_per_revision_read: drift,
            ..Self::new()
        }
    }

    /// Admit chains up to `depth` segments, as a deployment raising
    /// `ontology_max_chain_depth` would.
    #[must_use]
    pub fn with_max_chain_depth(mut self, depth: usize) -> Self {
        self.max_chain_depth = depth;
        self
    }

    fn revision_of(&self, tenant: &Tenant) -> GraphRevision {
        GraphRevision {
            source_epoch: self.epoch,
            revision: tenant.revision,
        }
    }
}

fn snapshot_data(tenant: &Tenant) -> TenantData {
    TenantData {
        nodes: tenant.nodes.clone(),
        edges: tenant.edges.clone(),
        revision: tenant.revision,
    }
}

/// Whether the compiled scope admits this call's tenant at all.
///
/// The fake models only the coarse decision — deny-all, allow-all, and the
/// tenant arm — because that is what the obligations turn on. Anything finer
/// belongs to a real store's statement, and a fake that pretended otherwise
/// would let a scoping bug pass here and fail in production.
fn scope_admits(scope: &toolkit_security::AccessScope, tenant: Uuid) -> bool {
    if scope.is_deny_all() {
        return false;
    }
    if scope.is_unconstrained() {
        return true;
    }
    let tenants = scope.all_uuid_values_for(toolkit_security::pep_properties::OWNER_TENANT_ID);
    tenants.is_empty() || tenants.contains(&tenant)
}

/// Read the rows a call should see: the snapshot's copy when one is carried,
/// the live rows otherwise.
fn visible<'a>(tenant: &'a Tenant, ctx: &StoreCtx<'_>) -> (&'a [FakeNode], &'a [FakeEdge], i64) {
    if let Some(snapshot) = ctx.snapshot
        && let Some(data) = tenant.snapshots.get(&snapshot.id)
    {
        return (&data.nodes, &data.edges, data.revision);
    }
    (&tenant.nodes, &tenant.edges, tenant.revision)
}

#[async_trait]
impl GraphStoreV1 for FakeGraphStore {
    fn capabilities(&self) -> StoreCapabilities {
        StoreCapabilities {
            scope_replace: true,
            snapshots: !self.declines_snapshots,
            // A real cosine arm over the stored vectors, not a stub.
            vector_search: true,
            labels: false,
            chunks: false,
            topology: false,
        }
    }

    async fn register_types_with(
        &self,
        ctx: &StoreCtx<'_>,
        batch: Vec<TypeRegistration>,
        options: TypeRegistrationOptions,
    ) -> Result<Vec<RegisteredType>, GraphStoreError> {
        if let Some(duplicate) =
            ontology::duplicate_type_id(batch.iter().map(|r| r.type_id.as_str()))
        {
            return Err(GraphStoreError::InvalidQuery {
                what: format!(
                    "`{duplicate}` is registered twice in one batch; a batch is one act and \
                     cannot name a type twice"
                ),
            });
        }
        let mut tenants = self.tenants.lock().map_err(|_| poisoned())?;
        let tenant = tenants.entry(ctx.tenant).or_default();

        // Atomic: analyze and decide everything before storing anything.
        let mut prepared = Vec::new();
        for registration in &batch {
            let chain = ontology::ancestors(&registration.type_id);
            let mut ancestors: Vec<(String, serde_json::Value)> = Vec::new();
            for ancestor in &chain[..chain.len().saturating_sub(1)] {
                let schema = batch
                    .iter()
                    .find(|r| &r.type_id == ancestor)
                    .map(|r| r.schema.clone())
                    .or_else(|| tenant.types.get(ancestor).map(|t| t.schema.clone()))
                    .ok_or_else(|| {
                        validation(
                            0,
                            ItemFamily::Node,
                            &registration.type_id,
                            &format!("ancestor `{ancestor}` is not registered"),
                        )
                    })?;
                ancestors.push((ancestor.clone(), schema));
            }
            let refs: Vec<&serde_json::Value> =
                ancestors.iter().map(|(_, schema)| schema).collect();
            let descriptor = ontology::analyze(
                &registration.type_id,
                &registration.schema,
                &refs,
                self.max_chain_depth,
            )
            .map_err(|error| {
                validation(
                    0,
                    ItemFamily::Node,
                    &registration.type_id,
                    &error.to_string(),
                )
            })?;

            // Compiled here for the same reason the built-in store compiles
            // it here: an unresolvable `$ref` is a type that can never admit
            // an instance, and the registration is where that is actionable.
            {
                let mut chain: Vec<(String, serde_json::Value)> = ancestors.clone();
                chain.push((descriptor.type_id.clone(), descriptor.schema.clone()));
                ontology::ChainValidator::compile(&descriptor.schema, chain).map_err(|error| {
                    validation(0, ItemFamily::Node, &descriptor.type_id, &error.to_string())
                })?;
            }

            if let Some(spec) = options.migration_for(&descriptor.type_id)
                && !tenant.types.contains_key(&descriptor.type_id)
            {
                return Err(GraphStoreError::InvalidQuery {
                    what: format!(
                        "the migration for `{}` has nothing to migrate: the type is not \
                         registered yet, so it holds no rows",
                        spec.type_id
                    ),
                });
            }
            let decided = match tenant.types.get(&descriptor.type_id).cloned() {
                None => Decided {
                    outcome: TypeOutcome::Created,
                    basis: None,
                    change: fresh_change(&descriptor.type_id),
                    revision: 1,
                    created_at: OffsetDateTime::now_utc(),
                    rewrites: Vec::new(),
                },
                Some(existing) => {
                    decide_existing(tenant, &existing, &descriptor, &ancestors, &options)?
                }
            };

            let kinds: BTreeMap<String, ontology::ScalarKind> = descriptor
                .index_paths
                .iter()
                .map(|p| (p.pointer.clone(), p.kind))
                .collect();
            prepared.push((
                TypeRecord {
                    type_id: descriptor.type_id,
                    type_uuid: descriptor.type_uuid,
                    kind: descriptor.kind,
                    is_abstract: descriptor.is_abstract,
                    schema: descriptor.schema,
                    effective_traits: descriptor.effective_traits,
                    created_at: decided.created_at,
                    revision: decided.revision,
                },
                kinds,
                decided,
            ));
        }

        let mut out = Vec::with_capacity(prepared.len());
        for (record, kinds, decided) in prepared {
            if !options.dry_run && decided.outcome != TypeOutcome::Unchanged {
                tenant.types.insert(record.type_id.clone(), record.clone());
                tenant.index_kinds.insert(record.type_id.clone(), kinds);
                // Validated above, written here: a migrated payload lands with
                // the same three marks the built-in store gives it — the new
                // version, the acting subject, and a stale vector.
                for rewrite in &decided.rewrites {
                    match rewrite.family {
                        ItemFamily::Node => {
                            if let Some(node) =
                                tenant.nodes.iter_mut().find(|n| n.key == rewrite.key)
                            {
                                node.payload = Some(rewrite.payload.clone());
                                node.version += 1;
                                // Only a type that composes its embedding
                                // input from the payload can have been made
                                // stale by rewriting it; clearing the epoch
                                // otherwise would re-embed the whole type for
                                // nothing.
                                if !record.effective_traits.vector_search.is_empty() {
                                    node.embedding_epoch = None;
                                }
                                node.audit.updated(&ctx.subject);
                            }
                        }
                        ItemFamily::Edge => {
                            if let Some(edge) =
                                tenant.edges.iter_mut().find(|e| e.key == rewrite.key)
                            {
                                edge.payload = Some(rewrite.payload.clone());
                                edge.audit.updated(&ctx.subject);
                            }
                        }
                    }
                }
                if decided.outcome == TypeOutcome::Updated {
                    // What a read answers has changed, so the revision has to
                    // move — the same obligation a label attach carries
                    // (ADR-0006). A `created` type changes no existing read.
                    tenant.revision += 1;
                }
            }
            out.push(RegisteredType {
                record,
                outcome: decided.outcome,
                basis: decided.basis,
                change: Some(decided.change),
            });
        }
        Ok(out)
    }

    async fn probe_readiness(&self) -> Vec<ComponentReadiness> {
        // An in-memory store has no database to be unreachable and no
        // migrations to be pending; the traversal backend it offers is the
        // two-query hop, which is what the built-in store falls back to.
        vec![
            ComponentReadiness::healthy(graph_storage_sdk::models::DATABASE),
            ComponentReadiness::new(
                graph_storage_sdk::models::SQLPGQ,
                ReadinessState::Degraded,
                "this store has no property graph",
                "nothing: every traversal is served by the two-query hop",
                "not applicable to an in-memory store",
            ),
        ]
    }

    async fn list_source_namespaces(
        &self,
        ctx: &StoreCtx<'_>,
    ) -> Result<Vec<SourceNamespaceOwner>, GraphStoreError> {
        let tenants = self.tenants.lock().map_err(|_| poisoned())?;
        Ok(tenants
            .get(&ctx.tenant)
            .map(|tenant| tenant.namespaces.values().cloned().collect())
            .unwrap_or_default())
    }

    async fn transfer_source_namespace(
        &self,
        ctx: &StoreCtx<'_>,
        namespace: &str,
        owner_principal: &str,
    ) -> Result<SourceNamespaceOwner, GraphStoreError> {
        if owner_principal.trim().is_empty() {
            return Err(GraphStoreError::InvalidQuery {
                what: "a transfer needs the principal to transfer to".to_owned(),
            });
        }
        let mut tenants = self.tenants.lock().map_err(|_| poisoned())?;
        let tenant = tenants.entry(ctx.tenant).or_default();
        let now = OffsetDateTime::now_utc();
        let previous = tenant
            .namespaces
            .get(namespace)
            .map(|row| row.owner_principal.clone());
        let row = SourceNamespaceOwner {
            namespace: namespace.to_owned(),
            owner_principal: owner_principal.to_owned(),
            claimed_at: tenant
                .namespaces
                .get(namespace)
                .map_or(now, |row| row.claimed_at),
            previous_owner: previous.filter(|owner| owner != owner_principal),
            transferred_at: Some(now),
            transferred_by: Some(ctx.subject.clone()),
        };
        tenant.namespaces.insert(namespace.to_owned(), row.clone());
        Ok(row)
    }

    async fn get_type(
        &self,
        ctx: &StoreCtx<'_>,
        id: &GtsTypeId,
    ) -> Result<TypeRecord, GraphStoreError> {
        if !scope_admits(ctx.scope, ctx.tenant) {
            return Err(GraphStoreError::NotFound);
        }
        let tenants = self.tenants.lock().map_err(|_| poisoned())?;
        tenants
            .get(&ctx.tenant)
            .and_then(|t| t.types.get(id).cloned())
            .ok_or(GraphStoreError::NotFound)
    }

    async fn list_types(
        &self,
        ctx: &StoreCtx<'_>,
        query: TypeQuery,
    ) -> Result<Page<TypeRecord>, GraphStoreError> {
        let tenants = self.tenants.lock().map_err(|_| poisoned())?;
        let Some(tenant) = tenants.get(&ctx.tenant) else {
            return Ok(Page {
                items: Vec::new(),
                next_cursor: None,
                revision: GraphRevision {
                    source_epoch: self.epoch,
                    revision: 0,
                },
            });
        };
        let (items, next_cursor) = catalogue_page(tenant, &query);
        Ok(Page {
            items,
            next_cursor,
            revision: self.revision_of(tenant),
        })
    }

    async fn resolve_type_set(
        &self,
        ctx: &StoreCtx<'_>,
        patterns: &[String],
    ) -> Result<TypeIdSet, GraphStoreError> {
        let tenants = self.tenants.lock().map_err(|_| poisoned())?;
        let Some(tenant) = tenants.get(&ctx.tenant) else {
            return Ok(TypeIdSet::default());
        };
        Ok(TypeIdSet(
            tenant
                .types
                .keys()
                .filter(|id| ontology::matches_any_pattern(id, patterns).unwrap_or(false))
                .cloned()
                .collect(),
        ))
    }

    async fn ingest(
        &self,
        ctx: &StoreCtx<'_>,
        req: IngestRequest,
        embedding: EmbeddingPlan,
    ) -> Result<IngestOutcome, GraphStoreError> {
        let mut tenants = self.tenants.lock().map_err(|_| poisoned())?;
        let tenant = tenants.entry(ctx.tenant).or_default();
        let request_hash = identity::ingest_request_hash(&req);

        // Tenant- *and* producer-scoped, as the protocol says: two producers
        // in one tenant that happen to choose the same key are two logical
        // requests, not a retry of one.
        let producer = ctx.subject.principal();
        if let Some(key) = &req.idempotency_key
            && let Some(receipt) = tenant.receipts.get(&(producer.clone(), key.clone()))
        {
            if receipt.request_hash != request_hash {
                return Err(GraphStoreError::IdempotencyMismatch);
            }
            if receipt.epoch != self.epoch {
                return Err(GraphStoreError::IdempotencyExpired);
            }
            let mut outcome = receipt.outcome.clone();
            outcome.replayed = true;
            return Ok(outcome);
        }

        if let Some(replace) = &req.replace_scope {
            fence(tenant, &producer, replace, &request_hash)?;
        }

        // The ownership boundary, before any working copy is taken: a
        // reference node names its source namespace in its own payload, and a
        // payload proves nothing about who may speak for it. Claims land in the
        // registry here, so a batch that is later refused for any other reason
        // has still not handed anyone a namespace it did not have — the claim
        // and the write commit together, as they do in the built-in store's
        // transaction.
        let writer = ctx.subject.principal();
        let mut claims: Vec<(String, SourceNamespaceOwner)> = Vec::new();
        for spec in &req.nodes {
            let family = tenant
                .types
                .get(&spec.type_id)
                .and_then(|record| record.effective_traits.family.clone());
            let namespace = match ownership::namespace_of(family.as_deref(), spec.payload.as_ref())
                .map_err(|error| {
                    validation(0, ItemFamily::Node, &spec.type_id, &error.to_string())
                })? {
                ownership::Namespaced::None => continue,
                ownership::Namespaced::Under(namespace) => namespace.to_owned(),
            };
            let held = tenant
                .namespaces
                .get(&namespace)
                .map(|row| row.owner_principal.clone())
                .or_else(|| {
                    claims
                        .iter()
                        .find(|(name, _)| name == &namespace)
                        .map(|(_, row)| row.owner_principal.clone())
                });
            match ownership::decide(held.as_deref(), &writer) {
                ownership::Claim::Allowed => {}
                ownership::Claim::Forbidden => {
                    return Err(GraphStoreError::SourceNamespaceForbidden { namespace });
                }
                ownership::Claim::Take => claims.push((
                    namespace.clone(),
                    SourceNamespaceOwner {
                        namespace,
                        owner_principal: writer.clone(),
                        claimed_at: OffsetDateTime::now_utc(),
                        previous_owner: None,
                        transferred_at: None,
                        transferred_by: None,
                    },
                )),
            }
        }

        // Which types a replacement may remove, read before the working
        // copies take their borrows. `scope_managed` defaults to true and a
        // type that turns it off is never removed by another producer's
        // re-sync; only `static` edges are re-derived by one.
        let managed_node_types: BTreeSet<String> = tenant
            .types
            .values()
            .filter(|record| {
                record.kind == graph_storage_sdk::models::TypeKind::Node
                    && record.effective_traits.scope_managed
            })
            .map(|record| record.type_id.clone())
            .collect();
        let static_edge_types: BTreeSet<String> = tenant
            .types
            .values()
            .filter(|record| record.effective_traits.family.as_deref() == Some("static"))
            .map(|record| record.type_id.clone())
            .collect();

        // Working copies: written back only once the whole batch succeeded, so
        // a partway failure leaves nothing.
        let mut nodes = tenant.nodes.clone();
        let mut edges = tenant.edges.clone();
        let mut next_id = self.next_id.load(std::sync::atomic::Ordering::SeqCst);
        let mut tally = IngestTally::new(req.options.report_per_item);
        let mut changed = false;

        let mut state = BatchState {
            next_id: &mut next_id,
            tally: &mut tally,
            subject: &ctx.subject,
        };
        for (index, spec) in req.nodes.iter().enumerate() {
            let decided = embedding.nodes.get(index).ok_or_else(|| {
                GraphStoreError::Internal(format!(
                    "embedding plan covers {} nodes; the batch has {}",
                    embedding.nodes.len(),
                    req.nodes.len()
                ))
            })?;
            // Resolved before the borrow `apply_node` takes, and from the same
            // shared decision the built-in store uses: a vector state that only
            // one implementation gets right is one the suite cannot see.
            let vector = plan_vector(
                nodes.iter().find(|n| n.key == spec.node_key),
                PlannedVector {
                    decided,
                    active_epoch: embedding.epoch,
                },
            );
            changed |= apply_node(tenant, &mut nodes, &edges, &mut state, index, spec, vector)?;
        }
        for (index, spec) in req.edges.iter().enumerate() {
            changed |= apply_edge(
                tenant,
                &mut nodes,
                &mut edges,
                &mut state,
                index,
                spec,
                &EdgeDeclaration {
                    create_phantoms: req.options.create_phantoms.unwrap_or(true),
                    scope: req
                        .replace_scope
                        .as_ref()
                        .map(|replace| (replace.attribute.clone(), replace.value.clone())),
                },
            )?;
        }

        // Scope replacement, after the batch's own writes: a node the batch
        // re-supplied is by definition still in the scope. Static edges go
        // first, then only those nodes nothing references any more — a node
        // an analysis edge still points at stays, because the conclusion
        // drawn about it survives the re-import of the thing it was drawn
        // about.
        if let Some(replace) = &req.replace_scope {
            changed |= replace_scope(
                ScopeReplacement {
                    nodes: &mut nodes,
                    edges: &mut edges,
                    managed_node_types: &managed_node_types,
                    static_edge_types: &static_edge_types,
                    types: &tenant.types,
                },
                &req,
                replace,
                &mut tally,
            );
        }
        tenant.nodes = nodes;
        tenant.edges = edges;
        self.next_id
            .store(next_id, std::sync::atomic::Ordering::SeqCst);
        for (namespace, row) in claims {
            tenant.namespaces.insert(namespace, row);
        }
        if changed {
            tenant.revision += 1;
        }
        if let Some(replace) = &req.replace_scope {
            let key = (replace.attribute.clone(), replace.value.clone());
            // An unowned scope is claimed by its first writer, as a source
            // namespace is.
            let owner_producer = tenant
                .scopes
                .get(&key)
                .map(|scope| scope.owner_producer.clone())
                .filter(|owner| !owner.is_empty())
                .unwrap_or_else(|| producer.clone());
            tenant.scopes.insert(
                key,
                FakeScope {
                    owner_producer,
                    generation: replace.generation,
                    request_hash: request_hash.clone(),
                },
            );
        }

        let (counts, per_item_nodes, per_item_edges) = tally.into_parts();
        let outcome = IngestOutcome {
            revision: self.revision_of(tenant),
            replayed: false,
            counts,
            per_item_nodes,
            per_item_edges,
        };
        if let Some(key) = &req.idempotency_key {
            tenant.receipts.insert(
                (producer, key.clone()),
                Receipt {
                    request_hash,
                    epoch: self.epoch,
                    outcome: outcome.clone(),
                },
            );
        }
        Ok(outcome)
    }

    async fn soft_delete(
        &self,
        ctx: &StoreCtx<'_>,
        req: DeleteRequest,
    ) -> Result<DeleteOutcome, GraphStoreError> {
        let mut tenants = self.tenants.lock().map_err(|_| poisoned())?;
        let tenant = tenants.entry(ctx.tenant).or_default();

        let (nodes, edges) = match req {
            DeleteRequest::Node(key) => {
                let Some(index) = tenant.nodes.iter().position(|n| n.key == key && !n.deleted)
                else {
                    // Rule 3 of the Soft Delete Contract: deleting an
                    // already-tombstoned row is a no-op, not an absence. A
                    // key that was never here still reads as absent.
                    let tombstoned = tenant.nodes.iter().any(|n| n.key == key);
                    return settle_no_op(self, tenant, tombstoned);
                };
                let id = tenant.nodes[index].id;
                let mut tombstoned = 0u64;
                for edge in &mut tenant.edges {
                    if !edge.deleted && (edge.src == id || edge.dst == id) {
                        edge.deleted = true;
                        edge.audit.tombstoned(&ctx.subject);
                        tombstoned += 1;
                    }
                }
                tenant.nodes[index].deleted = true;
                tenant.nodes[index].audit.tombstoned(&ctx.subject);
                (1u64, tombstoned)
            }
            DeleteRequest::Edge(key) => {
                let Some(position) = tenant.edges.iter().position(|e| e.key == key && !e.deleted)
                else {
                    let tombstoned = tenant.edges.iter().any(|e| e.key == key);
                    return settle_no_op(self, tenant, tombstoned);
                };
                // An edge is a statement about two nodes: tombstoning it needs
                // both endpoints visible, the rule the edge read follows.
                let (src, dst) = (tenant.edges[position].src, tenant.edges[position].dst);
                let visible = |id: i64| tenant.nodes.iter().any(|n| n.id == id && !n.deleted);
                if !(visible(src) && visible(dst)) {
                    return Err(GraphStoreError::NotFound);
                }
                let edge = &mut tenant.edges[position];
                edge.deleted = true;
                edge.audit.tombstoned(&ctx.subject);
                (0u64, 1u64)
            }
        };

        tenant.revision += 1;
        Ok(DeleteOutcome {
            revision: self.revision_of(tenant),
            tombstoned_nodes: nodes,
            tombstoned_edges: edges,
        })
    }

    async fn begin_read(&self, ctx: &StoreCtx<'_>) -> Result<ReadSnapshot, GraphStoreError> {
        assert!(
            !self.declines_snapshots,
            "a caller asked for a snapshot from a store that declares it has none; \
             the declaration is the contract, not a hint"
        );
        let mut tenants = self.tenants.lock().map_err(|_| poisoned())?;
        let tenant = tenants.entry(ctx.tenant).or_default();
        let id = Uuid::now_v7();
        let data = snapshot_data(tenant);
        let revision = self.revision_of(tenant);
        tenant.snapshots.insert(id, Box::new(data));
        Ok(ReadSnapshot { id, revision })
    }

    async fn end_read(&self, snapshot: ReadSnapshot) -> Result<(), GraphStoreError> {
        let mut tenants = self.tenants.lock().map_err(|_| poisoned())?;
        for tenant in tenants.values_mut() {
            tenant.snapshots.remove(&snapshot.id);
        }
        Ok(())
    }

    async fn revision(&self, ctx: &StoreCtx<'_>) -> Result<GraphRevision, GraphStoreError> {
        let drift = self.drift_per_revision_read
            * self
                .revision_reads
                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        let tenants = self.tenants.lock().map_err(|_| poisoned())?;
        let observed = tenants.get(&ctx.tenant).map_or(
            GraphRevision {
                source_epoch: self.epoch,
                revision: 0,
            },
            |t| self.revision_of(t),
        );
        Ok(GraphRevision {
            revision: observed.revision + drift,
            ..observed
        })
    }

    async fn get_node(
        &self,
        ctx: &StoreCtx<'_>,
        key: &NodeKey,
        adjacency_limit: u32,
    ) -> Result<NodeView, GraphStoreError> {
        if !scope_admits(ctx.scope, ctx.tenant) {
            return Err(GraphStoreError::NotFound);
        }
        let tenants = self.tenants.lock().map_err(|_| poisoned())?;
        let tenant = tenants.get(&ctx.tenant).ok_or(GraphStoreError::NotFound)?;
        let (nodes, edges, revision) = visible(tenant, ctx);
        let node = nodes
            .iter()
            .find(|n| &n.key == key && !n.deleted)
            .ok_or(GraphStoreError::NotFound)?;

        let by_id: BTreeMap<i64, &FakeNode> = nodes
            .iter()
            .filter(|n| !n.deleted)
            .map(|n| (n.id, n))
            .collect();
        let mut adjacency = Vec::new();
        let mut truncated = false;
        // The bound applies per direction, as in the built-in store: a node
        // with many incoming edges still shows all of its outgoing ones. A
        // neighbour the caller cannot see takes its slot and is then absent,
        // which is also what the built-in store does.
        let mut taken = [0u32; 2];
        for edge in edges.iter().filter(|e| !e.deleted) {
            let (side, other, slot) = if edge.src == node.id {
                (AdjacencySide::Outgoing, edge.dst, 0)
            } else if edge.dst == node.id {
                (AdjacencySide::Incoming, edge.src, 1)
            } else {
                continue;
            };
            if taken[slot] >= adjacency_limit {
                truncated = true;
                continue;
            }
            taken[slot] += 1;
            let Some(neighbour) = by_id.get(&other) else {
                continue;
            };
            adjacency.push(AdjacencyEntry {
                edge_key: edge.key.clone(),
                edge_type_id: edge.type_id.clone(),
                side,
                neighbor_key: neighbour.key.clone(),
                neighbor_type_id: neighbour.type_id.clone(),
            });
        }
        Ok(view_of(
            node,
            ctx.tenant,
            GraphRevision {
                source_epoch: self.epoch,
                revision,
            },
            adjacency,
            truncated,
        ))
    }

    async fn get_edge(
        &self,
        ctx: &StoreCtx<'_>,
        key: &EdgeKey,
    ) -> Result<EdgeView, GraphStoreError> {
        if !scope_admits(ctx.scope, ctx.tenant) {
            return Err(GraphStoreError::NotFound);
        }
        let tenants = self.tenants.lock().map_err(|_| poisoned())?;
        let tenant = tenants.get(&ctx.tenant).ok_or(GraphStoreError::NotFound)?;
        let (nodes, edges, revision) = visible(tenant, ctx);
        let edge = edges
            .iter()
            .find(|e| &e.key == key && !e.deleted)
            .ok_or(GraphStoreError::NotFound)?;
        // Both endpoints visible or the edge is not: the same induced-subgraph
        // rule the PostgreSQL store applies.
        let endpoint = |id: i64| nodes.iter().find(|n| n.id == id && !n.deleted);
        let (Some(src), Some(dst)) = (endpoint(edge.src), endpoint(edge.dst)) else {
            return Err(GraphStoreError::NotFound);
        };
        Ok(EdgeView {
            edge_key: edge.key.clone(),
            edge_type_id: edge.type_id.clone(),
            src: src.key.clone(),
            dst: dst.key.clone(),
            discriminator: edge.discriminator.clone(),
            payload: edge.payload.clone(),
            envelope: edge.audit.envelope(
                edge.key.clone(),
                ctx.tenant,
                GraphRevision {
                    source_epoch: self.epoch,
                    revision,
                },
            ),
        })
    }

    async fn hydrate_nodes(
        &self,
        ctx: &StoreCtx<'_>,
        ids: &[NodeId],
    ) -> Result<Vec<NodeView>, GraphStoreError> {
        if !scope_admits(ctx.scope, ctx.tenant) {
            return Ok(Vec::new());
        }
        let tenants = self.tenants.lock().map_err(|_| poisoned())?;
        let Some(tenant) = tenants.get(&ctx.tenant) else {
            return Ok(Vec::new());
        };
        let (nodes, _, revision) = visible(tenant, ctx);
        let revision = GraphRevision {
            source_epoch: self.epoch,
            revision,
        };
        let views: Vec<NodeView> = ids
            .iter()
            .filter_map(|id| nodes.iter().find(|n| n.id == *id && !n.deleted))
            .map(|n| view_of(n, ctx.tenant, revision, Vec::new(), false))
            .collect();
        self.rows_hydrated
            .fetch_add(views.len() as u64, std::sync::atomic::Ordering::Relaxed);
        self.hydrate_calls
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        Ok(views)
    }

    async fn node_types(
        &self,
        ctx: &StoreCtx<'_>,
        ids: &[NodeId],
    ) -> Result<Vec<(NodeId, GtsTypeId)>, GraphStoreError> {
        match self.node_types_answer {
            NodeTypesAnswer::Typed => {}
            NodeTypesAnswer::Unsupported => {
                return Err(GraphStoreError::Unsupported { what: "node_types" });
            }
            NodeTypesAnswer::Failing => {
                return Err(GraphStoreError::Unavailable {
                    reason: "node_types is failing, as this test asked".to_owned(),
                });
            }
        }
        if !scope_admits(ctx.scope, ctx.tenant) {
            return Ok(Vec::new());
        }
        let tenants = self.tenants.lock().map_err(|_| poisoned())?;
        let Some(tenant) = tenants.get(&ctx.tenant) else {
            return Ok(Vec::new());
        };
        let (nodes, _, _) = visible(tenant, ctx);
        Ok(ids
            .iter()
            .filter_map(|id| nodes.iter().find(|n| n.id == *id && !n.deleted))
            .map(|n| (n.id, n.type_id.clone()))
            .collect())
    }

    async fn search(
        &self,
        ctx: &StoreCtx<'_>,
        req: SearchRequest,
        vector: Option<VectorArm>,
    ) -> Result<SearchResponse, GraphStoreError> {
        if !scope_admits(ctx.scope, ctx.tenant) {
            return Ok(SearchResponse {
                truncated: None,
                hits: Vec::new(),
                revision: GraphRevision {
                    source_epoch: self.epoch,
                    revision: 0,
                },
            });
        }
        // Substring matching, not a text-search engine: enough to assert that
        // scoping and revision stamping hold on every arm. The vector arm, by
        // contrast, is real cosine over the stored vectors -- the acceptance
        // test (a document retrieved by its own text) has to mean the same
        // thing here as against the database.
        let tenants = self.tenants.lock().map_err(|_| poisoned())?;
        let Some(tenant) = tenants.get(&ctx.tenant) else {
            return Err(GraphStoreError::NotFound);
        };
        let (nodes, _, revision) = visible(tenant, ctx);
        // The caller's type filter, resolved through the platform matcher as
        // `resolve_type_set` does — a pattern list that resolves to nothing
        // admits nothing, which is not the same as an absent filter.
        let admitted: Option<BTreeSet<String>> = if req.type_patterns.is_empty() {
            None
        } else {
            Some(
                tenant
                    .types
                    .values()
                    .filter(|record| {
                        ontology::matches_any_pattern(&record.type_id, &req.type_patterns)
                            .unwrap_or(false)
                    })
                    .map(|record| record.type_id.clone())
                    .collect(),
            )
        };
        let live: Vec<&FakeNode> = nodes
            .iter()
            .filter(|n| !n.deleted)
            .filter(|n| {
                admitted
                    .as_ref()
                    .is_none_or(|types| types.contains(&n.type_id))
            })
            .collect();

        let lexical: Vec<&FakeNode> =
            if matches!(req.mode, SearchMode::Lexical | SearchMode::Hybrid) {
                let needle = req.query.clone().unwrap_or_default().to_lowercase();
                live.iter()
                    .copied()
                    .filter(|n| needle.is_empty() || n.search_text.to_lowercase().contains(&needle))
                    .take(req.arm_limit as usize)
                    .collect()
            } else {
                Vec::new()
            };

        let ranked: Vec<&FakeNode> = match &vector {
            Some(arm) if matches!(req.mode, SearchMode::Vector | SearchMode::Hybrid) => {
                // Only current vectors rank: a vector of another epoch came
                // from another model, and one whose input changed carries no
                // epoch at all.
                let mut scored: Vec<(f64, &FakeNode)> = live
                    .iter()
                    .copied()
                    .filter(|n| n.embedding_epoch == Some(arm.epoch))
                    .filter_map(|n| {
                        n.embedding
                            .as_ref()
                            .map(|stored| (cosine_distance(stored, &arm.query_vector), n))
                    })
                    .collect();
                scored.sort_by(|a, b| {
                    a.0.partial_cmp(&b.0)
                        .unwrap_or(std::cmp::Ordering::Equal)
                        .then_with(|| a.1.id.cmp(&b.1.id))
                });
                scored
                    .into_iter()
                    .map(|(_, n)| n)
                    .take(req.arm_limit as usize)
                    .collect()
            }
            _ => Vec::new(),
        };

        Ok(SearchResponse {
            truncated: None,
            hits: fuse_arms(&lexical, &ranked, req.limit as usize),
            revision: GraphRevision {
                source_epoch: self.epoch,
                revision,
            },
        })
    }

    async fn project_table(
        &self,
        ctx: &StoreCtx<'_>,
        req: ProjectionRequest,
    ) -> Result<toolkit_odata::Page<NodeRow>, GraphStoreError> {
        if !scope_admits(ctx.scope, ctx.tenant) {
            return Ok(toolkit_odata::Page {
                items: Vec::new(),
                page_info: empty_page_info(),
            });
        }
        let tenants = self.tenants.lock().map_err(|_| poisoned())?;
        let Some(tenant) = tenants.get(&ctx.tenant) else {
            return Err(GraphStoreError::NotFound);
        };
        let (nodes, _, revision) = visible(tenant, ctx);
        let limit = req.query.limit.unwrap_or(200);
        let selected: Vec<&FakeNode> = nodes
            .iter()
            .filter(|n| !n.deleted)
            .filter(|n| {
                req.type_set
                    .as_ref()
                    .is_none_or(|set| set.contains(&n.type_id))
            })
            .collect();

        // Column-only filter and ordering are the platform's on the real
        // store, and the fake answers the unfiltered page for them. A payload
        // path is this gear's own rule, so the fake evaluates the shared plan
        // -- the admissibility check and the semantics it implies are then
        // asserted against both implementations (ADR-0003).
        let selected: Vec<&FakeNode> = if projection::mentions_payload(&req.query) {
            let admitted = req.type_set.as_ref().map(|set| {
                let kinds: Vec<BTreeMap<String, ontology::ScalarKind>> = set
                    .0
                    .iter()
                    .map(|type_id| tenant.index_kinds.get(type_id).cloned().unwrap_or_default())
                    .collect();
                projection::admitted_paths(&kinds)
            });
            let plan = projection::plan(&req.query, admitted.as_ref())
                .map_err(|error| GraphStoreError::InvalidQuery { what: error.0 })?;
            if req.query.cursor.is_some() {
                return Err(GraphStoreError::InvalidQuery {
                    what: "the in-memory store does not page a payload projection".to_owned(),
                });
            }
            let mut rows: Vec<&FakeNode> = selected
                .into_iter()
                .filter(|n| plan.filter.as_ref().is_none_or(|p| eval::holds(p, n)))
                .collect();
            rows.sort_by(|a, b| eval::order(&plan, a, b));
            rows
        } else {
            selected
        };

        let items = selected
            .into_iter()
            .take(usize::try_from(limit).unwrap_or(usize::MAX))
            .map(|n| NodeRow {
                envelope: n.audit.envelope(
                    n.key.clone(),
                    ctx.tenant,
                    GraphRevision {
                        source_epoch: self.epoch,
                        revision,
                    },
                ),
                node_key: n.key.clone(),
                type_id: n.type_id.clone(),
                name: n.name.clone(),
                payload: n.payload.clone(),
            })
            .collect();
        Ok(toolkit_odata::Page {
            items,
            page_info: toolkit_odata::page::PageInfo {
                next_cursor: None,
                prev_cursor: None,
                limit,
            },
        })
    }

    async fn load_topology(
        &self,
        _ctx: &StoreCtx<'_>,
        _req: TopologyRequest,
    ) -> Result<TopologyPage, GraphStoreError> {
        Err(GraphStoreError::Unsupported { what: "topology" })
    }

    async fn resolve_node_ids(
        &self,
        ctx: &StoreCtx<'_>,
        keys: &[NodeKey],
    ) -> Result<Vec<(NodeKey, NodeId)>, GraphStoreError> {
        if !scope_admits(ctx.scope, ctx.tenant) {
            return Ok(Vec::new());
        }
        let tenants = self.tenants.lock().map_err(|_| poisoned())?;
        let Some(tenant) = tenants.get(&ctx.tenant) else {
            return Ok(Vec::new());
        };
        let (nodes, _, _) = visible(tenant, ctx);
        Ok(keys
            .iter()
            .filter_map(|key| {
                nodes
                    .iter()
                    .find(|n| &n.key == key && !n.deleted)
                    .map(|n| (key.clone(), n.id))
            })
            .collect())
    }

    async fn embedding_state(
        &self,
        ctx: &StoreCtx<'_>,
        keys: &[NodeKey],
    ) -> Result<Vec<Option<EmbeddingState>>, GraphStoreError> {
        if !scope_admits(ctx.scope, ctx.tenant) {
            return Ok(keys.iter().map(|_| None).collect());
        }
        let tenants = self.tenants.lock().map_err(|_| poisoned())?;
        let Some(tenant) = tenants.get(&ctx.tenant) else {
            return Ok(keys.iter().map(|_| None).collect());
        };
        let (nodes, _, _) = visible(tenant, ctx);
        Ok(keys
            .iter()
            .map(|key| {
                nodes
                    .iter()
                    .find(|n| &n.key == key && !n.deleted)
                    .map(|n| EmbeddingState {
                        input_hash: n.embedding_input_hash.clone(),
                        vector_epoch: if n.embedding.is_some() {
                            n.embedding_epoch
                        } else {
                            None
                        },
                    })
            })
            .collect())
    }
}

/// The fake's own engine, so traversal conformance has a second
/// implementation too.
pub struct FakeGraphEngine {
    store: std::sync::Arc<FakeGraphStore>,
}

impl FakeGraphEngine {
    pub fn new(store: std::sync::Arc<FakeGraphStore>) -> Self {
        Self { store }
    }
}

#[async_trait]
impl graph_storage_sdk::plugin_api::GraphEngineV1 for FakeGraphEngine {
    fn capabilities(&self) -> graph_storage_sdk::models::EngineCapabilities {
        graph_storage_sdk::models::EngineCapabilities::default()
    }

    async fn cursor(
        &self,
        ctx: &StoreCtx<'_>,
    ) -> Result<
        graph_storage_sdk::plugin_api::EngineCursor,
        graph_storage_sdk::plugin_api::GraphEngineError,
    > {
        let revision = GraphStoreV1::revision(self.store.as_ref(), ctx)
            .await
            .map_err(|error| {
                graph_storage_sdk::plugin_api::GraphEngineError::Internal(error.to_string())
            })?;
        Ok(graph_storage_sdk::plugin_api::EngineCursor { revision })
    }

    async fn expand(
        &self,
        ctx: &StoreCtx<'_>,
        req: graph_storage_sdk::plugin_api::ExpandRequest,
    ) -> Result<
        graph_storage_sdk::plugin_api::ExpandResponse,
        graph_storage_sdk::plugin_api::GraphEngineError,
    > {
        use graph_storage_sdk::models::Direction;

        let tenants = self.store.tenants.lock().map_err(|_| {
            graph_storage_sdk::plugin_api::GraphEngineError::Internal("poisoned".into())
        })?;
        let Some(tenant) = tenants.get(&ctx.tenant) else {
            return Ok(graph_storage_sdk::plugin_api::ExpandResponse {
                reached: Vec::new(),
                degrees: Vec::new(),
                edges: Vec::new(),
                truncated: None,
                served_by: graph_storage_sdk::plugin_api::HopBackend::TwoQuery,
            });
        };
        let (nodes, edges, _) = visible(tenant, ctx);
        let live: BTreeMap<i64, &FakeNode> = nodes
            .iter()
            .filter(|n| !n.deleted)
            .map(|n| (n.id, n))
            .collect();
        let frontier: std::collections::BTreeSet<i64> = req.frontier.iter().copied().collect();

        let mut reached = Vec::new();
        let mut out_edges = Vec::new();
        for edge in edges.iter().filter(|e| !e.deleted) {
            if let Some(set) = &req.edge_types
                && !set.contains(&edge.type_id)
            {
                continue;
            }
            let (Some(src), Some(dst)) = (live.get(&edge.src), live.get(&edge.dst)) else {
                continue;
            };
            let forward = frontier.contains(&edge.src)
                && matches!(req.direction, Direction::Outgoing | Direction::Either);
            let backward = frontier.contains(&edge.dst)
                && matches!(req.direction, Direction::Incoming | Direction::Either);
            if !forward && !backward {
                continue;
            }
            if forward {
                reached.push(edge.dst);
            }
            if backward {
                reached.push(edge.src);
            }
            out_edges.push(graph_storage_sdk::models::EdgeRef {
                edge_key: edge.key.clone(),
                edge_type_id: edge.type_id.clone(),
                src: src.key.clone(),
                dst: dst.key.clone(),
            });
        }
        reached.sort_unstable();
        reached.dedup();

        // The reached nodes' own degree in the authorized subgraph, as the
        // built-in engine computes it: a ranking only one implementation
        // gets right is a ranking the conformance suite cannot see.
        let degrees = if req.with_degrees {
            let mut incident: BTreeMap<i64, u32> = BTreeMap::new();
            for edge in edges.iter().filter(|e| !e.deleted) {
                if live.contains_key(&edge.src) && live.contains_key(&edge.dst) {
                    for id in [edge.src, edge.dst] {
                        *incident.entry(id).or_default() += 1;
                    }
                }
            }
            reached
                .iter()
                .map(|id| incident.get(id).copied().unwrap_or(0))
                .collect()
        } else {
            Vec::new()
        };

        Ok(graph_storage_sdk::plugin_api::ExpandResponse {
            reached,
            degrees,
            edges: out_edges,
            truncated: None,
            // The fake walks in memory; it has no pattern backend to decline.
            served_by: graph_storage_sdk::plugin_api::HopBackend::TwoQuery,
        })
    }

    async fn shortest_path(
        &self,
        _ctx: &StoreCtx<'_>,
        _req: graph_storage_sdk::plugin_api::ShortestPathRequest,
    ) -> Result<
        graph_storage_sdk::plugin_api::PathResponse,
        graph_storage_sdk::plugin_api::GraphEngineError,
    > {
        Err(
            graph_storage_sdk::plugin_api::GraphEngineError::Unsupported {
                what: "shortest_path",
            },
        )
    }

    async fn match_pattern(
        &self,
        _ctx: &StoreCtx<'_>,
        _req: graph_storage_sdk::plugin_api::PatternRequest,
    ) -> Result<
        graph_storage_sdk::plugin_api::PatternResponse,
        graph_storage_sdk::plugin_api::GraphEngineError,
    > {
        Err(
            graph_storage_sdk::plugin_api::GraphEngineError::Unsupported {
                what: "match_pattern",
            },
        )
    }
}

fn poisoned() -> GraphStoreError {
    GraphStoreError::Internal("fake store lock is poisoned".into())
}

/// What the fake decided about one identifier that is already registered.
struct Decided {
    outcome: TypeOutcome,
    basis: Option<AdmissionBasis>,
    change: TypeChange,
    revision: i32,
    created_at: OffsetDateTime,
    /// Payloads a migration produced, applied by the write loop — the fake
    /// decides with an immutable borrow of the tenant and writes afterwards,
    /// exactly as the built-in store validates before it writes.
    rewrites: Vec<Rewrite>,
}

/// One migrated row, keyed the way a producer names it.
struct Rewrite {
    family: ItemFamily,
    key: String,
    payload: serde_json::Value,
}

fn fresh_change(type_id: &str) -> TypeChange {
    TypeChange {
        type_id: type_id.to_owned(),
        state: TypeChangeState::New,
        backward: "compatible".to_owned(),
        forward: "compatible".to_owned(),
        diagnostics: Vec::new(),
        traits_changed: Vec::new(),
        rows: None,
        rows_rewritten: None,
        levels_not_evolvable_in_place: Vec::new(),
        migration_required: false,
        admissible: true,
    }
}

/// The same rule the built-in store applies, over in-memory rows.
///
/// The fake carries the data-backed ground too, and not as a stub: an
/// admission ground only the `PostgreSQL` store applies is a ground the
/// conformance suite cannot see, which is the lesson the endpoint-constraint
/// episode taught earlier in this prototype.
fn decide_existing(
    tenant: &Tenant,
    existing: &TypeRecord,
    descriptor: &ontology::TypeDescriptor,
    ancestors: &[(String, serde_json::Value)],
    options: &TypeRegistrationOptions,
) -> Result<Decided, GraphStoreError> {
    let update = options.on_existing == OnExisting::Update;
    let traits_changed =
        evolution::traits_diff(&existing.effective_traits, &descriptor.effective_traits);
    let unchanged = |traits_changed: Vec<graph_storage_sdk::models::TraitChange>| Decided {
        outcome: TypeOutcome::Unchanged,
        basis: None,
        change: TypeChange {
            type_id: descriptor.type_id.clone(),
            state: TypeChangeState::Unchanged,
            backward: "compatible".to_owned(),
            forward: "compatible".to_owned(),
            diagnostics: Vec::new(),
            traits_changed,
            rows: None,
            rows_rewritten: None,
            levels_not_evolvable_in_place: Vec::new(),
            migration_required: false,
            admissible: true,
        },
        revision: existing.revision,
        created_at: existing.created_at,
        rewrites: Vec::new(),
    };

    // Byte-identical re-registration converges. The fake stores the resolved
    // traits as a value rather than as JSON, so unlike the built-in store's
    // column it cannot go stale; the diff is still reported.
    if existing.schema == descriptor.schema {
        if options.migration_for(&descriptor.type_id).is_some() {
            return Err(GraphStoreError::InvalidQuery {
                what: format!(
                    "the migration for `{}` has nothing to migrate towards: the candidate \
                     schema is byte-identical to the registered one",
                    descriptor.type_id
                ),
            });
        }
        return Ok(unchanged(traits_changed));
    }

    let comparison = evolution::compare(
        &existing.schema,
        &descriptor.schema,
        ancestors.iter().cloned(),
    )
    .map_err(|error| validation(0, ItemFamily::Node, &descriptor.type_id, &error.to_string()))?;
    let state = comparison.state();
    let mut change = TypeChange {
        type_id: descriptor.type_id.clone(),
        state,
        backward: comparison.backward.as_str().to_owned(),
        forward: comparison.forward.as_str().to_owned(),
        diagnostics: comparison.diagnostics,
        traits_changed,
        rows: None,
        rows_rewritten: None,
        levels_not_evolvable_in_place: comparison.levels_not_evolvable_in_place,
        migration_required: !matches!(state, TypeChangeState::Compatible),
        admissible: false,
    };

    let accepted = |change: TypeChange, basis: AdmissionBasis, rewrites: Vec<Rewrite>| Decided {
        outcome: TypeOutcome::Updated,
        basis: Some(basis),
        change,
        revision: existing.revision.saturating_add(1),
        created_at: existing.created_at,
        rewrites,
    };

    let migration = options.migration_for(&descriptor.type_id);
    match evolution::decide(
        state,
        evolution::Asked {
            update,
            offered: evolution::offered(migration.is_some(), options.revalidate),
        },
    ) {
        evolution::Decision::Refuse => {
            if options.dry_run {
                return Ok(Decided {
                    outcome: TypeOutcome::Unchanged,
                    basis: None,
                    change,
                    revision: existing.revision,
                    created_at: existing.created_at,
                    rewrites: Vec::new(),
                });
            }
            Err(GraphStoreError::Conflict {
                reason: if update {
                    evolution::refusal_reason(&descriptor.type_id, state, &change.diagnostics, 5)
                } else {
                    format!(
                        "type `{}` is already registered with a different schema",
                        descriptor.type_id
                    )
                },
            })
        }
        evolution::Decision::Accept => {
            change.admissible = true;
            Ok(accepted(change, AdmissionBasis::SchemaProved, Vec::new()))
        }
        evolution::Decision::Migrate => {
            let Some(spec) = migration else {
                return Err(GraphStoreError::Internal(
                    "the rule asked for a migration where none was declared".to_owned(),
                ));
            };
            let plan = crate::domain::migration::compile(spec).map_err(|error| {
                GraphStoreError::InvalidQuery {
                    what: error.to_string(),
                }
            })?;
            let mut chain: Vec<(String, serde_json::Value)> = ancestors.to_vec();
            chain.push((descriptor.type_id.clone(), descriptor.schema.clone()));
            let validator =
                ontology::ChainValidator::compile(&descriptor.schema, chain).map_err(|error| {
                    validation(0, ItemFamily::Node, &descriptor.type_id, &error.to_string())
                })?;
            let (scanned, rewrites, failures) =
                migrate_fake(tenant, &descriptor.type_id, &plan, &validator);
            change.rows = Some(scanned);
            change.rows_rewritten = Some(rewrites.len() as u64);
            if failures.is_empty() {
                change.admissible = true;
                let basis = AdmissionBasis::Migrated {
                    rows_scanned: scanned,
                    rows_rewritten: rewrites.len() as u64,
                };
                return Ok(accepted(
                    change,
                    basis,
                    if options.dry_run {
                        Vec::new()
                    } else {
                        rewrites
                    },
                ));
            }
            if !options.dry_run {
                return Err(GraphStoreError::Validation { items: failures });
            }
            for failure in &failures {
                change.diagnostics.push(SchemaDiagnostic {
                    location: failure.pointer.clone().unwrap_or_default(),
                    finding: "row_invalid_after_migration".to_owned(),
                    message: failure.message.clone(),
                });
            }
            Ok(Decided {
                outcome: TypeOutcome::Unchanged,
                basis: None,
                change,
                revision: existing.revision,
                created_at: existing.created_at,
                rewrites: Vec::new(),
            })
        }
        evolution::Decision::Revalidate => {
            let mut chain: Vec<(String, serde_json::Value)> = ancestors.to_vec();
            chain.push((descriptor.type_id.clone(), descriptor.schema.clone()));
            let validator =
                ontology::ChainValidator::compile(&descriptor.schema, chain).map_err(|error| {
                    validation(0, ItemFamily::Node, &descriptor.type_id, &error.to_string())
                })?;
            let rows = rows_of_type(tenant, &descriptor.type_id);
            change.rows = Some(rows);
            let failures = revalidate_fake(tenant, &descriptor.type_id, &validator);
            if failures.is_empty() {
                change.admissible = true;
                return Ok(accepted(
                    change,
                    AdmissionBasis::DataBacked {
                        rows_validated: rows,
                    },
                    Vec::new(),
                ));
            }
            if !options.dry_run {
                return Err(GraphStoreError::Validation { items: failures });
            }
            for failure in &failures {
                change.diagnostics.push(SchemaDiagnostic {
                    location: failure.pointer.clone().unwrap_or_default(),
                    finding: "stored_row_invalid".to_owned(),
                    message: failure.message.clone(),
                });
            }
            Ok(Decided {
                outcome: TypeOutcome::Unchanged,
                basis: None,
                change,
                revision: existing.revision,
                created_at: existing.created_at,
                rewrites: Vec::new(),
            })
        }
    }
}

/// Live rows of one type, nodes and edges alike.
fn rows_of_type(tenant: &Tenant, type_id: &str) -> u64 {
    let nodes = tenant
        .nodes
        .iter()
        .filter(|node| !node.deleted && node.type_id == type_id)
        .count();
    let edges = tenant
        .edges
        .iter()
        .filter(|edge| !edge.deleted && edge.type_id == type_id)
        .count();
    (nodes + edges) as u64
}

/// Apply the plan to every live row of the type in memory, validate the
/// result, and report what would be written.
///
/// The fake carries the migration too, and not as a stub: a ground for
/// admission only the `PostgreSQL` store applies is a ground the conformance
/// suite cannot see.
fn migrate_fake(
    tenant: &Tenant,
    type_id: &str,
    plan: &crate::domain::migration::Plan,
    validator: &ontology::ChainValidator,
) -> (u64, Vec<Rewrite>, Vec<ItemError>) {
    let mut scanned = 0u64;
    let mut rewrites = Vec::new();
    let mut failures = Vec::new();

    for node in tenant
        .nodes
        .iter()
        .filter(|node| !node.deleted && node.type_id == type_id)
    {
        scanned += 1;
        let mut payload = node.payload.clone().unwrap_or(serde_json::Value::Null);
        if payload.is_null() {
            payload = serde_json::json!({});
        }
        let changed = plan.apply(&mut payload);
        let mut instance = serde_json::json!({ "node_key": node.key, "type": type_id });
        if let Some(name) = &node.name {
            instance["name"] = serde_json::json!(name);
        }
        instance["payload"] = payload.clone();
        let violations = validator.validate(&instance);
        if !violations.is_empty() {
            for (pointer, message) in violations {
                failures.push(ItemError {
                    index: usize::try_from(scanned - 1).unwrap_or(usize::MAX),
                    family: ItemFamily::Node,
                    gts_type: Some(type_id.to_owned()),
                    pointer: Some(pointer),
                    message: format!(
                        "node `{}` does not satisfy the candidate after the migration: {message}",
                        node.key
                    ),
                });
            }
            continue;
        }
        if changed {
            rewrites.push(Rewrite {
                family: ItemFamily::Node,
                key: node.key.clone(),
                payload,
            });
        }
    }

    for edge in tenant
        .edges
        .iter()
        .filter(|edge| !edge.deleted && edge.type_id == type_id)
    {
        scanned += 1;
        let mut payload = edge.payload.clone().unwrap_or(serde_json::json!({}));
        let changed = plan.apply(&mut payload);
        let key_of = |id: i64| {
            tenant
                .nodes
                .iter()
                .find(|node| node.id == id)
                .map_or_else(String::new, |node| node.key.clone())
        };
        let mut instance = serde_json::json!({
            "type": type_id,
            "src_node_key": key_of(edge.src),
            "dst_node_key": key_of(edge.dst),
        });
        instance["payload"] = payload.clone();
        let violations = validator.validate(&instance);
        if !violations.is_empty() {
            for (pointer, message) in violations {
                failures.push(ItemError {
                    index: usize::try_from(scanned - 1).unwrap_or(usize::MAX),
                    family: ItemFamily::Edge,
                    gts_type: Some(type_id.to_owned()),
                    pointer: Some(pointer),
                    message: format!(
                        "edge `{}` does not satisfy the candidate after the migration: {message}",
                        edge.key
                    ),
                });
            }
            continue;
        }
        if changed {
            rewrites.push(Rewrite {
                family: ItemFamily::Edge,
                key: edge.key.clone(),
                payload,
            });
        }
    }

    (scanned, rewrites, failures)
}

/// Does every live row of the type validate against the candidate?
fn revalidate_fake(
    tenant: &Tenant,
    type_id: &str,
    validator: &ontology::ChainValidator,
) -> Vec<ItemError> {
    let mut errors = Vec::new();
    for (index, node) in tenant
        .nodes
        .iter()
        .filter(|node| !node.deleted && node.type_id == type_id)
        .enumerate()
    {
        let mut instance = serde_json::json!({ "node_key": node.key, "type": type_id });
        if let Some(name) = &node.name {
            instance["name"] = serde_json::json!(name);
        }
        if let Some(payload) = &node.payload {
            instance["payload"] = payload.clone();
        }
        for (pointer, message) in validator.validate(&instance) {
            errors.push(ItemError {
                index,
                family: ItemFamily::Node,
                gts_type: Some(type_id.to_owned()),
                pointer: Some(pointer),
                message: format!("node `{}`: {message}", node.key),
            });
        }
    }
    for (index, edge) in tenant
        .edges
        .iter()
        .filter(|edge| !edge.deleted && edge.type_id == type_id)
        .enumerate()
    {
        let key_of = |id: i64| {
            tenant
                .nodes
                .iter()
                .find(|node| node.id == id)
                .map_or_else(String::new, |node| node.key.clone())
        };
        let mut instance = serde_json::json!({
            "type": type_id,
            "src_node_key": key_of(edge.src),
            "dst_node_key": key_of(edge.dst),
        });
        if let Some(payload) = &edge.payload {
            instance["payload"] = payload.clone();
        }
        for (pointer, message) in validator.validate(&instance) {
            errors.push(ItemError {
                index,
                family: ItemFamily::Edge,
                gts_type: Some(type_id.to_owned()),
                pointer: Some(pointer),
                message: format!("edge `{}`: {message}", edge.key),
            });
        }
    }
    errors
}

fn validation(index: usize, family: ItemFamily, type_id: &str, message: &str) -> GraphStoreError {
    GraphStoreError::Validation {
        items: vec![ItemError {
            index,
            family,
            gts_type: Some(type_id.to_owned()),
            pointer: None,
            message: message.to_owned(),
        }],
    }
}

fn view_of(
    node: &FakeNode,
    tenant_id: Uuid,
    revision: GraphRevision,
    adjacency: Vec<AdjacencyEntry>,
    truncated: bool,
) -> NodeView {
    NodeView {
        node_key: node.key.clone(),
        type_id: node.type_id.clone(),
        name: node.name.clone(),
        payload: node.payload.clone(),
        has_embedding: node.embedding.is_some(),
        labels: Vec::new(),
        adjacency,
        adjacency_truncated: truncated,
        envelope: node.audit.envelope(node.key.clone(), tenant_id, revision),
    }
}

/// Generation fencing on a scope replacement, before anything is written.
/// A delete that found nothing live: a no-op when the row is tombstoned, an
/// absence when the key was never there.
fn settle_no_op(
    store: &FakeGraphStore,
    tenant: &Tenant,
    tombstoned: bool,
) -> Result<DeleteOutcome, GraphStoreError> {
    if !tombstoned {
        return Err(GraphStoreError::NotFound);
    }
    Ok(DeleteOutcome {
        revision: store.revision_of(tenant),
        tombstoned_nodes: 0,
        tombstoned_edges: 0,
    })
}

fn fence(
    tenant: &Tenant,
    producer: &str,
    replace: &graph_storage_sdk::models::ReplaceScope,
    request_hash: &str,
) -> Result<(), GraphStoreError> {
    let key = (replace.attribute.clone(), replace.value.clone());
    let Some(scope) = tenant.scopes.get(&key) else {
        return Ok(());
    };
    if !scope.owner_producer.is_empty() && scope.owner_producer != producer {
        return Err(GraphStoreError::Conflict {
            reason: format!(
                "scope `{}={}` is owned by another producer; a replacement may only be \
                 submitted by its owner",
                replace.attribute, replace.value
            ),
        });
    }
    if replace.generation < scope.generation {
        return Err(GraphStoreError::StaleGeneration {
            recorded: scope.generation,
            offered: replace.generation,
        });
    }
    if replace.generation == scope.generation && scope.request_hash != request_hash {
        return Err(GraphStoreError::Conflict {
            reason: "same source generation with different content".into(),
        });
    }
    Ok(())
}

/// Apply one node spec to the working copy. Returns whether it changed state.
/// The mutable bookkeeping one batch carries from item to item: the id
/// allocator and the running tally. They travel together because every write
/// touches both, and separately they made every `apply_*` signature two
/// parameters longer than it had any reason to be.
struct BatchState<'a> {
    next_id: &'a mut i64,
    tally: &'a mut IngestTally,
    /// The subject stamped on every element this batch writes.
    subject: &'a Subject,
}

/// The vector columns of one fake row, spelled from the shared decision.
struct VectorWrite {
    embedding: Option<Vec<f32>>,
    epoch: Option<i64>,
    input_hash: Option<String>,
}

fn plan_vector(current: Option<&FakeNode>, planned: PlannedVector<'_>) -> VectorWrite {
    let stored = current.map(|row| StoredVector {
        has_vector: row.embedding.is_some(),
        input_hash: row.embedding_input_hash.as_deref(),
    });
    match decide_vector(stored, planned) {
        VectorOutcome::Store {
            vector,
            epoch,
            input_hash,
        } => VectorWrite {
            embedding: Some(vector),
            epoch,
            input_hash: Some(input_hash),
        },
        VectorOutcome::Absent { input_hash } => VectorWrite {
            embedding: None,
            epoch: None,
            input_hash: Some(input_hash),
        },
        VectorOutcome::Preserve => VectorWrite {
            embedding: current.and_then(|row| row.embedding.clone()),
            epoch: current.and_then(|row| row.embedding_epoch),
            input_hash: current.and_then(|row| row.embedding_input_hash.clone()),
        },
        VectorOutcome::Stale => VectorWrite {
            embedding: current.and_then(|row| row.embedding.clone()),
            epoch: None,
            input_hash: current.and_then(|row| row.embedding_input_hash.clone()),
        },
    }
}

fn apply_node(
    tenant: &Tenant,
    nodes: &mut Vec<FakeNode>,
    edges: &[FakeEdge],
    state: &mut BatchState<'_>,
    index: usize,
    spec: &graph_storage_sdk::models::NodeSpec,
    vector: VectorWrite,
) -> Result<bool, GraphStoreError> {
    let record = tenant.types.get(&spec.type_id).ok_or_else(|| {
        validation(
            index,
            ItemFamily::Node,
            &spec.type_id,
            "type is not registered",
        )
    })?;
    if record.is_abstract {
        return Err(validation(
            index,
            ItemFamily::Node,
            &spec.type_id,
            "abstract types cannot be instantiated",
        ));
    }

    let Some(existing) = nodes.iter_mut().find(|n| n.key == spec.node_key) else {
        // `Some(0)` is "there must be none" and holds; any other expectation
        // names a row that is not there (see the built-in store).
        if let Some(expected) = spec.expected_version
            && expected != 0
        {
            return Err(GraphStoreError::Conflict {
                reason: format!(
                    "expected version {expected}, but no node is stored under key `{}`",
                    spec.node_key
                ),
            });
        }
        *state.next_id += 1;
        nodes.push(FakeNode {
            id: *state.next_id,
            key: spec.node_key.clone(),
            type_id: spec.type_id.clone(),
            name: spec.name.clone(),
            search_text: crate::infra::store::ingest::compose_search_text(
                spec.name.as_deref(),
                spec.payload.as_ref(),
                &record.effective_traits.full_text_search,
            ),
            payload: spec.payload.clone(),
            embedding: vector.embedding,
            embedding_epoch: vector.epoch,
            embedding_input_hash: vector.input_hash,
            version: 1,
            deleted: false,
            audit: FakeAudit::created(state.subject),
        });
        return Ok(state.tally.node(&ItemOutcome::Inserted));
    };

    if existing.deleted {
        return Err(GraphStoreError::Conflict {
            reason: format!(
                "node key `{}` is tombstoned and cannot be re-ingested",
                spec.node_key
            ),
        });
    }
    if let Some(expected) = spec.expected_version
        && expected != existing.version
    {
        return Err(GraphStoreError::Conflict {
            reason: format!(
                "expected version {expected}, stored version is {}",
                existing.version
            ),
        });
    }

    let same_type = existing.type_id == spec.type_id;
    if !same_type {
        let was_phantom = tenant
            .types
            .get(&existing.type_id)
            .and_then(|t| t.effective_traits.family.clone())
            .as_deref()
            == Some("phantom");
        if !was_phantom {
            // A conflict, not a validation failure: the payload may be
            // perfectly valid under the new type, and the only permitted
            // transition is phantom materialization.
            return Err(GraphStoreError::Conflict {
                reason: format!(
                    "node `{}` is already registered under type `{}`; a same-key ingest may \
                     not change it",
                    spec.node_key, existing.type_id
                ),
            });
        }
    }

    let vector_unchanged = (
        &existing.embedding,
        existing.embedding_epoch,
        &existing.embedding_input_hash,
    ) == (&vector.embedding, vector.epoch, &vector.input_hash);
    let unchanged = same_type
        && existing.name == spec.name
        && existing.payload == spec.payload
        && vector_unchanged;
    if unchanged {
        return Ok(state.tally.node(&ItemOutcome::Unchanged));
    }

    if !same_type {
        // Rule 3 of the Phantom Materialization Contract: the endpoint check
        // that could not run while this node had no concrete type runs now,
        // against every edge the phantom accumulated meanwhile.
        revalidate_incident_edges(tenant, edges, existing.id, &spec.type_id, index)?;
    }

    existing.type_id.clone_from(&spec.type_id);
    existing.name.clone_from(&spec.name);
    existing.search_text = crate::infra::store::ingest::compose_search_text(
        spec.name.as_deref(),
        spec.payload.as_ref(),
        &record.effective_traits.full_text_search,
    );
    existing.payload.clone_from(&spec.payload);
    existing.embedding = vector.embedding;
    existing.embedding_epoch = vector.epoch;
    existing.embedding_input_hash = vector.input_hash;
    existing.version += 1;
    existing.audit.updated(state.subject);
    Ok(state.tally.node(&if same_type {
        ItemOutcome::Updated
    } else {
        ItemOutcome::Materialized
    }))
}

/// Every edge already incident to a node becoming concrete must still be
/// admissible under the concrete type.
fn revalidate_incident_edges(
    tenant: &Tenant,
    edges: &[FakeEdge],
    node_id: i64,
    concrete_type: &str,
    index: usize,
) -> Result<(), GraphStoreError> {
    for edge in edges.iter().filter(|e| !e.deleted) {
        let Some(record) = tenant.types.get(&edge.type_id) else {
            continue;
        };
        for (is_end, patterns, which) in [
            (
                edge.src == node_id,
                &record.effective_traits.src_types,
                "source",
            ),
            (
                edge.dst == node_id,
                &record.effective_traits.dst_types,
                "destination",
            ),
        ] {
            if !is_end || patterns.is_empty() {
                continue;
            }
            if !ontology::matches_any_pattern(concrete_type, patterns).unwrap_or(false) {
                return Err(GraphStoreError::Validation {
                    items: vec![ItemError {
                        index,
                        family: ItemFamily::Node,
                        gts_type: Some(concrete_type.to_owned()),
                        pointer: Some("/type".to_owned()),
                        message: format!(
                            "materializing this node as `{concrete_type}` would leave edge \
                             `{}` invalid: `{}` does not admit it as a {which} (accepts {})",
                            edge.key,
                            edge.type_id,
                            patterns.join(", ")
                        ),
                    }],
                });
            }
        }
    }
    Ok(())
}

/// Resolve one endpoint in the working copy, creating a phantom when allowed.
fn apply_endpoint(
    tenant: &Tenant,
    nodes: &mut Vec<FakeNode>,
    state: &mut BatchState<'_>,
    index: usize,
    type_id: &str,
    key: &str,
    create_phantoms: bool,
) -> Result<i64, GraphStoreError> {
    if let Some(existing) = nodes.iter().find(|n| n.key == key && !n.deleted) {
        return Ok(existing.id);
    }
    // A tombstoned key keeps its row until purge; an edge may neither link to
    // it nor push a second node under the same key beside it.
    if nodes.iter().any(|n| n.key == key && n.deleted) {
        return Err(GraphStoreError::Conflict {
            reason: format!(
                "edge[{index}] names endpoint `{key}`, which is tombstoned; the key cannot be \
                 linked to or re-ingested before purge"
            ),
        });
    }
    if !create_phantoms {
        return Err(validation(
            index,
            ItemFamily::Edge,
            type_id,
            "an endpoint does not exist and phantom creation is disabled",
        ));
    }
    let phantom_type = tenant
        .types
        .values()
        .find(|t| t.effective_traits.family.as_deref() == Some("phantom"))
        .ok_or_else(|| {
            validation(
                index,
                ItemFamily::Edge,
                type_id,
                "an endpoint does not exist and no phantom type is registered",
            )
        })?;
    *state.next_id += 1;
    nodes.push(FakeNode {
        id: *state.next_id,
        key: key.to_owned(),
        type_id: phantom_type.type_id.clone(),
        name: None,
        search_text: String::new(),
        payload: None,
        embedding: None,
        embedding_epoch: None,
        embedding_input_hash: None,
        version: 1,
        deleted: false,
        // A phantom is brought into being by the edge that named it, so the
        // subject writing that edge is the one recorded here.
        audit: FakeAudit::created(state.subject),
    });
    state.tally.phantom_created();
    Ok(*state.next_id)
}

/// What the batch as a whole says, which one edge spec does not carry.
struct EdgeDeclaration {
    create_phantoms: bool,
    /// The scope this batch declares, when it is a replacement. An edge
    /// written under one belongs to that scope's snapshot and leaves with it.
    scope: Option<(String, String)>,
}

/// Apply one edge spec to the working copy. Returns whether it changed state.
fn apply_edge(
    tenant: &Tenant,
    nodes: &mut Vec<FakeNode>,
    edges: &mut Vec<FakeEdge>,
    state: &mut BatchState<'_>,
    index: usize,
    spec: &graph_storage_sdk::models::EdgeSpec,
    declaration: &EdgeDeclaration,
) -> Result<bool, GraphStoreError> {
    let EdgeDeclaration {
        create_phantoms,
        scope,
    } = declaration;
    let create_phantoms = *create_phantoms;
    let scope = scope.clone();
    let record = tenant.types.get(&spec.type_id).cloned().ok_or_else(|| {
        validation(
            index,
            ItemFamily::Edge,
            &spec.type_id,
            "type is not registered",
        )
    })?;

    let before = state.tally.counts.phantoms_created;
    let src = apply_endpoint(
        tenant,
        nodes,
        state,
        index,
        &spec.type_id,
        &spec.src_node_key,
        create_phantoms,
    )?;
    let dst = apply_endpoint(
        tenant,
        nodes,
        state,
        index,
        &spec.type_id,
        &spec.dst_node_key,
        create_phantoms,
    )?;
    let mut changed = state.tally.counts.phantoms_created > before;

    // Endpoint constraints. A phantom endpoint is skipped: its concrete type
    // is not known yet, and the materialization path revalidates then.
    for (id, patterns, key, pointer) in [
        (
            src,
            &record.effective_traits.src_types,
            &spec.src_node_key,
            "/src_node_key",
        ),
        (
            dst,
            &record.effective_traits.dst_types,
            &spec.dst_node_key,
            "/dst_node_key",
        ),
    ] {
        let Some(endpoint) = nodes.iter().find(|n| n.id == id) else {
            continue;
        };
        let is_phantom = tenant
            .types
            .get(&endpoint.type_id)
            .and_then(|t| t.effective_traits.family.as_deref())
            == Some("phantom");
        if is_phantom || patterns.is_empty() {
            continue;
        }
        let admitted = ontology::matches_any_pattern(&endpoint.type_id, patterns).unwrap_or(false);
        if !admitted {
            return Err(GraphStoreError::Validation {
                items: vec![ItemError {
                    index,
                    family: ItemFamily::Edge,
                    gts_type: Some(spec.type_id.clone()),
                    pointer: Some(pointer.to_owned()),
                    message: format!(
                        "endpoint `{key}` is a `{}`, which `{}` does not admit; this edge \
                         type accepts {}",
                        endpoint.type_id,
                        spec.type_id,
                        patterns.join(", ")
                    ),
                }],
            });
        }
    }

    let edge_key = identity::derive_edge_key(record.type_uuid, spec);
    if let Some(owner) = edges
        .iter()
        .find(|e| e.key == edge_key)
        .and_then(|e| e.scope.as_ref())
        && let Some(declaring) = scope.as_ref()
        && owner != declaring
    {
        return Err(GraphStoreError::Conflict {
            reason: format!(
                "edge `{edge_key}` was declared by scope `{}={}` and may not be \
                 re-declared under `{}={}`; a move between scopes is a \
                 deletion and a re-declaration, not a write",
                owner.0, owner.1, declaring.0, declaring.1
            ),
        });
    }
    let outcome = match edges.iter_mut().find(|e| e.key == edge_key) {
        Some(existing) if existing.payload == spec.payload && !existing.deleted => {
            // A convergent replay still claims an edge nobody owns: ownership
            // is bookkeeping about who declared the edge, not content, so the
            // batch stays unchanged and the revision stays put -- the same
            // answer the built-in store gives. Without this, two scopes
            // re-declaring one unowned edge were both told they claimed it,
            // and neither replacement ever removed it.
            if existing.scope.is_none() && scope.is_some() {
                existing.scope.clone_from(&scope);
            }
            ItemOutcome::Unchanged
        }
        Some(existing) => {
            existing.payload.clone_from(&spec.payload);
            existing.deleted = false;
            // A scoped batch re-asserts ownership; an unscoped one leaves
            // whatever claim is already recorded, because writing an edge is
            // not the same as declaring a snapshot that contains it. What it
            // may not do is take an edge from another scope -- see the
            // built-in store for why that is a conflict rather than a write.
            if scope.is_some() {
                existing.scope.clone_from(&scope);
            }
            existing.audit.updated(state.subject);
            ItemOutcome::Updated
        }
        None => {
            edges.push(FakeEdge {
                key: edge_key,
                type_id: spec.type_id.clone(),
                src,
                dst,
                discriminator: spec.discriminator.clone(),
                payload: spec.payload.clone(),
                deleted: false,
                scope,
                audit: FakeAudit::created(state.subject),
            });
            ItemOutcome::Inserted
        }
    };
    changed |= state.tally.edge(&outcome);
    Ok(changed)
}

/// The working copies a scope replacement rewrites, and the types that decide
/// what it may touch.
struct ScopeReplacement<'a> {
    nodes: &'a mut Vec<FakeNode>,
    edges: &'a mut Vec<FakeEdge>,
    managed_node_types: &'a BTreeSet<String>,
    static_edge_types: &'a BTreeSet<String>,
    /// Needed to derive the deterministic key of each declared edge, which is
    /// what tells a re-declared edge from one the producer dropped.
    types: &'a BTreeMap<String, TypeRecord>,
}

/// Remove the scope's static content that the batch no longer names.
///
/// Static edges first, then only those nodes nothing references any more — a
/// node a *live* analysis edge still points at stays, because the conclusion
/// drawn about it survives the re-import of the thing it was drawn about.
/// Returns whether anything was removed.
fn replace_scope(
    working: ScopeReplacement<'_>,
    req: &IngestRequest,
    replace: &graph_storage_sdk::models::ReplaceScope,
    tally: &mut IngestTally,
) -> bool {
    let ScopeReplacement {
        nodes,
        edges,
        managed_node_types,
        static_edge_types,
        types,
    } = working;
    let written: BTreeSet<&str> = req
        .nodes
        .iter()
        .map(|spec| spec.node_key.as_str())
        .collect();
    // The edges this batch declared, by their deterministic key. An edge the
    // scope owns and this batch did not name is one the producer removed --
    // which is the whole point of a declarative snapshot, and the case the
    // node-only reckoning below could never see: with both endpoints
    // re-supplied nothing was stale, so nothing was removed and the edge
    // stayed visible forever.
    let declared: BTreeSet<String> = req
        .edges
        .iter()
        .filter_map(|spec| {
            let record = types.get(&spec.type_id)?;
            Some(identity::derive_edge_key(record.type_uuid, spec))
        })
        .collect();
    let owner = (replace.attribute.clone(), replace.value.clone());
    let dropped: Vec<i64> = nodes
        .iter()
        .filter(|node| {
            !node.deleted
                && managed_node_types.contains(&node.type_id)
                && !written.contains(node.key.as_str())
                && node
                    .payload
                    .as_ref()
                    .and_then(|payload| payload.get(&replace.attribute))
                    .and_then(serde_json::Value::as_str)
                    == Some(replace.value.as_str())
        })
        .map(|node| node.id)
        .collect();

    let before = edges.len();
    edges.retain(|edge| {
        if !static_edge_types.contains(&edge.type_id) {
            // An analysis edge is a conclusion about the content, not a copy
            // of it, and survives the re-import of what it was drawn about.
            return true;
        }
        // Owned by this scope and not re-declared: the producer dropped it.
        let abandoned = edge.scope.as_ref() == Some(&owner) && !declared.contains(&edge.key);
        // Or incident to a node that is itself departing, whoever owns it --
        // the endpoint is going, so the edge cannot stay.
        let orphaned = dropped.contains(&edge.src) || dropped.contains(&edge.dst);
        !(abandoned || orphaned)
    });
    tally.counts.scope_removed_edges = (before - edges.len()) as u64;

    if dropped.is_empty() {
        return tally.counts.scope_removed_edges > 0;
    }

    // A tombstoned edge is a deleted conclusion and must not keep a departing
    // node alive on its behalf; left in place it would make the scope stop
    // converging, permanently. Purged with the node, as the built-in store
    // purges it.
    edges.retain(|edge| {
        !(edge.deleted && (dropped.contains(&edge.src) || dropped.contains(&edge.dst)))
    });

    let referenced: BTreeSet<i64> = edges.iter().flat_map(|edge| [edge.src, edge.dst]).collect();
    let before = nodes.len();
    nodes.retain(|node| !dropped.contains(&node.id) || referenced.contains(&node.id));
    tally.counts.scope_removed_nodes = (before - nodes.len()) as u64;
    tally.counts.scope_removed_nodes > 0 || tally.counts.scope_removed_edges > 0
}

/// One page of the type catalogue, as the built-in store builds it.
///
/// Keyset over the identifier — the map is ordered, so "after this
/// identifier" is a range — and the page is *filled* rather than cut: the GTS
/// pattern is matched here rather than in a query, so a slice can lose every
/// row to it, and a page that came back empty with a continuation token is a
/// page every client stops at.
fn catalogue_page(tenant: &Tenant, query: &TypeQuery) -> (Vec<TypeRecord>, Option<String>) {
    let limit = query.top.map_or(usize::MAX, |top| top as usize);
    let mut items: Vec<TypeRecord> = Vec::new();
    let mut next_cursor = None;
    let mut walked = tenant
        .types
        .values()
        .filter(|record| {
            query
                .cursor
                .as_ref()
                .is_none_or(|cursor| &record.type_id > cursor)
        })
        .filter(|record| query.kind.is_none_or(|kind| kind == record.kind))
        .peekable();
    while let Some(record) = walked.next() {
        let admitted = query.pattern.as_ref().is_none_or(|pattern| {
            ontology::matches_any_pattern(&record.type_id, std::slice::from_ref(pattern))
                .unwrap_or(false)
        });
        if admitted {
            items.push(record.clone());
            if items.len() >= limit {
                // A cursor only when something follows it.
                next_cursor = walked.peek().map(|_| record.type_id.clone());
                break;
            }
        }
    }
    (items, next_cursor)
}

/// A single-page envelope: the fake never paginates, so neither cursor is set.
fn empty_page_info() -> toolkit_odata::page::PageInfo {
    toolkit_odata::page::PageInfo {
        next_cursor: None,
        prev_cursor: None,
        limit: 0,
    }
}

/// Cosine distance, the same measure pgvector's `<=>` operator serves.
fn cosine_distance(one: &[f32], other: &[f32]) -> f64 {
    let dot: f64 = one
        .iter()
        .zip(other)
        .map(|(a, b)| f64::from(*a) * f64::from(*b))
        .sum();
    let norm = |v: &[f32]| -> f64 {
        v.iter()
            .map(|x| f64::from(*x) * f64::from(*x))
            .sum::<f64>()
            .sqrt()
    };
    let (left, right) = (norm(one), norm(other));
    if left == 0.0 || right == 0.0 {
        return 1.0;
    }
    1.0 - dot / (left * right)
}

/// Reciprocal Rank Fusion over the two arms, with the same constant the
/// built-in store uses. Hits report which arms matched and at what rank, so a
/// caller can tell a lexical hit from a semantic one.
fn fuse_arms(
    lexical: &[&FakeNode],
    vector: &[&FakeNode],
    limit: usize,
) -> Vec<graph_storage_sdk::models::SearchHit> {
    use graph_storage_sdk::models::{ArmHit, SearchArm, SearchHit};
    const K: f64 = 60.0;

    let mut order: Vec<i64> = Vec::new();
    let mut fused: BTreeMap<i64, (f64, Vec<ArmHit>, &FakeNode)> = BTreeMap::new();
    for (arm, rows) in [(SearchArm::Lexical, lexical), (SearchArm::Vector, vector)] {
        for (position, node) in rows.iter().enumerate() {
            let rank = u32::try_from(position)
                .unwrap_or(u32::MAX)
                .saturating_add(1);
            let contribution = 1.0 / (K + f64::from(rank));
            let entry = fused
                .entry(node.id)
                .or_insert_with(|| (0.0, Vec::new(), node));
            if entry.1.is_empty() {
                order.push(node.id);
            }
            entry.0 += contribution;
            entry.1.push(ArmHit {
                arm,
                rank,
                score: contribution,
            });
        }
    }

    let mut hits: Vec<SearchHit> = order
        .into_iter()
        .filter_map(|id| fused.get(&id))
        .map(|(score, arms, node)| SearchHit {
            node_key: node.key.clone(),
            type_id: node.type_id.clone(),
            name: node.name.clone(),
            score: *score,
            arms: arms.clone(),
            snippet: None,
        })
        .collect();
    hits.sort_by(|a, b| {
        b.score
            .partial_cmp(&a.score)
            .unwrap_or(std::cmp::Ordering::Equal)
    });
    hits.truncate(limit);
    hits
}

/// In-memory evaluation of a projection plan over fake nodes.
mod eval {
    use std::cmp::Ordering;

    use toolkit_odata::SortDir;

    use super::FakeNode;
    use crate::domain::ontology::ScalarKind;
    use crate::domain::projection::{CmpOp, FieldRef, Plan, Predicate, Scalar, TextOp};

    /// One field's value on one row, in the field's kind.
    #[derive(Clone, Debug, PartialEq)]
    enum Cell {
        Null,
        Text(String),
        Num(f64),
        Bool(bool),
    }

    fn cell(field: &FieldRef, node: &FakeNode) -> Cell {
        match field {
            FieldRef::NodeKey => Cell::Text(node.key.clone()),
            FieldRef::Name => Cell::Text(node.name.clone().unwrap_or_default()),
            FieldRef::CreatedAt => rfc3339(node.audit.created_at),
            FieldRef::UpdatedAt => rfc3339(node.audit.updated_at),
            FieldRef::Payload { pointer, kind } => {
                let inner = pointer.strip_prefix("/payload").unwrap_or(pointer);
                let Some(value) = node.payload.as_ref().and_then(|p| p.pointer(inner)) else {
                    return Cell::Null;
                };
                match (kind, value) {
                    (ScalarKind::String | ScalarKind::DateTime, serde_json::Value::String(s)) => {
                        Cell::Text(s.clone())
                    }
                    (ScalarKind::Number | ScalarKind::Integer, serde_json::Value::Number(n)) => {
                        n.as_f64().map_or(Cell::Null, Cell::Num)
                    }
                    (ScalarKind::Boolean, serde_json::Value::Bool(b)) => Cell::Bool(*b),
                    _ => Cell::Null,
                }
            }
        }
    }

    fn rfc3339(at: time::OffsetDateTime) -> Cell {
        at.format(&time::format_description::well_known::Rfc3339)
            .map_or(Cell::Null, Cell::Text)
    }

    fn literal(value: &Scalar) -> Cell {
        match value {
            Scalar::Str(s) | Scalar::DateTime(s) => Cell::Text(s.clone()),
            Scalar::Num(n) => n.parse::<f64>().map_or(Cell::Null, Cell::Num),
            Scalar::Bool(b) => Cell::Bool(*b),
        }
    }

    /// SQL three-valued comparison collapsed to "holds": a NULL never holds.
    fn compare(a: &Cell, b: &Cell) -> Option<Ordering> {
        match (a, b) {
            (Cell::Text(x), Cell::Text(y)) => Some(x.cmp(y)),
            (Cell::Num(x), Cell::Num(y)) => x.partial_cmp(y),
            (Cell::Bool(x), Cell::Bool(y)) => Some(x.cmp(y)),
            _ => None,
        }
    }

    pub(super) fn holds(predicate: &Predicate, node: &FakeNode) -> bool {
        match predicate {
            Predicate::Compare { field, op, value } => {
                let Some(ordering) = compare(&cell(field, node), &literal(value)) else {
                    return false;
                };
                match op {
                    CmpOp::Eq => ordering == Ordering::Equal,
                    CmpOp::Ne => ordering != Ordering::Equal,
                    CmpOp::Gt => ordering == Ordering::Greater,
                    CmpOp::Ge => ordering != Ordering::Less,
                    CmpOp::Lt => ordering == Ordering::Less,
                    CmpOp::Le => ordering != Ordering::Greater,
                }
            }
            Predicate::In { field, values } => {
                let actual = cell(field, node);
                values
                    .iter()
                    .any(|v| compare(&actual, &literal(v)) == Some(Ordering::Equal))
            }
            Predicate::Text { field, op, needle } => match cell(field, node) {
                Cell::Text(text) => match op {
                    TextOp::Contains => text.contains(needle.as_str()),
                    TextOp::StartsWith => text.starts_with(needle.as_str()),
                    TextOp::EndsWith => text.ends_with(needle.as_str()),
                },
                _ => false,
            },
            Predicate::And(children) => children.iter().all(|c| holds(c, node)),
            Predicate::Or(children) => children.iter().any(|c| holds(c, node)),
            Predicate::Not(inner) => !holds(inner, node),
        }
    }

    /// The plan's order, nulls last in either direction -- the same rule the
    /// built-in store renders.
    pub(super) fn order(plan: &Plan, a: &FakeNode, b: &FakeNode) -> Ordering {
        for term in &plan.order {
            let (x, y) = (cell(&term.field, a), cell(&term.field, b));
            let ordering = match (&x, &y) {
                (Cell::Null, Cell::Null) => Ordering::Equal,
                (Cell::Null, _) => Ordering::Greater,
                (_, Cell::Null) => Ordering::Less,
                _ => {
                    let natural = compare(&x, &y).unwrap_or(Ordering::Equal);
                    match term.dir {
                        SortDir::Asc => natural,
                        SortDir::Desc => natural.reverse(),
                    }
                }
            };
            if ordering != Ordering::Equal {
                return ordering;
            }
        }
        Ordering::Equal
    }
}