1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
//! Graph Memory System - Inspired by Graphiti
//!
//! Temporal knowledge graph for tracking entities, relationships, and episodic memories.
//! Implements bi-temporal tracking and hybrid retrieval (semantic + graph traversal).
use anyhow::Result;
use chrono::{DateTime, Utc};
use rocksdb::{ColumnFamily, ColumnFamilyDescriptor, Options, WriteBatch, DB};
use rust_stemmers::{Algorithm, Stemmer};
use serde::{Deserialize, Serialize};
use std::cmp::Ordering as CmpOrdering;
use std::collections::{BinaryHeap, HashMap, HashSet, VecDeque};
use std::path::Path;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use uuid::Uuid;
use crate::constants::{
ENTITY_CONCEPT_MERGE_THRESHOLD, ENTITY_EMBEDDING_CACHE_MAX, LTP_MIN_STRENGTH, LTP_PRUNE_FLOOR,
};
// Column family names for the unified graph database
const CF_ENTITIES: &str = "entities";
const CF_RELATIONSHIPS: &str = "relationships";
const CF_EPISODES: &str = "episodes";
const CF_ENTITY_EDGES: &str = "entity_edges";
const CF_ENTITY_PAIR_INDEX: &str = "entity_pair_index";
const CF_ENTITY_EPISODES: &str = "entity_episodes";
const CF_NAME_INDEX: &str = "name_index";
const CF_LOWERCASE_INDEX: &str = "lowercase_index";
const CF_STEMMED_INDEX: &str = "stemmed_index";
const GRAPH_CF_NAMES: &[&str] = &[
CF_ENTITIES,
CF_RELATIONSHIPS,
CF_EPISODES,
CF_ENTITY_EDGES,
CF_ENTITY_PAIR_INDEX,
CF_ENTITY_EPISODES,
CF_NAME_INDEX,
CF_LOWERCASE_INDEX,
CF_STEMMED_INDEX,
];
/// Entity node in the knowledge graph
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EntityNode {
/// Unique identifier
pub uuid: Uuid,
/// Entity name (e.g., "John", "Paris", "Rust programming")
pub name: String,
/// Entity labels/types (e.g., ["Person"], ["Location", "City"])
pub labels: Vec<EntityLabel>,
/// When this entity was first created in the graph
pub created_at: DateTime<Utc>,
/// When this entity was last observed
pub last_seen_at: DateTime<Utc>,
/// How many times this entity has been mentioned
pub mention_count: usize,
/// Summary of this entity's context (built from surrounding edges)
pub summary: String,
/// Additional attributes based on entity type
pub attributes: HashMap<String, String>,
/// Semantic embedding of the entity name (for similarity search)
pub name_embedding: Option<Vec<f32>>,
/// Salience score (0.0 - 1.0): How important is this entity?
/// Higher salience = larger gravitational well in the memory universe
/// Factors: proper noun status, mention frequency, recency, user-defined importance
#[serde(default = "default_salience")]
pub salience: f32,
/// Whether this is a proper noun (names, places, products)
/// Proper nouns have higher base salience than common nouns
#[serde(default)]
pub is_proper_noun: bool,
/// Curvature selectivity: stdev(incident edge curvatures) / degree
///
/// Measures whether this entity participates in specific communities
/// (high selectivity) or connects to everything uniformly (low selectivity).
///
/// High selectivity → concept (e.g., "Hebbian learning" connects within neuroscience)
/// Low selectivity → stop word (e.g., "impl" connects to everything equally)
///
/// Used to gate LTP protection: low-selectivity entities cannot earn
/// permanent LTP regardless of activation count, mimicking habituation
/// in biological neural systems.
///
/// Computed during Forman-Ricci curvature pass. None = not yet computed.
#[serde(default)]
pub selectivity: Option<f32>,
}
fn default_salience() -> f32 {
0.5 // Default middle salience
}
/// Entity labels for ontological classification of graph nodes.
///
/// Extends Graphiti's base categorization with DevOps, software engineering,
/// and robotics domain types. Used by spreading activation (Layer 2) and
/// post-RRF re-ranking (Layer 4.9) for type-aware retrieval.
///
/// New variants are additive only — never remove existing variants to
/// maintain backward compatibility with MessagePack-serialized data.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum EntityLabel {
Person,
Organization,
Location,
Technology,
Concept,
Event,
Date,
Product,
Skill,
/// YAKE-extracted discriminative keyword (not a named entity)
/// Used for graph-based retrieval of rare/important terms like "sunrise"
Keyword,
/// Git repos, Jira projects, feature work, mission plans
Project,
/// Issues, tickets, work items, action items
Task,
/// READMEs, specs, design docs, RFCs, runbooks
Document,
/// Git repositories, container registries
Repository,
/// Microservices, APIs, daemons, ROS2 nodes
Service,
/// PostgreSQL, Redis, RocksDB, DynamoDB instances
Database,
/// Latency p99, error rate, SLOs, telemetry signals
Metric,
/// Env vars, feature flags, config files, parameters
Configuration,
/// staging, production, dev, CI, robot deployment zones
Environment,
/// CI/CD pipelines, data pipelines, ETL, mission workflows
Pipeline,
/// Engineering squads, SRE teams, robot fleet groups
Team,
/// SRE, tech lead, PM, architect, operator
Role,
/// Code modules, packages, crates, libraries, ROS2 packages
Module,
Other(String),
}
impl EntityLabel {
/// Get string representation of the entity label
#[allow(unused)] // Public API for serialization/display
pub fn as_str(&self) -> &str {
match self {
Self::Person => "Person",
Self::Organization => "Organization",
Self::Location => "Location",
Self::Technology => "Technology",
Self::Concept => "Concept",
Self::Event => "Event",
Self::Date => "Date",
Self::Product => "Product",
Self::Skill => "Skill",
Self::Keyword => "Keyword",
Self::Project => "Project",
Self::Task => "Task",
Self::Document => "Document",
Self::Repository => "Repository",
Self::Service => "Service",
Self::Database => "Database",
Self::Metric => "Metric",
Self::Configuration => "Configuration",
Self::Environment => "Environment",
Self::Pipeline => "Pipeline",
Self::Team => "Team",
Self::Role => "Role",
Self::Module => "Module",
Self::Other(s) => s.as_str(),
}
}
/// Static type hierarchy: returns parent labels for ontological matching.
///
/// Enables hierarchical type matching so "who manages" can match Team
/// (because Team is_a Organization-like group entity) and "what technology"
/// can match Service (because Service is_a Technology subtype).
///
/// Hierarchy is shallow (max depth 1) and fixed at compile time.
/// No graph storage, no runtime cost beyond a match.
///
/// Reference: Collins & Quillian (1969) "Retrieval time from semantic memory"
/// — type hierarchies reduce retrieval time for plausible paths.
pub fn parent_labels(&self) -> &'static [EntityLabel] {
match self {
// Organizational subtypes
Self::Team => &[EntityLabel::Organization],
Self::Role => &[EntityLabel::Concept],
// Technical subtypes
Self::Service | Self::Database | Self::Repository | Self::Module | Self::Pipeline => {
&[EntityLabel::Technology]
}
// Work / knowledge subtypes
Self::Task => &[EntityLabel::Event],
Self::Document
| Self::Configuration
| Self::Metric
| Self::Environment
| Self::Project => &[EntityLabel::Concept],
// Base types and Other have no parents
_ => &[],
}
}
/// Check if this label matches the expected label, considering type hierarchy.
///
/// Returns true if:
/// - Direct match (self == expected)
/// - Self's parent matches expected (Team matches Organization)
///
/// Used by spreading activation (Layer 2 entity penalty) and
/// Layer 4.9 (ontological re-ranking) for hierarchical type matching.
pub fn matches_with_hierarchy(&self, expected: &EntityLabel) -> bool {
if self == expected {
return true;
}
self.parent_labels().contains(expected)
}
}
/// Memory tier for edge consolidation
///
/// Based on hippocampal-cortical memory consolidation research:
/// - L1 (Working): Dense, fast encoding, aggressive pruning (Dentate Gyrus-like)
/// - L2 (Episodic): Moderate density, Hebbian selection (CA1/CA3-like)
/// - L3 (Semantic): Sparse, near-permanent (Neocortex-like)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum EdgeTier {
/// Working memory tier: new edges, dense, aggressive decay
#[default]
L1Working,
/// Episodic memory tier: proven edges, moderate decay
L2Episodic,
/// Semantic memory tier: consolidated edges, near-permanent
L3Semantic,
}
impl EdgeTier {
/// Get the initial weight for edges in this tier
pub fn initial_weight(&self) -> f32 {
use crate::constants::*;
match self {
Self::L1Working => L1_INITIAL_WEIGHT,
Self::L2Episodic => L2_PROMOTION_WEIGHT,
Self::L3Semantic => L3_PROMOTION_WEIGHT,
}
}
/// Get the prune threshold for this tier
pub fn prune_threshold(&self) -> f32 {
use crate::constants::*;
match self {
Self::L1Working => L1_PRUNE_THRESHOLD,
Self::L2Episodic => L2_PRUNE_THRESHOLD,
Self::L3Semantic => L3_PRUNE_THRESHOLD,
}
}
/// Get the promotion threshold to move to next tier
pub fn promotion_threshold(&self) -> Option<f32> {
use crate::constants::*;
match self {
Self::L1Working => Some(L1_PROMOTION_THRESHOLD),
Self::L2Episodic => Some(L2_PROMOTION_THRESHOLD),
Self::L3Semantic => None, // Already at highest tier
}
}
/// Get the next tier (for promotion)
pub fn next_tier(&self) -> Option<Self> {
match self {
Self::L1Working => Some(Self::L2Episodic),
Self::L2Episodic => Some(Self::L3Semantic),
Self::L3Semantic => None,
}
}
/// Get target density for this tier
pub fn target_density(&self) -> f32 {
use crate::constants::*;
match self {
Self::L1Working => L1_TARGET_DENSITY,
Self::L2Episodic => L2_TARGET_DENSITY,
Self::L3Semantic => L3_TARGET_DENSITY,
}
}
}
/// Long-Term Potentiation status for edges (PIPE-4)
///
/// Multi-scale LTP based on neuroscience research:
/// - Burst: Temporary protection from high-frequency activation (E-LTP)
/// - Weekly: Moderate protection from consistent routine use (L-LTP)
/// - Full: Maximum protection from sustained long-term use (systems consolidation)
///
/// Reference: Frey & Morris (1997) "Synaptic tagging and long-term potentiation"
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum LtpStatus {
/// Not potentiated - normal decay applies
#[default]
None,
/// Burst potentiated: 5+ activations in 24 hours
/// Temporary protection (2x slower decay) that expires after 48h
/// Represents early-phase LTP (protein synthesis independent)
Burst {
/// When burst was detected (for expiration check)
#[serde(with = "chrono::serde::ts_seconds")]
detected_at: DateTime<Utc>,
},
/// Weekly potentiated: 3+/week for 2+ weeks
/// Moderate protection (3x slower decay)
/// Represents late-phase LTP (habit formation)
Weekly,
/// Fully potentiated: 10+ activations OR 5+ over 30 days
/// Maximum protection (10x slower decay)
/// Represents systems consolidation (semantic memory)
Full,
}
impl LtpStatus {
/// Get the decay factor for this LTP status
pub fn decay_factor(&self) -> f32 {
use crate::constants::*;
match self {
Self::None => 1.0,
Self::Burst { detected_at } => {
// Check if burst has expired
let hours_since = (Utc::now() - *detected_at).num_hours();
if hours_since > LTP_BURST_DURATION_HOURS {
1.0 // Expired, normal decay
} else {
LTP_BURST_DECAY_FACTOR
}
}
Self::Weekly => LTP_WEEKLY_DECAY_FACTOR,
Self::Full => LTP_DECAY_FACTOR,
}
}
/// Check if this status provides any protection
pub fn is_potentiated(&self) -> bool {
!matches!(self, Self::None)
}
/// Check if burst protection has expired
pub fn is_burst_expired(&self) -> bool {
use crate::constants::LTP_BURST_DURATION_HOURS;
match self {
Self::Burst { detected_at } => {
(Utc::now() - *detected_at).num_hours() > LTP_BURST_DURATION_HOURS
}
_ => false,
}
}
/// Get priority for LTP upgrades (higher = stronger protection)
pub fn priority(&self) -> u8 {
match self {
Self::None => 0,
Self::Burst { .. } => 1,
Self::Weekly => 2,
Self::Full => 3,
}
}
}
/// Relationship edge between entities
///
/// Implements Hebbian synaptic plasticity: "Neurons that fire together, wire together"
/// - Strength increases with co-activation (strengthen method)
/// - Strength decays over time without use (decay method)
/// - Long-Term Potentiation (LTP): After threshold activations, becomes permanent
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RelationshipEdge {
/// Unique identifier for this edge
pub uuid: Uuid,
/// Source entity UUID
pub from_entity: Uuid,
/// Target entity UUID
pub to_entity: Uuid,
/// Type of relationship
pub relation_type: RelationType,
/// Confidence/strength of this relationship (0.0 to 1.0)
/// Dynamic: increases with co-activation, decays without use
pub strength: f32,
/// When this relationship was created
pub created_at: DateTime<Utc>,
/// When this relationship was last observed (temporal tracking)
pub valid_at: DateTime<Utc>,
/// Whether this relationship has been invalidated (temporal edge invalidation)
pub invalidated_at: Option<DateTime<Utc>>,
/// Source episode that created this relationship
pub source_episode_id: Option<Uuid>,
/// Additional context about the relationship
pub context: String,
// === Hebbian Synaptic Plasticity Fields ===
/// When this synapse was last activated (used in retrieval/traversal)
/// Used to calculate time-based decay
#[serde(default = "default_last_activated")]
pub last_activated: DateTime<Utc>,
/// Number of times both entities were co-accessed (Hebbian co-activation)
/// Higher count = stronger learned association
#[serde(default)]
pub activation_count: u32,
/// Long-Term Potentiation status (PIPE-4: multi-scale LTP)
/// Replaces simple bool with tiered protection levels:
/// - None: Normal decay
/// - Burst: Temporary 2x protection (5+ activations in 24h)
/// - Weekly: Moderate 3x protection (3+/week for 2 weeks)
/// - Full: Maximum 10x protection (10+ activations or 5+ over 30 days)
#[serde(default)]
pub ltp_status: LtpStatus,
/// Memory tier for consolidation (L1→L2→L3)
/// Edges start in L1 (working memory) and promote based on Hebbian strength
#[serde(default)]
pub tier: EdgeTier,
/// Activation timestamp history for temporal pattern detection (PIPE-4)
/// Only populated for L2+ edges (L1 edges die too quickly to need history)
/// Capacity: L2 = 20 timestamps, L3 = 50 timestamps
/// Enables: burst detection, weekly patterns, temporal query relevance
#[serde(default)]
pub activation_timestamps: Option<VecDeque<DateTime<Utc>>>,
/// Entity extraction confidence (PIPE-5: Unified LTP Readiness)
/// Average confidence of the entities connected by this edge.
/// Affects LTP threshold: high confidence → faster LTP (7 activations)
/// Low confidence → slower LTP (13 activations).
/// Based on synaptic tagging: behaviorally relevant synapses consolidate faster.
#[serde(default)]
pub entity_confidence: Option<f32>,
/// Minimum curvature selectivity of the two endpoint entities.
///
/// Cached from EntityNode.selectivity during curvature computation.
/// Used by decay() to gate LTP protection: if the weakest endpoint
/// is a stop word (low selectivity), LTP protection is reduced,
/// allowing curvature-accelerated decay to clean up noise edges
/// even if they're frequently co-activated.
///
/// None = not yet computed (full LTP protection applies).
#[serde(default)]
pub endpoint_selectivity: Option<f32>,
/// Forman-Ricci curvature of this edge (Leal, Restrepo, Stadler, Jost 2018)
///
/// For directed graphs:
/// F(→e→) = 2 - in_deg(source) - out_deg(target) [flow-through]
/// F(←e←) = 2 - out_deg(source) - in_deg(target) [flow-loss]
/// F(e) = F(→e→) + F(←e←) = 4 - deg(source) - deg(target)
///
/// Interpretation:
/// Positive: edge connects low-degree nodes (tight community interior)
/// Near zero: neutral / transitional
/// Negative: edge bridges high-degree hubs (information bottleneck)
///
/// Computed during heavy maintenance cycle. None = not yet computed.
///
/// Reference: arXiv:1811.07825 — "Forman-Ricci curvature for hypergraphs"
#[serde(default)]
pub forman_curvature: Option<f32>,
}
fn default_last_activated() -> DateTime<Utc> {
Utc::now()
}
// Hebbian learning constants now imported from crate::constants:
// - LTP_LEARNING_RATE (0.1): η for strength increase per co-activation
// - LTP_DECAY_HALF_LIFE_DAYS (14.0): λ for time-based decay
// - LTP_THRESHOLD (10): Activations needed for Full LTP
// - LTP_DECAY_FACTOR (0.1): Fully potentiated synapses decay 10x slower
// - LTP_MIN_STRENGTH (0.01): Floor to prevent complete forgetting
// PIPE-4 additions:
// - LTP_BURST_THRESHOLD (5): Activations in 24h for burst LTP
// - LTP_BURST_WINDOW_HOURS (24): Window for burst detection
// - LTP_WEEKLY_THRESHOLD (3): Activations per week for weekly LTP
// - LTP_WEEKLY_MIN_WEEKS (2): Minimum weeks of consistent activation
impl RelationshipEdge {
/// Strengthen this synapse (Hebbian learning)
///
/// Called when both connected entities are accessed together.
/// Formula: w_new = w_old + η × (1 - w_old) × co_activation_boost
///
/// PIPE-4: Multi-scale LTP detection
/// - Records activation timestamps for L2+ edges
/// - Detects burst patterns (5+ in 24h) → temporary protection
/// - Detects weekly patterns (3+/week for 2 weeks) → moderate protection
/// - Detects sustained patterns (10+ total or 5+ over 30 days) → full protection
///
/// Also handles tier promotion (L1→L2→L3) when strength exceeds tier threshold.
///
/// Returns `Some((old_tier_name, new_tier_name))` if a tier promotion occurred,
/// `None` otherwise. This enables the memory-edge coupling: edge promotions
/// can signal the memory layer to boost the associated memory's importance.
pub fn strengthen(&mut self) -> Option<(String, String)> {
use crate::constants::*;
let now = Utc::now();
self.activation_count += 1;
self.last_activated = now;
// PIPE-4: Record activation timestamp for L2+ edges
self.record_activation_timestamp(now);
// Hebbian strengthening with tier-specific boost
let tier_boost = match self.tier {
EdgeTier::L1Working => TIER_CO_ACCESS_BOOST,
EdgeTier::L2Episodic => TIER_CO_ACCESS_BOOST * 0.8,
EdgeTier::L3Semantic => TIER_CO_ACCESS_BOOST * 0.5,
};
let boost = (LTP_LEARNING_RATE + tier_boost) * (1.0 - self.strength);
self.strength = (self.strength + boost).min(1.0);
// PIPE-4: Multi-scale LTP detection (only upgrade, never downgrade)
let new_ltp_status = self.detect_ltp_status(now);
if new_ltp_status.priority() > self.ltp_status.priority() {
let old_status = self.ltp_status;
self.ltp_status = new_ltp_status;
// LTP bonus: immediate strength boost on upgrade
let bonus = match new_ltp_status {
LtpStatus::Burst { .. } => 0.05,
LtpStatus::Weekly => 0.1,
LtpStatus::Full => 0.2,
LtpStatus::None => 0.0,
};
self.strength = (self.strength + bonus).min(1.0);
tracing::debug!(
"Edge {} LTP upgrade: {:?} → {:?} (activations: {}, age: {} days)",
self.uuid,
old_status,
self.ltp_status,
self.activation_count,
(now - self.created_at).num_days()
);
}
// Check for burst expiration and potential downgrade
if self.ltp_status.is_burst_expired() {
// Burst expired - check if weekly pattern has emerged
let weekly_check = self.detect_weekly_pattern();
if weekly_check {
self.ltp_status = LtpStatus::Weekly;
} else {
self.ltp_status = LtpStatus::None;
}
}
// Tier promotion: check if strength exceeds current tier's promotion threshold
let mut promotion_result = None;
if let Some(threshold) = self.tier.promotion_threshold() {
if self.strength >= threshold {
if let Some(next_tier) = self.tier.next_tier() {
let old_tier = self.tier;
self.tier = next_tier;
// Preserve strength if already above next tier's initial weight
self.strength = self.strength.max(next_tier.initial_weight());
// PIPE-4: Initialize activation_timestamps on L1→L2 promotion
if old_tier == EdgeTier::L1Working {
self.activation_timestamps =
Some(VecDeque::with_capacity(ACTIVATION_HISTORY_L2_CAPACITY));
// Seed with current timestamp
if let Some(ref mut ts) = self.activation_timestamps {
ts.push_back(now);
}
}
// Expand capacity on L2→L3 promotion
if old_tier == EdgeTier::L2Episodic {
if let Some(ref mut ts) = self.activation_timestamps {
let current = ts.capacity();
if current < ACTIVATION_HISTORY_L3_CAPACITY {
ts.reserve(ACTIVATION_HISTORY_L3_CAPACITY - current);
}
}
}
tracing::debug!(
"Edge {} promoted: {:?} → {:?}",
self.uuid,
old_tier,
self.tier
);
promotion_result =
Some((format!("{:?}", old_tier), format!("{:?}", self.tier)));
}
}
}
// PIPE-5: L3 auto-LTP removed - now handled by unified ltp_readiness()
// The readiness formula combines strength + activation count + entity confidence,
// ensuring both intensity and repetition evidence are required for Full LTP.
promotion_result
}
/// Record an activation timestamp (PIPE-4)
///
/// Only records for L2+ edges. Maintains capacity limits.
fn record_activation_timestamp(&mut self, timestamp: DateTime<Utc>) {
use crate::constants::*;
// L1 edges don't track history (too transient)
if matches!(self.tier, EdgeTier::L1Working) {
return;
}
// Initialize if needed
if self.activation_timestamps.is_none() {
let capacity = match self.tier {
EdgeTier::L1Working => return,
EdgeTier::L2Episodic => ACTIVATION_HISTORY_L2_CAPACITY,
EdgeTier::L3Semantic => ACTIVATION_HISTORY_L3_CAPACITY,
};
self.activation_timestamps = Some(VecDeque::with_capacity(capacity));
}
if let Some(ref mut timestamps) = self.activation_timestamps {
let capacity = match self.tier {
EdgeTier::L1Working => return,
EdgeTier::L2Episodic => ACTIVATION_HISTORY_L2_CAPACITY,
EdgeTier::L3Semantic => ACTIVATION_HISTORY_L3_CAPACITY,
};
// Maintain capacity limit (ring buffer behavior)
while timestamps.len() >= capacity {
timestamps.pop_front();
}
timestamps.push_back(timestamp);
}
}
/// Detect LTP status based on unified readiness model (PIPE-4 + PIPE-5)
///
/// PIPE-5 unifies LTP detection into a single readiness score that combines:
/// - Activation count (repetition path)
/// - Strength (intensity/durability path)
/// - Entity confidence (synaptic tagging bonus)
///
/// Multiple paths can lead to Full LTP:
/// - High repetition alone (15+ activations)
/// - High intensity alone (0.95+ strength at L3)
/// - Balanced contribution from both
/// - High-confidence edges reach threshold ~30% faster
///
/// Temporal patterns (Burst, Weekly) remain separate as they represent
/// different consolidation mechanisms (E-LTP vs habit formation).
fn detect_ltp_status(&self, now: DateTime<Utc>) -> LtpStatus {
use crate::constants::*;
// PIPE-5: Unified LTP readiness for Full LTP
// Combines activation count, strength, and entity confidence
if self.ltp_readiness() >= LTP_READINESS_THRESHOLD {
return LtpStatus::Full;
}
// Legacy time-aware path: 5+ activations over 30+ days
// Kept for backward compatibility and edges that survived long decay
let edge_age_days = (now - self.created_at).num_days();
if edge_age_days >= LTP_TIME_AWARE_DAYS && self.activation_count >= LTP_TIME_AWARE_THRESHOLD
{
return LtpStatus::Full;
}
// Check for Weekly LTP (requires timestamp history)
// Temporal pattern: 3+/week for 2+ weeks indicates habit
if self.detect_weekly_pattern() {
return LtpStatus::Weekly;
}
// Check for Burst LTP (requires timestamp history)
// Temporal pattern: 5+ in 24h indicates high immediate interest
if self.detect_burst_pattern(now) {
return LtpStatus::Burst { detected_at: now };
}
LtpStatus::None
}
/// Detect burst pattern: 5+ activations in 24 hours (PIPE-4)
fn detect_burst_pattern(&self, now: DateTime<Utc>) -> bool {
use crate::constants::*;
use chrono::Duration;
let timestamps = match &self.activation_timestamps {
Some(ts) => ts,
None => return false,
};
let window_start = now - Duration::hours(LTP_BURST_WINDOW_HOURS);
let count_in_window = timestamps.iter().filter(|&&ts| ts >= window_start).count();
count_in_window >= LTP_BURST_THRESHOLD as usize
}
/// Detect weekly pattern: 3+/week for 2+ weeks (PIPE-4)
fn detect_weekly_pattern(&self) -> bool {
use crate::constants::*;
use chrono::Duration;
let timestamps = match &self.activation_timestamps {
Some(ts) => ts,
None => return false,
};
if timestamps.is_empty() {
return false;
}
let now = Utc::now();
let mut weeks_meeting_threshold = 0u32;
// Check each of the last LTP_WEEKLY_MIN_WEEKS weeks
for week_offset in 0..LTP_WEEKLY_MIN_WEEKS {
let week_end = now - Duration::weeks(week_offset as i64);
let week_start = week_end - Duration::weeks(1);
let count_in_week = timestamps
.iter()
.filter(|&&ts| ts >= week_start && ts < week_end)
.count();
if count_in_week >= LTP_WEEKLY_THRESHOLD as usize {
weeks_meeting_threshold += 1;
}
}
weeks_meeting_threshold >= LTP_WEEKLY_MIN_WEEKS
}
/// Get activation count within a time window (for temporal retrieval scoring)
pub fn activations_in_window(&self, start: DateTime<Utc>, end: DateTime<Utc>) -> usize {
match &self.activation_timestamps {
Some(ts) => ts.iter().filter(|&&t| t >= start && t <= end).count(),
None => 0,
}
}
/// Check if edge was active at similar time of day (for temporal retrieval)
pub fn time_of_day_match(&self, target_hour: u32, window_hours: u32) -> usize {
use chrono::Timelike;
match &self.activation_timestamps {
Some(ts) => ts
.iter()
.filter(|t| {
let hour = t.hour();
let diff = if hour > target_hour {
(hour - target_hour).min(24 + target_hour - hour)
} else {
(target_hour - hour).min(24 + hour - target_hour)
};
diff <= window_hours
})
.count(),
None => 0,
}
}
/// Apply time-based decay to this synapse
///
/// Uses tier-aware decay model (3-tier memory consolidation):
/// - L1 (Working): ~2.9%/hour decay (λ=0.029), max 48 hours before prune
/// - L2 (Episodic): ~3.1%/day decay (λ=0.031), max 30 days before prune
/// - L3 (Semantic): ~2%/month decay (λ=0.02/720h), near-permanent
///
/// PIPE-4: Multi-scale LTP protection
/// - Burst: 2x slower decay (temporary, 48h)
/// - Weekly: 3x slower decay (habit protection)
/// - Full: 10x slower decay (permanent protection)
///
/// **Important:** Updates `last_activated` to prevent double-decay on
/// repeated calls.
///
/// Returns true if synapse should be pruned (below tier's threshold)
pub fn decay(&mut self) -> bool {
use crate::decay::tier_decay_factor;
let now = Utc::now();
let elapsed = now.signed_duration_since(self.last_activated);
let hours_elapsed = elapsed.num_seconds() as f64 / 3600.0;
if hours_elapsed <= 0.0 {
return false;
}
// Cap max decay to protect against clock jumps (max 1 year = 8760 hours)
let hours_elapsed = hours_elapsed.min(8760.0);
// Tier-aware decay with PIPE-4 multi-scale LTP
let tier_num = match self.tier {
EdgeTier::L1Working => 0,
EdgeTier::L2Episodic => 1,
EdgeTier::L3Semantic => 2,
};
let raw_ltp_factor = self.ltp_status.decay_factor();
// Gate LTP protection by endpoint selectivity (habituation mechanism).
// Low-selectivity edges (connecting stop-word entities) get reduced
// LTP protection regardless of activation count, because high-frequency
// low-information signals should habituate, not potentiate.
//
// effective_ltp = raw_ltp * (selectivity / (selectivity + half_sat))
//
// selectivity=0.0 → effective_ltp=raw_ltp*0.0 = 1.0 (no protection)
// selectivity=0.5 → effective_ltp=raw_ltp*0.5 (half protection)
// selectivity=5.0 → effective_ltp=raw_ltp*0.91 (nearly full protection)
// selectivity=None → full protection (not yet computed, conservative)
let ltp_factor = match self.endpoint_selectivity {
Some(sel) if sel < crate::constants::SELECTIVITY_STOP_WORD_THRESHOLD => {
// Blend toward 1.0 (no protection) as selectivity → 0
let gate = sel / (sel + crate::constants::SELECTIVITY_HALF_SAT);
// ltp_factor is in (0, 1]: 0.1 = Full LTP, 1.0 = no LTP
// gate → 0 means override toward 1.0 (no protection)
raw_ltp_factor + (1.0 - raw_ltp_factor) * (1.0 - gate)
}
_ => raw_ltp_factor, // Not computed yet or above threshold: full protection
};
let (decay_factor, exceeded_max_age) =
tier_decay_factor(hours_elapsed, tier_num, ltp_factor);
self.strength *= decay_factor;
// Update last_activated to prevent double-decay on repeated calls
self.last_activated = now;
// Apply floor to prevent complete forgetting
let prune_threshold = self.tier.prune_threshold();
if self.strength < LTP_MIN_STRENGTH {
self.strength = LTP_MIN_STRENGTH;
}
// Downgrade expired burst LTP before prune decision
// decay_factor() already returns 1.0 for expired bursts (correct rate),
// but is_potentiated() still returns true — preventing pruning
if self.ltp_status.is_burst_expired() {
if self.detect_weekly_pattern() {
self.ltp_status = LtpStatus::Weekly;
} else {
self.ltp_status = LtpStatus::None;
}
}
// Strip LTP protection from near-zero edges (zombie edge cleanup)
// Prevents immortal edges that retain LTP despite negligible strength
if self.ltp_status.is_potentiated() && self.strength <= LTP_PRUNE_FLOOR {
self.ltp_status = LtpStatus::None;
}
// Return whether this synapse should be pruned
// Prune if: exceeded max age OR below prune threshold (unless any LTP protection)
if self.ltp_status.is_potentiated() {
false
} else {
exceeded_max_age || self.strength <= prune_threshold
}
}
/// Get the effective strength considering recency
///
/// This is a read-only version that calculates what the strength
/// would be after decay, without modifying the edge.
/// Uses tier-aware decay (L1/L2/L3 have different decay rates).
pub fn effective_strength(&self) -> f32 {
use crate::decay::tier_decay_factor;
let now = Utc::now();
let elapsed = now.signed_duration_since(self.last_activated);
let hours_elapsed = elapsed.num_seconds() as f64 / 3600.0;
if hours_elapsed <= 0.0 {
return self.strength;
}
let tier_num = match self.tier {
EdgeTier::L1Working => 0,
EdgeTier::L2Episodic => 1,
EdgeTier::L3Semantic => 2,
};
let ltp_factor = self.ltp_status.decay_factor();
let (decay_factor, _) = tier_decay_factor(hours_elapsed, tier_num, ltp_factor);
(self.strength * decay_factor).max(LTP_MIN_STRENGTH)
}
/// Check if this edge has any LTP protection (for backward compatibility)
pub fn is_potentiated(&self) -> bool {
self.ltp_status.is_potentiated()
}
// =========================================================================
// PIPE-5: Unified LTP Readiness Model
// =========================================================================
/// Get confidence-adjusted LTP threshold (PIPE-5)
///
/// High-confidence edges (strong entity extraction) need fewer activations.
/// Low-confidence edges need more activations to prove value.
///
/// Returns: threshold in range [LTP_THRESHOLD_MIN, LTP_THRESHOLD_MAX]
pub fn adjusted_threshold(&self) -> u32 {
use crate::constants::*;
let confidence = self.entity_confidence.unwrap_or(0.5);
// Linear interpolation: high confidence → low threshold
// confidence 0.0 → threshold_max (13)
// confidence 1.0 → threshold_min (7)
let range = LTP_THRESHOLD_MAX - LTP_THRESHOLD_MIN;
let threshold = LTP_THRESHOLD_MAX as f32 - (confidence * range as f32);
threshold.round() as u32
}
/// Get tier-specific strength floor for Full LTP (PIPE-5)
///
/// L2 edges have lower floor (still proving themselves).
/// L3 edges have higher floor (must demonstrate durability).
/// L1 edges return 1.0 (effectively impossible to reach Full LTP).
pub fn strength_floor(&self) -> f32 {
use crate::constants::*;
match self.tier {
EdgeTier::L1Working => 1.0, // L1 can't reach Full LTP via readiness
EdgeTier::L2Episodic => LTP_STRENGTH_FLOOR_L2,
EdgeTier::L3Semantic => LTP_STRENGTH_FLOOR_L3,
}
}
/// Calculate LTP readiness score (PIPE-5)
///
/// Unified formula combining activation count, strength, and entity confidence:
/// - count_score = activation_count / adjusted_threshold
/// - strength_score = strength / strength_floor
/// - tag_bonus = entity_confidence * TAG_WEIGHT
///
/// readiness = count_score * COUNT_WEIGHT + strength_score * STRENGTH_WEIGHT + tag_bonus
///
/// Full LTP when readiness >= 1.0
///
/// This allows multiple paths to LTP:
/// - Repetition-dominant: 15 activations can compensate for lower strength
/// - Intensity-dominant: 0.95 strength can compensate for fewer activations
/// - Balanced: 10 activations + 0.75 strength + moderate confidence
/// - Tagged boost: high-confidence edges reach LTP ~30% faster
pub fn ltp_readiness(&self) -> f32 {
use crate::constants::*;
// L1 edges can't reach Full LTP via readiness (too transient)
if matches!(self.tier, EdgeTier::L1Working) {
return 0.0;
}
let threshold = self.adjusted_threshold() as f32;
let floor = self.strength_floor();
// Count score: how close to activation threshold
let count_score = self.activation_count as f32 / threshold;
// Strength score: how close to strength floor
let strength_score = self.strength / floor;
// Tag bonus: entity confidence provides synaptic tagging advantage
let confidence = self.entity_confidence.unwrap_or(0.5);
let tag_bonus = confidence * LTP_READINESS_TAG_WEIGHT;
// Weighted combination
count_score * LTP_READINESS_COUNT_WEIGHT
+ strength_score * LTP_READINESS_STRENGTH_WEIGHT
+ tag_bonus
}
}
/// Relationship types for ontological edge classification.
///
/// Extends Graphiti's semantic model with management, operational, and
/// evolution relationships for DevOps, software engineering, and robotics.
///
/// New variants are additive only — never remove existing variants to
/// maintain backward compatibility with MessagePack-serialized data.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum RelationType {
/// Work relationships
WorksWith,
WorksAt,
EmployedBy,
/// Structural relationships
PartOf,
Contains,
OwnedBy,
/// Location relationships
LocatedIn,
LocatedAt,
/// Usage relationships
Uses,
CreatedBy,
DevelopedBy,
/// Causal relationships
Causes,
ResultsIn,
/// Learning relationships
Learned,
Knows,
Teaches,
/// Generic relationships (never penalized by ontological filtering)
RelatedTo,
AssociatedWith,
/// Memory co-retrieval (Hebbian association between memories)
CoRetrieved,
/// Sentence co-occurrence (entities appearing in same sentence)
/// Key for multi-hop: "Melanie" <-> "sunrise" when "Melanie painted a sunrise"
CoOccurs,
// =========================================================================
// Extended ontological relations (added 2026-03)
// =========================================================================
/// Management / Governance
/// Person/Team manages Project/Service/Team
Manages,
/// Service/Module depends on Service/Module
DependsOn,
/// Task requires Skill/Technology
Requires,
/// Configuration configures Service/Environment
Configures,
/// Preference / Recommendation
/// Person prefers Technology/Configuration/Approach
Prefers,
/// Person/Role recommends Technology/Approach
Recommends,
/// Document / Knowledge
/// Document documents Service/API/Project
Documents,
/// Module/Service implements Concept/Spec
Implements,
/// Operational
/// Pipeline deploys Service to Environment
DeploysTo,
/// Metric/Service monitors Service/Pipeline
Monitors,
/// Event/Pipeline triggers Pipeline/Task
Triggers,
/// Comparison / Evolution
/// Technology/Config superseded by newer version
SupersededBy,
/// Technology is alternative to Technology
AlternativeTo,
/// Assignment
/// Task assigned to Person/Team
AssignedTo,
/// Person/Role approves Task/Document
Approves,
/// Custom relationship
Custom(String),
}
impl RelationType {
/// Get string representation of the relation type
#[allow(unused)] // Public API for serialization/display
pub fn as_str(&self) -> &str {
match self {
Self::WorksWith => "WorksWith",
Self::WorksAt => "WorksAt",
Self::EmployedBy => "EmployedBy",
Self::PartOf => "PartOf",
Self::Contains => "Contains",
Self::OwnedBy => "OwnedBy",
Self::LocatedIn => "LocatedIn",
Self::LocatedAt => "LocatedAt",
Self::Uses => "Uses",
Self::CreatedBy => "CreatedBy",
Self::DevelopedBy => "DevelopedBy",
Self::Causes => "Causes",
Self::ResultsIn => "ResultsIn",
Self::Learned => "Learned",
Self::Knows => "Knows",
Self::Teaches => "Teaches",
Self::RelatedTo => "RelatedTo",
Self::AssociatedWith => "AssociatedWith",
Self::CoRetrieved => "CoRetrieved",
Self::CoOccurs => "CoOccurs",
Self::Manages => "Manages",
Self::DependsOn => "DependsOn",
Self::Requires => "Requires",
Self::Configures => "Configures",
Self::Prefers => "Prefers",
Self::Recommends => "Recommends",
Self::Documents => "Documents",
Self::Implements => "Implements",
Self::DeploysTo => "DeploysTo",
Self::Monitors => "Monitors",
Self::Triggers => "Triggers",
Self::SupersededBy => "SupersededBy",
Self::AlternativeTo => "AlternativeTo",
Self::AssignedTo => "AssignedTo",
Self::Approves => "Approves",
Self::Custom(s) => s.as_str(),
}
}
}
/// Episodic node representing a discrete experience/memory
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EpisodicNode {
/// Unique identifier
pub uuid: Uuid,
/// Human-readable name/title
pub name: String,
/// Episode content (the actual experience data)
pub content: String,
/// When the original event occurred (event time)
pub valid_at: DateTime<Utc>,
/// When this was ingested into the system (ingestion time)
pub created_at: DateTime<Utc>,
/// Entities extracted from this episode
pub entity_refs: Vec<Uuid>,
/// Source type
pub source: EpisodeSource,
/// Additional metadata
pub metadata: HashMap<String, String>,
}
/// Episode source types
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum EpisodeSource {
Message,
Document,
Event,
Observation,
}
/// Graph memory storage and operations
///
/// Uses a single RocksDB instance with 9 column families for all graph data.
/// This reduces file descriptor usage from 9 separate DBs to 1 (sharing WAL, MANIFEST, LOCK).
pub struct GraphMemory {
/// Unified RocksDB database with column families for entities, relationships,
/// episodes, and all index tables
db: Arc<DB>,
/// In-memory entity name index for fast lookups (loaded from name_index CF)
entity_name_index: Arc<parking_lot::RwLock<HashMap<String, Uuid>>>,
/// In-memory lowercase name index for O(1) case-insensitive lookups
entity_lowercase_index: Arc<parking_lot::RwLock<HashMap<String, Uuid>>>,
/// In-memory stemmed name index for O(1) linguistic lookups
/// Key: Porter-stemmed lowercase name, Value: Entity UUID
entity_stemmed_index: Arc<parking_lot::RwLock<HashMap<String, Uuid>>>,
// === Atomic counters for O(1) stats (P1 fix) ===
/// Entity count - initialized from entity_name_index.len(), updated on add
entity_count: Arc<AtomicUsize>,
/// Relationship count - initialized on startup, updated on add
relationship_count: Arc<AtomicUsize>,
/// Episode count - initialized on startup, updated on add
episode_count: Arc<AtomicUsize>,
/// Mutex for serializing synapse updates to prevent race conditions (SHO-64)
/// Uses parking_lot::Mutex for better performance than std::sync::Mutex
synapse_update_lock: Arc<parking_lot::Mutex<()>>,
/// In-memory cache of entity name embeddings for concept merging.
/// Maps entity UUID → embedding vector. Loaded on startup, updated on add.
/// Used when string-based dedup (exact/case/stemmed) fails — catches synonyms
/// like "authentication" ↔ "auth" via cosine similarity.
entity_embedding_cache: Arc<parking_lot::RwLock<Vec<(Uuid, Vec<f32>)>>>,
/// Edges found below prune threshold during lazy-decay reads.
/// Flushed as batch deletes on each maintenance cycle (no full scan needed).
pending_prune: parking_lot::Mutex<Vec<Uuid>>,
/// Entities that may have become orphaned from pruned edges.
/// Checked during flush_pending_maintenance().
pending_orphan_checks: parking_lot::Mutex<Vec<Uuid>>,
}
impl GraphMemory {
/// Get a reference to the underlying RocksDB instance (for backup/checkpoint).
pub fn get_db(&self) -> &DB {
&self.db
}
// Column family accessors — cheap HashMap lookups on DB internals
fn entities_cf(&self) -> &ColumnFamily {
self.db
.cf_handle(CF_ENTITIES)
.expect("entities CF must exist")
}
fn relationships_cf(&self) -> &ColumnFamily {
self.db
.cf_handle(CF_RELATIONSHIPS)
.expect("relationships CF must exist")
}
fn episodes_cf(&self) -> &ColumnFamily {
self.db
.cf_handle(CF_EPISODES)
.expect("episodes CF must exist")
}
fn entity_edges_cf(&self) -> &ColumnFamily {
self.db
.cf_handle(CF_ENTITY_EDGES)
.expect("entity_edges CF must exist")
}
fn entity_pair_index_cf(&self) -> &ColumnFamily {
self.db
.cf_handle(CF_ENTITY_PAIR_INDEX)
.expect("entity_pair_index CF must exist")
}
fn entity_episodes_cf(&self) -> &ColumnFamily {
self.db
.cf_handle(CF_ENTITY_EPISODES)
.expect("entity_episodes CF must exist")
}
fn name_index_cf(&self) -> &ColumnFamily {
self.db
.cf_handle(CF_NAME_INDEX)
.expect("name_index CF must exist")
}
fn lowercase_index_cf(&self) -> &ColumnFamily {
self.db
.cf_handle(CF_LOWERCASE_INDEX)
.expect("lowercase_index CF must exist")
}
fn stemmed_index_cf(&self) -> &ColumnFamily {
self.db
.cf_handle(CF_STEMMED_INDEX)
.expect("stemmed_index CF must exist")
}
/// Create a new graph memory system.
///
/// If `shared_cache` is provided, block-cache reads are charged against the
/// shared LRU cache (recommended for multi-tenant server mode). When `None`,
/// a small per-instance cache is created (standalone / test use).
pub fn new(path: &Path, shared_cache: Option<&rocksdb::Cache>) -> Result<Self> {
use crate::constants::ROCKSDB_GRAPH_WRITE_BUFFER_BYTES;
let graph_path = path.join("graph");
std::fs::create_dir_all(&graph_path)?;
let mut opts = Options::default();
opts.create_if_missing(true);
opts.create_missing_column_families(true);
opts.set_compression_type(rocksdb::DBCompressionType::Lz4);
opts.set_write_buffer_size(ROCKSDB_GRAPH_WRITE_BUFFER_BYTES);
opts.set_max_write_buffer_number(2);
// Shared block cache for multi-tenant, small local for standalone/tests.
use rocksdb::{BlockBasedOptions, Cache};
let mut block_opts = BlockBasedOptions::default();
let local_cache;
let cache = match shared_cache {
Some(c) => c,
None => {
local_cache = Cache::new_lru_cache(8 * 1024 * 1024); // 8MB standalone
&local_cache
}
};
block_opts.set_block_cache(cache);
block_opts.set_cache_index_and_filter_blocks(true);
opts.set_block_based_table_factory(&block_opts);
// Build column family descriptors — all CFs share the same options
let cf_descriptors: Vec<ColumnFamilyDescriptor> = GRAPH_CF_NAMES
.iter()
.map(|name| ColumnFamilyDescriptor::new(*name, opts.clone()))
.collect();
let db = Arc::new(DB::open_cf_descriptors(&opts, &graph_path, cf_descriptors)?);
// Migrate data from old separate-DB layout if needed
let migrated = Self::migrate_from_separate_dbs(path, &db)?;
if migrated > 0 {
tracing::info!(
"Migrated {} entries from separate graph DBs to column families",
migrated
);
}
// Load entity name index from name_index CF (O(n) but faster than deserializing entities)
// If empty, migrate from entities CF (one-time migration for existing data)
let entity_name_index = Self::load_or_migrate_name_index(&db)?;
// Load/migrate lowercase index for O(1) case-insensitive lookup
let entity_lowercase_index =
Self::load_or_migrate_lowercase_index(&db, &entity_name_index)?;
// Load/migrate stemmed index for O(1) linguistic lookup
let entity_stemmed_index = Self::load_or_migrate_stemmed_index(&db, &entity_name_index)?;
let entity_count = entity_name_index.len();
// Count relationships and episodes during startup (one-time cost)
// This is O(n) at startup, but get_stats() will be O(1) at runtime
let relationships_cf = db
.cf_handle(CF_RELATIONSHIPS)
.ok_or_else(|| anyhow::anyhow!("CF '{}' not found after DB open", CF_RELATIONSHIPS))?;
let episodes_cf = db
.cf_handle(CF_EPISODES)
.ok_or_else(|| anyhow::anyhow!("CF '{}' not found after DB open", CF_EPISODES))?;
let relationship_count = Self::count_cf_entries(&db, relationships_cf);
let episode_count = Self::count_cf_entries(&db, episodes_cf);
// Load entity embedding cache for concept merging
// Only entities with pre-computed name_embeddings are cached
let entities_cf = db
.cf_handle(CF_ENTITIES)
.ok_or_else(|| anyhow::anyhow!("CF '{}' not found after DB open", CF_ENTITIES))?;
let entity_embedding_cache =
Self::load_entity_embedding_cache(&db, entities_cf, &entity_name_index);
let embedding_cache_size = entity_embedding_cache.len();
let graph = Self {
db,
entity_name_index: Arc::new(parking_lot::RwLock::new(entity_name_index)),
entity_lowercase_index: Arc::new(parking_lot::RwLock::new(entity_lowercase_index)),
entity_stemmed_index: Arc::new(parking_lot::RwLock::new(entity_stemmed_index)),
entity_count: Arc::new(AtomicUsize::new(entity_count)),
relationship_count: Arc::new(AtomicUsize::new(relationship_count)),
episode_count: Arc::new(AtomicUsize::new(episode_count)),
synapse_update_lock: Arc::new(parking_lot::Mutex::new(())),
entity_embedding_cache: Arc::new(parking_lot::RwLock::new(entity_embedding_cache)),
pending_prune: parking_lot::Mutex::new(Vec::new()),
pending_orphan_checks: parking_lot::Mutex::new(Vec::new()),
};
if entity_count > 0 || relationship_count > 0 || episode_count > 0 {
tracing::info!(
"Loaded graph with {} entities ({} with embeddings), {} relationships, {} episodes",
entity_count,
embedding_cache_size,
relationship_count,
episode_count
);
}
Ok(graph)
}
/// Migrate data from the old separate-DB layout (pre-CF) into column families.
///
/// Detects old `graph_*` subdirectories, opens them read-only, copies all KV
/// pairs into the corresponding CF, then renames the old directory for rollback safety.
fn migrate_from_separate_dbs(base_path: &Path, db: &DB) -> Result<usize> {
let old_dirs: &[(&str, &str)] = &[
("graph_entities", CF_ENTITIES),
("graph_relationships", CF_RELATIONSHIPS),
("graph_episodes", CF_EPISODES),
("graph_entity_edges", CF_ENTITY_EDGES),
("graph_entity_pair_index", CF_ENTITY_PAIR_INDEX),
("graph_entity_episodes", CF_ENTITY_EPISODES),
("graph_entity_name_index", CF_NAME_INDEX),
("graph_entity_lowercase_index", CF_LOWERCASE_INDEX),
("graph_entity_stemmed_index", CF_STEMMED_INDEX),
];
let mut total_migrated = 0usize;
for (old_name, cf_name) in old_dirs {
let old_path = base_path.join(old_name);
if !old_path.exists() {
continue;
}
let cf = db
.cf_handle(cf_name)
.ok_or_else(|| anyhow::anyhow!("CF '{}' not found during migration", cf_name))?;
// Only migrate if the CF is empty (avoid double migration)
if db
.iterator_cf(cf, rocksdb::IteratorMode::Start)
.next()
.is_some()
{
// CF already has data — just rename the old dir
let renamed = base_path.join(format!("{}.pre_cf_migration", old_name));
if !renamed.exists() {
let _ = std::fs::rename(&old_path, &renamed);
}
continue;
}
// Open old DB read-only and copy all entries
let old_opts = Options::default();
match DB::open_for_read_only(&old_opts, &old_path, false) {
Ok(old_db) => {
let mut batch = WriteBatch::default();
let mut count = 0usize;
for item in old_db.iterator(rocksdb::IteratorMode::Start) {
match item {
Ok((key, value)) => {
batch.put_cf(cf, &key, &value);
count += 1;
// Flush in chunks to limit memory usage
if count % 10_000 == 0 {
db.write(std::mem::take(&mut batch))?;
batch = WriteBatch::default();
}
}
Err(e) => {
tracing::warn!("Error reading from old {}: {}", old_name, e);
break;
}
}
}
if count > 0 {
db.write(batch)?;
}
drop(old_db);
// Rename old directory for rollback safety
let renamed = base_path.join(format!("{}.pre_cf_migration", old_name));
if let Err(e) = std::fs::rename(&old_path, &renamed) {
tracing::warn!(
"Migrated {} entries from {} but failed to rename: {}",
count,
old_name,
e
);
} else {
tracing::info!(
"Migrated {} entries from {} to CF '{}'",
count,
old_name,
cf_name
);
}
total_migrated += count;
}
Err(e) => {
tracing::warn!("Failed to open old DB {} for migration: {}", old_name, e);
}
}
}
Ok(total_migrated)
}
/// Load entity name->UUID index from name_index CF, or migrate from entities CF if empty
fn load_or_migrate_name_index(db: &DB) -> Result<HashMap<String, Uuid>> {
let name_index_cf = db
.cf_handle(CF_NAME_INDEX)
.ok_or_else(|| anyhow::anyhow!("CF '{}' not found", CF_NAME_INDEX))?;
let entities_cf = db
.cf_handle(CF_ENTITIES)
.ok_or_else(|| anyhow::anyhow!("CF '{}' not found", CF_ENTITIES))?;
let mut index = HashMap::new();
// Try to load from name_index CF first
let iter = db.iterator_cf(name_index_cf, rocksdb::IteratorMode::Start);
for (key, value) in iter.flatten() {
if let (Ok(name), Ok(uuid_bytes)) = (
std::str::from_utf8(&key),
<[u8; 16]>::try_from(value.as_ref()),
) {
index.insert(name.to_string(), Uuid::from_bytes(uuid_bytes));
}
}
// If name_index CF is empty but entities exist, migrate (one-time operation)
if index.is_empty() {
let entity_iter = db.iterator_cf(entities_cf, rocksdb::IteratorMode::Start);
let mut migrated_count = 0;
for (_, value) in entity_iter.flatten() {
if let Ok((entity, _)) = crate::serialization::try_decode::<EntityNode>(&value) {
// Store in name_index CF: name -> UUID bytes
db.put_cf(
name_index_cf,
entity.name.as_bytes(),
entity.uuid.as_bytes(),
)?;
index.insert(entity.name.clone(), entity.uuid);
migrated_count += 1;
}
}
if migrated_count > 0 {
tracing::info!("Migrated {} entities to name index CF", migrated_count);
}
}
Ok(index)
}
/// Load lowercase name->UUID index, or migrate from name_index if empty
///
/// This enables O(1) case-insensitive entity lookup instead of O(n) linear search.
fn load_or_migrate_lowercase_index(
db: &DB,
name_index: &HashMap<String, Uuid>,
) -> Result<HashMap<String, Uuid>> {
let lowercase_cf = db
.cf_handle(CF_LOWERCASE_INDEX)
.ok_or_else(|| anyhow::anyhow!("CF '{}' not found", CF_LOWERCASE_INDEX))?;
let mut index = HashMap::new();
// Try to load from lowercase_index CF
let iter = db.iterator_cf(lowercase_cf, rocksdb::IteratorMode::Start);
for (key, value) in iter.flatten() {
if let (Ok(name), Ok(uuid_bytes)) = (
std::str::from_utf8(&key),
<[u8; 16]>::try_from(value.as_ref()),
) {
index.insert(name.to_string(), Uuid::from_bytes(uuid_bytes));
}
}
// If empty but name_index has data, migrate (one-time operation)
if index.is_empty() && !name_index.is_empty() {
for (name, uuid) in name_index {
let lowercase_name = name.to_lowercase();
db.put_cf(lowercase_cf, lowercase_name.as_bytes(), uuid.as_bytes())?;
index.insert(lowercase_name, *uuid);
}
tracing::info!(
"Migrated {} entities to lowercase index CF",
name_index.len()
);
}
Ok(index)
}
/// Load stemmed name->UUID index, or migrate from name_index if empty
///
/// This enables O(1) linguistic entity lookup: "running" matches "run"
/// Uses Porter2 stemmer for English language stemming.
fn load_or_migrate_stemmed_index(
db: &DB,
name_index: &HashMap<String, Uuid>,
) -> Result<HashMap<String, Uuid>> {
let stemmed_cf = db
.cf_handle(CF_STEMMED_INDEX)
.ok_or_else(|| anyhow::anyhow!("CF '{}' not found", CF_STEMMED_INDEX))?;
let mut index = HashMap::new();
// Try to load from stemmed_index CF
let iter = db.iterator_cf(stemmed_cf, rocksdb::IteratorMode::Start);
for (key, value) in iter.flatten() {
if let (Ok(name), Ok(uuid_bytes)) = (
std::str::from_utf8(&key),
<[u8; 16]>::try_from(value.as_ref()),
) {
index.insert(name.to_string(), Uuid::from_bytes(uuid_bytes));
}
}
// If empty but name_index has data, migrate (one-time operation)
if index.is_empty() && !name_index.is_empty() {
let stemmer = Stemmer::create(Algorithm::English);
for (name, uuid) in name_index {
let stemmed_name = Self::stem_entity_name(&stemmer, name);
db.put_cf(stemmed_cf, stemmed_name.as_bytes(), uuid.as_bytes())?;
index.insert(stemmed_name, *uuid);
}
tracing::info!("Migrated {} entities to stemmed index CF", name_index.len());
}
Ok(index)
}
/// Stem an entity name for linguistic matching
///
/// For multi-word names (e.g., "New York City"), stems each word and joins.
/// Returns lowercase stemmed version for consistent matching.
fn stem_entity_name(stemmer: &Stemmer, name: &str) -> String {
name.split_whitespace()
.map(|word| stemmer.stem(&word.to_lowercase()).to_string())
.collect::<Vec<_>>()
.join(" ")
}
/// Count entries in a column family (one-time startup cost)
fn count_cf_entries(db: &DB, cf: &ColumnFamily) -> usize {
db.iterator_cf(cf, rocksdb::IteratorMode::Start).count()
}
/// Load entity embedding cache from persisted entities.
///
/// Scans entities referenced by the name index and collects those with
/// pre-computed name_embeddings into an in-memory cache for O(n) concept
/// merging during `add_entity()`. Entities without embeddings (pre-upgrade
/// data) are skipped and will gain embeddings on their next mention.
fn load_entity_embedding_cache(
db: &DB,
entities_cf: &ColumnFamily,
name_index: &HashMap<String, Uuid>,
) -> Vec<(Uuid, Vec<f32>)> {
let mut cache = Vec::with_capacity(ENTITY_EMBEDDING_CACHE_MAX.min(name_index.len()));
for uuid in name_index.values() {
let key = uuid.as_bytes();
if let Ok(Some(value)) = db.get_cf(entities_cf, key) {
if let Ok((entity, _)) = crate::serialization::try_decode::<EntityNode>(&value) {
if let Some(emb) = entity.name_embedding {
cache.push((*uuid, emb));
if cache.len() >= ENTITY_EMBEDDING_CACHE_MAX {
break;
}
}
}
}
}
cache
}
/// Add or update an entity node
/// Salience is updated using the formula: salience = base_salience * (1 + 0.1 * ln(mention_count))
/// This means frequently mentioned entities grow in salience (gravitational wells get heavier)
///
/// BUG-002 FIX: Handles crash recovery for orphaned entities/stale indices
pub fn add_entity(&self, mut entity: EntityNode) -> Result<Uuid> {
// Multi-tier dedup pipeline: exact → case-insensitive → stemmed → embedding
// Each tier is faster than the next; short-circuits on first match.
// Tier 1: Exact name match (O(1))
let mut existing_uuid = {
let index = self.entity_name_index.read();
index.get(&entity.name).cloned()
};
// Tier 2: Case-insensitive match (O(1))
if existing_uuid.is_none() {
let lowercase_name = entity.name.to_lowercase();
let index = self.entity_lowercase_index.read();
existing_uuid = index.get(&lowercase_name).cloned();
}
// Tier 3: Stemmed match (O(1)) — "running" matches "run"
// Skip for proper nouns to prevent "Paris" → "pari" merging with "Parison"
if existing_uuid.is_none() && !entity.is_proper_noun {
let stemmer = Stemmer::create(Algorithm::English);
let stemmed_name = Self::stem_entity_name(&stemmer, &entity.name);
let index = self.entity_stemmed_index.read();
existing_uuid = index.get(&stemmed_name).cloned();
}
// Tier 4: Embedding-based concept merge (O(n) over cache)
// Catches synonyms like "authentication" ↔ "auth" that string matching misses.
// Only runs when the entity carries a name_embedding (populated by caller).
if existing_uuid.is_none() {
if let Some(ref new_emb) = entity.name_embedding {
let cache = self.entity_embedding_cache.read();
let mut best_match: Option<(Uuid, f32)> = None;
for (uuid, existing_emb) in cache.iter() {
let sim = crate::similarity::cosine_similarity(new_emb, existing_emb);
if sim >= ENTITY_CONCEPT_MERGE_THRESHOLD {
if best_match.map_or(true, |(_, best_sim)| sim > best_sim) {
best_match = Some((*uuid, sim));
}
}
}
if let Some((matched_uuid, sim)) = best_match {
tracing::debug!(
"Concept merge: '{}' matched existing entity {} (cosine={:.3})",
entity.name,
matched_uuid,
sim
);
existing_uuid = Some(matched_uuid);
}
}
}
let is_new_entity;
if let Some(uuid) = existing_uuid {
// BUG-002 FIX: Verify entity actually exists in DB (handles stale index)
if let Some(existing) = self.get_entity(&uuid)? {
// Update existing entity — merge into canonical node
entity.uuid = uuid;
entity.mention_count = existing.mention_count + 1;
entity.last_seen_at = Utc::now();
entity.created_at = existing.created_at;
entity.is_proper_noun = existing.is_proper_noun || entity.is_proper_noun;
// Preserve the canonical name (first-seen name wins)
entity.name = existing.name.clone();
// Merge labels: preserve all observed entity types
for label in &existing.labels {
if !entity.labels.contains(label) {
entity.labels.push(label.clone());
}
}
// Preserve existing embedding if the incoming one is None
if entity.name_embedding.is_none() {
entity.name_embedding = existing.name_embedding;
}
// Update salience with frequency boost
// Formula: salience = base_salience * (1 + 0.1 * ln(mention_count))
// This caps at about 1.3x boost at 20 mentions
let frequency_boost = 1.0 + 0.1 * (entity.mention_count as f32).ln();
entity.salience = (existing.salience * frequency_boost).min(1.0);
is_new_entity = false;
} else {
// BUG-002 FIX: Stale index entry - entity in index but not in DB
tracing::warn!(
"Stale index entry for entity '{}' (uuid={}), recreating",
entity.name,
uuid
);
entity.uuid = Uuid::new_v4();
entity.created_at = Utc::now();
entity.last_seen_at = entity.created_at;
entity.mention_count = 1;
is_new_entity = true;
}
} else {
// Genuinely new entity — no match at any tier
entity.uuid = Uuid::new_v4();
entity.created_at = Utc::now();
entity.last_seen_at = entity.created_at;
entity.mention_count = 1;
is_new_entity = true;
}
// BUG-002 FIX: Write index FIRST, then entity
let lowercase_name = entity.name.to_lowercase();
let stemmer = Stemmer::create(Algorithm::English);
let stemmed_name = Self::stem_entity_name(&stemmer, &entity.name);
// Update in-memory indices
{
let mut index = self.entity_name_index.write();
index.insert(entity.name.clone(), entity.uuid);
}
{
let mut lowercase_index = self.entity_lowercase_index.write();
lowercase_index.insert(lowercase_name.clone(), entity.uuid);
}
// Skip stemmed index for proper nouns to prevent "Paris" → "pari" collisions
if !entity.is_proper_noun {
let mut stemmed_index = self.entity_stemmed_index.write();
stemmed_index.insert(stemmed_name.clone(), entity.uuid);
}
// Update entity embedding cache for future concept merges
if let Some(ref emb) = entity.name_embedding {
let mut cache = self.entity_embedding_cache.write();
if is_new_entity {
cache.push((entity.uuid, emb.clone()));
// Evict oldest entries when cache exceeds the configured maximum.
// Oldest entries (index 0) are typically the least recently mentioned
// since they were loaded at startup or added earliest.
if cache.len() > ENTITY_EMBEDDING_CACHE_MAX {
let excess = cache.len() - ENTITY_EMBEDDING_CACHE_MAX;
cache.drain(..excess);
}
} else {
// Update existing entry in cache (embedding may have changed)
if let Some(entry) = cache.iter_mut().find(|(uuid, _)| *uuid == entity.uuid) {
entry.1 = emb.clone();
}
}
}
// Persist name->UUID mappings
self.db.put_cf(
self.name_index_cf(),
entity.name.as_bytes(),
entity.uuid.as_bytes(),
)?;
self.db.put_cf(
self.lowercase_index_cf(),
lowercase_name.as_bytes(),
entity.uuid.as_bytes(),
)?;
if !entity.is_proper_noun {
self.db.put_cf(
self.stemmed_index_cf(),
stemmed_name.as_bytes(),
entity.uuid.as_bytes(),
)?;
}
// Store entity in database
let key = entity.uuid.as_bytes();
let value = crate::serialization::encode(&entity)?;
self.db.put_cf(self.entities_cf(), key, value)?;
// Increment counter only for truly new entities
if is_new_entity {
self.entity_count.fetch_add(1, Ordering::Relaxed);
}
Ok(entity.uuid)
}
/// Get entity by UUID
pub fn get_entity(&self, uuid: &Uuid) -> Result<Option<EntityNode>> {
let key = uuid.as_bytes();
match self.db.get_cf(self.entities_cf(), key)? {
Some(value) => {
let (entity, _) = crate::serialization::try_decode::<EntityNode>(&value)?;
Ok(Some(entity))
}
None => Ok(None),
}
}
/// Delete an entity and all its index entries.
///
/// Removes the entity from:
/// 1. `entities` CF (primary storage)
/// 2. `entity_name_index` (exact name → UUID)
/// 3. `entity_lowercase_index` (lowercase name → UUID)
/// 4. `entity_stemmed_index` (stemmed name → UUID)
/// 5. `entity_embedding_cache` (in-memory embedding vector)
/// 6. `entity_pair_index` CF (co-occurrence pair entries)
/// 7. Decrements `entity_count`
///
/// Returns true if the entity existed and was deleted.
pub fn delete_entity(&self, uuid: &Uuid) -> Result<bool> {
let entity = match self.get_entity(uuid)? {
Some(e) => e,
None => return Ok(false),
};
// 1. Remove from entities CF
self.db.delete_cf(self.entities_cf(), uuid.as_bytes())?;
// 2-3-4. Remove from name indices (in-memory + persisted)
let lowercase_name = entity.name.to_lowercase();
let stemmer = Stemmer::create(Algorithm::English);
let stemmed_name = Self::stem_entity_name(&stemmer, &entity.name);
{
let mut index = self.entity_name_index.write();
index.remove(&entity.name);
}
self.db
.delete_cf(self.name_index_cf(), entity.name.as_bytes())?;
{
let mut index = self.entity_lowercase_index.write();
index.remove(&lowercase_name);
}
self.db
.delete_cf(self.lowercase_index_cf(), lowercase_name.as_bytes())?;
{
let mut index = self.entity_stemmed_index.write();
index.remove(&stemmed_name);
}
self.db
.delete_cf(self.stemmed_index_cf(), stemmed_name.as_bytes())?;
// 5. Remove from embedding cache
{
let mut cache = self.entity_embedding_cache.write();
cache.retain(|(id, _)| id != uuid);
}
// 6. Remove entity_pair_index entries (prefix scan)
let prefix = format!("{}:", uuid);
let mut pairs_to_delete = Vec::new();
let iter = self
.db
.prefix_iterator_cf(self.entity_pair_index_cf(), prefix.as_bytes());
for item in iter {
match item {
Ok((key, _)) => {
let key_str = String::from_utf8_lossy(&key);
if key_str.starts_with(&prefix) {
pairs_to_delete.push(key.to_vec());
} else {
break;
}
}
Err(_) => break,
}
}
// Also scan for reverse direction (other_uuid:this_uuid)
let suffix = format!(":{}", uuid);
let iter = self
.db
.iterator_cf(self.entity_pair_index_cf(), rocksdb::IteratorMode::Start);
for item in iter {
match item {
Ok((key, _)) => {
let key_str = String::from_utf8_lossy(&key);
if key_str.ends_with(&suffix) {
pairs_to_delete.push(key.to_vec());
}
}
Err(_) => break,
}
}
for key in &pairs_to_delete {
self.db.delete_cf(self.entity_pair_index_cf(), key)?;
}
// 7. Decrement counter
self.entity_count.fetch_sub(1, Ordering::Relaxed);
tracing::debug!("Deleted orphaned entity '{}' (uuid={})", entity.name, uuid);
Ok(true)
}
/// Find entity by name (case-insensitive, O(1) lookup)
///
/// Uses a multi-tier matching strategy:
/// 1. Exact match (O(1)) - fastest
/// 2. Case-insensitive match (O(1)) - common case
/// 3. Stemmed match (O(1)) - "running" matches "run"
/// 4. Substring match - "York" matches "New York City"
/// 5. Word-level match - "York" matches "New York"
pub fn find_entity_by_name(&self, name: &str) -> Result<Option<EntityNode>> {
// Tier 1: Exact match (O(1))
let uuid = {
let index = self.entity_name_index.read();
index.get(name).copied()
};
if let Some(uuid) = uuid {
return self.get_entity(&uuid);
}
// Tier 2: Case-insensitive match (O(1))
let name_lower = name.to_lowercase();
let uuid = {
let lowercase_index = self.entity_lowercase_index.read();
lowercase_index.get(&name_lower).copied()
};
if let Some(uuid) = uuid {
return self.get_entity(&uuid);
}
// Tier 3: Stemmed match (O(1)) - "running" matches "run", "conversations" matches "conversation"
let stemmer = Stemmer::create(Algorithm::English);
let stemmed_name = Self::stem_entity_name(&stemmer, name);
let uuid = {
let stemmed_index = self.entity_stemmed_index.read();
stemmed_index.get(&stemmed_name).copied()
};
if let Some(uuid) = uuid {
return self.get_entity(&uuid);
}
// Tier 4 & 5: Fuzzy matching (O(n) but bounded)
// Only do fuzzy matching for names >= 3 chars to avoid noise
// Deterministic: collect ALL matches, pick highest salience (break ties by shortest name)
if name.len() >= 3 {
let lowercase_index = self.entity_lowercase_index.read();
let mut candidates: Vec<(Uuid, String)> = Vec::new();
// Tier 4: Substring match - query is substring of entity
// e.g., "York" matches "New York City"
for (entity_name, uuid) in lowercase_index.iter() {
if entity_name.contains(&name_lower) {
candidates.push((*uuid, entity_name.clone()));
}
}
// Tier 5: Word-level match (only if Tier 4 found nothing)
if candidates.is_empty() {
let query_words: Vec<&str> = name_lower.split_whitespace().collect();
for (entity_name, uuid) in lowercase_index.iter() {
let entity_words: Vec<&str> = entity_name.split_whitespace().collect();
for qw in &query_words {
if entity_words.iter().any(|ew| ew == qw || ew.starts_with(qw)) {
candidates.push((*uuid, entity_name.clone()));
break;
}
}
}
}
// Pick best candidate: highest salience, then shortest name for ties
if !candidates.is_empty() {
let mut best: Option<(Uuid, f32, usize)> = None; // (uuid, salience, name_len)
for (uuid, name) in &candidates {
let salience = self.get_entity(uuid)?.map(|e| e.salience).unwrap_or(0.0);
match &best {
Some((_, best_sal, best_len))
if salience > *best_sal
|| (salience == *best_sal && name.len() < *best_len) =>
{
best = Some((*uuid, salience, name.len()));
}
None => {
best = Some((*uuid, salience, name.len()));
}
_ => {}
}
}
if let Some((uuid, _, _)) = best {
return self.get_entity(&uuid);
}
}
}
Ok(None)
}
/// Lightweight quality metrics for an existing entity in the graph.
/// Used by NER filtering to suppress known stop-word entities.
pub fn get_entity_reputation(&self, name: &str) -> Option<EntityReputation> {
// O(1) lookup via lowercase index
let uuid = {
let index = self.entity_lowercase_index.read();
index.get(&name.to_lowercase()).copied()
}?;
let entity = self.get_entity(&uuid).ok()??;
let degree = self.entity_edge_count(&uuid).unwrap_or(0);
Some(EntityReputation {
selectivity: entity.selectivity.unwrap_or(1.0), // Conservative default
mention_count: entity.mention_count,
degree,
salience: entity.salience,
})
}
/// Find all entities matching a name with fuzzy matching
///
/// Returns multiple matches ranked by match quality.
/// Useful for spreading activation across related entities.
pub fn find_entities_fuzzy(&self, name: &str, max_results: usize) -> Result<Vec<EntityNode>> {
let mut results = Vec::new();
let name_lower = name.to_lowercase();
// Skip very short queries
if name.len() < 2 {
return Ok(results);
}
let lowercase_index = self.entity_lowercase_index.read();
// Score and collect matches
let mut scored: Vec<(Uuid, f32)> = Vec::new();
for (entity_name, uuid) in lowercase_index.iter() {
let score = if entity_name == &name_lower {
1.0 // Exact match
} else if entity_name.starts_with(&name_lower) {
0.9 // Prefix match
} else if entity_name.contains(&name_lower) {
0.7 // Substring match
} else {
// Word-level match
let entity_words: Vec<&str> = entity_name.split_whitespace().collect();
let query_words: Vec<&str> = name_lower.split_whitespace().collect();
let mut word_score: f32 = 0.0;
for qw in &query_words {
for ew in &entity_words {
if ew == qw {
word_score += 0.5;
} else if ew.starts_with(qw) {
word_score += 0.3;
}
}
}
word_score.min(0.6) // Cap word-level score
};
if score > 0.0 {
scored.push((*uuid, score));
}
}
// Sort by score descending
scored.sort_by(|a, b| b.1.total_cmp(&a.1));
// Take top results
for (uuid, _score) in scored.into_iter().take(max_results) {
if let Some(entity) = self.get_entity(&uuid)? {
results.push(entity);
}
}
Ok(results)
}
/// Canonical pair key for the entity-pair index.
/// Uses min/max UUID ordering so A→B and B→A produce the same key.
fn pair_key(entity_a: &Uuid, entity_b: &Uuid) -> String {
if entity_a < entity_b {
format!("{entity_a}:{entity_b}")
} else {
format!("{entity_b}:{entity_a}")
}
}
/// Index an entity pair → edge UUID for O(1) dedup lookups
fn index_entity_pair(&self, entity_a: &Uuid, entity_b: &Uuid, edge_uuid: &Uuid) -> Result<()> {
let key = Self::pair_key(entity_a, entity_b);
self.db.put_cf(
self.entity_pair_index_cf(),
key.as_bytes(),
edge_uuid.as_bytes(),
)?;
Ok(())
}
/// Remove entity pair from the pair index
fn remove_entity_pair_index(&self, entity_a: &Uuid, entity_b: &Uuid) -> Result<()> {
let key = Self::pair_key(entity_a, entity_b);
self.db
.delete_cf(self.entity_pair_index_cf(), key.as_bytes())?;
Ok(())
}
/// Find existing relationship between two entities (either direction)
///
/// O(1) lookup via entity-pair index, with fallback to linear scan
/// for edges created before the pair index existed (migration path).
pub fn find_relationship_between(
&self,
entity_a: &Uuid,
entity_b: &Uuid,
) -> Result<Option<RelationshipEdge>> {
// Fast path: O(1) pair index lookup
let key = Self::pair_key(entity_a, entity_b);
if let Some(edge_uuid_bytes) = self
.db
.get_cf(self.entity_pair_index_cf(), key.as_bytes())?
{
if edge_uuid_bytes.len() == 16 {
let edge_uuid = Uuid::from_slice(&edge_uuid_bytes)?;
if let Some(edge) = self.get_relationship(&edge_uuid)? {
return Ok(Some(edge));
}
// Edge was deleted but pair index is stale — clean up and fall through
let _ = self
.db
.delete_cf(self.entity_pair_index_cf(), key.as_bytes());
}
}
// Slow path: linear scan for pre-index edges (backward compatibility)
// This path is only hit for edges created before the pair index existed.
// Once all old edges are either strengthened (which updates the index) or
// pruned, this path becomes dead code.
let edges_a = self.get_entity_relationships(entity_a)?;
for edge in edges_a {
if (edge.from_entity == *entity_a && edge.to_entity == *entity_b)
|| (edge.from_entity == *entity_b && edge.to_entity == *entity_a)
{
// Backfill pair index for this legacy edge
let _ = self.index_entity_pair(entity_a, entity_b, &edge.uuid);
return Ok(Some(edge));
}
}
Ok(None)
}
/// Find existing relationship between two entities with a specific relation type.
///
/// Unlike `find_relationship_between` which returns any edge between the pair,
/// this method only matches edges with the same `RelationType`. This allows
/// multiple semantically distinct edges (e.g. WorksWith + PartOf) between
/// the same entity pair.
pub fn find_relationship_between_typed(
&self,
entity_a: &Uuid,
entity_b: &Uuid,
relation_type: &RelationType,
) -> Result<Option<RelationshipEdge>> {
let edges = self.get_entity_relationships(entity_a)?;
for edge in edges {
if edge.relation_type == *relation_type
&& ((edge.from_entity == *entity_a && edge.to_entity == *entity_b)
|| (edge.from_entity == *entity_b && edge.to_entity == *entity_a))
{
return Ok(Some(edge));
}
}
Ok(None)
}
/// Add a relationship edge (or strengthen existing one)
///
/// If an edge already exists between the two entities, strengthens it
/// instead of creating a duplicate. This implements proper Hebbian learning:
/// "neurons that fire together, wire together" - repeated co-occurrence
/// strengthens the same synapse rather than creating parallel connections.
pub fn add_relationship(&self, mut edge: RelationshipEdge) -> Result<Uuid> {
// Check for existing relationship between these entities WITH SAME TYPE
// Different relation types (e.g. WorksWith vs PartOf) are distinct edges
if let Some(mut existing) = self.find_relationship_between_typed(
&edge.from_entity,
&edge.to_entity,
&edge.relation_type,
)? {
// Strengthen existing edge instead of creating duplicate
let _ = existing.strengthen();
existing.last_activated = Utc::now();
// Update context if new context is more informative
if edge.context.len() > existing.context.len() {
existing.context = edge.context;
}
// Persist the strengthened edge
let key = existing.uuid.as_bytes();
let value = crate::serialization::encode(&existing)?;
self.db.put_cf(self.relationships_cf(), key, value)?;
return Ok(existing.uuid);
}
// No existing edge - create new one
edge.uuid = Uuid::new_v4();
edge.created_at = Utc::now();
// Store relationship
let key = edge.uuid.as_bytes();
let value = crate::serialization::encode(&edge)?;
self.db.put_cf(self.relationships_cf(), key, value)?;
// Increment relationship counter
self.relationship_count.fetch_add(1, Ordering::Relaxed);
// Update entity->edges index for both entities
self.index_entity_edge(&edge.from_entity, &edge.uuid)?;
self.index_entity_edge(&edge.to_entity, &edge.uuid)?;
// Update entity-pair index for O(1) dedup lookups
self.index_entity_pair(&edge.from_entity, &edge.to_entity, &edge.uuid)?;
// Insert-time degree pruning: cap edges per entity to prevent O(n²) explosion.
// If either entity exceeds MAX_ENTITY_DEGREE, prune the weakest edges.
// This is the primary defense against graph bloat (132MB for 600KB of content).
self.prune_entity_if_over_degree(&edge.from_entity)?;
self.prune_entity_if_over_degree(&edge.to_entity)?;
Ok(edge.uuid)
}
/// Index an edge for an entity
fn index_entity_edge(&self, entity_uuid: &Uuid, edge_uuid: &Uuid) -> Result<()> {
let key = format!("{entity_uuid}:{edge_uuid}");
self.db
.put_cf(self.entity_edges_cf(), key.as_bytes(), b"1")?;
Ok(())
}
/// Prune an entity's edges if degree exceeds MAX_ENTITY_DEGREE
///
/// Loads all edges for the entity, sorts by effective strength, and deletes
/// the weakest edges that exceed the cap. LTP-protected edges are preserved
/// preferentially (sorted last, so they survive pruning).
///
/// This is called at insert time to prevent unbounded edge growth.
/// Amortized cost: O(1) for most insertions (only triggers when over cap),
/// O(d log d) when pruning is needed (d = entity degree).
fn prune_entity_if_over_degree(&self, entity_uuid: &Uuid) -> Result<()> {
use crate::constants::MAX_ENTITY_DEGREE;
// Fast path: count edges without loading them
let prefix = format!("{entity_uuid}:");
let iter = self
.db
.prefix_iterator_cf(self.entity_edges_cf(), prefix.as_bytes());
let mut edge_count = 0usize;
for (key, _) in iter.flatten() {
if let Ok(key_str) = std::str::from_utf8(&key) {
if !key_str.starts_with(&prefix) {
break;
}
edge_count += 1;
}
}
if edge_count <= MAX_ENTITY_DEGREE {
return Ok(());
}
// Over cap — load all edges, sort, prune weakest
let all_edges = self.get_entity_relationships(entity_uuid)?;
if all_edges.len() <= MAX_ENTITY_DEGREE {
return Ok(()); // Race condition guard
}
// Sort by pruning priority: LTP-protected edges last (survive pruning),
// then by effective strength descending (strongest survive)
let mut scored: Vec<(Uuid, f32, bool)> = all_edges
.iter()
.map(|e| {
let is_protected = e.is_potentiated();
(e.uuid, e.effective_strength(), is_protected)
})
.collect();
// Sort: unprotected+weak first (pruning candidates), protected+strong last (survivors)
scored.sort_by(|a, b| {
// Protected edges sort after unprotected
match a.2.cmp(&b.2) {
CmpOrdering::Equal => {
// Within same protection class, weaker edges first (prune candidates)
a.1.total_cmp(&b.1)
}
other => other,
}
});
// Prune excess: first N edges in sorted order are weakest/unprotected
let prune_count = scored.len() - MAX_ENTITY_DEGREE;
let to_prune: Vec<Uuid> = scored.iter().take(prune_count).map(|s| s.0).collect();
for edge_uuid in &to_prune {
if let Err(e) = self.delete_relationship(edge_uuid) {
tracing::warn!(
edge = %edge_uuid,
entity = %entity_uuid,
"Failed to prune edge during degree cap: {}",
e
);
}
}
if !to_prune.is_empty() {
tracing::debug!(
entity = %entity_uuid,
pruned = to_prune.len(),
remaining = MAX_ENTITY_DEGREE,
"Pruned edges exceeding degree cap"
);
}
Ok(())
}
/// Get relationships for an entity with optional limit
///
/// Uses batch reading (multi_get) to eliminate N+1 query pattern.
/// If limit is None, returns all edges (use sparingly for large graphs).
pub fn get_entity_relationships(&self, entity_uuid: &Uuid) -> Result<Vec<RelationshipEdge>> {
self.get_entity_relationships_limited(entity_uuid, None)
}
/// Get relationships for an entity with limit, ordered by effective strength
///
/// Collects ALL edge UUIDs first, batch-reads them, sorts by effective_strength
/// descending, then returns the top `limit` strongest edges. This ensures
/// traversal and queries always use the most valuable connections.
///
/// When no limit is specified, returns all edges sorted by strength.
pub fn get_entity_relationships_limited(
&self,
entity_uuid: &Uuid,
limit: Option<usize>,
) -> Result<Vec<RelationshipEdge>> {
let prefix = format!("{entity_uuid}:");
// Phase 1: Collect ALL edge UUIDs from index (fast prefix scan)
// We must read all to sort by strength — storage order is arbitrary
let mut edge_uuids: Vec<Uuid> = Vec::with_capacity(256);
let iter = self
.db
.prefix_iterator_cf(self.entity_edges_cf(), prefix.as_bytes());
for (key, _) in iter.flatten() {
if let Ok(key_str) = std::str::from_utf8(&key) {
if !key_str.starts_with(&prefix) {
break;
}
if let Some(edge_uuid_str) = key_str.split(':').nth(1) {
if let Ok(edge_uuid) = Uuid::parse_str(edge_uuid_str) {
edge_uuids.push(edge_uuid);
}
}
}
}
if edge_uuids.is_empty() {
return Ok(Vec::new());
}
// Phase 2: Batch read all edges using multi_get (single RocksDB call)
let keys: Vec<[u8; 16]> = edge_uuids.iter().map(|u| *u.as_bytes()).collect();
let key_refs: Vec<&[u8]> = keys.iter().map(|k| k.as_slice()).collect();
let results = self
.db
.batched_multi_get_cf(self.relationships_cf(), &key_refs, false);
let mut edges = Vec::with_capacity(edge_uuids.len());
for value in results.into_iter().flatten().flatten() {
if let Ok((edge, _)) = crate::serialization::try_decode::<RelationshipEdge>(&value) {
edges.push(edge);
}
}
// Phase 3: Sort by effective strength descending (strongest first)
// Snapshot strengths BEFORE sorting — effective_strength() calls Utc::now()
// internally, so repeated calls during sort can return different values,
// violating total ordering (Rust 1.81+ panics on this).
let mut strength_cache: HashMap<Uuid, f32> = HashMap::with_capacity(edges.len());
for edge in &edges {
strength_cache.insert(edge.uuid, edge.effective_strength());
}
edges.sort_by(|a, b| {
let sa = strength_cache.get(&a.uuid).copied().unwrap_or(0.0);
let sb = strength_cache.get(&b.uuid).copied().unwrap_or(0.0);
sb.total_cmp(&sa)
});
// Phase 3.5: Opportunistic pruning — queue edges that have decayed below
// their tier's threshold for batch deletion on next maintenance cycle.
// This replaces the eager full-scan apply_decay() with lazy on-read pruning.
let mut has_prunable = false;
for edge in &edges {
if edge.effective_strength() < edge.tier.prune_threshold()
&& !edge.ltp_status.is_potentiated()
{
has_prunable = true;
break;
}
}
if has_prunable {
let mut prune_queue = self.pending_prune.lock();
let mut orphan_queue = self.pending_orphan_checks.lock();
// Prevent unbounded growth — these queues are drained by maintenance,
// but if maintenance hasn't run, cap to avoid increasing lock contention.
if prune_queue.len() > 1000 {
tracing::debug!(
"Prune queue overflow ({}) — clearing to prevent lock contention",
prune_queue.len()
);
prune_queue.clear();
}
if orphan_queue.len() > 2000 {
orphan_queue.clear();
}
edges.retain(|edge| {
if edge.effective_strength() < edge.tier.prune_threshold()
&& !edge.ltp_status.is_potentiated()
{
prune_queue.push(edge.uuid);
orphan_queue.push(edge.from_entity);
orphan_queue.push(edge.to_entity);
false // remove from results
} else {
true
}
});
}
// Phase 4: Truncate to limit if specified
if let Some(max) = limit {
edges.truncate(max);
}
Ok(edges)
}
/// Calculate edge density for a specific entity (SHO-D5)
///
/// Returns the number of edges connected to this entity.
/// Used for per-entity density calculation: dense entities use vector search,
/// sparse entities use graph search.
///
/// This is an O(1) prefix count operation.
pub fn entity_edge_count(&self, entity_uuid: &Uuid) -> Result<usize> {
let prefix = format!("{entity_uuid}:");
let iter = self
.db
.prefix_iterator_cf(self.entity_edges_cf(), prefix.as_bytes());
let mut count = 0;
for (key, _) in iter.flatten() {
if let Ok(key_str) = std::str::from_utf8(&key) {
if !key_str.starts_with(&prefix) {
break;
}
count += 1;
}
}
Ok(count)
}
/// Calculate average edge density for a set of entities (SHO-D5)
///
/// Returns the mean number of edges per entity for the given UUIDs.
/// Used to determine optimal retrieval strategy:
/// - Low density (<5 edges): Trust graph search (sparse, high-signal)
/// - High density (>20 edges): Trust vector search (dense, noisy)
///
/// Returns None if no entities provided.
pub fn entities_average_density(&self, entity_uuids: &[Uuid]) -> Result<Option<f32>> {
if entity_uuids.is_empty() {
return Ok(None);
}
let mut total_edges = 0usize;
for uuid in entity_uuids {
total_edges += self.entity_edge_count(uuid)?;
}
Ok(Some(total_edges as f32 / entity_uuids.len() as f32))
}
/// Calculate edge density per tier for a specific entity (SHO-D5)
///
/// Returns counts of edges by tier: (L1_count, L2_count, L3_count, LTP_count)
/// Useful for understanding if an entity's graph is consolidated (mostly L3/LTP)
/// or still noisy (mostly L1).
pub fn entity_density_by_tier(
&self,
entity_uuid: &Uuid,
) -> Result<(usize, usize, usize, usize)> {
let edges = self.get_entity_relationships(entity_uuid)?;
let mut l1_count = 0;
let mut l2_count = 0;
let mut l3_count = 0;
let mut ltp_count = 0;
for edge in edges {
if edge.is_potentiated() {
ltp_count += 1;
} else {
match edge.tier {
EdgeTier::L1Working => l1_count += 1,
EdgeTier::L2Episodic => l2_count += 1,
EdgeTier::L3Semantic => l3_count += 1,
}
}
}
Ok((l1_count, l2_count, l3_count, ltp_count))
}
/// Calculate consolidated ratio for an entity (SHO-D5)
///
/// Returns the ratio of consolidated edges (L2 + L3 + LTP) to total edges.
/// High ratio (>0.7) = trust graph search, Low ratio (<0.3) = trust vector search.
///
/// Returns None if entity has no edges.
pub fn entity_consolidation_ratio(&self, entity_uuid: &Uuid) -> Result<Option<f32>> {
let (l1, l2, l3, ltp) = self.entity_density_by_tier(entity_uuid)?;
let total = l1 + l2 + l3 + ltp;
if total == 0 {
return Ok(None);
}
let consolidated = l2 + l3 + ltp;
Ok(Some(consolidated as f32 / total as f32))
}
/// Get relationship by UUID (raw, without decay applied)
pub fn get_relationship(&self, uuid: &Uuid) -> Result<Option<RelationshipEdge>> {
let key = uuid.as_bytes();
match self.db.get_cf(self.relationships_cf(), key)? {
Some(value) => {
let (edge, _) = crate::serialization::try_decode::<RelationshipEdge>(&value)?;
Ok(Some(edge))
}
None => Ok(None),
}
}
/// Get relationship by UUID with effective strength (lazy decay calculation)
///
/// Returns the edge with strength reflecting time-based decay.
/// This doesn't persist the decay - just calculates what the strength would be.
/// Use this for API responses to show accurate current strength.
pub fn get_relationship_with_effective_strength(
&self,
uuid: &Uuid,
) -> Result<Option<RelationshipEdge>> {
let key = uuid.as_bytes();
match self.db.get_cf(self.relationships_cf(), key)? {
Some(value) => {
let (mut edge, _) = crate::serialization::try_decode::<RelationshipEdge>(&value)?;
// Apply effective strength calculation (doesn't persist)
edge.strength = edge.effective_strength();
Ok(Some(edge))
}
None => Ok(None),
}
}
/// Delete a relationship by UUID
///
/// Removes the relationship from storage and decrements the counter.
/// Returns true if the relationship was found and deleted.
pub fn delete_relationship(&self, uuid: &Uuid) -> Result<bool> {
let key = uuid.as_bytes();
// Get the edge first to find both entities for index cleanup
let edge = match self.get_relationship(uuid)? {
Some(e) => e,
None => return Ok(false),
};
// Delete from main storage
self.db.delete_cf(self.relationships_cf(), key)?;
self.relationship_count.fetch_sub(1, Ordering::Relaxed);
// Remove from entity_edges index for BOTH entities
// (add_relationship indexes both from_entity and to_entity)
let from_key = format!("{}:{}", edge.from_entity, uuid);
if let Err(e) = self
.db
.delete_cf(self.entity_edges_cf(), from_key.as_bytes())
{
tracing::warn!(edge = %uuid, key = %from_key, error = %e, "Failed to delete from entity_edges index");
}
let to_key = format!("{}:{}", edge.to_entity, uuid);
if let Err(e) = self.db.delete_cf(self.entity_edges_cf(), to_key.as_bytes()) {
tracing::warn!(edge = %uuid, key = %to_key, error = %e, "Failed to delete from entity_edges index");
}
// Remove from entity-pair index
if let Err(e) = self.remove_entity_pair_index(&edge.from_entity, &edge.to_entity) {
tracing::warn!(edge = %uuid, "Failed to delete from entity_pair index: {}", e);
}
Ok(true)
}
/// Delete an episode and clean up associated indices and orphan edges
///
/// When a memory is deleted, its corresponding episode should also be removed.
/// This method:
/// 1. Removes the episode from the episodes DB
/// 2. Removes entity_episodes index entries
/// 3. Deletes relationship edges that were sourced from this episode
pub fn delete_episode(&self, episode_uuid: &Uuid) -> Result<bool> {
// Fetch episode to get entity_refs for index cleanup
let episode = match self.get_episode(episode_uuid)? {
Some(ep) => ep,
None => return Ok(false),
};
// Delete episode from main storage
self.db
.delete_cf(self.episodes_cf(), episode_uuid.as_bytes())?;
self.episode_count.fetch_sub(1, Ordering::Relaxed);
// Remove from entity_episodes inverted index
for entity_uuid in &episode.entity_refs {
let key = format!("{entity_uuid}:{episode_uuid}");
if let Err(e) = self.db.delete_cf(self.entity_episodes_cf(), key.as_bytes()) {
tracing::warn!(episode = %episode_uuid, key = %key, error = %e, "Failed to delete from entity_episodes index");
}
}
// Delete edges sourced from this episode
// Scan all relationships for matching source_episode_id
let iter = self
.db
.iterator_cf(self.relationships_cf(), rocksdb::IteratorMode::Start);
let mut edges_to_delete = Vec::new();
for (_, value) in iter.flatten() {
if let Ok((edge, _)) = crate::serialization::try_decode::<RelationshipEdge>(&value) {
if edge.source_episode_id == Some(*episode_uuid) {
edges_to_delete.push(edge.uuid);
}
}
}
for edge_uuid in &edges_to_delete {
if let Err(e) = self.delete_relationship(edge_uuid) {
tracing::debug!("Failed to delete orphan edge {}: {}", edge_uuid, e);
}
}
tracing::debug!(
"Deleted episode {} with {} entity_refs and {} sourced edges",
&episode_uuid.to_string()[..8],
episode.entity_refs.len(),
edges_to_delete.len()
);
Ok(true)
}
/// Clear all graph data (GDPR full erasure)
///
/// Wipes all entities, relationships, episodes, and all indices.
/// Resets all counters to zero.
/// Returns (entity_count, relationship_count, episode_count) that were cleared.
pub fn clear_all(&self) -> Result<(usize, usize, usize)> {
let entity_count = self.entity_count.load(Ordering::Relaxed);
let relationship_count = self.relationship_count.load(Ordering::Relaxed);
let episode_count = self.episode_count.load(Ordering::Relaxed);
// Clear each column family by iterating and batch-deleting
for cf_name in GRAPH_CF_NAMES {
let cf = self
.db
.cf_handle(cf_name)
.ok_or_else(|| anyhow::anyhow!("CF '{}' not found during clear_all", cf_name))?;
let mut batch = rocksdb::WriteBatch::default();
let iter = self.db.iterator_cf(cf, rocksdb::IteratorMode::Start);
for (key, _) in iter.flatten() {
batch.delete_cf(cf, &key);
}
self.db.write(batch)?;
}
// Clear in-memory indices
self.entity_name_index.write().clear();
self.entity_lowercase_index.write().clear();
self.entity_stemmed_index.write().clear();
// Reset counters
self.entity_count.store(0, Ordering::Relaxed);
self.relationship_count.store(0, Ordering::Relaxed);
self.episode_count.store(0, Ordering::Relaxed);
// Drain pending maintenance queues — they reference now-deleted entities/edges
let _ = std::mem::take(&mut *self.pending_prune.lock());
let _ = std::mem::take(&mut *self.pending_orphan_checks.lock());
tracing::info!(
"Graph data cleared (GDPR erasure): {} entities, {} relationships, {} episodes",
entity_count,
relationship_count,
episode_count
);
Ok((entity_count, relationship_count, episode_count))
}
/// Add an episodic node
pub fn add_episode(&self, episode: EpisodicNode) -> Result<Uuid> {
let key = episode.uuid.as_bytes();
let entity_count = episode.entity_refs.len();
tracing::debug!(
"add_episode: {} with {} entity_refs",
&episode.uuid.to_string()[..8],
entity_count
);
let value = crate::serialization::encode(&episode)?;
let already_existed = self.db.get_cf(self.episodes_cf(), key)?.is_some();
self.db.put_cf(self.episodes_cf(), key, value)?;
// Only increment counter for genuinely new episodes (not overwrites from retries)
if !already_existed {
let prev = self.episode_count.fetch_add(1, Ordering::Relaxed);
tracing::debug!("add_episode: count {} -> {}", prev, prev + 1);
}
// Update inverted index: entity_uuid -> episode_uuid
for entity_uuid in &episode.entity_refs {
self.index_entity_episode(entity_uuid, &episode.uuid)?;
}
Ok(episode.uuid)
}
/// Index an episode for an entity (inverted index)
fn index_entity_episode(&self, entity_uuid: &Uuid, episode_uuid: &Uuid) -> Result<()> {
let key = format!("{entity_uuid}:{episode_uuid}");
self.db
.put_cf(self.entity_episodes_cf(), key.as_bytes(), b"1")?;
Ok(())
}
/// Get episode by UUID
pub fn get_episode(&self, uuid: &Uuid) -> Result<Option<EpisodicNode>> {
let key = uuid.as_bytes();
match self.db.get_cf(self.episodes_cf(), key)? {
Some(value) => {
let (episode, _) = crate::serialization::try_decode::<EpisodicNode>(&value)?;
Ok(Some(episode))
}
None => Ok(None),
}
}
/// Get all episodes that contain a specific entity
///
/// Uses inverted index for O(k) lookup instead of O(n) full scan.
/// Collects episode UUIDs first, then batch-reads them using multi_get.
/// Crucial for spreading activation algorithm.
pub fn get_episodes_by_entity(&self, entity_uuid: &Uuid) -> Result<Vec<EpisodicNode>> {
let prefix = format!("{entity_uuid}:");
tracing::debug!("get_episodes_by_entity: prefix {}", &prefix[..12]);
// Phase 1: Collect episode UUIDs from index (fast prefix scan, no data transfer)
let mut episode_uuids: Vec<Uuid> = Vec::new();
let iter = self
.db
.prefix_iterator_cf(self.entity_episodes_cf(), prefix.as_bytes());
for (key, _) in iter.flatten() {
if let Ok(key_str) = std::str::from_utf8(&key) {
if !key_str.starts_with(&prefix) {
break;
}
if let Some(episode_uuid_str) = key_str.split(':').nth(1) {
if let Ok(episode_uuid) = Uuid::parse_str(episode_uuid_str) {
episode_uuids.push(episode_uuid);
}
}
}
}
if episode_uuids.is_empty() {
return Ok(Vec::new());
}
// Phase 2: Batch read all episodes using multi_get (single RocksDB call)
let keys: Vec<[u8; 16]> = episode_uuids.iter().map(|u| *u.as_bytes()).collect();
let key_refs: Vec<&[u8]> = keys.iter().map(|k| k.as_slice()).collect();
let results = self
.db
.batched_multi_get_cf(self.episodes_cf(), &key_refs, false);
let mut episodes = Vec::with_capacity(episode_uuids.len());
for value in results.into_iter().flatten().flatten() {
if let Ok((episode, _)) = crate::serialization::try_decode::<EpisodicNode>(&value) {
episodes.push(episode);
}
}
tracing::debug!("get_episodes_by_entity: found {} episodes", episodes.len());
Ok(episodes)
}
/// Traverse graph starting from an entity (breadth-first)
///
/// Implements Hebbian learning: edges traversed during retrieval are strengthened.
/// This means frequently accessed pathways become stronger over time.
///
/// Returns `TraversedEntity` with hop distance and decay factor for proper scoring:
/// - hop 0 (start entity): decay = 1.0
/// - hop 1: decay = 0.7
/// - hop 2: decay = 0.49
/// - etc.
///
/// Performance: Uses batch edge reading and limits to handle large graphs.
pub fn traverse_from_entity(
&self,
start_uuid: &Uuid,
max_depth: usize,
) -> Result<GraphTraversal> {
self.traverse_from_entity_filtered(start_uuid, max_depth, None)
}
/// BFS graph traversal with optional minimum edge strength filter.
///
/// When `min_strength` is Some, edges below the threshold are skipped
/// during traversal and NOT Hebbianly strengthened (prevents ghost edge revival).
pub fn traverse_from_entity_filtered(
&self,
start_uuid: &Uuid,
max_depth: usize,
min_strength: Option<f32>,
) -> Result<GraphTraversal> {
// Performance limits
const MAX_ENTITIES: usize = 200;
const MAX_EDGES_PER_NODE: usize = 100;
// Use tuned decay from constants (0.15 max decay → ~86% retention per hop)
// This enables deeper traversal than the old 0.7 factor
use crate::constants::IMPORTANCE_DECAY_MAX;
let hop_decay_factor: f32 = (-IMPORTANCE_DECAY_MAX).exp(); // e^(-0.15) ≈ 0.86
let mut visited_entities = HashSet::new();
let mut visited_edges = HashSet::new();
let mut current_level: Vec<(Uuid, usize)> = vec![(*start_uuid, 0)]; // (uuid, hop_distance)
let mut all_entities: Vec<TraversedEntity> = Vec::new();
let mut all_edges = Vec::new();
let mut edges_to_strengthen = Vec::new();
visited_entities.insert(*start_uuid);
if let Some(entity) = self.get_entity(start_uuid)? {
all_entities.push(TraversedEntity {
entity,
hop_distance: 0,
decay_factor: 1.0,
});
}
for depth in 0..max_depth {
// Early termination if we have enough entities
if all_entities.len() >= MAX_ENTITIES {
break;
}
let mut next_level = Vec::new();
for (entity_uuid, _hop) in ¤t_level {
// Use limited edge reading
let edges =
self.get_entity_relationships_limited(entity_uuid, Some(MAX_EDGES_PER_NODE))?;
for edge in edges {
if visited_edges.contains(&edge.uuid) {
continue;
}
visited_edges.insert(edge.uuid);
// Only traverse non-invalidated edges
if edge.invalidated_at.is_some() {
continue;
}
// Compute effective strength (lazy decay calculation)
let effective = edge.effective_strength();
// Skip weak edges if min_strength filter is set
if let Some(threshold) = min_strength {
if effective < threshold {
continue;
}
}
// Collect edge UUID for Hebbian strengthening (only for traversed edges)
edges_to_strengthen.push(edge.uuid);
// Return edge with effective strength
let mut edge_with_decay = edge.clone();
edge_with_decay.strength = effective;
all_edges.push(edge_with_decay);
// Add connected entity
let connected_uuid = if edge.from_entity == *entity_uuid {
edge.to_entity
} else {
edge.from_entity
};
if !visited_entities.contains(&connected_uuid) {
visited_entities.insert(connected_uuid);
let next_hop = depth + 1;
let decay = hop_decay_factor.powi(next_hop as i32);
if let Some(entity) = self.get_entity(&connected_uuid)? {
all_entities.push(TraversedEntity {
entity,
hop_distance: next_hop,
decay_factor: decay,
});
}
next_level.push((connected_uuid, next_hop));
}
}
}
if next_level.is_empty() {
break;
}
current_level = next_level;
}
// Apply Hebbian strengthening to all traversed edges atomically (SHO-65)
// "Neurons that fire together, wire together"
// Uses batch update for efficiency instead of individual writes
if !edges_to_strengthen.is_empty() {
match self.batch_strengthen_synapses(&edges_to_strengthen) {
Ok(count) => {
if count > 0 {
tracing::trace!("Strengthened {} synapses during traversal", count);
}
}
Err(e) => {
tracing::debug!("Failed to batch strengthen synapses: {}", e);
}
}
}
Ok(GraphTraversal {
entities: all_entities,
relationships: all_edges,
})
}
/// Weighted graph traversal with filtering (Dijkstra-style best-first)
///
/// Unlike BFS traverse_from_entity, this uses edge weights to prioritize
/// stronger connections. Enables Cypher-like pattern matching:
/// - Filter by relationship types
/// - Filter by minimum edge strength
/// - Score paths by cumulative weight
///
/// Returns entities sorted by path score (strongest connections first).
///
/// Performance: Uses batch edge reading and early termination to handle
/// large graphs (10000+ edges) efficiently.
pub fn traverse_weighted(
&self,
start_uuid: &Uuid,
max_depth: usize,
relation_types: Option<&[RelationType]>,
min_strength: f32,
) -> Result<GraphTraversal> {
// Performance limits - prevents exponential blowup on dense graphs
const MAX_ENTITIES: usize = 200; // Stop after finding this many entities
const MAX_EDGES_PER_NODE: usize = 100; // Limit edges loaded per node
const MAX_ITERATIONS: usize = 500; // Prevent infinite loops
// Priority queue entry: (negative score for max-heap, uuid, depth, path_score)
#[derive(Clone)]
struct PQEntry {
score: f32,
uuid: Uuid,
depth: usize,
}
impl PartialEq for PQEntry {
fn eq(&self, other: &Self) -> bool {
self.score == other.score
}
}
impl Eq for PQEntry {}
impl PartialOrd for PQEntry {
fn partial_cmp(&self, other: &Self) -> Option<CmpOrdering> {
Some(self.cmp(other))
}
}
impl Ord for PQEntry {
fn cmp(&self, other: &Self) -> CmpOrdering {
// BinaryHeap is a max-heap: higher score = popped first = explored first
self.score.total_cmp(&other.score)
}
}
let mut visited: HashMap<Uuid, f32> = HashMap::new(); // uuid -> best path score
let mut heap: BinaryHeap<PQEntry> = BinaryHeap::new();
let mut all_entities: Vec<TraversedEntity> = Vec::new();
let mut all_edges: Vec<RelationshipEdge> = Vec::new();
let mut edges_to_strengthen: Vec<Uuid> = Vec::new();
let mut iterations = 0;
// Start node
heap.push(PQEntry {
score: 1.0,
uuid: *start_uuid,
depth: 0,
});
visited.insert(*start_uuid, 1.0);
if let Some(entity) = self.get_entity(start_uuid)? {
all_entities.push(TraversedEntity {
entity,
hop_distance: 0,
decay_factor: 1.0,
});
}
while let Some(PQEntry { score, uuid, depth }) = heap.pop() {
iterations += 1;
// Early termination: entity/iteration limits reached, stop draining heap
if all_entities.len() >= MAX_ENTITIES || iterations >= MAX_ITERATIONS {
break;
}
// Depth limit: skip this node's children but keep processing others
if depth >= max_depth {
continue;
}
// Skip if we've found a better path to this node
if let Some(&best) = visited.get(&uuid) {
if score < best * 0.99 {
continue;
}
}
// Use limited edge reading to avoid loading 10000+ edges
let edges = self.get_entity_relationships_limited(&uuid, Some(MAX_EDGES_PER_NODE))?;
for edge in edges {
// Skip invalidated edges
if edge.invalidated_at.is_some() {
continue;
}
// Filter by relationship type if specified
if let Some(types) = relation_types {
if !types.contains(&edge.relation_type) {
continue;
}
}
// Filter by minimum strength
let effective = edge.effective_strength();
if effective < min_strength {
continue;
}
let connected_uuid = if edge.from_entity == uuid {
edge.to_entity
} else {
edge.from_entity
};
// Path score = parent_score * edge_strength (multiplicative decay)
let new_score = score * effective;
// Only visit if this is a better path
let dominated = visited
.get(&connected_uuid)
.is_some_and(|&best| new_score <= best);
if dominated {
continue;
}
// Track edge for Hebbian strengthening AFTER domination check
// so only edges on optimal paths are strengthened
edges_to_strengthen.push(edge.uuid);
let is_new_entity = !visited.contains_key(&connected_uuid);
visited.insert(connected_uuid, new_score);
// Add edge to results
let mut edge_with_strength = edge.clone();
edge_with_strength.strength = effective;
all_edges.push(edge_with_strength);
// Only add entity once (first discovery); better-path rediscovery
// updates visited score but doesn't duplicate the entity in results
if is_new_entity {
if let Some(entity) = self.get_entity(&connected_uuid)? {
all_entities.push(TraversedEntity {
entity,
hop_distance: depth + 1,
decay_factor: new_score,
});
}
}
heap.push(PQEntry {
score: new_score,
uuid: connected_uuid,
depth: depth + 1,
});
}
}
// Sort entities by path score (decay_factor) descending
all_entities.sort_by(|a, b| b.decay_factor.total_cmp(&a.decay_factor));
// Hebbian strengthening (deduplicate: same edge may appear on multiple paths)
edges_to_strengthen.sort();
edges_to_strengthen.dedup();
if !edges_to_strengthen.is_empty() {
if let Err(e) = self.batch_strengthen_synapses(&edges_to_strengthen) {
tracing::debug!("Failed to strengthen synapses: {}", e);
}
}
tracing::debug!(
"traverse_weighted: {} entities, {} edges (min_strength={:.2})",
all_entities.len(),
all_edges.len(),
min_strength
);
Ok(GraphTraversal {
entities: all_entities,
relationships: all_edges,
})
}
/// Bidirectional search between two entities (meet-in-middle)
///
/// Complexity: O(b^(d/2)) instead of O(b^d) for unidirectional search.
/// Finds the shortest weighted path between start and goal.
/// Returns entities along the path with their path scores.
///
/// Performance: Uses batch edge reading with limits.
pub fn traverse_bidirectional(
&self,
start_uuid: &Uuid,
goal_uuid: &Uuid,
max_depth: usize,
min_strength: f32,
) -> Result<GraphTraversal> {
const MAX_EDGES_PER_NODE: usize = 100;
// Track forward search from start
let mut forward_visited: HashMap<Uuid, (f32, usize)> = HashMap::new(); // uuid -> (score, depth)
let mut forward_parents: HashMap<Uuid, (Uuid, Uuid)> = HashMap::new(); // child -> (parent, edge_uuid)
let mut forward_frontier: Vec<(Uuid, f32, usize)> = vec![(*start_uuid, 1.0, 0)];
forward_visited.insert(*start_uuid, (1.0, 0));
// Track backward search from goal
let mut backward_visited: HashMap<Uuid, (f32, usize)> = HashMap::new();
let mut backward_parents: HashMap<Uuid, (Uuid, Uuid)> = HashMap::new();
let mut backward_frontier: Vec<(Uuid, f32, usize)> = vec![(*goal_uuid, 1.0, 0)];
backward_visited.insert(*goal_uuid, (1.0, 0));
let mut meeting_node: Option<Uuid> = None;
let mut best_path_score: f32 = 0.0;
let half_depth = max_depth / 2 + 1;
// Alternate forward and backward expansion
for _round in 0..half_depth {
// Expand forward frontier
let mut new_forward: Vec<(Uuid, f32, usize)> = Vec::new();
for (uuid, score, depth) in forward_frontier.drain(..) {
if depth >= half_depth {
continue;
}
let edges =
self.get_entity_relationships_limited(&uuid, Some(MAX_EDGES_PER_NODE))?;
for edge in edges {
if edge.invalidated_at.is_some() {
continue;
}
let effective = edge.effective_strength();
if effective < min_strength {
continue;
}
let connected = if edge.from_entity == uuid {
edge.to_entity
} else {
edge.from_entity
};
let new_score = score * effective;
// Check if we meet backward search
if let Some(&(back_score, _)) = backward_visited.get(&connected) {
let combined = new_score * back_score;
if combined > best_path_score {
best_path_score = combined;
meeting_node = Some(connected);
}
}
// Update forward frontier
let dominated = forward_visited
.get(&connected)
.is_some_and(|&(best, _)| new_score <= best);
if !dominated {
forward_visited.insert(connected, (new_score, depth + 1));
forward_parents.insert(connected, (uuid, edge.uuid));
new_forward.push((connected, new_score, depth + 1));
}
}
}
forward_frontier = new_forward;
// Expand backward frontier
let mut new_backward: Vec<(Uuid, f32, usize)> = Vec::new();
for (uuid, score, depth) in backward_frontier.drain(..) {
if depth >= half_depth {
continue;
}
let edges =
self.get_entity_relationships_limited(&uuid, Some(MAX_EDGES_PER_NODE))?;
for edge in edges {
if edge.invalidated_at.is_some() {
continue;
}
let effective = edge.effective_strength();
if effective < min_strength {
continue;
}
let connected = if edge.from_entity == uuid {
edge.to_entity
} else {
edge.from_entity
};
let new_score = score * effective;
// Check if we meet forward search
if let Some(&(fwd_score, _)) = forward_visited.get(&connected) {
let combined = fwd_score * new_score;
if combined > best_path_score {
best_path_score = combined;
meeting_node = Some(connected);
}
}
// Update backward frontier
let dominated = backward_visited
.get(&connected)
.is_some_and(|&(best, _)| new_score <= best);
if !dominated {
backward_visited.insert(connected, (new_score, depth + 1));
backward_parents.insert(connected, (uuid, edge.uuid));
new_backward.push((connected, new_score, depth + 1));
}
}
}
backward_frontier = new_backward;
// Early termination if we found a meeting point
if meeting_node.is_some() {
break;
}
}
// Reconstruct path from meeting node
let mut all_entities: Vec<TraversedEntity> = Vec::new();
let mut all_edges: Vec<RelationshipEdge> = Vec::new();
let mut edges_to_strengthen: Vec<Uuid> = Vec::new();
if let Some(meeting) = meeting_node {
// Forward path: start -> meeting
let mut path_forward: Vec<Uuid> = vec![meeting];
let mut current = meeting;
while let Some(&(parent, edge_uuid)) = forward_parents.get(¤t) {
path_forward.push(parent);
edges_to_strengthen.push(edge_uuid);
if let Some(edge) = self.get_relationship(&edge_uuid)? {
all_edges.push(edge);
}
current = parent;
}
path_forward.reverse();
// Backward path: meeting -> goal
let mut path_backward: Vec<Uuid> = Vec::new();
current = meeting;
while let Some(&(parent, edge_uuid)) = backward_parents.get(¤t) {
path_backward.push(parent);
edges_to_strengthen.push(edge_uuid);
if let Some(edge) = self.get_relationship(&edge_uuid)? {
all_edges.push(edge);
}
current = parent;
}
// Combine paths
let full_path: Vec<Uuid> = path_forward.into_iter().chain(path_backward).collect();
// Build entities with scores
for (i, uuid) in full_path.iter().enumerate() {
if let Some(entity) = self.get_entity(uuid)? {
let score = forward_visited
.get(uuid)
.map(|&(s, _)| s)
.or_else(|| backward_visited.get(uuid).map(|&(s, _)| s))
.unwrap_or(0.5);
all_entities.push(TraversedEntity {
entity,
hop_distance: i,
decay_factor: score,
});
}
}
} else {
// No path found - return empty traversal
tracing::debug!(
"traverse_bidirectional: no path between {:?} and {:?}",
start_uuid,
goal_uuid
);
}
// Hebbian strengthening for traversed edges
if !edges_to_strengthen.is_empty() {
if let Err(e) = self.batch_strengthen_synapses(&edges_to_strengthen) {
tracing::debug!("Failed to strengthen synapses: {}", e);
}
}
tracing::debug!(
"traverse_bidirectional: {} entities, {} edges, path_score={:.4}",
all_entities.len(),
all_edges.len(),
best_path_score
);
Ok(GraphTraversal {
entities: all_entities,
relationships: all_edges,
})
}
/// Subgraph pattern matching (Cypher-like MATCH patterns)
///
/// Pattern format: Vec of (relation_type, direction) tuples
/// Direction: true = outgoing (a->b), false = incoming (a<-b)
///
/// Example: MATCH (a)-[:WORKS_AT]->(b)-[:LOCATED_IN]->(c)
/// Pattern: vec![(WorksAt, true), (LocatedIn, true)]
///
/// Returns all entities that match the pattern starting from start_uuid.
pub fn match_pattern(
&self,
start_uuid: &Uuid,
pattern: &[(RelationType, bool)], // (relation_type, is_outgoing)
min_strength: f32,
) -> Result<Vec<Vec<TraversedEntity>>> {
let mut matches: Vec<Vec<TraversedEntity>> = Vec::new();
// Start entity
let start_entity = match self.get_entity(start_uuid)? {
Some(e) => e,
None => return Ok(matches),
};
// DFS backtracking search
let mut path: Vec<TraversedEntity> = vec![TraversedEntity {
entity: start_entity,
hop_distance: 0,
decay_factor: 1.0,
}];
self.match_pattern_recursive(
*start_uuid,
pattern,
0,
min_strength,
1.0,
&mut path,
&mut matches,
)?;
tracing::debug!(
"match_pattern: found {} matches for {}-step pattern",
matches.len(),
pattern.len()
);
Ok(matches)
}
#[allow(clippy::too_many_arguments)]
fn match_pattern_recursive(
&self,
current_uuid: Uuid,
pattern: &[(RelationType, bool)],
pattern_idx: usize,
min_strength: f32,
path_score: f32,
path: &mut Vec<TraversedEntity>,
matches: &mut Vec<Vec<TraversedEntity>>,
) -> Result<()> {
// Base case: completed the pattern
if pattern_idx >= pattern.len() {
matches.push(path.clone());
return Ok(());
}
const MAX_EDGES_PER_NODE: usize = 100;
let (required_type, is_outgoing) = &pattern[pattern_idx];
let edges =
self.get_entity_relationships_limited(¤t_uuid, Some(MAX_EDGES_PER_NODE))?;
for edge in edges {
if edge.invalidated_at.is_some() {
continue;
}
// Check relationship type
if edge.relation_type != *required_type {
continue;
}
// Check direction
let (next_uuid, direction_matches) = if *is_outgoing {
// Looking for current -> next
if edge.from_entity == current_uuid {
(edge.to_entity, true)
} else {
(edge.from_entity, false) // Wrong direction
}
} else {
// Looking for current <- next (incoming)
if edge.to_entity == current_uuid {
(edge.from_entity, true)
} else {
(edge.to_entity, false) // Wrong direction
}
};
if !direction_matches {
continue;
}
// Check strength
let effective = edge.effective_strength();
if effective < min_strength {
continue;
}
// Avoid cycles in pattern
if path.iter().any(|te| te.entity.uuid == next_uuid) {
continue;
}
// Add to path and recurse
if let Some(entity) = self.get_entity(&next_uuid)? {
let new_score = path_score * effective;
path.push(TraversedEntity {
entity,
hop_distance: pattern_idx + 1,
decay_factor: new_score,
});
self.match_pattern_recursive(
next_uuid,
pattern,
pattern_idx + 1,
min_strength,
new_score,
path,
matches,
)?;
path.pop();
}
}
Ok(())
}
/// Find entities matching a pattern from any starting point
///
/// Scans all entities and finds those that match the given pattern.
/// More expensive than match_pattern but doesn't require a known start.
///
/// Pattern: Vec of (relation_type, is_outgoing) tuples
/// Returns: All complete pattern matches with their paths.
pub fn find_pattern_matches(
&self,
pattern: &[(RelationType, bool)],
min_strength: f32,
limit: usize,
) -> Result<Vec<Vec<TraversedEntity>>> {
let mut all_matches: Vec<Vec<TraversedEntity>> = Vec::new();
// Iterate through all entities as potential starting points
let iter = self
.db
.iterator_cf(self.entities_cf(), rocksdb::IteratorMode::Start);
for result in iter {
if all_matches.len() >= limit {
break;
}
let (_, value) = result?;
let (entity, _) = crate::serialization::try_decode::<EntityNode>(&value)?;
let entity_matches = self.match_pattern(&entity.uuid, pattern, min_strength)?;
for m in entity_matches {
if all_matches.len() >= limit {
break;
}
all_matches.push(m);
}
}
tracing::debug!(
"find_pattern_matches: {} total matches (limit={})",
all_matches.len(),
limit
);
Ok(all_matches)
}
/// Invalidate a relationship (temporal edge invalidation)
///
/// Guarded by synapse_update_lock to prevent race with strengthen/decay.
pub fn invalidate_relationship(&self, edge_uuid: &Uuid) -> Result<()> {
let _guard = self
.synapse_update_lock
.try_lock_for(std::time::Duration::from_secs(5))
.ok_or_else(|| {
anyhow::anyhow!("synapse_update_lock timeout in invalidate_relationship")
})?;
if let Some(mut edge) = self.get_relationship(edge_uuid)? {
edge.invalidated_at = Some(Utc::now());
let key = edge.uuid.as_bytes();
let value = crate::serialization::encode(&edge)?;
self.db.put_cf(self.relationships_cf(), key, value)?;
}
Ok(())
}
/// Strengthen a synapse (Hebbian learning)
///
/// Called when an edge is traversed during memory retrieval.
/// Implements "neurons that fire together, wire together".
///
/// Uses a mutex to prevent race conditions during concurrent updates (SHO-64).
pub fn strengthen_synapse(&self, edge_uuid: &Uuid) -> Result<()> {
// Lock with timeout to prevent deadlock on panic
let _guard = self
.synapse_update_lock
.try_lock_for(std::time::Duration::from_secs(5))
.ok_or_else(|| anyhow::anyhow!("synapse_update_lock timeout in strengthen_synapse"))?;
if let Some(mut edge) = self.get_relationship(edge_uuid)? {
let _ = edge.strengthen();
let key = edge.uuid.as_bytes();
let value = crate::serialization::encode(&edge)?;
self.db.put_cf(self.relationships_cf(), key, value)?;
}
Ok(())
}
/// Batch strengthen multiple synapses atomically (SHO-65)
///
/// More efficient than calling strengthen_synapse individually for each edge.
/// Uses RocksDB WriteBatch for atomic multi-write and a single lock acquisition.
///
/// Returns the number of synapses successfully strengthened.
pub fn batch_strengthen_synapses(&self, edge_uuids: &[Uuid]) -> Result<usize> {
if edge_uuids.is_empty() {
return Ok(0);
}
// Single lock acquisition for entire batch, with timeout
let _guard = self
.synapse_update_lock
.try_lock_for(std::time::Duration::from_secs(5))
.ok_or_else(|| {
anyhow::anyhow!("synapse_update_lock timeout in batch_strengthen_synapses")
})?;
// Batch read all edges in a single RocksDB call (same pattern as get_entity_relationships_limited)
let keys: Vec<[u8; 16]> = edge_uuids.iter().map(|u| *u.as_bytes()).collect();
let key_refs: Vec<&[u8]> = keys.iter().map(|k| k.as_slice()).collect();
let results = self
.db
.batched_multi_get_cf(self.relationships_cf(), &key_refs, false);
let mut batch = WriteBatch::default();
let mut strengthened = 0;
for (i, result) in results.into_iter().enumerate() {
if let Ok(Some(value)) = result {
if let Ok((mut edge, _)) =
crate::serialization::try_decode::<RelationshipEdge>(&value)
{
let _ = edge.strengthen();
match crate::serialization::encode(&edge) {
Ok(encoded) => {
batch.put_cf(self.relationships_cf(), &keys[i], encoded);
strengthened += 1;
}
Err(e) => {
tracing::debug!("Failed to serialize edge {}: {}", edge_uuids[i], e);
}
}
}
}
}
// Atomic write of all updates
if strengthened > 0 {
self.db.write(batch)?;
}
Ok(strengthened)
}
/// Weaken edges in batch (anti-Hebbian: misleading retrieval feedback).
///
/// Applies multiplicative decay (`1 - decay_factor`) to each edge's strength.
/// Edges below their tier's prune threshold are queued for lazy removal.
/// Uses a single RocksDB `WriteBatch` and one lock acquisition.
///
/// Returns the number of edges successfully weakened.
pub fn batch_weaken_synapses(&self, edge_uuids: &[Uuid], decay_factor: f32) -> Result<usize> {
if edge_uuids.is_empty() {
return Ok(0);
}
let _guard = self
.synapse_update_lock
.try_lock_for(std::time::Duration::from_secs(5))
.ok_or_else(|| {
anyhow::anyhow!("synapse_update_lock timeout in batch_weaken_synapses")
})?;
let keys: Vec<[u8; 16]> = edge_uuids.iter().map(|u| *u.as_bytes()).collect();
let key_refs: Vec<&[u8]> = keys.iter().map(|k| k.as_slice()).collect();
let results = self
.db
.batched_multi_get_cf(self.relationships_cf(), &key_refs, false);
let mut batch = WriteBatch::default();
let mut weakened = 0;
let clamped_decay = decay_factor.clamp(0.0, 1.0);
for (i, result) in results.into_iter().enumerate() {
if let Ok(Some(value)) = result {
if let Ok((mut edge, _)) =
crate::serialization::try_decode::<RelationshipEdge>(&value)
{
edge.strength *= 1.0 - clamped_decay;
// Queue for pruning if below tier threshold
if edge.strength < edge.tier.prune_threshold() {
self.pending_prune.lock().push(edge.uuid);
}
match crate::serialization::encode(&edge) {
Ok(encoded) => {
batch.put_cf(self.relationships_cf(), keys[i], encoded);
weakened += 1;
}
Err(e) => {
tracing::debug!("Failed to serialize edge {}: {}", edge_uuids[i], e);
}
}
}
}
}
if weakened > 0 {
self.db.write(batch)?;
}
Ok(weakened)
}
/// Collect edge UUIDs for a set of memory UUIDs via their episodic entity refs.
///
/// For each memory, looks up its EpisodicNode to find entity_refs, then collects
/// all edges incident to those entities (capped at `max_edges`).
/// Used by feedback-driven Hebbian reinforcement.
pub fn collect_entity_edges_for_memories(
&self,
memory_uuids: &[Uuid],
max_edges: usize,
) -> Result<Vec<Uuid>> {
use std::collections::HashSet;
let mut entity_set: HashSet<Uuid> = HashSet::new();
// Phase 1: gather all entities referenced by these memories' episodes
for mem_uuid in memory_uuids.iter().take(20) {
if let Some(episode) = self.get_episode(mem_uuid)? {
for entity_ref in &episode.entity_refs {
entity_set.insert(*entity_ref);
}
}
}
if entity_set.is_empty() {
return Ok(Vec::new());
}
// Phase 2: collect edge UUIDs from entity_edges index (deduplicated)
let mut edge_set: HashSet<Uuid> = HashSet::new();
for entity_uuid in &entity_set {
let prefix = format!("{entity_uuid}:");
let iter = self
.db
.prefix_iterator_cf(self.entity_edges_cf(), prefix.as_bytes());
for (key, _) in iter.flatten() {
if edge_set.len() >= max_edges {
break;
}
if let Ok(key_str) = std::str::from_utf8(&key) {
if !key_str.starts_with(&prefix) {
break;
}
if let Some(edge_uuid_str) = key_str.split(':').nth(1) {
if let Ok(edge_uuid) = Uuid::parse_str(edge_uuid_str) {
edge_set.insert(edge_uuid);
}
}
}
}
if edge_set.len() >= max_edges {
break;
}
}
Ok(edge_set.into_iter().collect())
}
/// Record co-retrieval of memories (Hebbian learning between memories)
///
/// When memories are retrieved together, they form associations.
/// This creates or strengthens CoRetrieved edges between all pairs of memories.
///
/// Note: Limits to top N memories to avoid O(n²) explosion on large retrievals.
/// Returns the number of edges created/strengthened.
pub fn record_memory_coactivation(&self, memory_ids: &[Uuid]) -> Result<usize> {
const MAX_COACTIVATION_SIZE: usize = 20;
// Limit to top N to bound worst-case complexity
let memories_to_process = if memory_ids.len() > MAX_COACTIVATION_SIZE {
&memory_ids[..MAX_COACTIVATION_SIZE]
} else {
memory_ids
};
if memories_to_process.len() < 2 {
return Ok(0);
}
let _guard = self
.synapse_update_lock
.try_lock_for(std::time::Duration::from_secs(5))
.ok_or_else(|| {
anyhow::anyhow!("synapse_update_lock timeout in record_memory_coactivation")
})?;
let mut batch = WriteBatch::default();
let mut edges_updated = 0;
let mut new_edges = 0;
// Process all pairs
for i in 0..memories_to_process.len() {
for j in (i + 1)..memories_to_process.len() {
let mem_a = memories_to_process[i];
let mem_b = memories_to_process[j];
// Try to find existing edge between these memories
let existing_edge = self.find_edge_between_entities(&mem_a, &mem_b)?;
if let Some(mut edge) = existing_edge {
// Strengthen existing edge
let _ = edge.strengthen();
let key = edge.uuid.as_bytes();
if let Ok(value) = crate::serialization::encode(&edge) {
batch.put_cf(self.relationships_cf(), key, value);
edges_updated += 1;
}
} else {
// Create new CoRetrieved edge (bidirectional represented as single edge)
// Starts in L1 (working memory) with tier-specific initial weight
let edge = RelationshipEdge {
uuid: Uuid::new_v4(),
from_entity: mem_a,
to_entity: mem_b,
relation_type: RelationType::CoRetrieved,
strength: EdgeTier::L1Working.initial_weight(),
created_at: Utc::now(),
valid_at: Utc::now(),
invalidated_at: None,
source_episode_id: None,
context: String::new(),
last_activated: Utc::now(),
activation_count: 1,
ltp_status: LtpStatus::None,
activation_timestamps: None,
tier: EdgeTier::L1Working,
// PIPE-5: Memory-to-memory edges use default confidence
entity_confidence: None,
forman_curvature: None,
endpoint_selectivity: None,
};
let key = edge.uuid.as_bytes();
if let Ok(value) = crate::serialization::encode(&edge) {
batch.put_cf(self.relationships_cf(), key, value);
// Also index in the reverse direction for lookup
let idx_key_fwd = format!("mem_edge:{mem_a}:{mem_b}");
let idx_key_rev = format!("mem_edge:{mem_b}:{mem_a}");
batch.put_cf(
self.relationships_cf(),
idx_key_fwd.as_bytes(),
edge.uuid.as_bytes(),
);
batch.put_cf(
self.relationships_cf(),
idx_key_rev.as_bytes(),
edge.uuid.as_bytes(),
);
edges_updated += 1;
new_edges += 1;
}
}
}
}
if edges_updated > 0 {
self.db.write(batch)?;
// Update relationship counter for newly created edges
if new_edges > 0 {
self.relationship_count
.fetch_add(new_edges, Ordering::Relaxed);
}
}
Ok(edges_updated)
}
/// Find an edge between two entities/memories (in either direction)
fn find_edge_between_entities(
&self,
entity_a: &Uuid,
entity_b: &Uuid,
) -> Result<Option<RelationshipEdge>> {
// Check forward index
let idx_key = format!("mem_edge:{entity_a}:{entity_b}");
if let Some(edge_uuid_bytes) = self
.db
.get_cf(self.relationships_cf(), idx_key.as_bytes())?
{
if edge_uuid_bytes.len() == 16 {
let edge_uuid = Uuid::from_slice(&edge_uuid_bytes)?;
return self.get_relationship(&edge_uuid);
}
}
// Check reverse index
let idx_key_rev = format!("mem_edge:{entity_b}:{entity_a}");
if let Some(edge_uuid_bytes) = self
.db
.get_cf(self.relationships_cf(), idx_key_rev.as_bytes())?
{
if edge_uuid_bytes.len() == 16 {
let edge_uuid = Uuid::from_slice(&edge_uuid_bytes)?;
return self.get_relationship(&edge_uuid);
}
}
Ok(None)
}
/// Batch strengthen edges between memory pairs from replay consolidation
///
/// Takes edge boosts from memory replay and applies Hebbian strengthening.
/// Creates edges if they don't exist, strengthens if they do.
///
/// Returns (count_strengthened, promotion_boosts) where promotion_boosts contains
/// signals for any edge tier promotions that occurred (Direction 1 coupling).
pub fn strengthen_memory_edges(
&self,
edge_boosts: &[(String, String, f32)],
) -> Result<(usize, Vec<crate::memory::types::EdgePromotionBoost>)> {
use crate::constants::{EDGE_PROMOTION_MEMORY_BOOST_L2, EDGE_PROMOTION_MEMORY_BOOST_L3};
if edge_boosts.is_empty() {
return Ok((0, Vec::new()));
}
let _guard = self
.synapse_update_lock
.try_lock_for(std::time::Duration::from_secs(5))
.ok_or_else(|| {
anyhow::anyhow!("synapse_update_lock timeout in strengthen_edges_from_boosts")
})?;
let mut batch = WriteBatch::default();
let mut strengthened = 0;
let mut promotion_boosts = Vec::new();
for (from_id_str, to_id_str, boost) in edge_boosts {
// Parse UUIDs
let from_uuid = match Uuid::parse_str(from_id_str) {
Ok(u) => u,
Err(_) => {
tracing::debug!("Invalid from_id UUID: {}", from_id_str);
continue;
}
};
let to_uuid = match Uuid::parse_str(to_id_str) {
Ok(u) => u,
Err(_) => {
tracing::debug!("Invalid to_id UUID: {}", to_id_str);
continue;
}
};
// Find or create edge
let existing_edge = self.find_edge_between_entities(&from_uuid, &to_uuid)?;
if let Some(mut edge) = existing_edge {
// Strengthen existing edge — capture tier promotion if it occurs
let promotion = edge.strengthen();
let key = edge.uuid.as_bytes();
if let Ok(value) = crate::serialization::encode(&edge) {
batch.put_cf(self.relationships_cf(), key, value);
strengthened += 1;
// If a tier promotion occurred, emit boost signals for both memories
if let Some((old_tier, new_tier)) = promotion {
let boost = if new_tier.contains("L2") {
EDGE_PROMOTION_MEMORY_BOOST_L2
} else {
EDGE_PROMOTION_MEMORY_BOOST_L3
};
let entity_name = format!(
"{}↔{}",
&from_id_str[..8.min(from_id_str.len())],
&to_id_str[..8.min(to_id_str.len())]
);
// Boost both memories involved in the promoted edge
promotion_boosts.push(crate::memory::types::EdgePromotionBoost {
memory_id: from_id_str.clone(),
entity_name: entity_name.clone(),
old_tier: old_tier.clone(),
new_tier: new_tier.clone(),
boost,
});
promotion_boosts.push(crate::memory::types::EdgePromotionBoost {
memory_id: to_id_str.clone(),
entity_name,
old_tier,
new_tier,
boost,
});
}
}
} else {
// Create new ReplayStrengthened edge
// Replay edges start in L2 (episodic) with replay boost applied to initial strength.
// Without this, the computed replay priority score was discarded and all new edges
// started at identical strength regardless of their consolidation importance.
let edge = RelationshipEdge {
uuid: Uuid::new_v4(),
from_entity: from_uuid,
to_entity: to_uuid,
relation_type: RelationType::CoRetrieved,
strength: EdgeTier::L2Episodic.initial_weight() + boost,
created_at: Utc::now(),
valid_at: Utc::now(),
invalidated_at: None,
source_episode_id: None,
context: "replay_strengthened".to_string(),
last_activated: Utc::now(),
activation_count: 1,
ltp_status: LtpStatus::None,
activation_timestamps: None,
tier: EdgeTier::L2Episodic,
// PIPE-5: Replay edges use default confidence
entity_confidence: None,
forman_curvature: None,
endpoint_selectivity: None,
};
let key = edge.uuid.as_bytes();
if let Ok(value) = crate::serialization::encode(&edge) {
batch.put_cf(self.relationships_cf(), key, value);
// Index both directions
let idx_key_fwd = format!("mem_edge:{from_uuid}:{to_uuid}");
let idx_key_rev = format!("mem_edge:{to_uuid}:{from_uuid}");
batch.put_cf(
self.relationships_cf(),
idx_key_fwd.as_bytes(),
edge.uuid.as_bytes(),
);
batch.put_cf(
self.relationships_cf(),
idx_key_rev.as_bytes(),
edge.uuid.as_bytes(),
);
strengthened += 1;
}
}
}
if strengthened > 0 {
self.db.write(batch)?;
// Index new replay edges in entity_edges CF so they're visible to
// traversal and degree-cap enforcement (GQ-11 fix)
let mut entities_to_prune = Vec::new();
for (from_id_str, to_id_str, _boost) in edge_boosts {
let from_uuid = match Uuid::parse_str(from_id_str) {
Ok(u) => u,
Err(_) => continue,
};
let to_uuid = match Uuid::parse_str(to_id_str) {
Ok(u) => u,
Err(_) => continue,
};
// Only index edges that we actually wrote (find_edge_between_entities returns
// the edge if it existed before, so new edges are the ones that didn't exist)
if let Ok(Some(edge)) = self.find_edge_between_entities(&from_uuid, &to_uuid) {
if edge.context == "replay_strengthened" && edge.activation_count <= 1 {
if let Err(e) = self.index_entity_edge(&from_uuid, &edge.uuid) {
tracing::debug!("Failed to index replay edge for entity: {}", e);
}
if let Err(e) = self.index_entity_edge(&to_uuid, &edge.uuid) {
tracing::debug!("Failed to index replay edge for entity: {}", e);
}
entities_to_prune.push(from_uuid);
entities_to_prune.push(to_uuid);
}
}
}
// Enforce degree cap on affected entities
for entity_uuid in &entities_to_prune {
let _ = self.prune_entity_if_over_degree(entity_uuid);
}
tracing::debug!(
"Applied {} edge boosts from replay consolidation ({} tier promotions)",
strengthened,
promotion_boosts.len()
);
}
Ok((strengthened, promotion_boosts))
}
/// Strengthen graph edges between two causally-linked memories.
///
/// Resolves memory UUIDs to their entity_refs via EpisodicNodes, then strengthens
/// the cross-product of entity pairs. This couples the lineage system (explicit
/// causal chains) with the knowledge graph (spreading activation), so causally-linked
/// memories naturally co-activate during retrieval.
///
/// Returns the number of entity-pair edges strengthened.
pub fn strengthen_lineage_connection(
&self,
from_memory_uuid: &Uuid,
to_memory_uuid: &Uuid,
boost: f32,
) -> Result<usize> {
// Resolve entity_refs for both memories
let from_episode = self.get_episode(from_memory_uuid)?;
let to_episode = self.get_episode(to_memory_uuid)?;
let (from_entities, to_entities) = match (from_episode, to_episode) {
(Some(fe), Some(te)) if !fe.entity_refs.is_empty() && !te.entity_refs.is_empty() => {
(fe.entity_refs, te.entity_refs)
}
_ => return Ok(0),
};
// Cap entity lists to prevent O(N^2) explosion on heavily-tagged memories.
// 8 × 8 = 64 pairs max, which is reasonable for a single lineage edge.
const MAX_ENTITIES_PER_SIDE: usize = 8;
let from_capped = &from_entities[..from_entities.len().min(MAX_ENTITIES_PER_SIDE)];
let to_capped = &to_entities[..to_entities.len().min(MAX_ENTITIES_PER_SIDE)];
// Build cross-product of entity pairs with lineage boost
let mut edge_boosts: Vec<(String, String, f32)> =
Vec::with_capacity(from_capped.len() * to_capped.len());
for from_entity in from_capped {
for to_entity in to_capped {
if from_entity != to_entity {
edge_boosts.push((from_entity.to_string(), to_entity.to_string(), boost));
}
}
}
if edge_boosts.is_empty() {
return Ok(0);
}
let (strengthened, _promotions) = self.strengthen_memory_edges(&edge_boosts)?;
tracing::debug!(
from_memory = %&from_memory_uuid.to_string()[..8],
to_memory = %&to_memory_uuid.to_string()[..8],
entity_pairs = edge_boosts.len(),
strengthened,
boost,
"Lineage→graph edge strengthening"
);
Ok(strengthened)
}
/// Find memories associated with a given memory through co-retrieval
///
/// Uses weighted graph traversal prioritizing stronger associations.
/// Returns memory UUIDs sorted by association strength.
pub fn find_memory_associations(
&self,
memory_id: &Uuid,
max_results: usize,
) -> Result<Vec<(Uuid, f32)>> {
let mut associations: Vec<(Uuid, f32)> = Vec::new();
// Scan for edges involving this memory
let prefix_fwd = format!("mem_edge:{memory_id}:");
let iter = self
.db
.prefix_iterator_cf(self.relationships_cf(), prefix_fwd.as_bytes());
for item in iter {
let (key, value) = item?;
// Check if this is our prefix (RocksDB prefix_iterator may return extra)
let key_str = String::from_utf8_lossy(&key);
if !key_str.starts_with(&prefix_fwd) {
break;
}
// Get edge UUID from value and look up edge
if value.len() == 16 {
let edge_uuid = Uuid::from_slice(&value)?;
if let Some(edge) = self.get_relationship(&edge_uuid)? {
// Get the other memory in this edge
let other_id = if edge.from_entity == *memory_id {
edge.to_entity
} else {
edge.from_entity
};
// Get effective strength with decay
let effective_strength = edge.effective_strength();
if effective_strength > LTP_MIN_STRENGTH {
associations.push((other_id, effective_strength));
}
}
}
}
// Sort by strength descending and limit
associations.sort_by(|a, b| b.1.total_cmp(&a.1));
associations.truncate(max_results);
Ok(associations)
}
/// Strengthen entity-entity edges for a replayed memory's episode.
///
/// During consolidation replay, this reinforces the entity relationships that
/// were involved in the replayed memory. This is "Direction 3" of the Hebbian
/// maintenance system — entity-entity edges get strengthened alongside
/// memory-to-memory edges (Direction 1) and lazy pruning (Direction 2).
///
/// Algorithm:
/// 1. Look up EpisodicNode for episode_id → get entity_refs
/// 2. For each pair of entities, find their RelationshipEdge
/// 3. Call strengthen() on each edge (Hebbian boost + LTP detection + tier promotion)
/// 4. Batch write all updates
pub fn strengthen_episode_entity_edges(&self, episode_id: &Uuid) -> Result<usize> {
let episode = match self.get_episode(episode_id) {
Ok(Some(ep)) => ep,
Ok(None) => return Ok(0),
Err(_) => return Ok(0),
};
if episode.entity_refs.len() < 2 {
return Ok(0);
}
let _guard = self
.synapse_update_lock
.try_lock_for(std::time::Duration::from_secs(5))
.ok_or_else(|| {
anyhow::anyhow!("synapse_update_lock timeout in strengthen_episode_entity_edges")
})?;
let mut batch = WriteBatch::default();
let mut strengthened = 0;
// Iterate over unique entity pairs
let refs = &episode.entity_refs;
let max_pairs = refs.len().min(20); // Cap to avoid O(n²) on large episodes
for i in 0..max_pairs {
for j in (i + 1)..max_pairs {
let entity_a = &refs[i];
let entity_b = &refs[j];
// Find existing edge between this entity pair
if let Ok(Some(mut edge)) = self.find_edge_between_entities(entity_a, entity_b) {
if edge.invalidated_at.is_some() {
continue;
}
let _ = edge.strengthen();
let key = edge.uuid.as_bytes();
if let Ok(value) = crate::serialization::encode(&edge) {
batch.put_cf(self.relationships_cf(), key, value);
strengthened += 1;
}
}
// Don't create new edges — only strengthen existing ones from NER
}
}
if strengthened > 0 {
self.db.write(batch)?;
tracing::debug!(
"Strengthened {} entity-entity edges for episode {}",
strengthened,
&episode_id.to_string()[..8]
);
}
Ok(strengthened)
}
/// Get average Hebbian strength for a memory based on its entity relationships
///
/// This looks up the entities referenced by the memory and averages their
/// relationship strengths in the graph. Used for composite relevance scoring.
///
/// The algorithm:
/// 1. Look up memory's EpisodicNode (memory_id.0 == episode UUID)
/// 2. Get entity_refs from the episode
/// 3. For each entity, get relationships using get_entity_relationships
/// 4. Filter to edges where both endpoints are in the memory's entity set
/// 5. Return average effective_strength of these intra-memory edges
///
/// Returns 0.5 (neutral) if no entities or relationships found.
pub fn get_memory_hebbian_strength(&self, memory_id: &crate::memory::MemoryId) -> Option<f32> {
// 1. Look up EpisodicNode for this memory (memory_id.0 == episode UUID)
let episode = match self.get_episode(&memory_id.0) {
Ok(Some(ep)) => ep,
Ok(None) => return Some(0.5), // No episode found - neutral
Err(_) => return Some(0.5), // Error - neutral fallback
};
// 2. Get entity references from the episode
if episode.entity_refs.is_empty() {
return Some(0.5); // No entities - neutral
}
// Build a set of entity UUIDs for fast lookup
let entity_set: std::collections::HashSet<Uuid> =
episode.entity_refs.iter().cloned().collect();
// 3. Collect all intra-memory relationship strengths
let mut strengths: Vec<f32> = Vec::new();
let mut seen_edges: std::collections::HashSet<Uuid> = std::collections::HashSet::new();
const MAX_EDGES_PER_ENTITY: usize = 50; // Limit per entity for Hebbian lookup
for entity_uuid in &episode.entity_refs {
if let Ok(edges) =
self.get_entity_relationships_limited(entity_uuid, Some(MAX_EDGES_PER_ENTITY))
{
for edge in edges {
// Skip if already processed (edges are bidirectional in lookup)
if seen_edges.contains(&edge.uuid) {
continue;
}
seen_edges.insert(edge.uuid);
// 4. Only count edges where BOTH endpoints are in this memory's entities
if entity_set.contains(&edge.from_entity)
&& entity_set.contains(&edge.to_entity)
{
// Skip invalidated edges
if edge.invalidated_at.is_some() {
continue;
}
// Use effective_strength which applies time-based decay
strengths.push(edge.effective_strength());
}
}
}
}
// 5. Return average strength, or neutral if no intra-memory edges
if strengths.is_empty() {
Some(0.5)
} else {
let avg = strengths.iter().sum::<f32>() / strengths.len() as f32;
Some(avg)
}
}
/// Apply decay to a synapse
///
/// Returns true if the synapse should be pruned (non-potentiated and below threshold)
///
/// Uses a mutex to prevent race conditions during concurrent updates (SHO-64).
pub fn decay_synapse(&self, edge_uuid: &Uuid) -> Result<bool> {
// Lock to prevent concurrent read-modify-write race conditions
let _guard = self
.synapse_update_lock
.try_lock_for(std::time::Duration::from_secs(5))
.ok_or_else(|| anyhow::anyhow!("synapse_update_lock timeout in decay_synapse"))?;
if let Some(mut edge) = self.get_relationship(edge_uuid)? {
let should_prune = edge.decay();
let key = edge.uuid.as_bytes();
let value = crate::serialization::encode(&edge)?;
self.db.put_cf(self.relationships_cf(), key, value)?;
return Ok(should_prune);
}
Ok(false)
}
/// Batch decay multiple synapses atomically
///
/// Returns a vector of edge UUIDs that should be pruned.
pub fn batch_decay_synapses(&self, edge_uuids: &[Uuid]) -> Result<Vec<Uuid>> {
if edge_uuids.is_empty() {
return Ok(Vec::new());
}
// Single lock acquisition for entire batch, with timeout
let _guard = self
.synapse_update_lock
.try_lock_for(std::time::Duration::from_secs(5))
.ok_or_else(|| {
anyhow::anyhow!("synapse_update_lock timeout in batch_decay_synapses")
})?;
let mut batch = WriteBatch::default();
let mut to_prune = Vec::new();
for edge_uuid in edge_uuids {
if let Some(mut edge) = self.get_relationship(edge_uuid)? {
let should_prune = edge.decay();
let key = edge.uuid.as_bytes();
match crate::serialization::encode(&edge) {
Ok(value) => {
batch.put_cf(self.relationships_cf(), key, value);
if should_prune {
to_prune.push(*edge_uuid);
}
}
Err(e) => {
tracing::debug!("Failed to serialize edge {}: {}", edge_uuid, e);
}
}
}
}
// Atomic write of all updates
self.db.write(batch)?;
Ok(to_prune)
}
/// Apply decay to already-loaded edges in-place, avoiding double deserialization.
///
/// Mutates edges directly, serializes results into a WriteBatch, and returns
/// the UUIDs of edges that should be pruned. Used by `apply_decay()` which
/// already has the full edge list from `get_all_relationships()`.
fn batch_decay_edges_in_place(&self, edges: &mut [RelationshipEdge]) -> Result<Vec<Uuid>> {
if edges.is_empty() {
return Ok(Vec::new());
}
let _guard = self
.synapse_update_lock
.try_lock_for(std::time::Duration::from_secs(5))
.ok_or_else(|| {
anyhow::anyhow!("synapse_update_lock timeout in batch_decay_edges_in_place")
})?;
let mut batch = WriteBatch::default();
let mut to_prune = Vec::new();
for edge in edges.iter_mut() {
let strength_before = edge.strength;
let should_prune = edge.decay();
// Only write back edges whose strength actually changed (or need pruning).
// With 300s maintenance intervals, most edges won't have meaningful decay,
// so this reduces the WriteBatch from ~12MB (all 34k edges) to ~150KB.
if should_prune || (edge.strength - strength_before).abs() > f32::EPSILON {
let key = edge.uuid.as_bytes();
match crate::serialization::encode(&*edge) {
Ok(value) => {
batch.put_cf(self.relationships_cf(), key, value);
if should_prune {
to_prune.push(edge.uuid);
}
}
Err(e) => {
tracing::debug!("Failed to serialize edge {}: {}", edge.uuid, e);
}
}
}
}
self.db.write(batch)?;
Ok(to_prune)
}
/// Apply synaptic homeostasis: global downscaling of all edge strengths.
///
/// After each maintenance cycle, scales ALL edge weights by `factor` (typically 0.95).
/// Edges with LtpStatus::Full are protected — fully consolidated synapses resist
/// homeostatic downscaling, matching biological systems consolidation.
///
/// This prevents runaway strengthening and keeps total network energy bounded.
/// Strong edges survive; weak edges fall below prune thresholds and are cleared
/// in the next decay cycle.
///
/// Reference: Tononi & Cirelli (2003) "Sleep and synaptic homeostasis: a hypothesis"
pub fn apply_synaptic_homeostasis(&self, factor: f32) -> Result<usize> {
let mut all_edges = self.get_all_relationships()?;
if all_edges.is_empty() {
return Ok(0);
}
let _guard = self
.synapse_update_lock
.try_lock_for(std::time::Duration::from_secs(5))
.ok_or_else(|| {
anyhow::anyhow!("synapse_update_lock timeout in apply_synaptic_homeostasis")
})?;
let mut batch = WriteBatch::default();
let mut scaled_count = 0;
for edge in all_edges.iter_mut() {
// Fully potentiated edges are protected from homeostatic downscaling
if matches!(edge.ltp_status, LtpStatus::Full) {
continue;
}
let old_strength = edge.strength;
edge.strength *= factor;
// Never scale below absolute floor
edge.strength = edge.strength.max(crate::constants::LTP_MIN_STRENGTH);
if (edge.strength - old_strength).abs() > f32::EPSILON {
let key = edge.uuid.as_bytes();
if let Ok(value) = crate::serialization::encode(&*edge) {
batch.put_cf(self.relationships_cf(), key, value);
scaled_count += 1;
}
}
}
if scaled_count > 0 {
self.db.write(batch)?;
tracing::debug!(
"Synaptic homeostasis: scaled {} of {} edges by factor {}",
scaled_count,
all_edges.len(),
factor
);
}
Ok(scaled_count)
}
/// Apply decay to all synapses and prune weak edges (AUD-2)
///
/// Called during maintenance cycle to:
/// 1. Apply time-based decay to all edge strengths
/// 2. Remove edges that have decayed below threshold
/// 3. Detect orphaned entities (entities that lost all their edges)
/// 4. Apply synaptic homeostasis (global edge downscaling)
///
/// Returns a `GraphDecayResult` with pruned count and orphaned entity/memory IDs
/// for Direction 2 coupling (edge pruning → orphan detection).
pub fn apply_decay(&self) -> Result<crate::memory::types::GraphDecayResult> {
// Get all edges (need full data for orphan tracking)
let mut all_edges = self.get_all_relationships()?;
if all_edges.is_empty() {
return Ok(crate::memory::types::GraphDecayResult::default());
}
// Apply decay in-place on already-deserialized edges (avoids double deserialization)
let to_prune = self.batch_decay_edges_in_place(&mut all_edges)?;
if to_prune.is_empty() {
return Ok(crate::memory::types::GraphDecayResult::default());
}
// Collect entity UUIDs from edges being pruned (candidates for orphan status)
let pruned_set: std::collections::HashSet<Uuid> = to_prune.iter().copied().collect();
let mut orphan_candidates: std::collections::HashSet<Uuid> =
std::collections::HashSet::new();
for edge in &all_edges {
if pruned_set.contains(&edge.uuid) {
orphan_candidates.insert(edge.from_entity);
orphan_candidates.insert(edge.to_entity);
}
}
// Delete pruned edges
let mut pruned_count = 0;
for edge_uuid in &to_prune {
if self.delete_relationship(edge_uuid)? {
pruned_count += 1;
}
}
// Check which candidate entities became orphaned (lost ALL edges)
// Delete orphaned entities to prevent stale index pollution
let mut orphaned_entity_ids = Vec::new();
for entity_uuid in &orphan_candidates {
let remaining = self.get_entity_relationships(entity_uuid)?;
if remaining.is_empty() {
orphaned_entity_ids.push(entity_uuid.to_string());
if let Err(e) = self.delete_entity(entity_uuid) {
tracing::warn!("Failed to delete orphaned entity {}: {}", entity_uuid, e);
}
}
}
if pruned_count > 0 {
tracing::debug!(
"Graph decay: {} edges pruned (of {} total), {} entities orphaned",
pruned_count,
all_edges.len(),
orphaned_entity_ids.len()
);
}
// 4. Apply synaptic homeostasis (global edge downscaling)
// Runs after pruning so that homeostatic pressure doesn't interfere with
// the prune decision (edges are pruned at their true decayed strength first).
if let Err(e) =
self.apply_synaptic_homeostasis(crate::constants::HOMEOSTASIS_SCALING_FACTOR)
{
tracing::warn!("Synaptic homeostasis failed (non-fatal): {}", e);
}
Ok(crate::memory::types::GraphDecayResult {
pruned_count,
orphaned_entity_ids,
orphaned_memory_ids: Vec::new(), // Populated by memory layer via entity→memory lookup
})
}
/// Compute Forman-Ricci curvature for all active edges in the graph.
///
/// For a directed edge e = (u → v) in the knowledge graph:
/// F(→e→) = 2 - in_deg(u) - out_deg(v) [flow-through curvature]
/// F(←e←) = 2 - out_deg(u) - in_deg(v) [flow-loss curvature]
/// F(e) = F(→e→) + F(←e←) = 4 - deg(u) - deg(v)
///
/// The directed components reveal information flow structure:
/// - F(→e→) captures how much flow converges through this edge
/// - F(←e←) captures how much flow is lost/dispersed at this edge
///
/// Stores computed curvature on each edge and writes back to RocksDB.
///
/// Reference: Leal, Restrepo, Stadler, Jost (2018) arXiv:1811.07825
/// "Forman-Ricci curvature for hypergraphs"
pub fn compute_forman_ricci_curvature(&self) -> Result<CurvatureStats> {
let all_edges = self.get_all_relationships()?;
if all_edges.is_empty() {
return Ok(CurvatureStats {
edges_computed: 0,
mean_curvature: 0.0,
min_curvature: 0.0,
max_curvature: 0.0,
positive_count: 0,
zero_count: 0,
negative_count: 0,
});
}
// Phase 1: Build degree maps (in-degree and out-degree per entity)
// Single pass over all edges — O(|E|)
let mut in_degree: HashMap<Uuid, i32> = HashMap::new();
let mut out_degree: HashMap<Uuid, i32> = HashMap::new();
for edge in &all_edges {
*out_degree.entry(edge.from_entity).or_insert(0) += 1;
*in_degree.entry(edge.to_entity).or_insert(0) += 1;
}
// Phase 2: Compute curvature for each edge, collect per-entity curvatures
let mut entity_curvatures: HashMap<Uuid, Vec<f32>> = HashMap::new();
let mut sum_curvature: f64 = 0.0;
let mut min_curvature = f32::MAX;
let mut max_curvature = f32::MIN;
let mut positive_count: usize = 0;
let mut zero_count: usize = 0;
let mut negative_count: usize = 0;
// First pass: compute curvature values and collect per-entity
let mut edge_curvatures: Vec<f32> = Vec::with_capacity(all_edges.len());
for edge in &all_edges {
let src_in = in_degree.get(&edge.from_entity).copied().unwrap_or(0);
let src_out = out_degree.get(&edge.from_entity).copied().unwrap_or(0);
let tgt_in = in_degree.get(&edge.to_entity).copied().unwrap_or(0);
let tgt_out = out_degree.get(&edge.to_entity).copied().unwrap_or(0);
// Directed Forman-Ricci (Equations 5 + 7 from the paper)
let flow_through = 2 - src_in - tgt_out; // F(→e→)
let flow_loss = 2 - src_out - tgt_in; // F(←e←)
let curvature = (flow_through + flow_loss) as f32; // F(e) = 4 - deg(u) - deg(v)
edge_curvatures.push(curvature);
// Collect per-entity curvature for selectivity computation
entity_curvatures
.entry(edge.from_entity)
.or_default()
.push(curvature);
entity_curvatures
.entry(edge.to_entity)
.or_default()
.push(curvature);
// Update stats
sum_curvature += curvature as f64;
if curvature < min_curvature {
min_curvature = curvature;
}
if curvature > max_curvature {
max_curvature = curvature;
}
#[allow(clippy::float_cmp)]
if curvature > 0.0 {
positive_count += 1;
} else if curvature == 0.0 {
zero_count += 1;
} else {
negative_count += 1;
}
}
// Phase 3: Compute selectivity per entity
// selectivity = stdev(incident curvatures) / degree
// High selectivity → concept (mixed community + bridge edges)
// Low selectivity → stop word (uniform curvature across all edges)
let mut entity_selectivity: HashMap<Uuid, f32> = HashMap::new();
for (entity_id, curvs) in &entity_curvatures {
let n = curvs.len() as f32;
if n < 2.0 {
// Single edge: can't compute variance, assign neutral selectivity
entity_selectivity.insert(*entity_id, 1.0);
continue;
}
let mean = curvs.iter().sum::<f32>() / n;
let variance = curvs.iter().map(|c| (c - mean).powi(2)).sum::<f32>() / (n - 1.0);
let stdev = variance.sqrt();
let selectivity = stdev / n; // Normalize by degree
entity_selectivity.insert(*entity_id, selectivity);
}
// Phase 4: Write entity selectivity back to RocksDB
let mut entity_batch = WriteBatch::default();
for (entity_id, selectivity) in &entity_selectivity {
let key = entity_id.as_bytes();
if let Ok(Some(value)) = self.db.get_cf(self.entities_cf(), key) {
if let Ok((mut entity, _)) = crate::serialization::try_decode::<EntityNode>(&value)
{
entity.selectivity = Some(*selectivity);
if let Ok(encoded) = crate::serialization::encode(&entity) {
entity_batch.put_cf(self.entities_cf(), key, encoded);
}
}
}
}
self.db
.write(entity_batch)
.map_err(|e| anyhow::anyhow!("Failed to write entity selectivity batch: {}", e))?;
// Phase 5: Write edges with curvature + endpoint_selectivity
let mut edge_batch = WriteBatch::default();
for (mut edge, curvature) in all_edges.into_iter().zip(edge_curvatures.iter()) {
edge.forman_curvature = Some(*curvature);
// endpoint_selectivity = min of both endpoints
// The weakest link determines if this edge connects stop words
let src_sel = entity_selectivity
.get(&edge.from_entity)
.copied()
.unwrap_or(1.0);
let tgt_sel = entity_selectivity
.get(&edge.to_entity)
.copied()
.unwrap_or(1.0);
edge.endpoint_selectivity = Some(src_sel.min(tgt_sel));
let key = edge.uuid.as_bytes();
match crate::serialization::encode(&edge) {
Ok(value) => {
edge_batch.put_cf(self.relationships_cf(), key, value);
}
Err(e) => {
tracing::debug!("Failed to serialize edge {}: {}", edge.uuid, e);
}
}
}
let edges_computed = positive_count + zero_count + negative_count;
self.db
.write(edge_batch)
.map_err(|e| anyhow::anyhow!("Failed to write curvature batch: {}", e))?;
let stats = CurvatureStats {
edges_computed,
mean_curvature: if edges_computed > 0 {
(sum_curvature / edges_computed as f64) as f32
} else {
0.0
},
min_curvature: if edges_computed > 0 {
min_curvature
} else {
0.0
},
max_curvature: if edges_computed > 0 {
max_curvature
} else {
0.0
},
positive_count,
zero_count,
negative_count,
};
tracing::info!(
edges = stats.edges_computed,
mean = format!("{:.2}", stats.mean_curvature),
min = stats.min_curvature,
max = stats.max_curvature,
positive = stats.positive_count,
negative = stats.negative_count,
entities_with_selectivity = entity_selectivity.len(),
"Forman-Ricci curvature and selectivity computed"
);
Ok(stats)
}
/// Flush pending maintenance from opportunistic pruning queues.
///
/// Called every maintenance cycle (5 min). Instead of scanning all 34k+ edges,
/// this only processes edges that were found below prune threshold during normal
/// reads (via `get_entity_relationships_limited`). Typical cost: 0-50 targeted
/// deletes per cycle vs a full CF iterator scan.
pub fn flush_pending_maintenance(&self) -> Result<crate::memory::types::GraphDecayResult> {
// 1. Drain queues (fast — just swaps empty Vecs)
let to_prune: Vec<Uuid> = std::mem::take(&mut *self.pending_prune.lock());
let orphan_candidates: Vec<Uuid> = std::mem::take(&mut *self.pending_orphan_checks.lock());
if to_prune.is_empty() {
return Ok(crate::memory::types::GraphDecayResult::default());
}
// 2. Dedup UUIDs
let to_prune: std::collections::HashSet<Uuid> = to_prune.into_iter().collect();
let orphan_candidates: std::collections::HashSet<Uuid> =
orphan_candidates.into_iter().collect();
// 3. Batch delete pruned edges
let mut pruned_count = 0;
for edge_uuid in &to_prune {
if self.delete_relationship(edge_uuid)? {
pruned_count += 1;
}
}
// 4. Check which candidate entities became orphaned (lost ALL edges)
let mut orphaned_entity_ids = Vec::new();
for entity_uuid in &orphan_candidates {
let remaining = self.get_entity_relationships(entity_uuid)?;
if remaining.is_empty() {
orphaned_entity_ids.push(entity_uuid.to_string());
if let Err(e) = self.delete_entity(entity_uuid) {
tracing::warn!("Failed to delete orphaned entity {}: {}", entity_uuid, e);
}
}
}
if pruned_count > 0 {
tracing::debug!(
"Lazy pruning: {} edges deleted, {} entities orphaned",
pruned_count,
orphaned_entity_ids.len()
);
}
Ok(crate::memory::types::GraphDecayResult {
pruned_count,
orphaned_entity_ids,
orphaned_memory_ids: Vec::new(),
})
}
/// Adjust entity salience for all entities connected to the given memories.
///
/// Used by the reward loop to propagate recall feedback to entity reputation:
/// - Helpful recall → positive boost → entities become more trusted
/// - Misleading recall → negative penalty → entities lose reputation
/// - Habituation (ignored surfacings) → tiny penalty → noise entities decay
///
/// Looks up each memory's EpisodicNode, reads `entity_refs`, deduplicates,
/// then batch-updates salience clamped to [0.05, 1.0].
///
/// Returns the number of entities adjusted.
pub fn reinforce_entity_salience(&self, memory_uuids: &[Uuid], boost: f32) -> Result<usize> {
if memory_uuids.is_empty() || boost == 0.0 {
return Ok(0);
}
// Collect all unique entity UUIDs across all memories' episodes
let mut entity_uuids: std::collections::HashSet<Uuid> =
std::collections::HashSet::with_capacity(memory_uuids.len() * 4);
for mem_uuid in memory_uuids {
if let Some(episode) = self.get_episode(mem_uuid)? {
for entity_uuid in &episode.entity_refs {
entity_uuids.insert(*entity_uuid);
}
}
}
if entity_uuids.is_empty() {
return Ok(0);
}
// Batch-read all entities
let keys: Vec<[u8; 16]> = entity_uuids.iter().map(|u| *u.as_bytes()).collect();
let key_refs: Vec<&[u8]> = keys.iter().map(|k| k.as_slice()).collect();
let results = self
.db
.batched_multi_get_cf(self.entities_cf(), &key_refs, false);
let mut batch = rocksdb::WriteBatch::default();
let mut adjusted = 0;
for (i, result) in results.into_iter().enumerate() {
if let Ok(Some(value)) = result {
if let Ok((mut entity, _)) = crate::serialization::try_decode::<EntityNode>(&value)
{
let old_salience = entity.salience;
entity.salience = (entity.salience + boost).clamp(0.05, 1.0);
// Skip write if salience didn't actually change (already at boundary)
if (entity.salience - old_salience).abs() < f32::EPSILON {
continue;
}
if let Ok(encoded) = crate::serialization::encode(&entity) {
batch.put_cf(self.entities_cf(), &keys[i], encoded);
adjusted += 1;
}
}
}
}
if adjusted > 0 {
self.db.write(batch)?;
tracing::debug!(
adjusted,
boost,
"Entity salience reinforcement batch committed"
);
}
Ok(adjusted)
}
/// Get graph statistics - O(1) using atomic counters
pub fn get_stats(&self) -> Result<GraphStats> {
Ok(GraphStats {
entity_count: self.entity_count.load(Ordering::Relaxed),
relationship_count: self.relationship_count.load(Ordering::Relaxed),
episode_count: self.episode_count.load(Ordering::Relaxed),
})
}
/// Get all entities in the graph
pub fn get_all_entities(&self) -> Result<Vec<EntityNode>> {
let mut entities = Vec::new();
let mut read_opts = rocksdb::ReadOptions::default();
read_opts.fill_cache(false);
let iter =
self.db
.iterator_cf_opt(self.entities_cf(), read_opts, rocksdb::IteratorMode::Start);
for (_, value) in iter.flatten() {
if let Ok((entity, _)) = crate::serialization::try_decode::<EntityNode>(&value) {
entities.push(entity);
}
}
// Sort by mention count (most mentioned first)
entities.sort_by(|a, b| b.mention_count.cmp(&a.mention_count));
Ok(entities)
}
/// Get all relationships in the graph
pub fn get_all_relationships(&self) -> Result<Vec<RelationshipEdge>> {
let mut relationships = Vec::new();
// fill_cache(false) prevents this full scan from evicting hot data from
// the block cache. Decompressed blocks are used transiently and freed
// after the iterator advances, reducing peak C++ heap usage.
let mut read_opts = rocksdb::ReadOptions::default();
read_opts.fill_cache(false);
let iter = self.db.iterator_cf_opt(
self.relationships_cf(),
read_opts,
rocksdb::IteratorMode::Start,
);
for (_, value) in iter.flatten() {
if let Ok((edge, _)) = crate::serialization::try_decode::<RelationshipEdge>(&value) {
// Only include non-invalidated relationships
if edge.invalidated_at.is_none() {
relationships.push(edge);
}
}
}
// Sort by strength (strongest first)
relationships.sort_by(|a, b| b.strength.total_cmp(&a.strength));
Ok(relationships)
}
/// Get the Memory Universe visualization data
/// Returns entities as "stars" with positions based on their relationships,
/// sized by salience, and colored by entity type.
pub fn get_universe(&self) -> Result<MemoryUniverse> {
let entities = self.get_all_entities()?;
let relationships = self.get_all_relationships()?;
// Create entity UUID to index mapping for position calculation
let entity_indices: HashMap<Uuid, usize> = entities
.iter()
.enumerate()
.map(|(i, e)| (e.uuid, i))
.collect();
// Calculate 3D positions using a force-directed layout approximation
// High-salience entities are positioned more centrally
let mut stars: Vec<UniverseStar> = entities
.iter()
.enumerate()
.map(|(i, entity)| {
// Use a spiral galaxy layout with salience affecting radius
// Higher salience = closer to center
let angle = (i as f32) * 2.4; // Golden angle for even distribution
let base_radius = 1.0 - entity.salience; // High salience = small radius
let radius = base_radius * 100.0 + 10.0; // 10-110 range
let x = radius * angle.cos();
let y = radius * angle.sin();
let z = ((i as f32) * 0.1).sin() * 20.0; // Slight z variation
UniverseStar {
id: entity.uuid.to_string(),
name: entity.name.clone(),
entity_type: entity.labels.first().map(|l| l.as_str().to_string()),
salience: entity.salience,
mention_count: entity.mention_count,
is_proper_noun: entity.is_proper_noun,
position: Position3D { x, y, z },
color: entity_type_color(entity.labels.first()),
size: 5.0 + entity.salience * 20.0, // Size 5-25 based on salience
}
})
.collect();
// Apply gravitational forces FIRST, before creating connections
// This ensures connection positions match final star positions
for rel in &relationships {
if let (Some(from_idx), Some(to_idx)) = (
entity_indices.get(&rel.from_entity),
entity_indices.get(&rel.to_entity),
) {
// Apply small gravitational pull based on effective (decay-aware) strength
let pull_factor = rel.effective_strength() * 0.05;
let from_pos = stars[*from_idx].position.clone();
let to_pos = stars[*to_idx].position.clone();
let dx = (to_pos.x - from_pos.x) * pull_factor;
let dy = (to_pos.y - from_pos.y) * pull_factor;
let dz = (to_pos.z - from_pos.z) * pull_factor;
stars[*from_idx].position.x += dx;
stars[*from_idx].position.y += dy;
stars[*from_idx].position.z += dz;
stars[*to_idx].position.x -= dx;
stars[*to_idx].position.y -= dy;
stars[*to_idx].position.z -= dz;
}
}
// Create gravitational connections AFTER star positions are finalized
// This ensures from_position/to_position match current star positions
let connections: Vec<GravitationalConnection> = relationships
.iter()
.filter_map(|rel| {
let from_idx = entity_indices.get(&rel.from_entity)?;
let to_idx = entity_indices.get(&rel.to_entity)?;
Some(GravitationalConnection {
id: rel.uuid.to_string(),
from_id: rel.from_entity.to_string(),
to_id: rel.to_entity.to_string(),
relation_type: rel.relation_type.as_str().to_string(),
strength: rel.effective_strength(),
from_position: stars[*from_idx].position.clone(),
to_position: stars[*to_idx].position.clone(),
})
})
.collect();
// Calculate universe bounds
let (min_x, max_x, min_y, max_y, min_z, max_z) = stars.iter().fold(
(f32::MAX, f32::MIN, f32::MAX, f32::MIN, f32::MAX, f32::MIN),
|(min_x, max_x, min_y, max_y, min_z, max_z), star| {
(
min_x.min(star.position.x),
max_x.max(star.position.x),
min_y.min(star.position.y),
max_y.max(star.position.y),
min_z.min(star.position.z),
max_z.max(star.position.z),
)
},
);
Ok(MemoryUniverse {
stars,
connections,
total_entities: entities.len(),
total_connections: relationships.len(),
bounds: UniverseBounds {
min: Position3D {
x: min_x,
y: min_y,
z: min_z,
},
max: Position3D {
x: max_x,
y: max_y,
z: max_z,
},
},
})
}
}
/// Helper function to get color for entity type
fn entity_type_color(label: Option<&EntityLabel>) -> String {
match label {
Some(EntityLabel::Person) => "#FF6B6B".to_string(), // Coral red
Some(EntityLabel::Organization) => "#4ECDC4".to_string(), // Teal
Some(EntityLabel::Location) => "#45B7D1".to_string(), // Sky blue
Some(EntityLabel::Technology) => "#96CEB4".to_string(), // Sage green
Some(EntityLabel::Product) => "#FFEAA7".to_string(), // Soft yellow
Some(EntityLabel::Event) => "#DDA0DD".to_string(), // Plum
Some(EntityLabel::Skill) => "#98D8C8".to_string(), // Mint
Some(EntityLabel::Concept) => "#F7DC6F".to_string(), // Gold
Some(EntityLabel::Date) => "#BB8FCE".to_string(), // Light purple
Some(EntityLabel::Keyword) => "#FF9F43".to_string(), // Orange for YAKE keywords
Some(EntityLabel::Project) => "#E74C3C".to_string(), // Red — project anchors
Some(EntityLabel::Task) => "#F39C12".to_string(), // Amber — work items
Some(EntityLabel::Document) => "#1ABC9C".to_string(), // Turquoise — knowledge
Some(EntityLabel::Repository) => "#2ECC71".to_string(), // Emerald — code entities
Some(EntityLabel::Service) => "#3498DB".to_string(), // Blue — architectural
Some(EntityLabel::Database) => "#9B59B6".to_string(), // Purple — data stores
Some(EntityLabel::Metric) => "#E67E22".to_string(), // Dark orange — telemetry
Some(EntityLabel::Configuration) => "#95A5A6".to_string(), // Silver — config
Some(EntityLabel::Environment) => "#16A085".to_string(), // Dark teal — infra
Some(EntityLabel::Pipeline) => "#2980B9".to_string(), // Dark blue — CI/CD
Some(EntityLabel::Team) => "#27AE60".to_string(), // Green — organizational
Some(EntityLabel::Role) => "#8E44AD".to_string(), // Dark purple — roles
Some(EntityLabel::Module) => "#D35400".to_string(), // Pumpkin — code modules
Some(EntityLabel::Other(_)) => "#AEB6BF".to_string(), // Gray
None => "#AEB6BF".to_string(), // Gray default
}
}
/// 3D position in the memory universe
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Position3D {
pub x: f32,
pub y: f32,
pub z: f32,
}
/// A star in the memory universe (represents an entity)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UniverseStar {
pub id: String,
pub name: String,
pub entity_type: Option<String>,
pub salience: f32,
pub mention_count: usize,
pub is_proper_noun: bool,
pub position: Position3D,
pub color: String,
pub size: f32,
}
/// A gravitational connection between stars (represents a relationship)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GravitationalConnection {
pub id: String,
pub from_id: String,
pub to_id: String,
pub relation_type: String,
pub strength: f32,
pub from_position: Position3D,
pub to_position: Position3D,
}
/// Bounds of the memory universe
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UniverseBounds {
pub min: Position3D,
pub max: Position3D,
}
/// The complete memory universe visualization
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryUniverse {
pub stars: Vec<UniverseStar>,
pub connections: Vec<GravitationalConnection>,
pub total_entities: usize,
pub total_connections: usize,
pub bounds: UniverseBounds,
}
/// Entity with hop distance from traversal origin
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TraversedEntity {
pub entity: EntityNode,
/// Number of hops from the starting entity (0 = start entity)
pub hop_distance: usize,
/// Decay factor based on hop distance: 1.0 at hop 0, decays with each hop
pub decay_factor: f32,
}
/// Result of graph traversal
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GraphTraversal {
/// Entities found during traversal with hop distance info
pub entities: Vec<TraversedEntity>,
pub relationships: Vec<RelationshipEdge>,
}
/// Graph statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GraphStats {
pub entity_count: usize,
pub relationship_count: usize,
pub episode_count: usize,
}
/// Summary statistics from Forman-Ricci curvature computation
///
/// Lightweight reputation signal for an entity, derived from graph topology.
/// Used by NER quality gating to penalize/reject known stop-word entities.
#[derive(Debug, Clone)]
pub struct EntityReputation {
/// Curvature selectivity: high = concept, low = stop-word hub
pub selectivity: f32,
/// How many times this entity has been mentioned
pub mention_count: usize,
/// Number of edges incident to this entity
pub degree: usize,
/// Feedback-driven salience (reward loop output, 0.05–1.0)
pub salience: f32,
}
/// Captures the distribution of curvature across the knowledge graph.
/// Positive curvature = tightly-connected community interior edges.
/// Negative curvature = bridge/bottleneck edges between hubs.
///
/// Reference: Leal, Restrepo, Stadler, Jost (2018) arXiv:1811.07825
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CurvatureStats {
/// Number of edges with curvature computed
pub edges_computed: usize,
/// Mean curvature across all edges
pub mean_curvature: f32,
/// Minimum curvature (most negative = strongest bottleneck)
pub min_curvature: f32,
/// Maximum curvature (most positive = tightest community)
pub max_curvature: f32,
/// Number of edges with positive curvature (community-interior)
pub positive_count: usize,
/// Number of edges with zero curvature
pub zero_count: usize,
/// Number of edges with negative curvature (bridges/bottlenecks)
pub negative_count: usize,
}
/// Extracted entity with salience information
#[derive(Debug, Clone)]
pub struct ExtractedEntity {
pub name: String,
pub label: EntityLabel,
pub base_salience: f32,
}
/// Simple entity extraction (rule-based NER) with salience detection
pub struct EntityExtractor {
/// Common person name indicators
person_indicators: HashSet<String>,
/// Common organization indicators (suffixes like Inc, Corp)
org_indicators: HashSet<String>,
/// Known organization names (direct matches)
org_keywords: HashSet<String>,
/// Known location names (cities, countries, regions)
location_keywords: HashSet<String>,
/// Common technology keywords
tech_keywords: HashSet<String>,
/// Common words that should NOT be extracted as entities
/// (stop words that start with capitals at sentence beginning)
stop_words: HashSet<String>,
// Extended ontological keyword dictionaries (2026-03)
/// Service/infrastructure keywords (microservices, daemons, proxies)
service_keywords: HashSet<String>,
/// Database system keywords
database_keywords: HashSet<String>,
/// CI/CD and data pipeline keywords
pipeline_keywords: HashSet<String>,
/// Deployment environment keywords
environment_keywords: HashSet<String>,
/// Observability and metric keywords
metric_keywords: HashSet<String>,
}
impl EntityExtractor {
pub fn new() -> Self {
let person_indicators: HashSet<String> =
vec!["mr", "mrs", "ms", "dr", "prof", "sir", "madam"]
.into_iter()
.map(String::from)
.collect();
let org_indicators: HashSet<String> = vec![
"inc",
"corp",
"ltd",
"llc",
"company",
"corporation",
"university",
"institute",
"foundation",
]
.into_iter()
.map(String::from)
.collect();
let tech_keywords: HashSet<String> = vec![
"rust",
"python",
"java",
"javascript",
"typescript",
"react",
"vue",
"angular",
"docker",
"kubernetes",
"aws",
"azure",
"gcp",
"sql",
"nosql",
"mongodb",
"postgresql",
"redis",
"kafka",
"api",
"rest",
"graphql",
]
.into_iter()
.map(String::from)
.collect();
// Known organization names (global - India-first, then worldwide)
let org_keywords: HashSet<String> = vec![
// Indian Companies - IT/Tech
"tcs",
"infosys",
"wipro",
"hcl",
"tech mahindra",
"cognizant",
"mindtree",
"mphasis",
"ltimindtree",
"persistent",
"zensar",
"cyient",
"hexaware",
"coforge",
"birlasoft",
"sonata software",
"mastek",
"newgen",
// Indian Companies - Startups/Unicorns
"flipkart",
"paytm",
"zomato",
"swiggy",
"ola",
"oyo",
"byju's",
"byjus",
"razorpay",
"phonepe",
"cred",
"zerodha",
"groww",
"upstox",
"policybazaar",
"nykaa",
"meesho",
"udaan",
"delhivery",
"freshworks",
"zoho",
"postman",
"browserstack",
"chargebee",
"clevertap",
"druva",
"hasura",
"innovaccer",
"lenskart",
"mamaearth",
"unacademy",
"vedantu",
"physicswallah",
"dream11",
"mpl",
"winzo",
"slice",
"jupiter",
"fi",
"niyo",
"smallcase",
"koo",
"sharechat",
"dailyhunt",
"pratilipi",
"inshorts",
"rapido",
"urban company",
"dunzo",
"bigbasket",
"grofers",
"blinkit",
"jiomart",
"tata neu",
// Indian Conglomerates
"tata",
"reliance",
"jio",
"adani",
"birla",
"mahindra",
"godrej",
"bajaj",
"hdfc",
"icici",
"kotak",
"axis",
"sbi",
"bharti",
"airtel",
"vodafone",
"idea",
"hero",
"tvs",
"maruti",
"suzuki",
"hyundai",
"kia",
"mg",
"tata motors",
"larsen",
"toubro",
"l&t",
"itc",
"hindustan unilever",
"hul",
"nestle",
"britannia",
"parle",
"amul",
"dabur",
"patanjali",
"emami",
"marico",
// Indian Banks & Finance
"rbi",
"sebi",
"nse",
"bse",
"npci",
"upi",
"bhim",
"paisa",
"mswipe",
"pine labs",
"billdesk",
"ccavenue",
"instamojo",
"cashfree",
// Indian Institutions
"iit",
"iim",
"iisc",
"nit",
"bits",
"isro",
"drdo",
"barc",
"tifr",
"aiims",
"iiser",
"iiit",
"srm",
"vit",
"manipal",
"amity",
"lovely",
// Global Tech Giants
"microsoft",
"google",
"apple",
"amazon",
"meta",
"facebook",
"netflix",
"alphabet",
"youtube",
"instagram",
"whatsapp",
"tiktok",
"snapchat",
"twitter",
"x",
"linkedin",
"pinterest",
"reddit",
"discord",
"telegram",
// Global Enterprise Tech
"salesforce",
"oracle",
"ibm",
"sap",
"vmware",
"dell",
"hp",
"hpe",
"cisco",
"juniper",
"palo alto",
"crowdstrike",
"fortinet",
"splunk",
"servicenow",
"workday",
"atlassian",
"jira",
"confluence",
"trello",
"asana",
"monday",
"notion",
"airtable",
"figma",
"canva",
"miro",
// Global Cloud & Infrastructure
"aws",
"azure",
"gcp",
"digitalocean",
"linode",
"vultr",
"cloudflare",
"akamai",
"fastly",
"vercel",
"netlify",
"heroku",
"render",
"railway",
// Global Hardware/Chip
"intel",
"amd",
"nvidia",
"qualcomm",
"broadcom",
"arm",
"tsmc",
"samsung",
"mediatek",
"apple silicon",
"marvell",
"micron",
"sk hynix",
"western digital",
// Global AI/ML Companies
"openai",
"anthropic",
"deepmind",
"cohere",
"stability",
"midjourney",
"hugging face",
"databricks",
"snowflake",
"palantir",
"c3ai",
"datarobot",
// Global Fintech
"stripe",
"square",
"block",
"paypal",
"venmo",
"wise",
"revolut",
"robinhood",
"coinbase",
"binance",
"kraken",
"gemini",
"ftx",
"blockchain",
"ripple",
// Global Dev Tools
"github",
"gitlab",
"bitbucket",
"jetbrains",
"vscode",
"sublime",
"vim",
"docker",
"kubernetes",
"terraform",
"ansible",
"puppet",
"chef",
// Global Consulting
"accenture",
"deloitte",
"pwc",
"kpmg",
"ey",
"mckinsey",
"bcg",
"bain",
// Global Auto/EV
"tesla",
"rivian",
"lucid",
"nio",
"byd",
"xpeng",
"volkswagen",
"bmw",
"mercedes",
"audi",
"porsche",
"toyota",
"honda",
"nissan",
"ford",
"gm",
// Global Aerospace
"spacex",
"boeing",
"airbus",
"lockheed",
"northrop",
"raytheon",
"nasa",
"esa",
"jaxa",
"isro",
"blue origin",
"virgin galactic",
// Universities - India
"delhi university",
"jnu",
"bhu",
"amu",
"jadavpur",
"presidency",
"st stephens",
"loyola",
"xavier",
"symbiosis",
"nmims",
"sp jain",
"xlri",
"fms",
"iift",
"mdi",
"great lakes",
"ism dhanbad",
// Universities - Global
"mit",
"stanford",
"harvard",
"yale",
"princeton",
"caltech",
"berkeley",
"oxford",
"cambridge",
"imperial",
"eth zurich",
"epfl",
"tsinghua",
"peking",
"nus",
"nanyang",
"kaist",
"university of tokyo",
"melbourne",
]
.into_iter()
.map(String::from)
.collect();
// Known location names (global - India-first, then worldwide)
let location_keywords: HashSet<String> = vec![
// Indian Metro Cities
"mumbai",
"delhi",
"bangalore",
"bengaluru",
"hyderabad",
"chennai",
"kolkata",
"pune",
"ahmedabad",
"surat",
"jaipur",
"lucknow",
// Indian Tier-1 Cities
"kochi",
"cochin",
"thiruvananthapuram",
"trivandrum",
"coimbatore",
"madurai",
"visakhapatnam",
"vizag",
"vijayawada",
"nagpur",
"indore",
"bhopal",
"chandigarh",
"mohali",
"panchkula",
"noida",
"gurgaon",
"gurugram",
"faridabad",
"ghaziabad",
"greater noida",
"dwarka",
// Indian Tier-2 Cities
"mysore",
"mangalore",
"hubli",
"belgaum",
"nashik",
"aurangabad",
"rajkot",
"vadodara",
"baroda",
"gandhinagar",
"kanpur",
"varanasi",
"allahabad",
"prayagraj",
"agra",
"meerut",
"dehradun",
"rishikesh",
"haridwar",
"amritsar",
"jalandhar",
"ludhiana",
"shimla",
"manali",
"dharamshala",
"jammu",
"srinagar",
"ranchi",
"jamshedpur",
"patna",
"guwahati",
"shillong",
"imphal",
"kohima",
"gangtok",
"darjeeling",
"bhubaneswar",
"cuttack",
"rourkela",
"raipur",
"bilaspur",
// Indian States & UTs
"maharashtra",
"karnataka",
"tamil nadu",
"telangana",
"andhra pradesh",
"kerala",
"gujarat",
"rajasthan",
"uttar pradesh",
"madhya pradesh",
"west bengal",
"bihar",
"odisha",
"jharkhand",
"chhattisgarh",
"punjab",
"haryana",
"himachal pradesh",
"uttarakhand",
"goa",
"assam",
"meghalaya",
"manipur",
"nagaland",
"tripura",
"mizoram",
"arunachal pradesh",
"sikkim",
"jammu and kashmir",
"ladakh",
// Indian Regions
"silicon valley of india",
"electronic city",
"whitefield",
"marathahalli",
"koramangala",
"indiranagar",
"hsr layout",
"jayanagar",
"malleshwaram",
"bandra",
"andheri",
"powai",
"lower parel",
"bkc",
"navi mumbai",
"thane",
"connaught place",
"nehru place",
"saket",
"cyber city",
"dlf",
"hitech city",
"madhapur",
"gachibowli",
"ecr",
"omr",
"it corridor",
// Asian Cities
"singapore",
"hong kong",
"tokyo",
"osaka",
"seoul",
"busan",
"beijing",
"shanghai",
"shenzhen",
"guangzhou",
"hangzhou",
"taipei",
"bangkok",
"kuala lumpur",
"jakarta",
"manila",
"ho chi minh",
"hanoi",
"dubai",
"abu dhabi",
"doha",
"riyadh",
"tel aviv",
"istanbul",
// European Cities
"london",
"paris",
"berlin",
"munich",
"frankfurt",
"amsterdam",
"rotterdam",
"brussels",
"zurich",
"geneva",
"vienna",
"prague",
"warsaw",
"budapest",
"barcelona",
"madrid",
"milan",
"rome",
"lisbon",
"dublin",
"edinburgh",
"manchester",
"stockholm",
"oslo",
"helsinki",
"copenhagen",
"athens",
"moscow",
"st petersburg",
// North American Cities
"new york",
"los angeles",
"san francisco",
"seattle",
"boston",
"chicago",
"austin",
"denver",
"portland",
"miami",
"atlanta",
"dallas",
"houston",
"phoenix",
"san diego",
"san jose",
"oakland",
"palo alto",
"mountain view",
"cupertino",
"menlo park",
"redwood city",
"washington dc",
"philadelphia",
"detroit",
"toronto",
"vancouver",
"montreal",
"calgary",
"ottawa",
"mexico city",
"guadalajara",
// South American Cities
"sao paulo",
"rio de janeiro",
"buenos aires",
"santiago",
"bogota",
"lima",
"medellin",
"cartagena",
// African Cities
"johannesburg",
"cape town",
"lagos",
"nairobi",
"cairo",
"casablanca",
"accra",
"addis ababa",
"kigali",
// Australian/NZ Cities
"sydney",
"melbourne",
"brisbane",
"perth",
"auckland",
"wellington",
// Countries - Asia
"india",
"china",
"japan",
"south korea",
"korea",
"taiwan",
"singapore",
"malaysia",
"thailand",
"vietnam",
"indonesia",
"philippines",
"bangladesh",
"pakistan",
"sri lanka",
"nepal",
"bhutan",
"myanmar",
"cambodia",
"laos",
// Countries - Middle East
"uae",
"emirates",
"saudi arabia",
"qatar",
"bahrain",
"kuwait",
"oman",
"israel",
"turkey",
"iran",
"iraq",
"jordan",
"lebanon",
"egypt",
// Countries - Europe
"uk",
"united kingdom",
"britain",
"england",
"scotland",
"wales",
"ireland",
"france",
"germany",
"italy",
"spain",
"portugal",
"netherlands",
"belgium",
"switzerland",
"austria",
"poland",
"czech",
"hungary",
"romania",
"bulgaria",
"greece",
"sweden",
"norway",
"finland",
"denmark",
"russia",
"ukraine",
// Countries - Americas
"usa",
"united states",
"america",
"canada",
"mexico",
"brazil",
"argentina",
"chile",
"colombia",
"peru",
"venezuela",
// Countries - Africa/Oceania
"south africa",
"nigeria",
"kenya",
"ghana",
"ethiopia",
"rwanda",
"australia",
"new zealand",
// Famous Tech Hubs
"silicon valley",
"bay area",
"wall street",
"tech city",
"shoreditch",
"station f",
"blockchain island",
"crypto valley",
"startup nation",
"innovation district",
"tech park",
"it park",
"sez",
"special economic zone",
]
.into_iter()
.map(String::from)
.collect();
// Stop words: common words that appear capitalized at sentence start
// These aren't named entities even when capitalized
let stop_words: HashSet<String> = vec![
// Articles & pronouns
"the", "a", "an", "this", "that", "these", "those", "i", "we", "you", "he", "she", "it",
"they", // Common verbs (appear at sentence start)
"is", "are", "was", "were", "been", "being", "have", "has", "had", "do", "does", "did",
"will", "would", "could", "should", "may", "might", // Question words
"if", "when", "where", "what", "why", "how",
]
.into_iter()
.map(String::from)
.collect();
// Service/infrastructure keywords
let service_keywords: HashSet<String> = vec![
"microservice",
"daemon",
"worker",
"cron",
"lambda",
"serverless",
"gateway",
"proxy",
"nginx",
"envoy",
"istio",
"grpc",
"graphql",
"webhook",
"middleware",
"sidecar",
"ingress",
"loadbalancer",
]
.into_iter()
.map(String::from)
.collect();
// Database system keywords
let database_keywords: HashSet<String> = vec![
"postgresql",
"postgres",
"mysql",
"mariadb",
"sqlite",
"dynamodb",
"cassandra",
"elasticsearch",
"opensearch",
"clickhouse",
"timescaledb",
"cockroachdb",
"neo4j",
"arangodb",
"rocksdb",
"leveldb",
"badger",
"redb",
"sled",
"foundationdb",
"vitess",
"couchbase",
"couchdb",
"influxdb",
"questdb",
"duckdb",
"dragonfly",
"valkey",
]
.into_iter()
.map(String::from)
.collect();
// CI/CD and pipeline keywords
let pipeline_keywords: HashSet<String> = vec![
"jenkins",
"circleci",
"travis",
"argo",
"tekton",
"spinnaker",
"buildkite",
"drone",
"concourse",
"woodpecker",
"flux",
"argocd",
"terraform",
"pulumi",
"ansible",
"airflow",
"dagster",
"prefect",
]
.into_iter()
.map(String::from)
.collect();
// Deployment environment keywords
let environment_keywords: HashSet<String> = vec![
"staging",
"production",
"prod",
"dev",
"development",
"sandbox",
"canary",
"preview",
"qa",
"uat",
"integration",
"preprod",
"hotfix",
"nightly",
"edge",
]
.into_iter()
.map(String::from)
.collect();
// Observability and metric keywords
let metric_keywords: HashSet<String> = vec![
"latency",
"throughput",
"p99",
"p95",
"p50",
"slo",
"sla",
"sli",
"uptime",
"availability",
"mttr",
"mttf",
"error rate",
"saturation",
"prometheus",
"grafana",
"datadog",
"newrelic",
"jaeger",
"tempo",
"loki",
"opentelemetry",
"otel",
]
.into_iter()
.map(String::from)
.collect();
Self {
person_indicators,
org_indicators,
org_keywords,
location_keywords,
tech_keywords,
stop_words,
service_keywords,
database_keywords,
pipeline_keywords,
environment_keywords,
metric_keywords,
}
}
/// Calculate base salience for an entity based on its type and detection confidence
///
/// Salience values by entity type:
/// - Person: 0.8 (highest - people are key context)
/// - Organization/Product: 0.7
/// - Location/Technology/Event: 0.6
/// - Skill: 0.5
/// - Concept: 0.4
/// - Date/Other: 0.3
///
/// Proper nouns receive a 20% boost (capped at 1.0).
pub fn calculate_base_salience(label: &EntityLabel, is_proper_noun: bool) -> f32 {
let type_salience = match label {
EntityLabel::Person => 0.8, // People are highly salient
EntityLabel::Organization => 0.7, // Organizations are important
EntityLabel::Location => 0.6, // Locations matter for context
EntityLabel::Technology => 0.6, // Tech keywords matter for dev context
EntityLabel::Product => 0.7, // Products are specific entities
EntityLabel::Event => 0.6, // Events are temporal anchors
EntityLabel::Skill => 0.5, // Skills are somewhat important
EntityLabel::Keyword => 0.55, // YAKE keywords - discriminative terms
EntityLabel::Concept => 0.4, // Concepts are more generic
EntityLabel::Date => 0.3, // Dates are structural, not salient
EntityLabel::Project => 0.7, // Projects are specific, high-salience anchors
EntityLabel::Task => 0.55, // Tasks are common but specific work items
EntityLabel::Document => 0.5, // Documents provide contextual reference
EntityLabel::Repository => 0.65, // Repos are identifiable code entities
EntityLabel::Service => 0.65, // Services are architectural anchors
EntityLabel::Database => 0.6, // Databases are infrastructure anchors
EntityLabel::Metric => 0.5, // Metrics are precise but numerous
EntityLabel::Configuration => 0.45, // Config is low-salience, high-frequency
EntityLabel::Environment => 0.5, // Environments are contextual
EntityLabel::Pipeline => 0.6, // Pipelines are operational entities
EntityLabel::Team => 0.7, // Teams are organizational anchors
EntityLabel::Role => 0.55, // Roles are semi-generic
EntityLabel::Module => 0.55, // Modules are code-level entities
EntityLabel::Other(_) => 0.3, // Unknown types get low salience
};
// Proper nouns get a 20% boost
if is_proper_noun {
(type_salience * 1.2_f32).min(1.0_f32)
} else {
type_salience
}
}
/// Check if a word is likely a proper noun (not just capitalized at sentence start)
fn is_likely_proper_noun(&self, word: &str, position: usize, prev_char: Option<char>) -> bool {
// If it's not at position 0 and is capitalized, it's likely a proper noun
if position > 0 {
return true;
}
// At position 0, check if previous character was punctuation (sentence start)
// If previous char was '.', '!', '?' then this might just be sentence capitalization
if let Some(c) = prev_char {
if c == '.' || c == '!' || c == '?' {
// It's at sentence start - could be either
// Check if it's a common word
let lower = word.to_lowercase();
return !self.stop_words.contains(&lower);
}
}
// Default to proper noun for capitalized words
true
}
/// Extract entities from text with salience information
pub fn extract_with_salience(&self, text: &str) -> Vec<ExtractedEntity> {
let mut entities = Vec::new();
let mut seen = HashSet::new();
let mut skip_until_index = 0; // For skipping sub-spans of multi-word entities
// Split into words and detect capitalized sequences
let words: Vec<&str> = text.split_whitespace().collect();
for (i, word) in words.iter().enumerate() {
// Skip if this word is part of a multi-word entity we already extracted
if i < skip_until_index {
continue;
}
let clean_word = word.trim_matches(|c: char| !c.is_alphanumeric());
if clean_word.is_empty() {
continue;
}
let lower = clean_word.to_lowercase();
// Skip common stop words
if self.stop_words.contains(&lower) {
continue;
}
// Check for known organization keywords (direct match, min 2 chars to filter "x" noise)
if lower.len() >= 2 && self.org_keywords.contains(&lower) && !seen.contains(&lower) {
let entity = ExtractedEntity {
name: clean_word.to_string(),
label: EntityLabel::Organization,
base_salience: Self::calculate_base_salience(&EntityLabel::Organization, true),
};
entities.push(entity);
seen.insert(lower.clone());
continue;
}
// Check for known location keywords (direct match)
if self.location_keywords.contains(&lower) && !seen.contains(&lower) {
let entity = ExtractedEntity {
name: clean_word.to_string(),
label: EntityLabel::Location,
base_salience: Self::calculate_base_salience(&EntityLabel::Location, true),
};
entities.push(entity);
seen.insert(lower.clone());
continue;
}
// Check for technology keywords (always proper nouns in tech context)
// Check extended ontological keyword dictionaries (more specific before generic)
if self.database_keywords.contains(&lower) && !seen.contains(&lower) {
entities.push(ExtractedEntity {
name: clean_word.to_string(),
label: EntityLabel::Database,
base_salience: Self::calculate_base_salience(&EntityLabel::Database, true),
});
seen.insert(lower.clone());
continue;
}
if self.pipeline_keywords.contains(&lower) && !seen.contains(&lower) {
entities.push(ExtractedEntity {
name: clean_word.to_string(),
label: EntityLabel::Pipeline,
base_salience: Self::calculate_base_salience(&EntityLabel::Pipeline, true),
});
seen.insert(lower.clone());
continue;
}
if self.service_keywords.contains(&lower) && !seen.contains(&lower) {
entities.push(ExtractedEntity {
name: clean_word.to_string(),
label: EntityLabel::Service,
base_salience: Self::calculate_base_salience(&EntityLabel::Service, true),
});
seen.insert(lower.clone());
continue;
}
if self.environment_keywords.contains(&lower) && !seen.contains(&lower) {
entities.push(ExtractedEntity {
name: clean_word.to_string(),
label: EntityLabel::Environment,
base_salience: Self::calculate_base_salience(&EntityLabel::Environment, false),
});
seen.insert(lower.clone());
continue;
}
if self.metric_keywords.contains(&lower) && !seen.contains(&lower) {
entities.push(ExtractedEntity {
name: clean_word.to_string(),
label: EntityLabel::Metric,
base_salience: Self::calculate_base_salience(&EntityLabel::Metric, false),
});
seen.insert(lower.clone());
continue;
}
// Generic technology keywords (catch-all for tech not matched above)
if self.tech_keywords.contains(&lower) && !seen.contains(&lower) {
let entity = ExtractedEntity {
name: clean_word.to_string(),
label: EntityLabel::Technology,
base_salience: Self::calculate_base_salience(&EntityLabel::Technology, true),
};
entities.push(entity);
seen.insert(lower.clone());
continue;
}
// Check for capitalized words (potential entities)
if clean_word
.chars()
.next()
.map(|c| c.is_uppercase())
.unwrap_or(false)
{
let mut entity_name = clean_word.to_string();
let mut entity_label = EntityLabel::Other("Unknown".to_string());
// Determine previous character for proper noun detection
let prev_char = if i > 0 {
words[i - 1].chars().last()
} else {
None
};
let is_proper = self.is_likely_proper_noun(clean_word, i, prev_char);
// Check for person indicators
if i > 0
&& self
.person_indicators
.contains(&words[i - 1].to_lowercase())
{
entity_label = EntityLabel::Person;
}
// Check for multi-word capitalized sequences.
// Include capitalized stop words (Of, The, And) in entity names
// to preserve proper nouns like "Bank Of America", "University Of Delhi".
let mut j = i + 1;
while j < words.len()
&& words[j]
.chars()
.next()
.map(|c| c.is_uppercase())
.unwrap_or(false)
{
let next_word = words[j].trim_matches(|c: char| !c.is_alphanumeric());
entity_name.push(' ');
entity_name.push_str(next_word);
j += 1;
}
// Set skip_until_index to avoid extracting sub-spans
// e.g., if we extracted "John Smith", skip "Smith" on next iteration
if j > i + 1 {
skip_until_index = j;
}
let entity_name_lower = entity_name.to_lowercase();
// Check multi-word entity against known lists
if self.org_keywords.contains(&entity_name_lower) {
entity_label = EntityLabel::Organization;
} else if self.location_keywords.contains(&entity_name_lower) {
entity_label = EntityLabel::Location;
}
// Check for organization indicators (suffixes)
if matches!(entity_label, EntityLabel::Other(_)) {
for word in entity_name.split_whitespace() {
if self.org_indicators.contains(&word.to_lowercase()) {
entity_label = EntityLabel::Organization;
break;
}
}
}
// Only extract entities we have evidence for
// Don't guess on single unknown capitalized words - they're often noise
if matches!(entity_label, EntityLabel::Other(_)) {
if entity_name.contains(' ') {
// Multi-word capitalized sequences (like "John Smith", "New York")
// are likely proper names — use Concept as safe default
// Concept(0.4) + proper noun boost(1.2x) = 0.48 salience
// Hebbian strengthening will promote genuinely important entities
entity_label = EntityLabel::Concept;
} else {
// Single capitalized word not in any keyword list
// Skip it - we don't have enough evidence it's a real entity
// The neural NER model handles these cases properly
continue;
}
}
let entity_key = entity_name_lower;
if !seen.contains(&entity_key) {
let base_salience = Self::calculate_base_salience(&entity_label, is_proper);
let entity = ExtractedEntity {
name: entity_name,
label: entity_label,
base_salience,
};
entities.push(entity);
seen.insert(entity_key);
}
}
}
// HYBRID APPROACH: POS-based extraction + YAKE importance scoring
//
// 1. POS extraction ensures ALL content words are captured (no frequency bias)
// 2. YAKE provides discriminativeness scores for boosting rare/important terms
//
// This solves the "sunrise problem": YAKE alone buries rare words at position 41,
// but POS ensures "sunrise" is extracted, and YAKE boosts its salience.
use crate::embeddings::keywords::{KeywordConfig, KeywordExtractor};
use crate::memory::query_parser::{extract_chunks, PosTag};
// Get YAKE importance scores for discriminative weighting
let kw_config = KeywordConfig {
max_keywords: 100, // Get many keywords for lookup
ngrams: 1,
min_length: 3,
..Default::default()
};
let kw_extractor = KeywordExtractor::with_config(kw_config);
let keywords = kw_extractor.extract(text);
// Build a lookup map: term -> importance (0.0-1.0)
let yake_importance: std::collections::HashMap<String, f32> = keywords
.into_iter()
.map(|kw| (kw.text.to_lowercase(), kw.importance))
.collect();
// POS-based extraction for comprehensive coverage
let chunk_extraction = extract_chunks(text);
// Add all proper nouns (these are likely named entities we might have missed)
for proper_noun in &chunk_extraction.proper_nouns {
let term_lower = proper_noun.to_lowercase();
if !seen.contains(&term_lower) && term_lower.len() >= 3 {
// Boost salience if YAKE identified this as discriminative
let yake_boost = yake_importance.get(&term_lower).copied().unwrap_or(0.0);
let entity = ExtractedEntity {
name: proper_noun.clone(),
label: EntityLabel::Person,
base_salience: 0.7 + (yake_boost * 0.2), // 0.7-0.9
};
entities.push(entity);
seen.insert(term_lower);
}
}
// Add all content words as Keyword entities
// POS ensures comprehensive extraction, YAKE boosts discriminative terms
for chunk in &chunk_extraction.chunks {
for word in &chunk.words {
let term_lower = word.text.to_lowercase();
// Skip if already extracted or too short
if seen.contains(&term_lower) || term_lower.len() < 4 {
continue;
}
// Skip stop words
if self.stop_words.contains(&term_lower) {
continue;
}
// Base salience by POS, boosted by YAKE importance
let yake_boost = yake_importance.get(&term_lower).copied().unwrap_or(0.0);
let (label, base_salience) = match word.pos {
PosTag::Noun | PosTag::ProperNoun => {
// Nouns are most important, start at 0.5
(EntityLabel::Keyword, 0.5)
}
PosTag::Verb => {
// Verbs connect entities, start at 0.4
(EntityLabel::Keyword, 0.4)
}
PosTag::Adjective => {
// Adjectives are modifiers, start at 0.35
(EntityLabel::Keyword, 0.35)
}
_ => continue,
};
// Boost by YAKE importance (0.0-0.3 boost based on discriminativeness)
let final_salience = base_salience + (yake_boost * 0.3);
let entity = ExtractedEntity {
name: word.text.clone(),
label,
base_salience: final_salience,
};
entities.push(entity);
seen.insert(term_lower);
}
}
entities
}
/// Extract co-occurrence pairs from text for graph edge creation
///
/// Returns pairs of (entity1, entity2) that appear in the same sentence.
/// This enables creating edges between words that co-occur, which is critical
/// for multi-hop retrieval (e.g., connecting "Melanie" to "sunrise" when
/// they appear in the same sentence about painting).
pub fn extract_cooccurrence_pairs(&self, text: &str) -> Vec<(String, String)> {
use crate::memory::query_parser::extract_chunks;
let chunk_extraction = extract_chunks(text);
let mut pairs = Vec::new();
// Get all co-occurrence pairs from chunks (same sentence)
for chunk in &chunk_extraction.chunks {
let content_words = chunk.content_words();
// Create pairs between all content words in the same sentence
for i in 0..content_words.len() {
for j in (i + 1)..content_words.len() {
let w1 = content_words[i].text.to_lowercase();
let w2 = content_words[j].text.to_lowercase();
// Skip very short words and stop words
if w1.len() >= 3
&& w2.len() >= 3
&& !self.stop_words.contains(&w1)
&& !self.stop_words.contains(&w2)
{
pairs.push((w1, w2));
}
}
}
}
pairs
}
}
impl Default for EntityExtractor {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::Duration;
/// Create a test relationship edge with specified strength and last_activated (L1 tier)
fn create_test_edge(strength: f32, days_since_activated: i64) -> RelationshipEdge {
create_test_edge_with_tier(strength, days_since_activated, EdgeTier::L1Working)
}
/// Create a test relationship edge with specified strength, last_activated, and tier
fn create_test_edge_with_tier(
strength: f32,
days_since_activated: i64,
tier: EdgeTier,
) -> RelationshipEdge {
RelationshipEdge {
uuid: Uuid::new_v4(),
from_entity: Uuid::new_v4(),
to_entity: Uuid::new_v4(),
relation_type: RelationType::RelatedTo,
strength,
created_at: Utc::now(),
valid_at: Utc::now(),
invalidated_at: None,
source_episode_id: None,
context: String::new(),
last_activated: Utc::now() - Duration::days(days_since_activated),
activation_count: 0,
ltp_status: LtpStatus::None,
activation_timestamps: None,
tier,
entity_confidence: None, // PIPE-5: Default for tests
forman_curvature: None,
endpoint_selectivity: None,
}
}
#[test]
fn test_hebbian_strengthen_increases_strength() {
use crate::constants::*;
// Use L2 tier to avoid L1 promotion resetting strength
let mut edge = create_test_edge_with_tier(0.3, 0, EdgeTier::L2Episodic);
let initial_strength = edge.strength;
let _ = edge.strengthen();
// With tier boost (L2 gets 80% of TIER_CO_ACCESS_BOOST), strength should increase
let tier_boost = TIER_CO_ACCESS_BOOST * 0.8;
let expected_boost = (LTP_LEARNING_RATE + tier_boost) * (1.0 - initial_strength);
assert!(
edge.strength > initial_strength,
"Strengthen should increase strength (expected boost {expected_boost})"
);
assert_eq!(edge.activation_count, 1);
}
#[test]
fn test_hebbian_strengthen_asymptotic() {
use crate::constants::*;
// Use L3 tier (no promotion) with high initial strength
let mut edge = create_test_edge_with_tier(0.95, 0, EdgeTier::L3Semantic);
let _ = edge.strengthen();
// High strength should still increase but slowly (asymptotic to 1.0)
// L3 tier boost = TIER_CO_ACCESS_BOOST * 0.5 = 0.075
let tier_boost = TIER_CO_ACCESS_BOOST * 0.5;
let expected_min = 0.95 + (LTP_LEARNING_RATE + tier_boost) * 0.05 - 0.01;
assert!(
edge.strength > expected_min,
"Expected > {expected_min}, got {}",
edge.strength
);
assert!(edge.strength <= 1.0);
}
#[test]
fn test_hebbian_strengthen_formula() {
use crate::constants::*;
// Test: w_new = w_old + (η + tier_boost) × (1 - w_old)
// Use L2 tier (tier_boost = TIER_CO_ACCESS_BOOST * 0.8) at 0.3 to avoid promotion
let mut edge = create_test_edge_with_tier(0.3, 0, EdgeTier::L2Episodic);
let _ = edge.strengthen();
// L2 tier boost = 0.15 * 0.8 = 0.12
// Expected: 0.3 + (0.1 + 0.12) * (1 - 0.3) = 0.3 + 0.22 * 0.7 = 0.454
let tier_boost = TIER_CO_ACCESS_BOOST * 0.8;
let expected = 0.3 + (LTP_LEARNING_RATE + tier_boost) * 0.7;
assert!(
(edge.strength - expected).abs() < 0.001,
"Expected {expected}, got {}",
edge.strength
);
}
#[test]
fn test_ltp_threshold_potentiation() {
let mut edge = create_test_edge(0.5, 0);
assert!(!edge.is_potentiated());
// Strengthen 10 times (LTP_THRESHOLD = 10)
for _ in 0..10 {
let _ = edge.strengthen();
}
assert!(
edge.is_potentiated(),
"Should be potentiated after 10 activations"
);
assert!(
matches!(edge.ltp_status, LtpStatus::Full),
"Should have Full LTP status after 10 activations"
);
assert!(
edge.strength > 0.7,
"Potentiated edge should have bonus strength"
);
}
#[test]
fn test_pipe4_burst_ltp_detection() {
// Create an L2 edge with low strength to avoid early tier promotion
let mut edge = create_test_edge_with_tier(0.22, 0, EdgeTier::L2Episodic);
// Strengthen 5 times (LTP_BURST_THRESHOLD = 5) within 24 hours
for _ in 0..5 {
let _ = edge.strengthen();
}
// Should have burst LTP (5+ activations in 24h)
// Edge may promote to L3 during strengthening, but should keep Burst status
assert!(
matches!(edge.ltp_status, LtpStatus::Burst { .. }),
"Should have Burst LTP after 5 rapid activations, got {:?}",
edge.ltp_status
);
}
#[test]
fn test_pipe4_activation_timestamps_recorded() {
// L2 edges should record activation timestamps
let mut edge = create_test_edge_with_tier(0.22, 0, EdgeTier::L2Episodic);
// Strengthen a few times
for _ in 0..3 {
let _ = edge.strengthen();
}
// Should have recorded timestamps (edge may have promoted to L3, but still tracks)
assert!(
edge.activation_timestamps.is_some(),
"L2+ edge should have activation timestamps"
);
assert_eq!(
edge.activation_timestamps.as_ref().unwrap().len(),
3,
"Should have 3 recorded timestamps"
);
}
#[test]
fn test_pipe4_fresh_l1_no_timestamps() {
// Fresh L1 edges should NOT have activation timestamps
let edge = create_test_edge(0.3, 0);
assert!(matches!(edge.tier, EdgeTier::L1Working));
assert!(
edge.activation_timestamps.is_none(),
"Fresh L1 edges should not have timestamps"
);
}
#[test]
fn test_pipe4_l1_promotes_and_tracks() {
// L1 edges that promote to L2 should start tracking timestamps
let mut edge = create_test_edge(0.3, 0);
assert!(matches!(edge.tier, EdgeTier::L1Working));
// Strengthen until it promotes to L2 (L1_PROMOTION_THRESHOLD = 0.5)
while matches!(edge.tier, EdgeTier::L1Working) {
let _ = edge.strengthen();
}
// After promotion to L2, should start tracking
assert!(
matches!(edge.tier, EdgeTier::L2Episodic),
"Should have promoted to L2"
);
// Timestamps are initialized on promotion
assert!(
edge.activation_timestamps.is_some(),
"L2 edges should track timestamps after promotion"
);
}
#[test]
fn test_pipe4_ltp_status_decay_factors() {
// Test that each LTP status has correct decay factor
use crate::constants::*;
assert_eq!(LtpStatus::None.decay_factor(), 1.0);
assert_eq!(LtpStatus::Weekly.decay_factor(), LTP_WEEKLY_DECAY_FACTOR);
assert_eq!(LtpStatus::Full.decay_factor(), LTP_DECAY_FACTOR);
// Burst factor depends on expiration
let burst = LtpStatus::Burst {
detected_at: Utc::now(),
};
assert_eq!(burst.decay_factor(), LTP_BURST_DECAY_FACTOR);
}
#[test]
fn test_pipe4_burst_to_full_upgrade() {
// LTP should upgrade from Burst to Full after 10 activations
let mut edge = create_test_edge_with_tier(0.22, 0, EdgeTier::L2Episodic);
// Get to burst LTP (5 activations)
for _ in 0..5 {
let _ = edge.strengthen();
}
assert!(
matches!(edge.ltp_status, LtpStatus::Burst { .. }),
"Should have Burst after 5 activations, got {:?}",
edge.ltp_status
);
// Continue strengthening to Full LTP (10 total)
for _ in 0..5 {
let _ = edge.strengthen();
}
// Should now be Full (upgraded from Burst via 10 activations)
assert!(
matches!(edge.ltp_status, LtpStatus::Full),
"Should have upgraded to Full LTP after 10 activations"
);
}
#[test]
fn test_pipe4_activations_in_window() {
let mut edge = create_test_edge_with_tier(0.22, 0, EdgeTier::L2Episodic);
// Record some activations
for _ in 0..5 {
let _ = edge.strengthen();
}
let now = Utc::now();
let hour_ago = now - chrono::Duration::hours(1);
let day_ago = now - chrono::Duration::days(1);
// All activations are recent (within last second really)
let in_hour = edge.activations_in_window(hour_ago, now);
let in_day = edge.activations_in_window(day_ago, now);
assert!(in_hour >= 5, "Expected 5+ in hour window, got {in_hour}");
assert!(in_day >= 5, "Expected 5+ in day window, got {in_day}");
}
// =========================================================================
// PIPE-5: Unified LTP Readiness Model Tests
// =========================================================================
#[test]
fn test_pipe5_adjusted_threshold_default() {
// Default confidence (None → 0.5) should give default threshold (10)
let edge = create_test_edge_with_tier(0.5, 0, EdgeTier::L2Episodic);
assert!(edge.entity_confidence.is_none());
let threshold = edge.adjusted_threshold();
// confidence 0.5 → threshold = 13 - (0.5 * 6) = 10
assert_eq!(threshold, 10, "Default confidence should give threshold 10");
}
#[test]
fn test_pipe5_adjusted_threshold_high_confidence() {
// High confidence (0.9) should give lower threshold (7-8)
let mut edge = create_test_edge_with_tier(0.5, 0, EdgeTier::L2Episodic);
edge.entity_confidence = Some(0.9);
let threshold = edge.adjusted_threshold();
// confidence 0.9 → threshold = 13 - (0.9 * 6) = 7.6 → 8
assert!(
threshold <= 8,
"High confidence should give threshold <= 8, got {threshold}"
);
}
#[test]
fn test_pipe5_adjusted_threshold_low_confidence() {
// Low confidence (0.2) should give higher threshold (12-13)
let mut edge = create_test_edge_with_tier(0.5, 0, EdgeTier::L2Episodic);
edge.entity_confidence = Some(0.2);
let threshold = edge.adjusted_threshold();
// confidence 0.2 → threshold = 13 - (0.2 * 6) = 11.8 → 12
assert!(
threshold >= 11,
"Low confidence should give threshold >= 11, got {threshold}"
);
}
#[test]
fn test_pipe5_strength_floor_by_tier() {
use crate::constants::*;
let l1_edge = create_test_edge_with_tier(0.5, 0, EdgeTier::L1Working);
let l2_edge = create_test_edge_with_tier(0.5, 0, EdgeTier::L2Episodic);
let l3_edge = create_test_edge_with_tier(0.5, 0, EdgeTier::L3Semantic);
assert_eq!(
l1_edge.strength_floor(),
1.0,
"L1 should have floor 1.0 (impossible)"
);
assert_eq!(
l2_edge.strength_floor(),
LTP_STRENGTH_FLOOR_L2,
"L2 floor mismatch"
);
assert_eq!(
l3_edge.strength_floor(),
LTP_STRENGTH_FLOOR_L3,
"L3 floor mismatch"
);
}
#[test]
fn test_pipe5_ltp_readiness_l1_returns_zero() {
// L1 edges should always return 0 readiness (can't reach Full LTP)
let mut edge = create_test_edge_with_tier(0.99, 0, EdgeTier::L1Working);
edge.activation_count = 100;
edge.entity_confidence = Some(1.0);
assert_eq!(
edge.ltp_readiness(),
0.0,
"L1 edges should always return 0 readiness"
);
}
#[test]
fn test_pipe5_ltp_readiness_balanced_path() {
use crate::constants::*;
// Balanced: 10 activations + 0.75 strength + 0.5 confidence
// count_score = 10 / 10 = 1.0
// strength_score = 0.75 / 0.65 = 1.15
// tag_bonus = 0.5 * 0.3 = 0.15
// readiness = 1.0 * 0.5 + 1.15 * 0.5 + 0.15 = 0.5 + 0.575 + 0.15 = 1.225
let mut edge = create_test_edge_with_tier(0.75, 0, EdgeTier::L2Episodic);
edge.activation_count = 10;
edge.entity_confidence = Some(0.5);
let readiness = edge.ltp_readiness();
assert!(
readiness >= LTP_READINESS_THRESHOLD,
"Balanced path should reach LTP, readiness = {}",
readiness
);
}
#[test]
fn test_pipe5_ltp_readiness_repetition_dominant() {
use crate::constants::*;
// Repetition dominant: 15 activations + 0.50 strength (below floor)
// count_score = 15 / 10 = 1.5
// strength_score = 0.50 / 0.65 = 0.77
// tag_bonus = 0.5 * 0.3 = 0.15
// readiness = 1.5 * 0.5 + 0.77 * 0.5 + 0.15 = 0.75 + 0.385 + 0.15 = 1.285
let mut edge = create_test_edge_with_tier(0.50, 0, EdgeTier::L2Episodic);
edge.activation_count = 15;
edge.entity_confidence = Some(0.5);
let readiness = edge.ltp_readiness();
assert!(
readiness >= LTP_READINESS_THRESHOLD,
"Repetition-dominant path should reach LTP, readiness = {}",
readiness
);
}
#[test]
fn test_pipe5_ltp_readiness_intensity_dominant() {
use crate::constants::*;
// Intensity dominant: 5 activations + 0.95 strength (L3)
// count_score = 5 / 10 = 0.5
// strength_score = 0.95 / 0.80 = 1.1875
// tag_bonus = 0.5 * 0.3 = 0.15
// readiness = 0.5 * 0.5 + 1.1875 * 0.5 + 0.15 = 0.25 + 0.59 + 0.15 = 0.99
// Need more strength or count for intensity-only path on L3
let mut edge = create_test_edge_with_tier(0.99, 0, EdgeTier::L3Semantic);
edge.activation_count = 6;
edge.entity_confidence = Some(0.5);
let readiness = edge.ltp_readiness();
// count_score = 6/10 = 0.6, strength_score = 0.99/0.80 = 1.24
// readiness = 0.6*0.5 + 1.24*0.5 + 0.15 = 0.3 + 0.62 + 0.15 = 1.07
assert!(
readiness >= LTP_READINESS_THRESHOLD,
"Intensity-dominant path should reach LTP, readiness = {}",
readiness
);
}
#[test]
fn test_pipe5_ltp_readiness_high_confidence_boost() {
use crate::constants::*;
// High confidence edge reaches LTP faster
// 7 activations + 0.65 strength + 0.9 confidence
// threshold = 13 - 0.9*6 = 7.6 → 8
// count_score = 7 / 8 = 0.875
// strength_score = 0.65 / 0.65 = 1.0
// tag_bonus = 0.9 * 0.3 = 0.27
// readiness = 0.875 * 0.5 + 1.0 * 0.5 + 0.27 = 0.44 + 0.5 + 0.27 = 1.21
let mut edge = create_test_edge_with_tier(0.65, 0, EdgeTier::L2Episodic);
edge.activation_count = 7;
edge.entity_confidence = Some(0.9);
let readiness = edge.ltp_readiness();
assert!(
readiness >= LTP_READINESS_THRESHOLD,
"High-confidence should boost to LTP, readiness = {}",
readiness
);
}
#[test]
fn test_pipe5_weak_edge_no_ltp() {
use crate::constants::*;
// Weak edge: 4 activations + 0.40 strength + 0.3 confidence
// threshold = 13 - 0.3*6 = 11.2 → 11
// count_score = 4 / 11 = 0.36
// strength_score = 0.40 / 0.65 = 0.62
// tag_bonus = 0.3 * 0.3 = 0.09
// readiness = 0.36 * 0.5 + 0.62 * 0.5 + 0.09 = 0.18 + 0.31 + 0.09 = 0.58
let mut edge = create_test_edge_with_tier(0.40, 0, EdgeTier::L2Episodic);
edge.activation_count = 4;
edge.entity_confidence = Some(0.3);
let readiness = edge.ltp_readiness();
assert!(
readiness < LTP_READINESS_THRESHOLD,
"Weak edge should NOT reach LTP, readiness = {}",
readiness
);
}
#[test]
fn test_pipe5_unified_detect_ltp_status() {
// Test that detect_ltp_status uses the unified readiness formula
let mut edge = create_test_edge_with_tier(0.75, 0, EdgeTier::L2Episodic);
edge.activation_count = 10;
edge.entity_confidence = Some(0.5);
edge.activation_timestamps = Some(std::collections::VecDeque::new());
let status = edge.detect_ltp_status(Utc::now());
assert_eq!(
status,
LtpStatus::Full,
"Balanced path should grant Full LTP via readiness"
);
}
#[test]
fn test_pipe5_l3_no_auto_ltp_without_activations() {
// L3 with high strength but low activation count should NOT auto-LTP
// This tests that the old auto-LTP behavior is removed
let mut edge = create_test_edge_with_tier(0.85, 0, EdgeTier::L3Semantic);
edge.activation_count = 2; // Low count
edge.entity_confidence = Some(0.5);
edge.activation_timestamps = Some(std::collections::VecDeque::new());
// count_score = 2/10 = 0.2, strength_score = 0.85/0.80 = 1.06
// readiness = 0.2*0.5 + 1.06*0.5 + 0.15 = 0.1 + 0.53 + 0.15 = 0.78
let status = edge.detect_ltp_status(Utc::now());
assert_eq!(
status,
LtpStatus::None,
"L3 high strength alone should NOT grant Full LTP, needs activations too"
);
}
#[test]
fn test_decay_reduces_strength() {
// Use L2 tier for multi-day decay testing (L1 max age is only 4 hours)
let mut edge = create_test_edge_with_tier(0.5, 7, EdgeTier::L2Episodic);
let initial_strength = edge.strength;
edge.decay();
assert!(
edge.strength < initial_strength,
"Decay should reduce strength (initial: {}, after: {})",
initial_strength,
edge.strength
);
}
#[test]
fn test_decay_tier_aware() {
// Test tier-aware decay: L2 episodic with exponential decay (λ=0.031/day) over 7 days
// Expected: e^(-0.031 * 7) ≈ 0.805, so strength decays to ~80%
let mut edge = create_test_edge_with_tier(1.0, 7, EdgeTier::L2Episodic);
edge.decay();
// After 7 days with L2 exponential decay, expect moderate reduction (~80% retained)
// but well above floor since within max age
assert!(
edge.strength < 0.85,
"After 7 days with L2 decay, strength should be below 0.85, got {}",
edge.strength
);
assert!(
edge.strength > 0.75,
"After 7 days with L2 decay, strength should be above 0.75, got {}",
edge.strength
);
assert!(
edge.strength > LTP_MIN_STRENGTH,
"Strength should still be above floor, got {}",
edge.strength
);
}
#[test]
fn test_decay_minimum_floor() {
// Use L3 tier for very old edge testing (L3 has 10 year max age)
let mut edge = create_test_edge_with_tier(0.02, 100, EdgeTier::L3Semantic);
edge.decay();
assert!(
edge.strength >= LTP_MIN_STRENGTH,
"Strength should not go below minimum floor"
);
}
#[test]
fn test_potentiated_decay_slower() {
// Use L2 tier for multi-day decay comparison
let mut edge1 = create_test_edge_with_tier(0.8, 7, EdgeTier::L2Episodic);
let mut edge2 = create_test_edge_with_tier(0.8, 7, EdgeTier::L2Episodic);
edge2.ltp_status = LtpStatus::Full; // Full LTP = 10x slower decay
edge1.decay();
edge2.decay();
assert!(
edge2.strength > edge1.strength,
"Potentiated edge should decay slower (normal: {}, potentiated: {})",
edge1.strength,
edge2.strength
);
}
#[test]
fn test_effective_strength_read_only() {
// Use L2 tier for multi-day testing
let edge = create_test_edge_with_tier(0.5, 7, EdgeTier::L2Episodic);
let initial_strength = edge.strength;
let effective = edge.effective_strength();
// effective_strength should not modify the edge
assert_eq!(edge.strength, initial_strength);
assert!(effective < initial_strength);
}
#[test]
fn test_decay_prune_threshold() {
// Use L2 tier for decay testing beyond its max age (14 days)
let mut weak_edge = create_test_edge_with_tier(LTP_MIN_STRENGTH, 30, EdgeTier::L2Episodic);
// No LTP status = normal decay
assert!(matches!(weak_edge.ltp_status, LtpStatus::None));
let should_prune = weak_edge.decay();
// Non-potentiated edge at minimum strength past max age should be prunable
assert!(
should_prune,
"Weak non-potentiated edge past max age should be marked for pruning"
);
}
#[test]
fn test_potentiated_above_floor_never_pruned() {
// Potentiated edge above LTP_PRUNE_FLOOR should be protected
let mut edge = create_test_edge_with_tier(0.1, 30, EdgeTier::L2Episodic);
edge.ltp_status = LtpStatus::Full;
let should_prune = edge.decay();
assert!(
!should_prune,
"Potentiated edges above LTP_PRUNE_FLOOR should not be pruned"
);
}
#[test]
fn test_potentiated_at_floor_stripped_and_prunable() {
// Potentiated edge at/below LTP_PRUNE_FLOOR should have LTP stripped
let mut edge = create_test_edge_with_tier(LTP_MIN_STRENGTH, 30, EdgeTier::L2Episodic);
edge.ltp_status = LtpStatus::Full;
let should_prune = edge.decay();
// LTP gets stripped because strength <= LTP_PRUNE_FLOOR,
// then normal prune logic applies (strength at floor, past max age)
assert!(
should_prune,
"Zombie potentiated edges at floor strength should be prunable"
);
assert!(
matches!(edge.ltp_status, LtpStatus::None),
"LTP status should be stripped when strength at floor"
);
}
#[test]
fn test_salience_calculation() {
let person_salience = EntityExtractor::calculate_base_salience(&EntityLabel::Person, false);
let person_proper_salience =
EntityExtractor::calculate_base_salience(&EntityLabel::Person, true);
assert_eq!(person_salience, 0.8);
assert!((person_proper_salience - 0.96).abs() < 0.01); // 0.8 * 1.2 = 0.96
}
#[test]
fn test_salience_caps_at_one() {
// Person (0.8) * 1.2 = 0.96, should not exceed 1.0
let salience = EntityExtractor::calculate_base_salience(&EntityLabel::Person, true);
assert!(salience <= 1.0);
}
#[test]
fn test_hebbian_strength_no_episode() {
// Create a temporary graph memory for testing
let temp_dir = tempfile::tempdir().unwrap();
let graph = GraphMemory::new(temp_dir.path(), None).unwrap();
// Random memory ID with no associated episode should return 0.5 (neutral)
let fake_memory_id = crate::memory::MemoryId(Uuid::new_v4());
let strength = graph.get_memory_hebbian_strength(&fake_memory_id);
assert_eq!(strength, Some(0.5), "No episode should return neutral 0.5");
}
#[test]
fn test_hebbian_strength_with_episode_no_edges() {
let temp_dir = tempfile::tempdir().unwrap();
let graph = GraphMemory::new(temp_dir.path(), None).unwrap();
// Create entities
let entity1 = EntityNode {
uuid: Uuid::new_v4(),
name: "Entity1".to_string(),
labels: vec![EntityLabel::Person],
created_at: Utc::now(),
last_seen_at: Utc::now(),
mention_count: 1,
summary: String::new(),
attributes: std::collections::HashMap::new(),
name_embedding: None,
salience: 0.5,
is_proper_noun: false,
selectivity: None,
};
let entity2 = EntityNode {
uuid: Uuid::new_v4(),
name: "Entity2".to_string(),
labels: vec![EntityLabel::Organization],
created_at: Utc::now(),
last_seen_at: Utc::now(),
mention_count: 1,
summary: String::new(),
attributes: std::collections::HashMap::new(),
name_embedding: None,
salience: 0.5,
is_proper_noun: false,
selectivity: None,
};
let entity1_uuid = graph.add_entity(entity1.clone()).unwrap();
let entity2_uuid = graph.add_entity(entity2.clone()).unwrap();
// Create episode with entities but no edges
let memory_id = crate::memory::MemoryId(Uuid::new_v4());
let episode = EpisodicNode {
uuid: memory_id.0,
name: "Test Episode".to_string(),
content: "Test content".to_string(),
valid_at: Utc::now(),
created_at: Utc::now(),
entity_refs: vec![entity1_uuid, entity2_uuid],
source: EpisodeSource::Message,
metadata: std::collections::HashMap::new(),
};
graph.add_episode(episode).unwrap();
// Episode with entities but no edges should return 0.5
let strength = graph.get_memory_hebbian_strength(&memory_id);
assert_eq!(
strength,
Some(0.5),
"Episode without edges should return neutral 0.5"
);
}
#[test]
fn test_hebbian_strength_with_edges() {
let temp_dir = tempfile::tempdir().unwrap();
let graph = GraphMemory::new(temp_dir.path(), None).unwrap();
// Create entities
let entity1_uuid = Uuid::new_v4();
let entity2_uuid = Uuid::new_v4();
let entity1 = EntityNode {
uuid: entity1_uuid,
name: "Entity1".to_string(),
labels: vec![EntityLabel::Person],
created_at: Utc::now(),
last_seen_at: Utc::now(),
mention_count: 1,
summary: String::new(),
attributes: std::collections::HashMap::new(),
name_embedding: None,
salience: 0.5,
is_proper_noun: false,
selectivity: None,
};
let entity2 = EntityNode {
uuid: entity2_uuid,
name: "Entity2".to_string(),
labels: vec![EntityLabel::Organization],
created_at: Utc::now(),
last_seen_at: Utc::now(),
mention_count: 1,
summary: String::new(),
attributes: std::collections::HashMap::new(),
name_embedding: None,
salience: 0.5,
is_proper_noun: false,
selectivity: None,
};
graph.add_entity(entity1).unwrap();
graph.add_entity(entity2).unwrap();
// Create episode
let memory_id = crate::memory::MemoryId(Uuid::new_v4());
let episode = EpisodicNode {
uuid: memory_id.0,
name: "Test Episode".to_string(),
content: "Test content".to_string(),
valid_at: Utc::now(),
created_at: Utc::now(),
entity_refs: vec![entity1_uuid, entity2_uuid],
source: EpisodeSource::Message,
metadata: std::collections::HashMap::new(),
};
graph.add_episode(episode).unwrap();
// Create edge between entities with known strength
let edge = RelationshipEdge {
uuid: Uuid::new_v4(),
from_entity: entity1_uuid,
to_entity: entity2_uuid,
relation_type: RelationType::RelatedTo,
strength: 0.8,
created_at: Utc::now(),
valid_at: Utc::now(),
invalidated_at: None,
source_episode_id: Some(memory_id.0),
context: "Test context".to_string(),
last_activated: Utc::now(), // Just activated - no decay
activation_count: 5,
ltp_status: LtpStatus::None,
activation_timestamps: None,
tier: EdgeTier::L2Episodic, // Use L2 since it has activation count
entity_confidence: None, // PIPE-5: Default for tests
forman_curvature: None,
endpoint_selectivity: None,
};
graph.add_relationship(edge).unwrap();
// Should return the edge strength (0.8, with minimal decay since just activated)
let strength = graph.get_memory_hebbian_strength(&memory_id);
assert!(strength.is_some());
let s = strength.unwrap();
assert!(s > 0.75 && s <= 0.8, "Strength should be ~0.8, got {}", s);
}
// =========================================================================
// BEHAVIORAL LOOP TESTS
// Verify cognitive loops are closed (not just structurally present).
// =========================================================================
#[test]
fn test_loop_episode_idempotency() {
// Verify: calling add_episode() twice with same UUID doesn't inflate episode_count
let temp_dir = tempfile::tempdir().unwrap();
let graph = GraphMemory::new(temp_dir.path(), None).unwrap();
let memory_uuid = Uuid::new_v4();
let entity_uuid = Uuid::new_v4();
let entity = EntityNode {
uuid: entity_uuid,
name: "IdempotentEntity".to_string(),
labels: vec![EntityLabel::Concept],
created_at: Utc::now(),
last_seen_at: Utc::now(),
mention_count: 1,
summary: String::new(),
attributes: std::collections::HashMap::new(),
name_embedding: None,
salience: 0.5,
is_proper_noun: false,
selectivity: None,
};
graph.add_entity(entity).unwrap();
let episode = EpisodicNode {
uuid: memory_uuid,
name: "Test Episode".to_string(),
content: "Test content for idempotency".to_string(),
valid_at: Utc::now(),
created_at: Utc::now(),
entity_refs: vec![entity_uuid],
source: EpisodeSource::Message,
metadata: std::collections::HashMap::new(),
};
// First insert
graph.add_episode(episode.clone()).unwrap();
let count_after_first = graph.episode_count.load(Ordering::Relaxed);
// Second insert (same UUID — simulates retry)
graph.add_episode(episode).unwrap();
let count_after_second = graph.episode_count.load(Ordering::Relaxed);
assert_eq!(
count_after_first, count_after_second,
"episode_count should not inflate on overwrite (got {} then {})",
count_after_first, count_after_second
);
}
#[test]
fn test_loop_decay_reduces_edge_strength() {
// Verify: apply_decay() actually reduces edge strength (decay loop is closed)
let temp_dir = tempfile::tempdir().unwrap();
let graph = GraphMemory::new(temp_dir.path(), None).unwrap();
let from_uuid = Uuid::new_v4();
let to_uuid = Uuid::new_v4();
// Create entities
for (uuid, name) in [(from_uuid, "DecayFrom"), (to_uuid, "DecayTo")] {
let entity = EntityNode {
uuid,
name: name.to_string(),
labels: vec![EntityLabel::Concept],
created_at: Utc::now(),
last_seen_at: Utc::now(),
mention_count: 1,
summary: String::new(),
attributes: std::collections::HashMap::new(),
name_embedding: None,
salience: 0.5,
is_proper_noun: false,
selectivity: None,
};
graph.add_entity(entity).unwrap();
}
// Create edge with strength 0.5, last activated 30 days ago (well past decay threshold)
let edge_uuid = Uuid::new_v4();
let edge = RelationshipEdge {
uuid: edge_uuid,
from_entity: from_uuid,
to_entity: to_uuid,
relation_type: RelationType::RelatedTo,
strength: 0.5,
created_at: Utc::now() - Duration::days(60),
valid_at: Utc::now(),
invalidated_at: None,
source_episode_id: None,
context: "decay test".to_string(),
last_activated: Utc::now() - Duration::days(30),
activation_count: 1,
ltp_status: LtpStatus::None,
activation_timestamps: None,
tier: EdgeTier::L1Working,
entity_confidence: None,
forman_curvature: None,
endpoint_selectivity: None,
};
graph.add_relationship(edge).unwrap();
// Run decay
let result = graph.apply_decay().unwrap();
// Edge should have been affected (either decayed or pruned)
if result.pruned_count == 0 {
// Not pruned — check it was weakened
let updated = graph.get_relationship(&edge_uuid).unwrap();
if let Some(updated_edge) = updated {
assert!(
updated_edge.strength < 0.5,
"Edge strength should have decayed from 0.5, got {}",
updated_edge.strength
);
}
}
// If pruned, the loop is working (edge was weak enough to remove)
}
#[test]
fn test_loop_feedback_strengthens_edges() {
// Verify: batch_strengthen_synapses() actually increases edge strength (feedback loop)
let temp_dir = tempfile::tempdir().unwrap();
let graph = GraphMemory::new(temp_dir.path(), None).unwrap();
let from_uuid = Uuid::new_v4();
let to_uuid = Uuid::new_v4();
for (uuid, name) in [(from_uuid, "FeedbackFrom"), (to_uuid, "FeedbackTo")] {
let entity = EntityNode {
uuid,
name: name.to_string(),
labels: vec![EntityLabel::Concept],
created_at: Utc::now(),
last_seen_at: Utc::now(),
mention_count: 1,
summary: String::new(),
attributes: std::collections::HashMap::new(),
name_embedding: None,
salience: 0.5,
is_proper_noun: false,
selectivity: None,
};
graph.add_entity(entity).unwrap();
}
let initial_strength = 0.3;
let edge = RelationshipEdge {
uuid: Uuid::new_v4(), // add_relationship() will assign a new UUID
from_entity: from_uuid,
to_entity: to_uuid,
relation_type: RelationType::RelatedTo,
strength: initial_strength,
created_at: Utc::now(),
valid_at: Utc::now(),
invalidated_at: None,
source_episode_id: None,
context: "feedback test".to_string(),
last_activated: Utc::now(),
activation_count: 1,
ltp_status: LtpStatus::None,
activation_timestamps: None,
tier: EdgeTier::L2Episodic,
entity_confidence: None,
forman_curvature: None,
endpoint_selectivity: None,
};
let edge_uuid = graph.add_relationship(edge).unwrap();
// Simulate "Helpful" feedback → strengthen
let count = graph.batch_strengthen_synapses(&[edge_uuid]).unwrap();
assert_eq!(count, 1, "Should have strengthened 1 edge");
let updated = graph.get_relationship(&edge_uuid).unwrap().unwrap();
assert!(
updated.strength > initial_strength,
"Edge strength should increase after Helpful feedback: {} -> {}",
initial_strength,
updated.strength
);
}
// =========================================================================
// Forman-Ricci Curvature Tests
// Reference: Leal, Restrepo, Stadler, Jost (2018) arXiv:1811.07825
// =========================================================================
/// Helper: create an entity node with a given name
fn make_entity(graph: &GraphMemory, name: &str) -> Uuid {
let uuid = Uuid::new_v4();
let entity = EntityNode {
uuid,
name: name.to_string(),
labels: vec![EntityLabel::Concept],
created_at: Utc::now(),
last_seen_at: Utc::now(),
mention_count: 1,
summary: String::new(),
attributes: std::collections::HashMap::new(),
name_embedding: None,
salience: 0.5,
is_proper_noun: false,
selectivity: None,
};
// add_entity may dedup and return a different UUID
graph.add_entity(entity).unwrap()
}
/// Helper: create a directed edge from → to
fn make_edge(graph: &GraphMemory, from: Uuid, to: Uuid) -> Uuid {
let edge = RelationshipEdge {
uuid: Uuid::new_v4(),
from_entity: from,
to_entity: to,
relation_type: RelationType::RelatedTo,
strength: 0.5,
created_at: Utc::now(),
valid_at: Utc::now(),
invalidated_at: None,
source_episode_id: None,
context: String::new(),
last_activated: Utc::now(),
activation_count: 1,
ltp_status: LtpStatus::None,
activation_timestamps: None,
tier: EdgeTier::L2Episodic,
entity_confidence: None,
forman_curvature: None,
endpoint_selectivity: None,
};
graph.add_relationship(edge).unwrap()
}
#[test]
fn test_forman_curvature_isolated_edge() {
// Single edge A → B: deg(A) = 1, deg(B) = 1
// F(e) = 4 - 1 - 1 = 2 (positive = tight community)
let temp_dir = tempfile::tempdir().unwrap();
let graph = GraphMemory::new(temp_dir.path(), None).unwrap();
let a = make_entity(&graph, "NodeA");
let b = make_entity(&graph, "NodeB");
let edge_id = make_edge(&graph, a, b);
let stats = graph.compute_forman_ricci_curvature().unwrap();
assert_eq!(stats.edges_computed, 1);
assert_eq!(stats.positive_count, 1);
assert_eq!(stats.negative_count, 0);
let edge = graph.get_relationship(&edge_id).unwrap().unwrap();
let curv = edge.forman_curvature.expect("curvature should be computed");
// F(e) = 4 - deg(A) - deg(B) = 4 - 1 - 1 = 2
assert!(
(curv - 2.0).abs() < f32::EPSILON,
"Isolated edge curvature should be 2.0, got {}",
curv
);
}
#[test]
fn test_forman_curvature_hub_topology() {
// Star topology: Hub → {A, B, C, D}
// For edge Hub→A: deg(Hub) = 4 (out), deg(A) = 1 (in)
// in_deg(Hub) = 0, out_deg(Hub) = 4
// in_deg(A) = 1, out_deg(A) = 0
// F(→e→) = 2 - in(Hub) - out(A) = 2 - 0 - 0 = 2
// F(←e←) = 2 - out(Hub) - in(A) = 2 - 4 - 1 = -3
// F(e) = 2 + (-3) = -1
// Equivalently: F(e) = 4 - deg(Hub) - deg(A) = 4 - 4 - 1 = -1
let temp_dir = tempfile::tempdir().unwrap();
let graph = GraphMemory::new(temp_dir.path(), None).unwrap();
let hub = make_entity(&graph, "Hub");
let a = make_entity(&graph, "SpokeA");
let b = make_entity(&graph, "SpokeB");
let c = make_entity(&graph, "SpokeC");
let d = make_entity(&graph, "SpokeD");
let edge_a = make_edge(&graph, hub, a);
make_edge(&graph, hub, b);
make_edge(&graph, hub, c);
make_edge(&graph, hub, d);
let stats = graph.compute_forman_ricci_curvature().unwrap();
assert_eq!(stats.edges_computed, 4);
// All edges should have negative curvature (hub bridges)
assert_eq!(
stats.negative_count, 4,
"All hub edges should be negative, got {} negative",
stats.negative_count
);
let edge = graph.get_relationship(&edge_a).unwrap().unwrap();
let curv = edge.forman_curvature.unwrap();
// F(e) = 4 - 4 - 1 = -1
assert!(
(curv - (-1.0)).abs() < f32::EPSILON,
"Hub→Spoke curvature should be -1.0, got {}",
curv
);
}
#[test]
fn test_forman_curvature_triangle() {
// Triangle: A→B, B→C, C→A
// Each node: in_deg=1, out_deg=1, total deg=2
// F(e) = 4 - 2 - 2 = 0 (neutral / transitional)
let temp_dir = tempfile::tempdir().unwrap();
let graph = GraphMemory::new(temp_dir.path(), None).unwrap();
let a = make_entity(&graph, "TriA");
let b = make_entity(&graph, "TriB");
let c = make_entity(&graph, "TriC");
make_edge(&graph, a, b);
make_edge(&graph, b, c);
make_edge(&graph, c, a);
let stats = graph.compute_forman_ricci_curvature().unwrap();
assert_eq!(stats.edges_computed, 3);
assert_eq!(
stats.zero_count, 3,
"Triangle edges should all be zero curvature"
);
assert!(
stats.mean_curvature.abs() < f32::EPSILON,
"Mean curvature of triangle should be 0.0, got {}",
stats.mean_curvature
);
}
#[test]
fn test_forman_curvature_empty_graph() {
let temp_dir = tempfile::tempdir().unwrap();
let graph = GraphMemory::new(temp_dir.path(), None).unwrap();
let stats = graph.compute_forman_ricci_curvature().unwrap();
assert_eq!(stats.edges_computed, 0);
assert_eq!(stats.mean_curvature, 0.0);
}
#[test]
fn test_forman_curvature_bridge_detection() {
// Two triangles connected by a bridge:
// Triangle 1: A→B, B→C, C→A
// Bridge: C→D
// Triangle 2: D→E, E→F, F→D
//
// Bridge edge C→D: deg(C) = 3 (in from B, out to A, out to D)
// deg(D) = 3 (in from C, in from F, out to E)
// F(C→D) = 4 - 3 - 3 = -2 (most negative = bottleneck)
let temp_dir = tempfile::tempdir().unwrap();
let graph = GraphMemory::new(temp_dir.path(), None).unwrap();
let a = make_entity(&graph, "BridgeA");
let b = make_entity(&graph, "BridgeB");
let c = make_entity(&graph, "BridgeC");
let d = make_entity(&graph, "BridgeD");
let e = make_entity(&graph, "BridgeE");
let f = make_entity(&graph, "BridgeF");
// Triangle 1
make_edge(&graph, a, b);
make_edge(&graph, b, c);
make_edge(&graph, c, a);
// Bridge
let bridge_id = make_edge(&graph, c, d);
// Triangle 2
make_edge(&graph, d, e);
make_edge(&graph, e, f);
make_edge(&graph, f, d);
let stats = graph.compute_forman_ricci_curvature().unwrap();
assert_eq!(stats.edges_computed, 7);
// Bridge should be the most negative edge
let bridge = graph.get_relationship(&bridge_id).unwrap().unwrap();
let bridge_curv = bridge.forman_curvature.unwrap();
assert!(
bridge_curv <= stats.min_curvature + f32::EPSILON,
"Bridge should be among most negative edges: bridge={}, min={}",
bridge_curv,
stats.min_curvature
);
assert!(
bridge_curv < 0.0,
"Bridge curvature should be negative, got {}",
bridge_curv
);
}
#[test]
fn test_selectivity_hub_vs_concept() {
// Hub connected to many unrelated spokes → uniform curvature → LOW selectivity
// Concept node in a tight cluster → varied curvature → HIGH selectivity
//
// Topology:
// Hub → {S1, S2, S3, S4, S5, S6} (star — uniform edges)
// A → B → C → A (triangle — tight community)
// A → Hub (bridge connecting triangle to star)
//
// Hub: all incident edges have similar curvature (uniform negative)
// → low stdev/degree → low selectivity
// A: participates in triangle (curvature=0-ish) AND bridge to hub (curvature<<0)
// → high stdev across incident edges → high selectivity
let temp_dir = tempfile::tempdir().unwrap();
let graph = GraphMemory::new(temp_dir.path(), None).unwrap();
let hub = make_entity(&graph, "SelectHub");
let s1 = make_entity(&graph, "Spoke1");
let s2 = make_entity(&graph, "Spoke2");
let s3 = make_entity(&graph, "Spoke3");
let s4 = make_entity(&graph, "Spoke4");
let s5 = make_entity(&graph, "Spoke5");
let s6 = make_entity(&graph, "Spoke6");
let a = make_entity(&graph, "ConceptA");
let b = make_entity(&graph, "ConceptB");
let c = make_entity(&graph, "ConceptC");
// Star
make_edge(&graph, hub, s1);
make_edge(&graph, hub, s2);
make_edge(&graph, hub, s3);
make_edge(&graph, hub, s4);
make_edge(&graph, hub, s5);
make_edge(&graph, hub, s6);
// Triangle
make_edge(&graph, a, b);
make_edge(&graph, b, c);
make_edge(&graph, c, a);
// Bridge
make_edge(&graph, a, hub);
graph.compute_forman_ricci_curvature().unwrap();
let hub_entity = graph.get_entity(&hub).unwrap().unwrap();
let a_entity = graph.get_entity(&a).unwrap().unwrap();
let hub_sel = hub_entity.selectivity.expect("hub should have selectivity");
let a_sel = a_entity
.selectivity
.expect("concept A should have selectivity");
// Concept node A should have higher selectivity than the hub
// because A's incident edges span different curvature regimes
assert!(
a_sel > hub_sel,
"Concept node selectivity ({}) should exceed hub selectivity ({})",
a_sel,
hub_sel
);
}
#[test]
fn test_selectivity_gated_ltp_decay() {
// Two edges with identical LTP (Full) but different endpoint_selectivity.
// Low-selectivity edge should decay MORE (less LTP protection).
// High-selectivity edge should decay LESS (full LTP protection).
let now = Utc::now();
let one_hour_ago = now - chrono::Duration::hours(1);
let mut low_sel_edge = RelationshipEdge {
uuid: Uuid::new_v4(),
from_entity: Uuid::new_v4(),
to_entity: Uuid::new_v4(),
relation_type: RelationType::RelatedTo,
strength: 0.8,
created_at: one_hour_ago,
valid_at: one_hour_ago,
invalidated_at: None,
source_episode_id: None,
context: String::new(),
last_activated: one_hour_ago,
activation_count: 20,
ltp_status: LtpStatus::Full,
activation_timestamps: None,
tier: EdgeTier::L2Episodic,
entity_confidence: None,
forman_curvature: Some(-5.0),
endpoint_selectivity: Some(0.05), // very low = stop-word
};
let mut high_sel_edge = RelationshipEdge {
uuid: Uuid::new_v4(),
from_entity: Uuid::new_v4(),
to_entity: Uuid::new_v4(),
relation_type: RelationType::RelatedTo,
strength: 0.8,
created_at: one_hour_ago,
valid_at: one_hour_ago,
invalidated_at: None,
source_episode_id: None,
context: String::new(),
last_activated: one_hour_ago,
activation_count: 20,
ltp_status: LtpStatus::Full,
activation_timestamps: None,
tier: EdgeTier::L2Episodic,
entity_confidence: None,
forman_curvature: Some(-5.0),
endpoint_selectivity: Some(2.0), // high = concept, above threshold
};
low_sel_edge.decay();
high_sel_edge.decay();
// Both started at 0.8. Low-selectivity should have decayed more.
assert!(
low_sel_edge.strength < high_sel_edge.strength,
"Low-selectivity edge ({}) should decay more than high-selectivity edge ({})",
low_sel_edge.strength,
high_sel_edge.strength
);
// High-selectivity edge with Full LTP should retain most of its strength
// LTP_DECAY_FACTOR = 0.1 → 10x slower decay → after 1 hour should be ~0.79+
assert!(
high_sel_edge.strength > 0.7,
"High-selectivity Full LTP edge should retain most strength, got {}",
high_sel_edge.strength
);
}
#[test]
fn test_selectivity_none_preserves_ltp() {
// Edge with endpoint_selectivity=None (not yet computed) should get
// full LTP protection — conservative default.
let now = Utc::now();
let one_hour_ago = now - chrono::Duration::hours(1);
let mut edge_none = RelationshipEdge {
uuid: Uuid::new_v4(),
from_entity: Uuid::new_v4(),
to_entity: Uuid::new_v4(),
relation_type: RelationType::RelatedTo,
strength: 0.8,
created_at: one_hour_ago,
valid_at: one_hour_ago,
invalidated_at: None,
source_episode_id: None,
context: String::new(),
last_activated: one_hour_ago,
activation_count: 20,
ltp_status: LtpStatus::Full,
activation_timestamps: None,
tier: EdgeTier::L2Episodic,
entity_confidence: None,
forman_curvature: None,
endpoint_selectivity: None, // not computed yet
};
let mut edge_high = RelationshipEdge {
uuid: Uuid::new_v4(),
from_entity: Uuid::new_v4(),
to_entity: Uuid::new_v4(),
relation_type: RelationType::RelatedTo,
strength: 0.8,
created_at: one_hour_ago,
valid_at: one_hour_ago,
invalidated_at: None,
source_episode_id: None,
context: String::new(),
last_activated: one_hour_ago,
activation_count: 20,
ltp_status: LtpStatus::Full,
activation_timestamps: None,
tier: EdgeTier::L2Episodic,
entity_confidence: None,
forman_curvature: Some(-2.0),
endpoint_selectivity: Some(5.0), // high selectivity
};
edge_none.decay();
edge_high.decay();
// Both should get full LTP protection, so strengths should be equal
let diff = (edge_none.strength - edge_high.strength).abs();
assert!(
diff < 0.001,
"None selectivity should match high selectivity: none={}, high={}, diff={}",
edge_none.strength,
edge_high.strength,
diff
);
}
#[test]
fn test_endpoint_selectivity_written_to_edges() {
// After compute_forman_ricci_curvature(), edges should have
// endpoint_selectivity set based on their source entity's selectivity.
let temp_dir = tempfile::tempdir().unwrap();
let graph = GraphMemory::new(temp_dir.path(), None).unwrap();
let a = make_entity(&graph, "EndpointA");
let b = make_entity(&graph, "EndpointB");
let c = make_entity(&graph, "EndpointC");
let e1 = make_edge(&graph, a, b);
let e2 = make_edge(&graph, b, c);
graph.compute_forman_ricci_curvature().unwrap();
let edge1 = graph.get_relationship(&e1).unwrap().unwrap();
let edge2 = graph.get_relationship(&e2).unwrap().unwrap();
// All edges should have endpoint_selectivity set after curvature pass
assert!(
edge1.endpoint_selectivity.is_some(),
"Edge 1 should have endpoint_selectivity after curvature computation"
);
assert!(
edge2.endpoint_selectivity.is_some(),
"Edge 2 should have endpoint_selectivity after curvature computation"
);
// A has degree 1 (only outgoing to B) — selectivity = stdev/degree = 0/1 = 0
// B has degree 2 (in from A, out to C) — selectivity = stdev/degree
let entity_a = graph.get_entity(&a).unwrap().unwrap();
let entity_b = graph.get_entity(&b).unwrap().unwrap();
assert!(
entity_a.selectivity.is_some(),
"Entity A should have selectivity"
);
assert!(
entity_b.selectivity.is_some(),
"Entity B should have selectivity"
);
}
#[test]
fn test_entity_reputation_returns_none_for_unknown() {
let temp_dir = tempfile::tempdir().unwrap();
let graph = GraphMemory::new(temp_dir.path(), None).unwrap();
assert!(graph.get_entity_reputation("nonexistent").is_none());
}
#[test]
fn test_entity_reputation_reflects_graph_state() {
let temp_dir = tempfile::tempdir().unwrap();
let graph = GraphMemory::new(temp_dir.path(), None).unwrap();
let hub = make_entity(&graph, "HubEntity");
let a = make_entity(&graph, "SpokeA");
let b = make_entity(&graph, "SpokeB");
let c = make_entity(&graph, "SpokeC");
make_edge(&graph, hub, a);
make_edge(&graph, hub, b);
make_edge(&graph, hub, c);
make_edge(&graph, a, b); // give a,b some edges too
graph.compute_forman_ricci_curvature().unwrap();
let rep = graph.get_entity_reputation("HubEntity").unwrap();
assert_eq!(rep.degree, 3);
assert_eq!(rep.mention_count, 1);
// Hub has lower selectivity than spokes
let rep_a = graph.get_entity_reputation("SpokeA").unwrap();
assert!(
rep.selectivity <= rep_a.selectivity || rep.degree > rep_a.degree,
"Hub should have lower selectivity or higher degree than spoke"
);
}
#[test]
fn test_entity_reputation_case_insensitive() {
let temp_dir = tempfile::tempdir().unwrap();
let graph = GraphMemory::new(temp_dir.path(), None).unwrap();
make_entity(&graph, "TestEntity");
assert!(graph.get_entity_reputation("testentity").is_some());
assert!(graph.get_entity_reputation("TESTENTITY").is_some());
}
}