mcpls-core 0.7.0

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

use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
use std::sync::Arc;

use chrono::{DateTime, Utc};
use lsp_types::{Diagnostic as LspDiagnostic, Uri};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use tracing::{debug, warn};

use crate::bridge::indexing::{IndexingPolicy, IndexingReset, IndexingState, IndexingTracker};
use crate::bridge::resources::{DiagnosticsResourceUri, PublishedDiagnosticsUri};
use crate::bridge::{
    DiagnosticsAvailability, DocumentTracker, DocumentVersion, Opening, uri_to_path,
};
use crate::config::{BoundedText, ServerId};
use crate::util::{WarnLimiter, truncate_string};

mod bounds;
mod pulled_index;

pub use bounds::BoundedDiagnostics;
use bounds::{MAX_ENTRY_TEXT_BYTES, cap_diagnostics_entry_size};
use pulled_index::{PulledIndex, point};
pub use pulled_index::{ReportedSeverity, reported_code};

/// Maximum number of log entries to store.
const MAX_LOG_ENTRIES: usize = 100;

/// Global budget for distinct-URI diagnostic entries, shared work-conservingly
/// across every registered diagnostics-route server rather than claimed by
/// one server alone.
///
/// Guards against unbounded growth when a spawned LSP server publishes
/// diagnostics for an unbounded number of distinct URIs over a long-running
/// session, matching the bounding already applied to `logs`/`messages`.
/// Eviction only triggers once this global total is reached; it then targets
/// whichever server most exceeds its fair share of
/// `MAX_DIAGNOSTIC_ENTRIES / diagnostics_route_count` (see
/// [`NotificationCache::set_diagnostics_route_count`]). If no server exceeds
/// its share, eviction falls back to the writer's own oldest entry instead
/// -- even if the writer is itself within its share -- since it is the one
/// whose new entry needs room; a narrower fallback further evicts from the
/// largest other in-share server only if the writer itself has no entries
/// yet (its very first write) and every existing server is already within
/// its own share, since otherwise there would be nothing to evict and the
/// aggregate cap could be exceeded (see the private `server_to_evict_from`
/// for both fallbacks). A quieter, non-writer server that is within its fair
/// share is otherwise never touched (#266). A single active server can
/// still use the full budget when other registered servers are idle (#276)
/// instead of being capped at a static equal split regardless of how much
/// of it they actually use. Which single entry within the chosen server (or
/// another over-share one) is actually removed is further refined by
/// emptiness -- see the private `entry_to_evict` (#284).
pub const MAX_DIAGNOSTIC_ENTRIES: usize = 1000;

/// A `file:` URI normalized for cache lookup; only built by [`Self::of`], so a
/// raw URI string can never be mistaken for a key.
///
/// On Windows, URI comparisons must be case-insensitive: the filesystem is
/// case-insensitive and different tools (e.g. rust-analyzer vs std) may
/// produce drive letters in different cases (`C:` vs `c:`).
/// Lowercasing the entire URI is safe for `file://` URIs because they have
/// no case-sensitive query or fragment components.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct DiagnosticsKey(String);

impl DiagnosticsKey {
    pub(crate) fn of(uri: &Uri) -> Self {
        let text: &str = uri.as_ref();
        if cfg!(windows) {
            Self(text.to_ascii_lowercase())
        } else {
            Self(text.to_owned())
        }
    }
}

/// How a cached entry's URI relates to the canonical path of its file.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Spelling {
    /// The server published under the canonical spelling of the path.
    Canonical,
    /// The server published under a symlink alias of the file at this key.
    Alias(DiagnosticsKey),
}

/// Where a cached diagnostics list came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
enum Provenance {
    /// Delivered by `textDocument/publishDiagnostics`.
    Pushed,
    /// Answered to a `textDocument/diagnostic` request.
    Pulled,
}

/// Identifies one cache slot: a published URI and the way its diagnostics arrived.
///
/// A file has at most one `Pulled` slot, always under its canonical URI, next
/// to its `Pushed` slots, so neither source erases the other.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
struct SlotKey {
    uri: DiagnosticsKey,
    provenance: Provenance,
}

impl SlotKey {
    const fn pushed(uri: DiagnosticsKey) -> Self {
        Self {
            uri,
            provenance: Provenance::Pushed,
        }
    }

    const fn pulled(uri: DiagnosticsKey) -> Self {
        Self {
            uri,
            provenance: Provenance::Pulled,
        }
    }
}

/// Orders the pulls of one server: a later request gets a greater ticket.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct PullTicket(u64);

/// Counts how often a server's diagnostics were cleared, so a pull answered by
/// a process that has since been replaced can be recognized.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct ClearEpoch(u64);

/// A pull request's claim on the cache, issued by [`NotificationCache::begin_pull`]
/// before the request is sent and redeemed by
/// [`NotificationCache::store_pulled_diagnostics`].
#[derive(Debug, Clone, Copy)]
pub struct PullStamp {
    ticket: PullTicket,
    epoch: ClearEpoch,
    version: DocumentVersion,
}

impl PullStamp {
    /// Document version the pull was requested at.
    pub(crate) const fn version(self) -> DocumentVersion {
        self.version
    }
}

/// Whether the tracker still holds the document version a pull was requested at.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VersionCheck {
    /// The tracked version still equals the stamped one.
    Current,
    /// The document was resynced to another version while the pull was in flight.
    Moved,
}

/// Why a pull report was not stored.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Discard {
    /// A pull issued later already stored its report.
    OlderTicket,
    /// The server's diagnostics were cleared after the pull was issued.
    ServerCleared,
    /// The document moved to another version while the pull was in flight.
    VersionMoved,
    /// No entry could be evicted to make room.
    NoRoom,
}

/// What a stored pull report did to the file's pulled slot.
#[derive(Debug)]
pub enum SlotChange {
    /// The slot already held exactly this list.
    Identical,
    /// The slot was replaced; `before` is the file's snapshot taken just
    /// before, so the merged views can be compared. `None` when the caller
    /// did not ask for one (nobody is subscribed): the view is then taken to
    /// have changed.
    Replaced { before: Option<DiagnosticSources> },
}

/// Whether a pull write takes the snapshot a view comparison needs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SnapshotBefore {
    /// Take it.
    Take,
    /// Skip it; nobody compares views.
    Skip,
}

/// A capacity eviction found nothing it may remove.
#[derive(Debug)]
struct NoRoom {
    /// Files whose slots were evicted before the search ran dry.
    evicted: Vec<DiagnosticsKey>,
}

/// Result of [`NotificationCache::store_pulled_diagnostics`].
#[derive(Debug)]
#[must_use]
pub enum PullWrite {
    /// The report is now the file's pulled slot.
    Stored {
        slot: SlotChange,
        /// Files whose slots were evicted to make room.
        evicted: Vec<DiagnosticsKey>,
    },
    /// The report was dropped and is handed back.
    Discarded {
        reason: Discard,
        /// Files whose slots were evicted before the pull was dropped.
        evicted: Vec<DiagnosticsKey>,
        items: BoundedDiagnostics,
    },
}

/// Result of [`NotificationCache::write_published_diagnostics`].
#[derive(Debug)]
#[must_use]
pub enum PushWrite {
    /// The publish is now cached.
    Stored {
        /// Files whose slots were evicted to make room for the published one.
        evicted: Vec<DiagnosticsKey>,
    },
    /// The publish was refused and nothing about the file changed: its URI
    /// spellings are at their cap, or no entry could be evicted to make room.
    Dropped {
        /// Files whose slots were evicted before the publish was refused.
        evicted: Vec<DiagnosticsKey>,
    },
}

impl PushWrite {
    /// Files whose slots were evicted by the write.
    #[must_use]
    pub fn evicted(&self) -> &[DiagnosticsKey] {
        match self {
            Self::Stored { evicted } | Self::Dropped { evicted } => evicted,
        }
    }
}

/// Whether the merged diagnostics of a file differ before and after a write.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChangeOutcome {
    /// A read would now return something else.
    Changed,
    /// A read would return the same diagnostics.
    Unchanged,
}

impl ChangeOutcome {
    /// Compares two merged views as multisets of serialized diagnostics; an
    /// absent view differs from a present but empty one.
    pub(crate) fn of(before: Option<&DiagnosticInfo>, after: Option<&DiagnosticInfo>) -> Self {
        Self::compare(before, after, |d| serde_json::to_vec(d).ok())
    }

    /// [`Self::of`] over a caller-chosen serializer. A diagnostic that cannot
    /// be serialized makes its view incomparable, which reads as a change:
    /// the conservative side is to notify.
    fn compare(
        before: Option<&DiagnosticInfo>,
        after: Option<&DiagnosticInfo>,
        serialize: impl Fn(&LspDiagnostic) -> Option<Vec<u8>>,
    ) -> Self {
        let fingerprint = |info: &DiagnosticInfo| -> Option<Vec<Vec<u8>>> {
            let mut items = info
                .diagnostics
                .iter()
                .map(&serialize)
                .collect::<Option<Vec<_>>>()?;
            items.sort_unstable();
            Some(items)
        };
        match (before, after) {
            (None, None) => Self::Unchanged,
            (Some(before), Some(after)) => match (fingerprint(before), fingerprint(after)) {
                (Some(before), Some(after)) if before == after => Self::Unchanged,
                _ => Self::Changed,
            },
            _ => Self::Changed,
        }
    }
}

/// What the document tracker says about the document a push is for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DocumentSync {
    /// The server was last told this version of the document.
    Synced(DocumentVersion),
    /// The document is not open for the server.
    NotOpen,
    /// No tracker is attached, so there is nothing to compare with.
    Unattached,
}

/// Whether a push supersedes the pulled slot of its file.
///
/// A push carrying a newer document version than the pull answered does. Any
/// push does when the tracked document is no longer at the pulled version
/// (it moved on, or a closed or evicted document restarted its version) or is
/// not open. While the document still is at the pulled version the pull
/// stays, whether the push carries an equal, a lower or no version: servers
/// that push and pull one version keep both slots, and a versionless flycheck
/// push must not erase the pulled native diagnostics (bridge/004). A document
/// closed and reopened since the pull is handled by [`NotificationCache`]
/// itself, since its version can coincide with the pulled one again.
///
/// Without a tracker ([`DocumentSync::Unattached`]) only a newer version counts.
fn pull_is_superseded(
    pulled: DocumentVersion,
    pushed: Option<DocumentVersion>,
    sync: DocumentSync,
) -> bool {
    match (pushed, sync) {
        (Some(pushed), _) if pushed > pulled => true,
        (_, DocumentSync::Unattached) => false,
        (_, DocumentSync::NotOpen) => true,
        (_, DocumentSync::Synced(current)) => current != pulled,
    }
}

/// Which file's slots a capacity eviction must leave alone.
#[derive(Debug, Clone, Copy)]
enum Protect<'a> {
    Nothing,
    File(&'a DiagnosticsKey),
}

/// Indices into a pushed entry's diagnostics that a pull of the same document
/// state (same opening, same version) reported as well.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
struct Covered(BTreeSet<usize>);

/// Most `source` values learned per server from its pull reports.
const MAX_LEARNED_PULL_SOURCES: usize = 32;

/// Longest `source` value that is learned.
const MAX_DIAGNOSTIC_SOURCE_BYTES: usize = 128;

/// The `source` of a diagnostic (`"Pylance"`, `"rustc"`), bounded so a server
/// cannot make the cache remember an arbitrary amount of text.
#[derive(Debug, Clone, PartialEq, Eq)]
struct DiagnosticSource(BoundedText<MAX_DIAGNOSTIC_SOURCE_BYTES>);

impl DiagnosticSource {
    fn of(diagnostic: &LspDiagnostic) -> Option<Self> {
        let text = diagnostic.source.as_deref()?;
        BoundedText::new(text).ok().map(Self)
    }
}

/// Whether a pushed entry still describes the document state the tracker last
/// synced to the server, and what of it a pull has since answered for.
///
/// Computed under the cache lock from the entry, the tracker and the file's
/// pulled slot, so a read and the notification decision behind it agree.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Freshness {
    /// Nothing is excluded: the entry is current, unversioned, the document is
    /// not tracked, or no pull at the synced state answers for the file.
    Current,
    /// The entry is older (or from another opening) than the synced state and
    /// the same server's pull at that state exists: the covered items are
    /// what that pull did not repeat, so they are dropped from the merge.
    Superseded { covered: Covered },
}

impl Freshness {
    fn excludes(&self, index: usize) -> bool {
        match self {
            Self::Current => false,
            Self::Superseded { covered } => covered.0.contains(&index),
        }
    }
}

/// How a cached entry's diagnostics arrived, with the bookkeeping that only
/// exists for that way.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Origin {
    /// Delivered by `textDocument/publishDiagnostics`.
    Pushed {
        spelling: Spelling,
        /// Document version the server published the diagnostics for, if any.
        version: Option<DocumentVersion>,
        /// The tracked opening of the document when the publish arrived, or
        /// `None` without a tracker or an open document.
        opening: Option<Opening>,
        /// The diagnostics a pull of the same document state reported too;
        /// reset by a new publish, grown when the pulled slot is retired.
        covered: Covered,
    },
    /// Answered to a `textDocument/diagnostic` request, always for a known
    /// document version and under the file's canonical URI.
    Pulled {
        /// Orders the pulls of the file's pulled slot.
        ticket: PullTicket,
        /// The tracked opening of the document when the report was stored, or
        /// `None` without a tracker or an open document.
        opening: Option<Opening>,
        /// Document version the pull was requested at.
        version: DocumentVersion,
    },
}

impl Origin {
    /// Document version the entry's diagnostics were produced for.
    const fn version(&self) -> Option<DocumentVersion> {
        match self {
            Self::Pushed { version, .. } => *version,
            Self::Pulled { version, .. } => Some(*version),
        }
    }

    const fn provenance(&self) -> Provenance {
        match self {
            Self::Pushed { .. } => Provenance::Pushed,
            Self::Pulled { .. } => Provenance::Pulled,
        }
    }
}

/// One cached diagnostics entry with all of its bookkeeping, so the indices
/// derived from it are only ever touched by `insert_entry`/`take_entry`.
#[derive(Debug)]
struct CachedEntry {
    /// URI the entry is stored under.
    uri: Uri,
    diagnostics: Vec<LspDiagnostic>,
    /// Server that published the entry.
    owner: ServerId,
    /// Position in `owner`'s write order.
    seq: u64,
    origin: Origin,
}

impl CachedEntry {
    /// The entry as a [`DiagnosticInfo`], with the version taken from its origin.
    fn info(&self) -> DiagnosticInfo {
        DiagnosticInfo {
            uri: self.uri.clone(),
            version: self.origin.version(),
            diagnostics: self.diagnostics.clone(),
        }
    }

    /// Key of the file this entry belongs to, given the entry's own `key`.
    const fn file<'a>(&'a self, key: &'a SlotKey) -> &'a DiagnosticsKey {
        match &self.origin {
            Origin::Pushed {
                spelling: Spelling::Alias(canonical),
                ..
            } => canonical,
            Origin::Pushed {
                spelling: Spelling::Canonical,
                ..
            }
            | Origin::Pulled { .. } => &key.uri,
        }
    }
}

/// The cache key under which diagnostics for the file behind `uri` are
/// stored, for matching [`NotificationCache::clear_server_diagnostics`]
/// results against a subscription.
pub fn diagnostics_cache_key(uri: &DiagnosticsResourceUri) -> Option<DiagnosticsKey> {
    let path = crate::bridge::resources::parse_uri(uri.as_str()).ok()?;
    let lsp_uri = crate::bridge::try_path_to_uri(path.as_path())?;
    Some(DiagnosticsKey::of(&lsp_uri))
}

/// Maximum number of distinct published URIs (a canonical path and its
/// symlink aliases) whose diagnostics are unioned under one file; bounds how
/// far a misbehaving server can fan a single file out.
const MAX_SOURCES_PER_FILE: usize = 8;

/// Maximum number of server messages to store.
const MAX_SERVER_MESSAGES: usize = 50;

/// Most empty-entry removals remembered for replay on `subscriptions/listen`:
/// as many as the cache can hold entries, so a full cache cleared at once
/// (e.g. a server restart) loses no replayable clear.
const MAX_RECENT_EVICTIONS: usize = MAX_DIAGNOSTIC_ENTRIES;

/// Most evicted files remembered for `NotificationCache::availability`.
const MAX_EVICTION_MARKS: usize = MAX_DIAGNOSTIC_ENTRIES;

/// How long an empty-entry removal stays replayable.
const EVICTION_REPLAY_WINDOW: std::time::Duration = std::time::Duration::from_mins(2);

/// File keys of empty entries removed within `EVICTION_REPLAY_WINDOW`.
///
/// `at` is the source of truth; `order` is an expiry queue over it in which an
/// item whose instant differs from `at`'s is stale (the key was re-recorded or
/// dropped) and is skipped. Re-recording a key adds an order item, so `order`
/// is rebuilt from `at` once it exceeds twice `at`'s size, keeping both
/// bounded under churn on few keys. Over `MAX_RECENT_EVICTIONS` the oldest
/// record is forgotten and logged once per window.
#[derive(Debug, Default)]
struct EvictionRecord {
    at: HashMap<DiagnosticsKey, std::time::Instant>,
    order: VecDeque<(DiagnosticsKey, std::time::Instant)>,
    overflow_warn: WarnLimiter,
}

impl EvictionRecord {
    fn record(&mut self, file: DiagnosticsKey, now: std::time::Instant) {
        self.prune_expired(now);
        self.at.insert(file.clone(), now);
        self.order.push_back((file, now));
        while self.at.len() > MAX_RECENT_EVICTIONS {
            self.forget_oldest(now);
        }
        if self.order.len() > self.at.len().saturating_mul(2) {
            self.compact();
        }
    }

    fn contains(&self, key: &DiagnosticsKey, now: std::time::Instant) -> bool {
        self.at
            .get(key)
            .is_some_and(|at| now.saturating_duration_since(*at) <= EVICTION_REPLAY_WINDOW)
    }

    fn is_live(&self, key: &DiagnosticsKey, at: std::time::Instant) -> bool {
        self.at.get(key) == Some(&at)
    }

    fn prune_expired(&mut self, now: std::time::Instant) {
        while let Some((key, at)) = self
            .order
            .pop_front_if(|(_, at)| now.saturating_duration_since(*at) > EVICTION_REPLAY_WINDOW)
        {
            if self.is_live(&key, at) {
                self.at.remove(&key);
            }
        }
    }

    fn forget_oldest(&mut self, now: std::time::Instant) {
        while let Some((key, at)) = self.order.pop_front() {
            if self.is_live(&key, at) {
                self.at.remove(&key);
                self.warn_overflow(now);
                return;
            }
        }
    }

    fn warn_overflow(&mut self, now: std::time::Instant) {
        if self.overflow_warn.due(now, EVICTION_REPLAY_WINDOW) {
            warn!(
                "more than {MAX_RECENT_EVICTIONS} diagnostics clears evicted within {}s, \
                 forgetting the oldest; a re-attaching listen may miss them",
                EVICTION_REPLAY_WINDOW.as_secs()
            );
        }
    }

    fn compact(&mut self) {
        let mut live: Vec<_> = self.at.iter().map(|(k, at)| (k.clone(), *at)).collect();
        live.sort_by_key(|(_, at)| *at);
        self.order = live.into();
    }

    #[cfg(test)]
    fn len(&self) -> usize {
        self.at.len()
    }

    #[cfg(test)]
    fn is_empty(&self) -> bool {
        self.at.is_empty()
    }
}

/// What was cached for a file when capacity eviction removed its last entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EvictedContent {
    /// Only empty lists: the file was clean.
    Clean,
    /// A non-empty list: what the server said is no longer known.
    Lost,
}

#[derive(Debug)]
struct EvictionMark {
    owner: ServerId,
    content: EvictedContent,
    seq: u64,
}

/// Files whose entries capacity eviction removed, so a read can tell a clean
/// file or lost diagnostics from a file nothing was ever published for.
///
/// Bounded to `MAX_EVICTION_MARKS`; once the oldest mark of a server is
/// forgotten the server is `overflowed`, and a file without entry or mark is
/// then reported as possibly evicted rather than as pending. A server's marks
/// and overflow are dropped with its diagnostics (respawn), and a file's mark
/// with its next entry. The overflow also ends with the server's next accepted
/// write, so a file forgotten before it reads as pending again instead of
/// possibly evicted for as long as the process runs.
#[derive(Debug, Default)]
struct EvictionMarks {
    by_file: HashMap<DiagnosticsKey, EvictionMark>,
    order: BTreeMap<u64, DiagnosticsKey>,
    next_seq: u64,
    overflowed: HashSet<ServerId>,
}

impl EvictionMarks {
    fn record(&mut self, file: DiagnosticsKey, owner: ServerId, content: EvictedContent) {
        let content = match self.by_file.get(&file) {
            Some(previous) if previous.content == EvictedContent::Lost => EvictedContent::Lost,
            _ => content,
        };
        self.forget_file(&file);
        let seq = self.next_seq;
        self.next_seq = self.next_seq.saturating_add(1);
        self.order.insert(seq, file.clone());
        self.by_file.insert(
            file,
            EvictionMark {
                owner,
                content,
                seq,
            },
        );
        while self.by_file.len() > MAX_EVICTION_MARKS {
            let Some((_, oldest)) = self.order.pop_first() else {
                break;
            };
            if let Some(mark) = self.by_file.remove(&oldest) {
                self.overflowed.insert(mark.owner);
            }
        }
    }

    fn forget_file(&mut self, file: &DiagnosticsKey) {
        if let Some(mark) = self.by_file.remove(file) {
            self.order.remove(&mark.seq);
        }
    }

    fn forget_server(&mut self, server: &ServerId) {
        self.by_file.retain(|_, mark| &mark.owner != server);
        self.order.retain(|_, file| self.by_file.contains_key(file));
        self.overflowed.remove(server);
    }

    fn content(&self, file: &DiagnosticsKey) -> Option<EvictedContent> {
        self.by_file.get(file).map(|mark| mark.content)
    }

    fn has_overflowed(&self, server: &ServerId) -> bool {
        self.overflowed.contains(server)
    }

    /// Ends `server`'s overflow and returns whether it was set. Called before
    /// the write's own evictions, which can start a new one.
    fn clear_overflow(&mut self, server: &ServerId) -> bool {
        self.overflowed.remove(server)
    }

    fn restore_overflow(&mut self, server: &ServerId) {
        self.overflowed.insert(server.clone());
    }
}

/// Borrows a diagnostic's free-form `message` as plain text, regardless of
/// whether the server sent it as a plain string or (per LSP 3.18)
/// `MarkupContent`.
pub fn message_as_str(message: &lsp_types::Message) -> &str {
    match message {
        lsp_types::Message::String(s) => s,
        lsp_types::Message::MarkupContent(m) => &m.value,
    }
}

/// Information about diagnostics for a document.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiagnosticInfo {
    /// URI of the document.
    pub uri: Uri,
    /// Document version when diagnostics were received.
    pub version: Option<DocumentVersion>,
    /// List of diagnostics.
    pub diagnostics: Vec<LspDiagnostic>,
}

/// How an entry of a [`DiagnosticSources`] snapshot arrived.
#[derive(Debug, Clone, PartialEq, Eq)]
enum SourceOrigin {
    /// Published under this spelling of the path.
    Pushed(Spelling),
    /// Answered to a pull, under the canonical spelling.
    Pulled,
}

impl SourceOrigin {
    const fn is_pulled(&self) -> bool {
        matches!(self, Self::Pulled)
    }
}

impl From<&Origin> for SourceOrigin {
    fn from(origin: &Origin) -> Self {
        match origin {
            Origin::Pushed { spelling, .. } => Self::Pushed(spelling.clone()),
            Origin::Pulled { .. } => Self::Pulled,
        }
    }
}

/// One cached entry of a [`DiagnosticSources`] snapshot.
#[derive(Debug, Clone)]
struct SourceEntry {
    info: DiagnosticInfo,
    origin: SourceOrigin,
    freshness: Freshness,
}

/// Owned snapshot of the diagnostics cached for one file, possibly spread
/// over several published URIs (a canonical path plus symlink aliases) and
/// over a pushed and a pulled source.
///
/// Taken under the cache lock by [`NotificationCache::diagnostic_sources`];
/// the clone/dedupe/sort/cap work in [`Self::merge`] then runs after the
/// guard is dropped, so the diagnostics pump is never blocked behind it.
#[derive(Debug, Clone)]
pub struct DiagnosticSources {
    requested: Uri,
    entries: Vec<SourceEntry>,
}

impl DiagnosticSources {
    /// Replaces the snapshot's pulled entry with `diagnostics`, for a pull
    /// report that was answered but not stored.
    pub(crate) fn with_pulled(
        mut self,
        file: &Uri,
        version: Option<DocumentVersion>,
        diagnostics: BoundedDiagnostics,
    ) -> Self {
        self.entries.retain(|entry| !entry.origin.is_pulled());
        self.entries.push(SourceEntry {
            info: DiagnosticInfo {
                uri: file.clone(),
                version,
                diagnostics: diagnostics.0,
            },
            origin: SourceOrigin::Pulled,
            freshness: Freshness::Current,
        });
        self
    }

    /// Collapses the sources into one entry for the requested file.
    ///
    /// - No source: `None`.
    /// - One pushed source: returned unchanged, with its own `uri` and
    ///   `version`, even when it is a symlink alias.
    /// - Otherwise: pulled diagnostics come first and are never collapsed
    ///   among themselves; a pushed diagnostic is dropped when it duplicates a
    ///   pulled one (same problem, see `PulledIndex::contains_same_problem`) or an earlier
    ///   pushed one (equal in every field). The result is ordered by range
    ///   (stable) and re-capped to the per-entry size bound. The entry's `uri`
    ///   is the requested one and its `version` is that of the pushed source
    ///   published under the canonical spelling, else the pulled one's, else
    ///   `None`.
    ///
    /// # Examples
    ///
    /// ```
    /// use lsp_types::Uri;
    /// use mcpls_core::bridge::NotificationCache;
    ///
    /// let cache = NotificationCache::new();
    /// let uri = Uri::from("file:///workspace/main.rs".to_owned());
    /// let sources = cache.diagnostic_sources(&uri);
    /// assert!(sources.merge().is_none());
    /// ```
    #[must_use]
    pub fn merge(self) -> Option<DiagnosticInfo> {
        let Self { requested, entries } = self;
        let has_pulled = entries.iter().any(|entry| entry.origin.is_pulled());
        if entries.len() <= 1 && !has_pulled {
            return entries.into_iter().next().map(|entry| entry.info);
        }
        let version = entries
            .iter()
            .find(|entry| {
                entry.origin == SourceOrigin::Pushed(Spelling::Canonical)
                    && entry.freshness == Freshness::Current
            })
            .and_then(|entry| entry.info.version)
            .or_else(|| {
                entries
                    .iter()
                    .find(|entry| entry.origin.is_pulled())
                    .and_then(|entry| entry.info.version)
            });

        let (pulled, pushed): (Vec<SourceEntry>, Vec<SourceEntry>) = entries
            .into_iter()
            .partition(|entry| entry.origin.is_pulled());
        let pulled: Vec<LspDiagnostic> = pulled
            .into_iter()
            .flat_map(|entry| entry.info.diagnostics)
            .collect();
        let index = PulledIndex::new(&pulled);
        let mut seen: HashSet<Vec<u8>> = HashSet::new();
        let mut kept_pushed = Vec::new();
        let pushed_items = pushed.into_iter().flat_map(|entry| {
            let SourceEntry {
                info, freshness, ..
            } = entry;
            info.diagnostics
                .into_iter()
                .enumerate()
                .filter(move |(position, _)| !freshness.excludes(*position))
                .map(|(_, diagnostic)| diagnostic)
        });
        for diagnostic in pushed_items {
            if index.contains_same_problem(&diagnostic) {
                continue;
            }
            // A serialization error cannot happen for a `Diagnostic`; keeping
            // the item is the safe fallback.
            if serde_json::to_vec(&diagnostic).map_or(true, |bytes| seen.insert(bytes)) {
                kept_pushed.push(diagnostic);
            }
        }
        drop(index);
        let mut merged = pulled;
        merged.extend(kept_pushed);
        merged.sort_by_key(|d| (point(d.range.start), point(d.range.end)));
        cap_diagnostics_entry_size(&requested, &mut merged);

        Some(DiagnosticInfo {
            uri: requested,
            version,
            diagnostics: merged,
        })
    }
}

/// A log entry from the LSP server.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct LogEntry {
    /// Log level.
    pub level: LogLevel,
    /// Log message.
    pub message: String,
    /// Timestamp when the log was received.
    pub timestamp: DateTime<Utc>,
}

/// Log severity level.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "lowercase")]
#[schemars(inline)]
pub enum LogLevel {
    /// Error log level.
    Error,
    /// Warning log level.
    Warning,
    /// Info log level.
    Info,
    /// Debug log level.
    Debug,
}

impl LogLevel {
    const fn rank(self) -> u8 {
        match self {
            Self::Error => 0,
            Self::Warning => 1,
            Self::Info => 2,
            Self::Debug => 3,
        }
    }

    /// Whether a log of this level is at least as severe as `min`.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcpls_core::bridge::LogLevel;
    ///
    /// assert!(LogLevel::Error.meets(LogLevel::Warning));
    /// assert!(!LogLevel::Debug.meets(LogLevel::Info));
    /// assert!(LogLevel::Debug.meets(LogLevel::Debug));
    /// ```
    #[must_use]
    pub const fn meets(self, min: Self) -> bool {
        self.rank() <= min.rank()
    }
}

impl From<lsp_types::MessageType> for LogLevel {
    fn from(msg_type: lsp_types::MessageType) -> Self {
        match msg_type {
            lsp_types::MessageType::Error => Self::Error,
            lsp_types::MessageType::Warning => Self::Warning,
            lsp_types::MessageType::Info => Self::Info,
            // LOG and unknown message types default to Debug
            _ => Self::Debug,
        }
    }
}

/// A message from the LSP server.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ServerMessage {
    /// Message type.
    pub message_type: MessageType,
    /// Message content.
    pub message: String,
    /// Timestamp when the message was received.
    pub timestamp: DateTime<Utc>,
}

/// Server message type.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum MessageType {
    /// Error message.
    Error,
    /// Warning message.
    Warning,
    /// Info message.
    Info,
    /// Log message.
    Log,
}

impl From<lsp_types::MessageType> for MessageType {
    fn from(msg_type: lsp_types::MessageType) -> Self {
        match msg_type {
            lsp_types::MessageType::Error => Self::Error,
            lsp_types::MessageType::Warning => Self::Warning,
            lsp_types::MessageType::Info => Self::Info,
            // LOG and unknown message types default to Log
            _ => Self::Log,
        }
    }
}

/// Cache for LSP server notifications.
#[derive(Debug)]
pub struct NotificationCache {
    /// Diagnostics entries by published URI.
    entries: HashMap<SlotKey, CachedEntry>,
    /// Per-server entry keys ordered oldest-write-first, keyed by a
    /// monotonic sequence number rather than position: a re-publish removes
    /// its old entry by key in `O(log n)` instead of scanning for it, which a
    /// plain `VecDeque` would require. Not independently capped per server --
    /// only the aggregate across all servers is bounded, by
    /// `MAX_DIAGNOSTIC_ENTRIES` -- but each server's own map length is what
    /// eviction compares against its fair share (see
    /// [`NotificationCache::server_to_evict_from`]) to decide which server
    /// loses an entry once the aggregate is full, so one server's write
    /// volume can never evict another's entries while it still has room
    /// left in the global budget (#266, #276).
    order: HashMap<ServerId, BTreeMap<u64, SlotKey>>,
    /// Canonical file key -> keys of the entries (the canonical path and its
    /// symlink aliases) whose diagnostics are unioned on read.
    files: HashMap<DiagnosticsKey, BTreeSet<SlotKey>>,
    /// Next sequence number to assign in `order`. Shared across every
    /// server's order map and monotonically increasing for the cache's
    /// lifetime; never reused, so it never collides with an older entry
    /// still pending eviction.
    next_diagnostic_seq: u64,
    /// Next ticket handed to a pull by [`Self::begin_pull`].
    next_pull_ticket: u64,
    /// Per server, the `source` values its non-empty full pull reports carried,
    /// so a pushed item with such a source is known to be one the server
    /// reports through pulls too. Dropped with the server's diagnostics.
    pull_sources: HashMap<ServerId, Vec<DiagnosticSource>>,
    /// Per-server count of [`Self::clear_server_diagnostics`] calls; absent
    /// means epoch zero.
    clear_epochs: HashMap<ServerId, ClearEpoch>,
    /// Number of registered diagnostics-route servers currently sharing the
    /// `MAX_DIAGNOSTIC_ENTRIES` budget, explicitly configured via
    /// [`NotificationCache::set_diagnostics_route_count`].
    ///
    /// `None` until that setter is called -- `per_server_budget` then falls
    /// back to the number of servers whose `order` entry is
    /// non-empty (i.e. currently holds at least one entry) rather than
    /// treating an unset count as `1`, which used to hand a single early
    /// publisher the entire budget with no fair-share partitioning at all
    /// (#283). The explicit setter remains the preferred path when the
    /// caller knows it up front: it pre-accounts for servers that are
    /// registered but have not published anything yet, avoiding a window
    /// where an early publisher is temporarily over-allocated before a
    /// slower server's first write grows `order`.
    diagnostics_route_count: Option<usize>,

    /// Count of entries in `entries` whose diagnostics list is currently
    /// empty (`[]`), i.e. an LSP server reporting a previously-tracked file
    /// as now clean. A plain counter, not a duplicated key set, so `0` is an
    /// `O(1)` signal that lets `entry_to_evict` skip its empty-entry search
    /// entirely in the common steady state of a codebase full of real
    /// diagnostics (#284) -- which entry is empty is still answered by
    /// looking the key up in `entries` itself (see the private
    /// `is_empty_entry`), not by mirroring membership here. Maintained only
    /// by `insert_entry`/`take_entry`.
    empty_diagnostics_count: usize,
    /// Empty entries removed within `EVICTION_REPLAY_WINDOW`. Only empty
    /// entries are recorded: a clear lost to eviction is what a listen
    /// re-attaching after its lease gap must still replay, while replaying a
    /// removed non-empty entry would make clients re-read "not published" and
    /// drop valid errors, so a non-empty entry evicted by capacity is never
    /// replayed. Written only by `evict_entry`, never by publishers.
    recent_evictions: EvictionRecord,
    /// Files whose last entry capacity eviction removed; see
    /// [`Self::availability`]. Unlike `recent_evictions` it is written by
    /// capacity evictions only, never by a server clear.
    eviction_marks: EvictionMarks,
    /// Tracker whose synced versions tell whether a push supersedes a pulled
    /// slot; see [`Self::attach_documents`].
    documents: Option<Arc<DocumentTracker>>,
    /// Recent log entries (FIFO queue with max size).
    logs: VecDeque<LogEntry>,
    /// Recent server messages (FIFO queue with max size).
    messages: VecDeque<ServerMessage>,
    /// Server ids whose `textDocument/publishDiagnostics` push notifications
    /// are known to be dark: `Translator::respawn_if_dead` replaced a crashed
    /// process for this id, and the replacement's notification receiver is
    /// drained and discarded rather than wired into a running
    /// `diagnostics_pump` (#249's documented trade-off -- the pump's
    /// remaining dependencies live in `serve_with`'s scope, not
    /// `Translator`'s). Once marked, an id is never unmarked here: only a
    /// full mcpls process restart actually restores push diagnostics for
    /// that server, so clearing this on a later respawn attempt would
    /// misreport the cache as fresh again.
    push_degraded: HashSet<ServerId>,
    /// Workspace-indexing readiness per server, driven by recognized
    /// out-of-band signals (rust-analyzer's `experimental/serverStatus`, and
    /// a generic `$/progress` `begin`/`end` sequence) rather than the
    /// `initialize`/`initialized` handshake. See
    /// `Self::observe_indexing_signal` and [`Self::observe_progress`].
    indexing: IndexingTracker,
}

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

impl NotificationCache {
    /// Create a new notification cache.
    #[must_use]
    pub fn new() -> Self {
        Self {
            entries: HashMap::with_capacity(32),
            order: HashMap::new(),
            files: HashMap::new(),
            next_diagnostic_seq: 0,
            next_pull_ticket: 0,
            pull_sources: HashMap::new(),
            clear_epochs: HashMap::new(),
            diagnostics_route_count: None,
            empty_diagnostics_count: 0,
            recent_evictions: EvictionRecord::default(),
            eviction_marks: EvictionMarks::default(),
            documents: None,
            logs: VecDeque::with_capacity(MAX_LOG_ENTRIES),
            messages: VecDeque::with_capacity(MAX_SERVER_MESSAGES),
            push_degraded: HashSet::new(),
            indexing: IndexingTracker::new(),
        }
    }

    /// Configure how many diagnostics-route servers share the global
    /// `MAX_DIAGNOSTIC_ENTRIES` budget.
    ///
    /// Each server's fair share becomes `MAX_DIAGNOSTIC_ENTRIES / count`
    /// (minimum 1). This does not cap any server's entries by itself -- the
    /// aggregate cache is only ever trimmed once it reaches
    /// `MAX_DIAGNOSTIC_ENTRIES` total -- it only decides, at that point,
    /// which server's oldest entry is the one that gets evicted. Call once
    /// after server registration completes and before diagnostics start
    /// flowing, to pre-account for servers that are registered but have not
    /// published anything yet. If never called, `per_server_budget` derives
    /// the count from the number of servers currently holding at least one
    /// entry instead (#283) -- a consumer that forgets to call this still
    /// gets fair-share partitioning once more than one server has written an
    /// entry, rather than silently handing the whole budget to a single
    /// early publisher.
    pub(crate) fn set_diagnostics_route_count(&mut self, count: usize) {
        self.diagnostics_route_count = Some(count.max(1));
    }

    #[cfg(test)]
    pub(crate) const fn configured_route_count(&self) -> Option<usize> {
        self.diagnostics_route_count
    }

    /// Current per-server fair share of `MAX_DIAGNOSTIC_ENTRIES`, divided
    /// evenly across the configured server count and floored at 1 so a
    /// large server count can never reduce a server's share to zero.
    ///
    /// Uses the explicit count from [`Self::set_diagnostics_route_count`]
    /// when set; otherwise falls back to the number of servers whose
    /// `order` entry is non-empty (#283) -- matching
    /// `server_to_evict_from`'s own `!order.is_empty()` filter, so a server
    /// that has been fully evicted or reassigned away from (an empty but
    /// still-present order map) is not double-counted in the denominator.
    /// Both are floored at 1 so a fresh cache with no entries and no
    /// explicit count yet still yields a usable budget instead of dividing
    /// by zero.
    ///
    /// This is a tie-breaker for eviction, not a hard per-server cap: a
    /// server may hold more than its fair share of entries at any time, as
    /// long as the aggregate across all servers stays within
    /// `MAX_DIAGNOSTIC_ENTRIES` (#276).
    fn per_server_budget(&self) -> usize {
        let count = self
            .diagnostics_route_count
            .unwrap_or_else(|| {
                self.order
                    .values()
                    .filter(|order| !order.is_empty())
                    .count()
            })
            .max(1);
        MAX_DIAGNOSTIC_ENTRIES
            .checked_div(count)
            .unwrap_or(1)
            .max(1)
    }

    /// Picks which server's oldest entry to evict once the aggregate cache
    /// is full: whichever registered server holds the most entries, if that
    /// exceeds its fair share ([`Self::per_server_budget`]) -- so a noisy
    /// server can only ever evict its own entries, never a quiet server's
    /// that is still within its share (#266). If every server (including
    /// `writer`) is within its share, falls back to `writer`'s own oldest
    /// entry, since it is the one currently growing. Falls back further, to
    /// whichever server holds the most entries regardless of share, only in
    /// the edge case where `writer` has no entries of its own yet (its very
    /// first write) while the aggregate is already full purely from other
    /// servers each individually within their share -- otherwise there
    /// would be nothing to evict from and the aggregate cap could be
    /// exceeded despite every server behaving fairly.
    ///
    /// Ties in entry count are broken by `ServerId`, not left to
    /// `HashMap`'s iteration order: `Iterator::max_by_key` returns the
    /// *last* equally-maximal element it sees, and a `HashMap`'s iteration
    /// order is randomized per process, so an `order.len()`-only key would
    /// make the eviction target for a genuine tie vary from run to run.
    /// Every candidate here is a distinct `order` key, so pairing
    /// the count with `id.as_str()` makes the sort key unique per server --
    /// no two entries can ever tie on the full key, which eliminates the
    /// non-determinism outright rather than just picking a fixed side of it.
    fn server_to_evict_from(&self, writer: &ServerId) -> Option<ServerId> {
        let largest = self
            .order
            .iter()
            .filter(|(_, order)| !order.is_empty())
            .max_by_key(|(id, order)| (order.len(), id.as_str()));

        let budget = self.per_server_budget();
        if let Some((id, order)) = largest
            && order.len() > budget
        {
            return Some(id.clone());
        }

        if self
            .order
            .get(writer)
            .is_some_and(|order| !order.is_empty())
        {
            return Some(writer.clone());
        }

        largest.map(|(id, _)| id.clone())
    }

    /// Whether the cached entry for `key` currently has an empty (`[]`)
    /// diagnostics list, i.e. an LSP server reporting a previously-tracked
    /// file as now clean. Derived directly from `entries` rather than
    /// from a separately maintained key set, so there is nothing else to
    /// keep in sync (#284).
    fn is_empty_entry(&self, key: &SlotKey) -> bool {
        self.entries
            .get(key)
            .is_some_and(|entry| entry.diagnostics.is_empty())
    }

    /// Whether `key` is a slot of the file `protect` names.
    fn is_protected(&self, key: &SlotKey, protect: Protect<'_>) -> bool {
        match protect {
            Protect::Nothing => false,
            Protect::File(file) => self
                .entries
                .get(key)
                .is_some_and(|entry| entry.file(key) == file),
        }
    }

    /// Oldest unprotected entry in `server`'s own order map whose diagnostics
    /// list is empty, if it has one.
    fn oldest_empty_entry_in(
        &self,
        server: &ServerId,
        protect: Protect<'_>,
    ) -> Option<(u64, SlotKey)> {
        let order = self.order.get(server)?;
        order
            .iter()
            .find(|(_, key)| self.is_empty_entry(key) && !self.is_protected(key, protect))
            .map(|(&seq, key)| (seq, key.clone()))
    }

    /// Oldest unprotected entry in `server`'s own order map.
    fn oldest_entry_in(&self, server: &ServerId, protect: Protect<'_>) -> Option<(u64, SlotKey)> {
        self.order
            .get(server)?
            .iter()
            .find(|(_, key)| !self.is_protected(key, protect))
            .map(|(&seq, key)| (seq, key.clone()))
    }

    /// Which single entry to remove next when the aggregate cache is full
    /// and a genuinely new URI needs room, returned as `(owner, seq, key)`
    /// so the caller can remove it from every index it appears in.
    ///
    /// [`Self::server_to_evict_from`] decides which server is fairness's
    /// primary target; this picks *which of that server's entries* to
    /// actually remove, preferring an empty (`[]`) one over its
    /// strictly-oldest entry wherever one can be found without disturbing a
    /// server that is within its own fair share (#284):
    ///
    /// 1. If the chosen victim itself holds an empty entry, evict its oldest
    ///    one -- a `[]` publish carries no diagnostic content to lose, so
    ///    this lets an older, still-meaningful entry from the same server
    ///    survive in its place.
    /// 2. Otherwise, if some *other* server that also exceeds
    ///    [`Self::per_server_budget`] holds an empty entry, evict that one
    ///    instead of destroying the chosen victim's real diagnostics (S1):
    ///    fairness only protects a server that is within its share, so an
    ///    over-share server's own clean entry is fair game regardless of
    ///    which over-share server `server_to_evict_from` happened to name.
    ///    Ties use the same `(count, id)` key as `server_to_evict_from`, for
    ///    the same determinism reason.
    /// 3. Otherwise -- no empty entry exists anywhere over-budget -- falls
    ///    back to the chosen victim's strictly-oldest entry, exactly as
    ///    before #284.
    ///
    /// Step 1/2's search is skipped entirely when `empty_diagnostics_count`
    /// is `0`, so the common steady state (a codebase full of real
    /// diagnostics, no clean-file churn) pays no extra cost over a plain
    /// oldest-first lookup (#284).
    ///
    /// Entries of the file `protect` names are never picked: a pull write
    /// must not evict the same file's pushed slot it is merged with. When the
    /// chosen server has nothing else, the largest other server's oldest
    /// unprotected entry is taken instead.
    fn entry_to_evict(
        &self,
        writer: &ServerId,
        protect: Protect<'_>,
    ) -> Option<(ServerId, u64, SlotKey)> {
        let evict_from = self.server_to_evict_from(writer)?;

        if self.empty_diagnostics_count > 0 {
            if let Some((seq, key)) = self.oldest_empty_entry_in(&evict_from, protect) {
                return Some((evict_from, seq, key));
            }

            let budget = self.per_server_budget();
            let cross_server_pick = self
                .order
                .iter()
                .filter(|(id, order)| order.len() > budget && *id != &evict_from)
                .filter_map(|(id, order)| {
                    self.oldest_empty_entry_in(id, protect)
                        .map(|(seq, key)| (id, order.len(), seq, key))
                })
                .max_by_key(|(id, len, ..)| (*len, id.as_str()));

            if let Some((id, _, seq, key)) = cross_server_pick {
                return Some((id.clone(), seq, key));
            }
        }

        if let Some((seq, key)) = self.oldest_entry_in(&evict_from, protect) {
            return Some((evict_from, seq, key));
        }
        self.order
            .iter()
            .filter(|(id, _)| *id != &evict_from)
            .filter_map(|(id, order)| {
                self.oldest_entry_in(id, protect)
                    .map(|(seq, key)| (id, order.len(), seq, key))
            })
            .max_by_key(|(id, len, ..)| (*len, id.as_str()))
            .map(|(id, _, seq, key)| (id.clone(), seq, key))
    }

    /// Store diagnostics for a document published by `server_id`, indexed
    /// under its canonical file so every spelling of one file is read back as
    /// the union of what each published.
    ///
    /// Each diagnostic's `message` is truncated to `MAX_ENTRY_TEXT_BYTES`,
    /// and the whole list is bounded to `MAX_DIAGNOSTICS_ENTRY_BYTES`
    /// serialized bytes, before storing (#311). When that bound requires
    /// dropping diagnostics, the *survivors* come back sorted by severity
    /// ([`ReportedSeverity`] order: `ERROR` first, a diagnostic without a
    /// severity counting as information), not in the original
    /// publish/file-position order -- see [`Self::diagnostics`].
    ///
    /// If diagnostics already exist for the URI, they are replaced and the
    /// entry is repositioned to the back of its owner's eviction order, so
    /// a URI republished on every edit is tracked as most-recently-written
    /// and evicted last, not first -- and, since it is not a new distinct
    /// URI, never triggers eviction on its own.
    ///
    /// Eviction is work-conserving (#276): storing diagnostics for a
    /// genuinely new URI only evicts an existing entry once the *aggregate*
    /// across every server reaches `MAX_DIAGNOSTIC_ENTRIES`, and then only
    /// the least-recently-written entry of whichever server most exceeds its
    /// fair share, or -- per the fallbacks documented on
    /// `server_to_evict_from` -- the writer's own oldest entry when no
    /// server exceeds its share. A quieter, non-writer server that is within
    /// its fair share is never touched, outside the narrow edge case also
    /// documented there. This lets a single active server use the full
    /// aggregate budget while other registered servers are idle, instead of
    /// being capped at a static equal split regardless of how much of it
    /// they actually use. Which exact entry is removed is further refined by
    /// emptiness -- see the private `entry_to_evict` (#284).
    ///
    /// An empty publish replaces only its own source's entry. At most
    /// `MAX_SOURCES_PER_FILE` spellings are kept per file: a further alias is
    /// dropped before anything is stored, but the canonical spelling is always
    /// admitted, evicting the oldest alias, so a server fanning one file out
    /// cannot suppress the canonical publishes.
    ///
    /// The files whose entries were evicted to make room are returned so the
    /// caller can tell their subscribers (#649).
    pub(crate) fn write_published_diagnostics(
        &mut self,
        server_id: &ServerId,
        published: &PublishedDiagnosticsUri,
        version: Option<DocumentVersion>,
        diagnostics: BoundedDiagnostics,
    ) -> PushWrite {
        let source_key = SlotKey::pushed(DiagnosticsKey::of(published.source()));
        let canonical_key = DiagnosticsKey::of(published.canonical());

        let already_indexed = self
            .entries
            .get(&source_key)
            .is_some_and(|entry| entry.file(&source_key) == &canonical_key);
        let at_capacity = self.pushed_slot_count(&canonical_key) >= MAX_SOURCES_PER_FILE;
        if !already_indexed && at_capacity {
            let alias_to_evict = published
                .is_canonical()
                .then(|| self.oldest_alias_source(&canonical_key))
                .flatten();
            let Some(oldest_alias) = alias_to_evict else {
                debug!(
                    "dropping diagnostics for {}: {MAX_SOURCES_PER_FILE} published URIs already cached for {}",
                    published.source().as_ref(),
                    published.canonical().as_ref()
                );
                return PushWrite::Dropped {
                    evicted: Vec::new(),
                };
            };
            self.evict_entry(&oldest_alias);
        }

        let diagnostics = diagnostics.into_vec();

        self.drop_superseded_pull(&canonical_key, published.canonical(), version);

        // A replacement leaves its previous owner's order map (the owner may
        // differ when the diagnostics route changed, e.g. on respawn) and
        // never needs room; only a genuinely new URI can trigger eviction.
        drop(self.take_entry(&source_key));
        let evicted = match self.make_room(server_id, Protect::Nothing) {
            Ok(evicted) => evicted,
            Err(NoRoom { evicted }) => {
                debug!(
                    "dropping diagnostics for {}: no entry could be evicted to make room",
                    published.source().as_ref()
                );
                return PushWrite::Dropped { evicted };
            }
        };

        let seq = self.next_seq();
        let opening = self.document_opening(published.canonical());
        let spelling = if published.is_canonical() {
            Spelling::Canonical
        } else {
            Spelling::Alias(canonical_key)
        };
        self.insert_entry(
            source_key,
            CachedEntry {
                uri: published.source().clone(),
                diagnostics,
                owner: server_id.clone(),
                seq,
                origin: Origin::Pushed {
                    spelling,
                    version,
                    opening,
                    covered: Covered::default(),
                },
            },
        );
        PushWrite::Stored { evicted }
    }

    /// [`Self::write_published_diagnostics`] for tests that do not look at
    /// what the write evicted.
    #[cfg(test)]
    pub(crate) fn store_published_diagnostics(
        &mut self,
        server_id: &ServerId,
        published: &PublishedDiagnosticsUri,
        version: Option<i32>,
        diagnostics: Vec<LspDiagnostic>,
    ) {
        drop(self.write_published_diagnostics(
            server_id,
            published,
            version.map(DocumentVersion::new),
            BoundedDiagnostics::new(published.source(), diagnostics),
        ));
    }

    const fn next_seq(&mut self) -> u64 {
        let seq = self.next_diagnostic_seq;
        self.next_diagnostic_seq = self.next_diagnostic_seq.saturating_add(1);
        seq
    }

    /// Number of pushed slots (canonical and aliases) indexed under `file`.
    fn pushed_slot_count(&self, file: &DiagnosticsKey) -> usize {
        self.files.get(file).map_or(0, |slots| {
            slots
                .iter()
                .filter(|slot| slot.provenance == Provenance::Pushed)
                .count()
        })
    }

    /// Removes `file`'s pulled slot when a push shows that its content is
    /// older than the file, by [`pull_is_superseded`]'s rule.
    ///
    /// The document's synced version is read from the attached tracker for
    /// the server that owns the pulled slot; a push that carries a document
    /// version newer than the pulled one supersedes it without the tracker.
    fn drop_superseded_pull(
        &mut self,
        file: &DiagnosticsKey,
        canonical: &Uri,
        pushed_version: Option<DocumentVersion>,
    ) {
        let slot = SlotKey::pulled(file.clone());
        let Some(entry) = self.entries.get(&slot) else {
            return;
        };
        let Origin::Pulled {
            opening: pulled_opening,
            version: pulled,
            ..
        } = entry.origin
        else {
            return;
        };
        let owner = entry.owner.clone();
        let sync = self.document_sync(&owner, canonical);
        let reopened =
            self.documents.is_some() && pulled_opening != self.document_opening(canonical);
        if reopened || pull_is_superseded(pulled, pushed_version, sync) {
            debug!(
                "dropping the pulled diagnostics of {}: superseded by a push \
                 (pulled {pulled:?}, pushed {pushed_version:?}, {sync:?})",
                canonical.as_ref()
            );
            drop(self.take_entry(&slot));
        }
    }

    /// Attaches the document tracker whose synced versions decide whether a
    /// push supersedes a pulled slot. Without one, only a push carrying a
    /// newer document version does.
    pub(crate) fn attach_documents(&mut self, documents: Arc<DocumentTracker>) {
        self.documents = Some(documents);
    }

    /// What the attached tracker says about the document `canonical` names,
    /// for `owner`.
    fn document_sync(&self, owner: &ServerId, canonical: &Uri) -> DocumentSync {
        let Some(documents) = &self.documents else {
            return DocumentSync::Unattached;
        };
        uri_to_path(canonical)
            .and_then(|path| documents.synced_version(&path, owner))
            .map_or(DocumentSync::NotOpen, DocumentSync::Synced)
    }

    /// Which opening of the document `canonical` names the attached tracker
    /// holds, `None` when none is attached or it is not open.
    fn document_opening(&self, canonical: &Uri) -> Option<Opening> {
        let path = uri_to_path(canonical)?;
        self.documents.as_ref()?.opening(&path)
    }

    /// Issues the claim a pull of `server`'s diagnostics for a document at
    /// `version` needs to redeem in [`Self::store_pulled_diagnostics`].
    ///
    /// Taken before the request is sent: the ticket orders concurrent pulls
    /// of one file and the epoch exposes a clear that happened meanwhile.
    pub(crate) fn begin_pull(&mut self, server: &ServerId, version: DocumentVersion) -> PullStamp {
        let ticket = PullTicket(self.next_pull_ticket);
        self.next_pull_ticket = self.next_pull_ticket.saturating_add(1);
        PullStamp {
            ticket,
            epoch: self.clear_epochs.get(server).copied().unwrap_or_default(),
            version,
        }
    }

    /// Stores a `textDocument/diagnostic` report as `file`'s pulled slot,
    /// next to whatever the server pushed for it.
    ///
    /// The report is discarded unless `stamp`'s ticket is newer than the one
    /// stored, the server's diagnostics were not cleared since the stamp was
    /// issued, and `check` says the document still has the stamped version.
    /// Capacity evictions leave the written file's own slots alone and are
    /// returned so the caller can tell their subscribers.
    ///
    /// A slot that was evicted between two pulls no longer carries a ticket,
    /// so an older pull can then be stored; the next pull replaces it.
    #[cfg(test)]
    pub(crate) fn store_pulled_diagnostics(
        &mut self,
        server_id: &ServerId,
        file: &Uri,
        stamp: PullStamp,
        check: VersionCheck,
        items: BoundedDiagnostics,
    ) -> PullWrite {
        self.store_pulled_diagnostics_with(
            server_id,
            file,
            stamp,
            check,
            items,
            SnapshotBefore::Take,
        )
    }

    /// As [`Self::store_pulled_diagnostics`], taking the "before" snapshot of
    /// a replaced slot only when `before` says so: cloning a file's entries
    /// is wasted when no subscriber will compare views.
    pub(crate) fn store_pulled_diagnostics_with(
        &mut self,
        server_id: &ServerId,
        file: &Uri,
        stamp: PullStamp,
        check: VersionCheck,
        items: BoundedDiagnostics,
        before: SnapshotBefore,
    ) -> PullWrite {
        let discard = |reason, items| PullWrite::Discarded {
            reason,
            evicted: Vec::new(),
            items,
        };
        if stamp.epoch
            != self
                .clear_epochs
                .get(server_id)
                .copied()
                .unwrap_or_default()
        {
            return discard(Discard::ServerCleared, items);
        }
        if check == VersionCheck::Moved {
            return discard(Discard::VersionMoved, items);
        }
        let file_key = DiagnosticsKey::of(file);
        let slot_key = SlotKey::pulled(file_key.clone());
        if self.entries.get(&slot_key).is_some_and(|stored| {
            matches!(stored.origin, Origin::Pulled { ticket, .. } if ticket >= stamp.ticket)
        }) {
            return discard(Discard::OlderTicket, items);
        }

        let opening = self.document_opening(file);
        let same_state = self.entries.get(&slot_key).is_some_and(|entry| {
            entry.diagnostics == items.0
                && matches!(
                    entry.origin,
                    Origin::Pulled { opening: stored, version, .. }
                        if stored == opening && version == stamp.version
                )
        });
        let gained = self.coverage_gained(&slot_key);
        let slot = if same_state && gained.is_empty() {
            SlotChange::Identical
        } else {
            SlotChange::Replaced {
                before: (before == SnapshotBefore::Take).then(|| self.diagnostic_sources(file)),
            }
        };

        drop(self.take_entry_with_coverage(&slot_key, gained));
        let evicted = match self.make_room(server_id, Protect::File(&file_key)) {
            Ok(evicted) => evicted,
            Err(NoRoom { evicted }) => {
                return PullWrite::Discarded {
                    reason: Discard::NoRoom,
                    evicted,
                    items,
                };
            }
        };

        if !items.0.is_empty() {
            self.learn_pull_sources(server_id, &items.0);
        }
        let seq = self.next_seq();
        self.insert_entry(
            slot_key,
            CachedEntry {
                uri: file.clone(),
                diagnostics: items.0,
                owner: server_id.clone(),
                seq,
                origin: Origin::Pulled {
                    ticket: stamp.ticket,
                    opening,
                    version: stamp.version,
                },
            },
        );
        PullWrite::Stored { slot, evicted }
    }

    /// Stores `diagnostics` as `file`'s pulled slot at document version 1, as
    /// an answered, current pull would.
    #[cfg(test)]
    pub(crate) fn store_pulled_for_test(
        &mut self,
        server_id: &ServerId,
        file: &Uri,
        diagnostics: Vec<LspDiagnostic>,
    ) {
        let stamp = self.begin_pull(server_id, DocumentVersion::FIRST);
        drop(self.store_pulled_diagnostics(
            server_id,
            file,
            stamp,
            VersionCheck::Current,
            BoundedDiagnostics::new(file, diagnostics),
        ));
    }

    /// Stores `uri`'s diagnostics as the canonical spelling of its own file.
    #[cfg(test)]
    pub(crate) fn store_diagnostics(
        &mut self,
        server_id: &ServerId,
        uri: &Uri,
        version: Option<i32>,
        diagnostics: Vec<LspDiagnostic>,
    ) {
        let published = PublishedDiagnosticsUri::for_test(uri.clone(), uri.clone());
        self.store_published_diagnostics(server_id, &published, version, diagnostics);
    }

    /// Adds `entry` under `key`, which must not be cached yet, to every
    /// index. Together with [`Self::take_entry`] the only code that touches
    /// `order`, `files` and `empty_diagnostics_count`.
    fn insert_entry(&mut self, key: SlotKey, entry: CachedEntry) {
        debug_assert!(!self.entries.contains_key(&key));
        debug_assert_eq!(key.provenance, entry.origin.provenance());
        self.eviction_marks.forget_file(entry.file(&key));
        self.order
            .entry(entry.owner.clone())
            .or_default()
            .insert(entry.seq, key.clone());
        self.files
            .entry(entry.file(&key).clone())
            .or_default()
            .insert(key.clone());
        if entry.diagnostics.is_empty() {
            self.empty_diagnostics_count = self.empty_diagnostics_count.saturating_add(1);
        }
        self.entries.insert(key, entry);
    }

    /// Removes the entry cached under `key` from every index and returns it.
    ///
    /// The one place a pulled slot leaves the cache (replacement, a superseding
    /// push, eviction, a server clear): before it goes, the pushed entries it
    /// answered for are marked as covered, so no exit path can lose the
    /// evidence that a later read needs to drop what the pull already fixed.
    fn take_entry(&mut self, key: &SlotKey) -> Option<CachedEntry> {
        let gained = if key.provenance == Provenance::Pulled {
            self.coverage_gained(key)
        } else {
            Vec::new()
        };
        self.take_entry_with_coverage(key, gained)
    }

    /// [`Self::take_entry`] with the coverage `key`'s slot gains already
    /// computed, for a caller that needed it before removing the entry.
    fn take_entry_with_coverage(
        &mut self,
        key: &SlotKey,
        gained: Vec<(SlotKey, BTreeSet<usize>)>,
    ) -> Option<CachedEntry> {
        for (pushed, gained) in gained {
            if let Some(CachedEntry {
                origin: Origin::Pushed { covered, .. },
                ..
            }) = self.entries.get_mut(&pushed)
            {
                covered.0.extend(gained);
            }
        }
        let entry = self.entries.remove(key)?;
        if let Some(order) = self.order.get_mut(&entry.owner) {
            order.remove(&entry.seq);
        }
        let file = entry.file(key);
        if let Some(members) = self.files.get_mut(file) {
            members.remove(key);
            if members.is_empty() {
                self.files.remove(file);
            }
        }
        if entry.diagnostics.is_empty() {
            self.empty_diagnostics_count = self.empty_diagnostics_count.saturating_sub(1);
        }
        Some(entry)
    }

    /// What the pulled slot `slot` would add to the coverage of the pushed
    /// entries of its file: for each same-server pushed entry at the slot's
    /// document version (and opening), the indices of items that are the same
    /// problem as one the pull reported.
    fn coverage_gained(&self, slot: &SlotKey) -> Vec<(SlotKey, BTreeSet<usize>)> {
        let Some(pulled) = self.entries.get(slot) else {
            return Vec::new();
        };
        let Origin::Pulled {
            opening, version, ..
        } = &pulled.origin
        else {
            return Vec::new();
        };
        let Some(members) = self.files.get(&slot.uri) else {
            return Vec::new();
        };
        let index = PulledIndex::new(&pulled.diagnostics);
        members
            .iter()
            .filter(|key| key.provenance == Provenance::Pushed)
            .filter_map(|key| {
                let entry = self.entries.get(key)?;
                let Origin::Pushed {
                    opening: pushed_opening,
                    covered,
                    ..
                } = &entry.origin
                else {
                    return None;
                };
                let same_state = entry.owner == pulled.owner
                    && entry.origin.version() == Some(*version)
                    && pushed_opening.is_none_or(|pushed| Some(pushed) == *opening);
                if !same_state {
                    return None;
                }
                let gained: BTreeSet<usize> = entry
                    .diagnostics
                    .iter()
                    .enumerate()
                    .filter(|(position, diagnostic)| {
                        !covered.0.contains(position) && index.contains_same_problem(diagnostic)
                    })
                    .map(|(position, _)| position)
                    .collect();
                (!gained.is_empty()).then(|| (key.clone(), gained))
            })
            .collect()
    }

    /// Remembers the `source` values of a non-empty full pull report of
    /// `owner`, up to `MAX_LEARNED_PULL_SOURCES`.
    fn learn_pull_sources(&mut self, owner: &ServerId, items: &[LspDiagnostic]) {
        let learned = self.pull_sources.entry(owner.clone()).or_default();
        for source in items.iter().filter_map(DiagnosticSource::of) {
            if learned.len() >= MAX_LEARNED_PULL_SOURCES {
                break;
            }
            if !learned.contains(&source) {
                learned.push(source);
            }
        }
    }

    /// Whether the pushed `entry` of the file `key` (read as `requested`) is
    /// older than the state the tracker last synced for its server, and which
    /// of its items the server's pull at that state does not repeat.
    ///
    /// An item is covered when a pull of the entry's own state reported the
    /// same problem (recorded when that pull's slot left the cache), or when
    /// its `source` is one the server's pull reports carry -- which is how
    /// a push-only flycheck item (`rustc`, `clippy`) stays visible: no pull
    /// ever reports that source. Nothing is excluded without a pulled slot of
    /// the same server at the synced state, and an entry of another opening
    /// is never covered by a learned source.
    fn push_freshness(
        &self,
        key: &DiagnosticsKey,
        requested: &Uri,
        entry: &CachedEntry,
    ) -> Freshness {
        let Origin::Pushed {
            opening, covered, ..
        } = &entry.origin
        else {
            return Freshness::Current;
        };
        let Some(version) = entry.origin.version() else {
            return Freshness::Current;
        };
        let DocumentSync::Synced(synced) = self.document_sync(&entry.owner, requested) else {
            return Freshness::Current;
        };
        let current_opening = self.document_opening(requested);
        let same_opening = opening.is_none_or(|opening| Some(opening) == current_opening);
        if same_opening && version == synced {
            return Freshness::Current;
        }
        let answered_at_synced_state =
            self.entries
                .get(&SlotKey::pulled(key.clone()))
                .is_some_and(|pulled| {
                    pulled.owner == entry.owner
                        && matches!(
                            pulled.origin,
                            Origin::Pulled { opening: pulled_opening, version: pulled_version, .. }
                                if pulled_version == synced && pulled_opening == current_opening
                        )
                });
        if !answered_at_synced_state {
            return Freshness::Current;
        }
        let mut covered = covered.clone();
        if same_opening && let Some(learned) = self.pull_sources.get(&entry.owner) {
            covered.0.extend(
                entry
                    .diagnostics
                    .iter()
                    .enumerate()
                    .filter(|(_, diagnostic)| {
                        DiagnosticSource::of(diagnostic)
                            .is_some_and(|source| learned.contains(&source))
                    })
                    .map(|(position, _)| position),
            );
        }
        Freshness::Superseded { covered }
    }

    /// Evicts entries until one more fits under `MAX_DIAGNOSTIC_ENTRIES`, on
    /// behalf of a write by `writer`, and returns the files whose slots were
    /// evicted.
    ///
    /// Ends `writer`'s eviction overflow first, since an accepted write does;
    /// the overflow is restored when no room can be made, so a refused write
    /// leaves it as it was. Slots of the file `protect` names are never evicted.
    fn make_room(
        &mut self,
        writer: &ServerId,
        protect: Protect<'_>,
    ) -> Result<Vec<DiagnosticsKey>, NoRoom> {
        let was_overflowed = self.eviction_marks.clear_overflow(writer);
        let mut evicted = Vec::new();
        while self.entries.len() >= MAX_DIAGNOSTIC_ENTRIES {
            let Some((_, _, victim)) = self.entry_to_evict(writer, protect) else {
                if was_overflowed {
                    self.eviction_marks.restore_overflow(writer);
                }
                return Err(NoRoom { evicted });
            };
            evicted.extend(self.evict_for_capacity(&victim));
        }
        Ok(evicted)
    }

    /// Removes the entry under `key` for good (eviction, alias replacement,
    /// server clear) and remembers an empty one in the replay ring, so a
    /// clear lost in a listen's lease gap is still replayed.
    fn evict_entry(&mut self, key: &SlotKey) {
        let Some(entry) = self.take_entry(key) else {
            return;
        };
        if entry.diagnostics.is_empty() {
            self.record_empty_eviction(entry.file(key).clone(), std::time::Instant::now());
        }
    }

    /// Evicts the entry under `key` to make room and returns its file, after
    /// remembering what was lost for [`Self::availability`].
    ///
    /// A clean entry is remembered only when it was the file's last one: while
    /// other slots of the file remain, they answer reads.
    fn evict_for_capacity(&mut self, key: &SlotKey) -> Option<DiagnosticsKey> {
        let entry = self.entries.get(key)?;
        let file = entry.file(key).clone();
        let owner = entry.owner.clone();
        let content = if entry.diagnostics.is_empty() {
            EvictedContent::Clean
        } else {
            EvictedContent::Lost
        };
        self.evict_entry(key);
        if content == EvictedContent::Lost || !self.files.contains_key(&file) {
            self.eviction_marks.record(file.clone(), owner, content);
        }
        Some(file)
    }

    fn record_empty_eviction(&mut self, file: DiagnosticsKey, now: std::time::Instant) {
        self.recent_evictions.record(file, now);
    }

    /// Whether `uri` had an empty entry removed within the replay window and
    /// has not been cached again since.
    fn was_recently_evicted(&self, uri: &Uri, now: std::time::Instant) -> bool {
        let key = DiagnosticsKey::of(uri);
        !self.has_diagnostics(uri) && self.recent_evictions.contains(&key, now)
    }

    /// Whether a `subscriptions/listen` attaching now must be told about
    /// `uri`: it has cached diagnostics, or a clear for it was removed
    /// recently enough that a client re-attaching after a lease gap may have
    /// missed it.
    pub(crate) fn is_listen_replayable(&self, uri: &Uri) -> bool {
        self.has_diagnostics(uri) || self.was_recently_evicted(uri, std::time::Instant::now())
    }

    /// Panics unless `order`, `files` and `empty_diagnostics_count` describe
    /// exactly the cached entries.
    #[cfg(test)]
    fn assert_consistent(&self) {
        let mut ordered = 0;
        for (server, order) in &self.order {
            for (seq, key) in order {
                let entry = self
                    .entries
                    .get(key)
                    .unwrap_or_else(|| panic!("ordered key has no entry"));
                assert_eq!((&entry.owner, entry.seq), (server, *seq));
                ordered += 1;
            }
        }
        assert_eq!(ordered, self.entries.len(), "order and entries diverge");

        let mut filed = 0;
        for (file, members) in &self.files {
            assert!(!members.is_empty(), "empty file set kept");
            for key in members {
                let entry = self
                    .entries
                    .get(key)
                    .unwrap_or_else(|| panic!("filed key has no entry"));
                assert_eq!(entry.file(key), file);
                filed += 1;
            }
        }
        assert_eq!(filed, self.entries.len(), "files and entries diverge");

        let empty = self
            .entries
            .values()
            .filter(|entry| entry.diagnostics.is_empty())
            .count();
        assert_eq!(empty, self.empty_diagnostics_count);

        let marks = &self.eviction_marks;
        assert_eq!(marks.by_file.len(), marks.order.len(), "marks diverge");
        for (seq, file) in &marks.order {
            assert_eq!(marks.by_file.get(file).map(|mark| mark.seq), Some(*seq));
        }
    }

    /// The least recently written non-canonical source indexed under
    /// `canonical_key`.
    fn oldest_alias_source(&self, canonical_key: &DiagnosticsKey) -> Option<SlotKey> {
        self.files
            .get(canonical_key)?
            .iter()
            .filter_map(|source| {
                let entry = self.entries.get(source)?;
                matches!(
                    entry.origin,
                    Origin::Pushed {
                        spelling: Spelling::Alias(_),
                        ..
                    }
                )
                .then_some((entry.seq, source))
            })
            .min_by_key(|(seq, _)| *seq)
            .map(|(_, source)| source.clone())
    }

    /// Keys of every entry cached for the file `key` names: its indexed
    /// slots plus a pushed entry stored directly under `key` itself.
    fn source_keys(&self, key: &DiagnosticsKey) -> BTreeSet<SlotKey> {
        let mut keys: BTreeSet<SlotKey> =
            self.files.get(key).into_iter().flatten().cloned().collect();
        let direct = SlotKey::pushed(key.clone());
        if self.entries.contains_key(&direct) {
            keys.insert(direct);
        }
        keys
    }

    /// Store a log entry.
    ///
    /// Maintains a maximum of `MAX_LOG_ENTRIES` entries, removing oldest when full.
    /// `message` is truncated to `MAX_ENTRY_TEXT_BYTES` before storing.
    pub(crate) fn store_log(&mut self, level: LogLevel, message: String) {
        let entry = LogEntry {
            level,
            message: truncate_string(message, MAX_ENTRY_TEXT_BYTES),
            timestamp: Utc::now(),
        };

        if self.logs.len() >= MAX_LOG_ENTRIES {
            self.logs.pop_front();
        }
        self.logs.push_back(entry);
    }

    /// Store a server message.
    ///
    /// Maintains a maximum of `MAX_SERVER_MESSAGES` entries, removing oldest when full.
    /// `message` is truncated to `MAX_ENTRY_TEXT_BYTES` before storing.
    pub(crate) fn store_message(&mut self, message_type: MessageType, message: String) {
        let msg = ServerMessage {
            message_type,
            message: truncate_string(message, MAX_ENTRY_TEXT_BYTES),
            timestamp: Utc::now(),
        };

        if self.messages.len() >= MAX_SERVER_MESSAGES {
            self.messages.pop_front();
        }
        self.messages.push_back(msg);
    }

    /// Record a workspace-readiness signal from an unrecognized/custom LSP
    /// notification (`LspNotification::Other`), updating `server_id`'s
    /// tracked [`IndexingState`] if the notification is one this cache
    /// understands.
    ///
    /// Currently recognizes rust-analyzer's `experimental/serverStatus`
    /// notification: a `quiescent` boolean of `false` marks the
    /// server [`IndexingState::Loading`], `true` marks it
    /// [`IndexingState::Ready`]. Any other method, or a `serverStatus`
    /// payload missing/malformed the field, leaves the current state
    /// untouched rather than erroring -- an unrecognized signal is
    /// equivalent to no signal.
    ///
    /// Once a server reaches [`IndexingState::Ready`] it never regresses on
    /// its own: this only tracks the *initial* workspace load, not later
    /// re-indexing triggered by large-scale file changes. See
    /// [`Self::reset_indexing_state`] for the one case that does move a
    /// server back out of `Ready`/`Loading`.
    pub(crate) fn observe_indexing_signal(
        &mut self,
        server_id: &ServerId,
        method: &str,
        params: Option<&serde_json::Value>,
    ) {
        self.indexing
            .observe_server_status(server_id, method, params);
    }

    /// Record a `$/progress` notification toward `server_id`'s tracked
    /// [`IndexingState`] -- the generic LSP counterpart to
    /// `Self::observe_indexing_signal`'s rust-analyzer-specific
    /// `experimental/serverStatus`. See
    /// [`crate::bridge::indexing::IndexingTracker::observe_progress`] for
    /// the full begin/end/settle/latch transition rules.
    pub(crate) fn observe_progress(
        &mut self,
        server_id: &ServerId,
        params: &lsp_types::ProgressParams,
    ) {
        self.indexing.observe_progress(server_id, params);
    }

    /// Configure `server_id`'s [`IndexingPolicy`] -- see
    /// [`crate::bridge::indexing::IndexingTracker::set_policy`].
    pub(crate) fn set_indexing_policy(&mut self, server_id: ServerId, policy: IndexingPolicy) {
        self.indexing.set_policy(server_id, policy);
    }

    /// Current tracked workspace-indexing readiness for `server_id`.
    ///
    /// Returns [`IndexingState::Unknown`] for a server no readiness signal
    /// has ever been observed for -- see `Self::observe_indexing_signal`.
    ///
    /// A `Loading` entry older than `INDEXING_STALENESS_BOUND` is read
    /// back as `Unknown` rather than `Loading`: this is the self-heal for a
    /// `quiescent: true` notification dropped by a full channel, or a
    /// server that stalled mid-index, applied at *read* time based on the
    /// signal's own age so it can never be triggered by (and can never
    /// affect) any individual caller's own wait -- see
    /// `Translator::wait_for_indexing_ready`.
    #[must_use]
    pub fn indexing_state(&self, server_id: &ServerId) -> IndexingState {
        self.indexing.state(server_id)
    }

    /// Reset `server_id`'s tracked [`IndexingState`] as `reset` says;
    /// [`IndexingReset::Forget`] reverts it to [`IndexingState::Unknown`],
    /// [`IndexingReset::AwaitReplacement`] to [`IndexingState::Loading`] until
    /// the replacement's first signal when the server has reported one before.
    ///
    /// `Translator::respawn_if_dead` calls this after replacing a crashed
    /// server's process, since the new process starts indexing from
    /// scratch and has sent no signal of its own yet -- a stale
    /// `Ready`/`Loading` carried over from the crashed connection must not
    /// leak into requests routed to its replacement. This is the only
    /// production caller: a timed-out [`Self::indexing_state`] read does
    /// *not* call this, so one caller's wait can never affect another's.
    pub(crate) fn reset_indexing_state(&mut self, server_id: &ServerId, reset: IndexingReset) {
        self.indexing.reset(server_id, reset);
    }

    /// Get diagnostics for a document URI.
    ///
    /// If the stored list was ever truncated by `store_published_diagnostics`'s
    /// `MAX_DIAGNOSTICS_ENTRY_BYTES` cap (#311), the diagnostics here are in
    /// severity order (`ERROR` first), not the original publish/file-position
    /// order -- callers that assume file-position order should not rely on
    /// it after a cap-triggered truncation.
    ///
    /// Looks up the pushed entry stored under exactly `uri`. A file reachable
    /// through symlinks may have its diagnostics spread over several
    /// published URIs, and a pull may have stored its own list next to them;
    /// use [`Self::diagnostic_sources`] to read the union.
    #[inline]
    #[must_use]
    pub fn diagnostics(&self, uri: &Uri) -> Option<DiagnosticInfo> {
        self.entries
            .get(&SlotKey::pushed(DiagnosticsKey::of(uri)))
            .map(CachedEntry::info)
    }

    /// Snapshot of every entry cached for the file `uri` names, to be
    /// [merged](DiagnosticSources::merge) after the cache lock is released.
    ///
    /// Clones the entries (at most 8 pushed and 1 pulled, each bounded to
    /// 1 MiB) so the merge can run without the lock.
    ///
    /// # Examples
    ///
    /// ```
    /// use lsp_types::Uri;
    /// use mcpls_core::bridge::NotificationCache;
    ///
    /// let cache = NotificationCache::new();
    /// let uri = Uri::from("file:///workspace/main.rs".to_owned());
    /// let snapshot = cache.diagnostic_sources(&uri);
    /// // Merge once the cache lock has been released.
    /// assert!(snapshot.merge().is_none());
    /// ```
    #[must_use]
    pub fn diagnostic_sources(&self, uri: &Uri) -> DiagnosticSources {
        let key = DiagnosticsKey::of(uri);
        let entries = self
            .source_keys(&key)
            .into_iter()
            .filter_map(|source| {
                let entry = self.entries.get(&source)?;
                Some(SourceEntry {
                    info: entry.info(),
                    origin: SourceOrigin::from(&entry.origin),
                    freshness: self.push_freshness(&key, uri, entry),
                })
            })
            .collect();
        DiagnosticSources {
            requested: uri.clone(),
            entries,
        }
    }

    /// Whether any diagnostics entry (possibly empty) is cached for the file
    /// `uri` names, under any of its published URIs.
    ///
    /// # Examples
    ///
    /// ```
    /// use lsp_types::Uri;
    /// use mcpls_core::bridge::NotificationCache;
    ///
    /// let cache = NotificationCache::new();
    /// let uri = Uri::from("file:///workspace/main.rs".to_owned());
    /// assert!(!cache.has_diagnostics(&uri));
    /// ```
    #[must_use]
    pub fn has_diagnostics(&self, uri: &Uri) -> bool {
        let key = DiagnosticsKey::of(uri);
        self.entries.contains_key(&SlotKey::pushed(key.clone())) || self.files.contains_key(&key)
    }

    /// Whether the cache has an answer for the file `uri` names, read for the
    /// diagnostics server `route`.
    ///
    /// An entry, or the memory that capacity eviction removed only clean
    /// entries of the file, is [`DiagnosticsAvailability::Published`]. Lost
    /// diagnostics, or no trace of the file although eviction forgot some of
    /// `route`'s files, is [`DiagnosticsAvailability::Evicted`]. Anything else
    /// is [`DiagnosticsAvailability::Pending`]: nothing was published since
    /// the server started.
    ///
    /// # Examples
    ///
    /// ```
    /// use lsp_types::Uri;
    /// use mcpls_core::bridge::{DiagnosticsAvailability, NotificationCache};
    ///
    /// let cache = NotificationCache::new();
    /// let uri = Uri::from("file:///workspace/main.rs".to_owned());
    /// assert_eq!(cache.availability(&uri, None), DiagnosticsAvailability::Pending);
    /// ```
    #[must_use]
    pub fn availability(&self, uri: &Uri, route: Option<&ServerId>) -> DiagnosticsAvailability {
        if self.has_diagnostics(uri) {
            return DiagnosticsAvailability::Published;
        }
        match self.eviction_marks.content(&DiagnosticsKey::of(uri)) {
            Some(EvictedContent::Clean) => DiagnosticsAvailability::Published,
            Some(EvictedContent::Lost) => DiagnosticsAvailability::Evicted,
            None if route.is_some_and(|server| self.eviction_marks.has_overflowed(server)) => {
                DiagnosticsAvailability::Evicted
            }
            None => DiagnosticsAvailability::Pending,
        }
    }

    /// Server that published the currently cached diagnostics for `uri`, if
    /// any. Used to look up that server's negotiated position encoding for a
    /// cache-only read that has no live LSP round trip of its own to resolve
    /// one from.
    #[inline]
    #[must_use]
    pub fn diagnostics_owner(&self, uri: &Uri) -> Option<&ServerId> {
        let key = DiagnosticsKey::of(uri);
        self.entries
            .get(&SlotKey::pushed(key.clone()))
            .or_else(|| {
                let slots = self.files.get(&key)?;
                slots
                    .iter()
                    .filter(|slot| slot.provenance == Provenance::Pushed)
                    .chain(slots.iter())
                    .find_map(|source| self.entries.get(source))
            })
            .map(|entry| &entry.owner)
    }

    /// All stored log entries.
    #[inline]
    #[must_use]
    pub const fn logs(&self) -> &VecDeque<LogEntry> {
        &self.logs
    }

    /// All stored server messages.
    #[inline]
    #[must_use]
    pub const fn messages(&self) -> &VecDeque<ServerMessage> {
        &self.messages
    }

    /// Clear all diagnostics owned by a single server.
    ///
    /// Used when a server crashes and respawns: its own stale entries must
    /// be invalidated without disturbing any other server's cache entries
    /// (#266). Returns the keys of the cleared files so a caller can tell
    /// subscribers which resources changed (see [`diagnostics_cache_key`]).
    ///
    /// Also invalidates every pull of this server issued before the call, so
    /// a report answered by the replaced process is not stored afterwards.
    pub(crate) fn clear_server_diagnostics(&mut self, server_id: &ServerId) -> Vec<DiagnosticsKey> {
        let epoch = self.clear_epochs.entry(server_id.clone()).or_default();
        epoch.0 = epoch.0.saturating_add(1);
        self.eviction_marks.forget_server(server_id);
        self.pull_sources.remove(server_id);
        let Some(order) = self.order.remove(server_id) else {
            return Vec::new();
        };
        let mut cleared = Vec::with_capacity(order.len());
        for key in order.into_values() {
            if let Some(entry) = self.entries.get(&key) {
                cleared.push(entry.file(&key).clone());
            }
            self.evict_entry(&key);
        }
        cleared.sort_unstable();
        cleared.dedup();
        cleared
    }

    /// Records that publishes of `owner` for `files` never reached the cache
    /// (the delivery mailbox could not hold them), so those files read as lost
    /// diagnostics instead of `pending`, until the owner's next publish for
    /// them. The owner's older entries of such a file are removed: a newer
    /// publish exists that the cache cannot show, and older content must not
    /// pass for it.
    ///
    /// Returns the files whose view changed, for the caller to announce.
    pub(crate) fn record_lost_files(
        &mut self,
        owner: &ServerId,
        files: &[DiagnosticsKey],
    ) -> Vec<DiagnosticsKey> {
        for file in files {
            let stale: Vec<SlotKey> = self
                .files
                .get(file)
                .into_iter()
                .flatten()
                .filter(|key| {
                    key.provenance == Provenance::Pushed
                        && self
                            .entries
                            .get(key)
                            .is_some_and(|entry| entry.owner == *owner)
                })
                .cloned()
                .collect();
            for key in stale {
                self.evict_entry(&key);
            }
            if !self.has_diagnostics_for(file) {
                self.eviction_marks
                    .record(file.clone(), owner.clone(), EvictedContent::Lost);
            }
        }
        files.to_vec()
    }

    /// Records that `owner` lost more publishes than the mailbox could name,
    /// as capacity eviction does.
    pub(crate) fn record_unnamed_loss(&mut self, owner: &ServerId) {
        self.eviction_marks.restore_overflow(owner);
    }

    /// Whether any entry is cached for the file `key` names.
    fn has_diagnostics_for(&self, key: &DiagnosticsKey) -> bool {
        self.files.contains_key(key) || self.entries.contains_key(&SlotKey::pushed(key.clone()))
    }

    /// Marks `server_id`'s push-based diagnostics as no longer live -- see
    /// the `push_degraded` field doc for why this is permanent for the life
    /// of the cache.
    pub(crate) fn mark_push_degraded(&mut self, server_id: &ServerId) {
        self.push_degraded.insert(server_id.clone());
    }

    /// Marks `server_id`'s push-based diagnostics as live again, after its
    /// notification pump was re-wired by a manual restart.
    pub(crate) fn clear_push_degraded(&mut self, server_id: &ServerId) {
        self.push_degraded.remove(server_id);
    }

    /// Whether `server_id`'s push-based diagnostics are known to be
    /// degraded (see [`Self::mark_push_degraded`]) -- callers such as
    /// `get_cached_diagnostics` and `read_resource` use this to flag a
    /// cache-only result as potentially incomplete rather than presenting it as
    /// current.
    #[inline]
    #[must_use]
    pub(crate) fn is_push_degraded(&self, server_id: &ServerId) -> bool {
        self.push_degraded.contains(server_id)
    }

    /// Get the number of documents with stored diagnostics.
    #[inline]
    #[must_use]
    #[cfg(test)]
    pub(crate) fn diagnostics_count(&self) -> usize {
        self.entries.len()
    }

    /// Get the number of stored log entries.
    #[inline]
    #[must_use]
    #[cfg(test)]
    pub(crate) fn logs_count(&self) -> usize {
        self.logs.len()
    }

    /// Get the number of stored server messages.
    #[inline]
    #[must_use]
    #[cfg(test)]
    pub(crate) fn messages_count(&self) -> usize {
        self.messages.len()
    }
}

/// Applies one lifecycle-lane notification to `cache`.
///
/// Only `$/progress` and the generic `Other` variant (which carries e.g.
/// rust-analyzer's `experimental/serverStatus`) ever travel on that lane,
/// since the notification lane handles diagnostics/log/showMessage instead
/// (see `LspClient::message_loop_inner`'s routing).
///
/// Shared by `diagnostics_pump`'s lifecycle-lane arm (wiring a freshly
/// spawned server's own pump) and `Translator::respawn_if_dead`'s
/// lifecycle-lane forwarding task (wiring a respawned server's replacement
/// process), so the two can't silently drift apart on which notification
/// variants feed which `NotificationCache` method.
///
/// Public because [`LspServer::take_lifecycle_rx`](crate::lsp::LspServer::take_lifecycle_rx)
/// is: whoever drains that receiver needs this as the sink that feeds the
/// indexing state.
///
/// # Examples
///
/// ```
/// use mcpls_core::bridge::{IndexingState, NotificationCache, apply_lifecycle_notification};
/// use mcpls_core::config::ServerId;
/// use mcpls_core::lsp::LspNotification;
///
/// let mut cache = NotificationCache::new();
/// let server_id = ServerId::from_static("rust");
/// apply_lifecycle_notification(
///     &mut cache,
///     &server_id,
///     LspNotification::Other {
///         method: "experimental/serverStatus".into(),
///         params: Some(serde_json::json!({"quiescent": true})),
///     },
/// );
/// assert_eq!(cache.indexing_state(&server_id), IndexingState::Ready);
/// ```
pub fn apply_lifecycle_notification(
    cache: &mut NotificationCache,
    server_id: &ServerId,
    notif: crate::lsp::LspNotification,
) {
    match notif {
        crate::lsp::LspNotification::Progress(params) => {
            cache.observe_progress(server_id, &params);
        }
        crate::lsp::LspNotification::Other { method, params } => {
            cache.observe_indexing_signal(server_id, &method, params.as_ref());
        }
        crate::lsp::LspNotification::PublishDiagnostics(_)
        | crate::lsp::LspNotification::LogMessage(_)
        | crate::lsp::LspNotification::ShowMessage(_) => {}
    }
}

/// Handles one lifecycle-lane notification of `server_id`: warns when a pinned
/// `tsserver` was ignored, then applies it to `cache` when there is one.
///
/// Every consumer of the lifecycle lane goes through here, so no consumer can
/// skip a step (#658).
pub async fn on_lifecycle(
    cache: Option<&tokio::sync::Mutex<NotificationCache>>,
    server_id: &ServerId,
    pinned_tsserver: Option<&std::path::Path>,
    notif: crate::lsp::LspNotification,
) {
    crate::lsp::tsserver_pin::warn_if_pin_ignored(pinned_tsserver, &notif, server_id);
    if let Some(cache) = cache {
        apply_lifecycle_notification(&mut *cache.lock().await, server_id, notif);
    }
}

#[cfg(test)]
mod pull_tests;

#[cfg(test)]
mod tests {
    use lsp_types::{Position, Range};

    use super::bounds::*;
    use super::*;
    use crate::bridge::indexing::IndexingReset;
    use crate::test_lsp::CapturedLogs;

    /// Every test in this module that doesn't exercise multi-server
    /// fairness routes through one implicit server, so `set_diagnostics_route_count`
    /// is left at its default of `1` (full `MAX_DIAGNOSTIC_ENTRIES` budget).
    fn test_server() -> ServerId {
        ServerId::from_static("test-server")
    }

    #[test]
    fn test_notification_cache_new() {
        let cache = NotificationCache::new();
        assert_eq!(cache.diagnostics_count(), 0);
        assert_eq!(cache.logs_count(), 0);
        assert_eq!(cache.messages_count(), 0);
    }

    #[test]
    fn test_store_and_diagnostics() {
        let mut cache = NotificationCache::new();
        let uri: Uri = Uri::from("file:///test.rs");

        let diagnostic = LspDiagnostic {
            range: Range {
                start: Position {
                    line: 0,
                    character: 0,
                },
                end: Position {
                    line: 0,
                    character: 5,
                },
            },
            severity: Some(lsp_types::DiagnosticSeverity::Error),
            message: "test error".to_string().into(),
            code: None,
            source: None,
            code_description: None,
            related_information: None,
            tags: None,
            data: None,
        };

        cache.store_diagnostics(&test_server(), &uri, Some(1), vec![diagnostic]);

        let stored = cache.diagnostics(&uri).unwrap();
        assert_eq!(stored.uri, uri);
        assert_eq!(stored.version.map(DocumentVersion::get), Some(1));
        assert_eq!(stored.diagnostics.len(), 1);
        assert_eq!(
            stored.diagnostics[0].message,
            lsp_types::Message::String("test error".to_string())
        );
    }

    /// #311: a single diagnostic's `message` must be bounded independently
    /// of `MAX_DIAGNOSTIC_ENTRIES`, which only caps the number of entries.
    #[test]
    fn test_store_diagnostics_truncates_oversized_message() {
        let mut cache = NotificationCache::new();
        let uri: Uri = Uri::from("file:///test.rs");
        let oversized = "a".repeat(MAX_ENTRY_TEXT_BYTES + 100);

        let diagnostic = LspDiagnostic {
            range: Range {
                start: Position {
                    line: 0,
                    character: 0,
                },
                end: Position {
                    line: 0,
                    character: 5,
                },
            },
            severity: Some(lsp_types::DiagnosticSeverity::Error),
            message: oversized.clone().into(),
            code: None,
            source: None,
            code_description: None,
            related_information: None,
            tags: None,
            data: None,
        };

        cache.store_diagnostics(&test_server(), &uri, Some(1), vec![diagnostic]);

        let stored = cache.diagnostics(&uri).unwrap();
        let stored = message_as_str(&stored.diagnostics[0].message);
        assert!(stored.len() < oversized.len());
        assert!(stored.ends_with("... (truncated)"));
    }

    /// Minimal diagnostic with an arbitrary `message`, for tests that only
    /// care about size/count bounds rather than range/severity details.
    fn minimal_diagnostic(message: String) -> LspDiagnostic {
        LspDiagnostic {
            range: Range {
                start: Position {
                    line: 0,
                    character: 0,
                },
                end: Position {
                    line: 0,
                    character: 5,
                },
            },
            severity: Some(lsp_types::DiagnosticSeverity::Error),
            message: message.into(),
            code: None,
            source: None,
            code_description: None,
            related_information: None,
            tags: None,
            data: None,
        }
    }

    /// #693: one severity order serves the report and the size cap, and a
    /// diagnostic without a severity counts as information in both.
    #[test]
    fn test_reported_severity_orders_most_severe_first_and_defaults_to_information() {
        let mut severityless = minimal_diagnostic("none".to_string());
        severityless.severity = None;
        let mut hint = minimal_diagnostic("hint".to_string());
        hint.severity = Some(lsp_types::DiagnosticSeverity::Hint);

        assert_eq!(
            ReportedSeverity::of(&severityless),
            ReportedSeverity::Information
        );
        assert!(ReportedSeverity::of(&severityless) < ReportedSeverity::of(&hint));
        assert!(ReportedSeverity::Error < ReportedSeverity::Warning);
        assert!(ReportedSeverity::Warning < ReportedSeverity::Information);
    }

    /// #311 C1: `MAX_ENTRY_TEXT_BYTES` alone bounds one `message` field, not
    /// the whole entry -- many diagnostics, each individually small, must
    /// still be capped in aggregate.
    #[test]
    fn test_store_diagnostics_caps_aggregate_size_for_many_small_diagnostics() {
        let mut cache = NotificationCache::new();
        let uri: Uri = Uri::from("file:///test.rs");

        // Each diagnostic is far under MAX_ENTRY_TEXT_BYTES individually,
        // but 5000 of them comfortably exceeds MAX_DIAGNOSTICS_ENTRY_BYTES
        // in aggregate.
        let diagnostics: Vec<LspDiagnostic> = (0..5000)
            .map(|i| {
                minimal_diagnostic(format!(
                    "diagnostic number {i}, padded: {}",
                    "x".repeat(200)
                ))
            })
            .collect();
        let original_count = diagnostics.len();

        cache.store_diagnostics(&test_server(), &uri, Some(1), diagnostics);

        let stored = &cache.diagnostics(&uri).unwrap().diagnostics;
        assert!(
            stored.len() < original_count,
            "aggregate cap must trim the list, kept {} of {original_count}",
            stored.len()
        );
        assert!(!stored.is_empty(), "must keep at least one diagnostic");
        let serialized_len = serde_json::to_vec(stored).unwrap().len();
        assert!(
            serialized_len <= MAX_DIAGNOSTICS_ENTRY_BYTES,
            "stored entry must fit the aggregate cap, got {serialized_len} bytes"
        );
    }

    /// #311 S6: a naive flat halve would keep only the first N/2
    /// diagnostics even when far more than that would actually fit --
    /// truncation must find the largest prefix that fits instead.
    #[test]
    fn test_store_diagnostics_truncation_keeps_largest_fitting_prefix() {
        let mut cache = NotificationCache::new();
        let uri: Uri = Uri::from("file:///test.rs");

        // Each diagnostic serializes to roughly 300 bytes; ~3800 of them
        // fit under the 1 MiB cap, well over half of the 5000 published --
        // a flat halve would incorrectly stop at 2500.
        let diagnostics: Vec<LspDiagnostic> = (0..5000)
            .map(|i| minimal_diagnostic(format!("diagnostic {i}: {}", "x".repeat(250))))
            .collect();

        cache.store_diagnostics(&test_server(), &uri, Some(1), diagnostics);

        let stored = &cache.diagnostics(&uri).unwrap().diagnostics;
        assert!(
            stored.len() > 2600,
            "largest-fitting-prefix search must keep far more than half, kept {}",
            stored.len()
        );
        let serialized_len = serde_json::to_vec(stored).unwrap().len();
        assert!(serialized_len <= MAX_DIAGNOSTICS_ENTRY_BYTES);
        // The search must find the *largest* fitting prefix, not just *a*
        // fitting one: one more diagnostic than what was kept must no
        // longer fit (otherwise it should have been kept too).
        let mut with_one_more = stored.clone();
        with_one_more.push(minimal_diagnostic(format!(
            "diagnostic overflow: {}",
            "x".repeat(250)
        )));
        assert!(
            serde_json::to_vec(&with_one_more).unwrap().len() > MAX_DIAGNOSTICS_ENTRY_BYTES,
            "kept count must be the largest that fits, not merely a fitting count"
        );
    }

    /// #311 S6: truncation must prefer keeping higher-severity diagnostics,
    /// not just whichever the server happened to publish first -- a late
    /// `ERROR` must survive over leading `HINT`-level noise.
    #[test]
    fn test_store_diagnostics_truncation_prefers_higher_severity() {
        let mut cache = NotificationCache::new();
        let uri: Uri = Uri::from("file:///test.rs");

        let mut diagnostics: Vec<LspDiagnostic> = (0..5000)
            .map(|i| {
                let mut d = minimal_diagnostic(format!("hint {i}: {}", "x".repeat(200)));
                d.severity = Some(lsp_types::DiagnosticSeverity::Hint);
                d
            })
            .collect();
        let mut trailing_error = minimal_diagnostic("the one real error".to_string());
        trailing_error.severity = Some(lsp_types::DiagnosticSeverity::Error);
        diagnostics.push(trailing_error);

        cache.store_diagnostics(&test_server(), &uri, Some(1), diagnostics);

        let stored = &cache.diagnostics(&uri).unwrap().diagnostics;
        assert!(
            stored
                .iter()
                .any(|d| message_as_str(&d.message) == "the one real error"),
            "the trailing ERROR diagnostic must survive truncation over leading HINT noise"
        );
    }

    /// #311 S7 / M7: truncating the diagnostics list must not be silent --
    /// a caller with no visibility into this cache would otherwise have no
    /// way to know a `get_cached_diagnostics` result is incomplete.
    #[test]
    fn test_store_diagnostics_warns_when_truncating_list() {
        use tracing_subscriber::layer::SubscriberExt as _;

        let mut cache = NotificationCache::new();
        let uri: Uri = Uri::from("file:///test.rs");
        let diagnostics: Vec<LspDiagnostic> = (0..5000)
            .map(|i| minimal_diagnostic(format!("diagnostic {i}: {}", "x".repeat(250))))
            .collect();

        let captured = CapturedLogs::default();
        let subscriber = tracing_subscriber::registry().with(captured.clone());
        let guard = tracing::subscriber::set_default(subscriber);
        cache.store_diagnostics(&test_server(), &uri, Some(1), diagnostics);
        drop(guard);

        let messages = captured.messages();
        assert!(
            messages
                .iter()
                .any(|m| m.contains("highest-severity") && m.contains("file:///test.rs")),
            "expected a truncation warning naming the URI, got: {messages:?}"
        );
    }

    /// #311 S7: dropping a diagnostic's `data` breaks the LSP contract that
    /// it round-trips to a later `textDocument/codeAction` request -- this
    /// must be logged, not silent.
    #[test]
    fn test_store_diagnostics_warns_when_dropping_data_blob() {
        use tracing_subscriber::layer::SubscriberExt as _;

        let mut cache = NotificationCache::new();
        let uri: Uri = Uri::from("file:///test.rs");
        let mut diagnostic = minimal_diagnostic("small message".to_string());
        diagnostic.data = Some(serde_json::json!({
            "blob": "x".repeat(MAX_DIAGNOSTICS_ENTRY_BYTES + 1000),
        }));

        let captured = CapturedLogs::default();
        let subscriber = tracing_subscriber::registry().with(captured.clone());
        let guard = tracing::subscriber::set_default(subscriber);
        cache.store_diagnostics(&test_server(), &uri, Some(1), vec![diagnostic]);
        drop(guard);

        let messages = captured.messages();
        assert!(
            messages.iter().any(|m| m.contains("code-action")),
            "expected a warning noting the code-action quick-fix impact, got: {messages:?}"
        );
    }

    /// #311 C1: a single diagnostic dominated by an oversized `data` blob
    /// must be capped even though `message` alone is small -- the aggregate
    /// list-halving path can't shrink a one-element list, so the opaque
    /// fields on that single diagnostic must be dropped instead.
    #[test]
    fn test_store_diagnostics_drops_oversized_data_blob_on_single_diagnostic() {
        let mut cache = NotificationCache::new();
        let uri: Uri = Uri::from("file:///test.rs");

        let mut diagnostic = minimal_diagnostic("small message".to_string());
        diagnostic.data = Some(serde_json::json!({
            "blob": "x".repeat(MAX_DIAGNOSTICS_ENTRY_BYTES + 1000),
        }));

        cache.store_diagnostics(&test_server(), &uri, Some(1), vec![diagnostic]);

        let stored = &cache.diagnostics(&uri).unwrap().diagnostics;
        assert_eq!(stored.len(), 1);
        assert_eq!(
            stored[0].message,
            lsp_types::Message::String("small message".to_string())
        );
        assert!(
            stored[0].data.is_none(),
            "oversized data blob must be dropped"
        );
        let serialized_len = serde_json::to_vec(stored).unwrap().len();
        assert!(
            serialized_len <= MAX_DIAGNOSTICS_ENTRY_BYTES,
            "stored entry must fit the aggregate cap after dropping data, got {serialized_len} bytes"
        );
    }

    /// #311 C1 follow-up: an oversized `source` (not `data`) on a single
    /// diagnostic must also be brought back under the cap -- the
    /// opaque-field-drop mitigation alone does not touch `source`, which is
    /// a plain string and must be truncated instead.
    #[test]
    fn test_store_diagnostics_truncates_oversized_source_on_single_diagnostic() {
        let mut cache = NotificationCache::new();
        let uri: Uri = Uri::from("file:///test.rs");

        let mut diagnostic = minimal_diagnostic("small message".to_string());
        diagnostic.source = Some("x".repeat(MAX_DIAGNOSTICS_ENTRY_BYTES + 1000));

        cache.store_diagnostics(&test_server(), &uri, Some(1), vec![diagnostic]);

        let stored = &cache.diagnostics(&uri).unwrap().diagnostics;
        assert_eq!(stored.len(), 1);
        assert_eq!(
            stored[0].message,
            lsp_types::Message::String("small message".to_string())
        );
        let serialized_len = serde_json::to_vec(stored).unwrap().len();
        assert!(
            serialized_len <= MAX_DIAGNOSTICS_ENTRY_BYTES,
            "stored entry must fit the aggregate cap after truncating source, got {serialized_len} bytes"
        );
    }

    /// #311 C1 follow-up: `cap_diagnostics_entry_size`'s postcondition --
    /// the result always fits `MAX_DIAGNOSTICS_ENTRY_BYTES` -- must hold
    /// even when every uncapped field is maxed out simultaneously, not just
    /// one at a time. This is the terminal-enforcement guarantee itself,
    /// exercised end to end through `store_diagnostics` rather than by
    /// calling the private function directly.
    #[test]
    fn test_store_diagnostics_caps_single_diagnostic_with_every_field_maxed_out() {
        let mut cache = NotificationCache::new();
        let uri: Uri = Uri::from("file:///test.rs");

        // Each field individually exceeds MAX_ENTRY_TEXT_BYTES (so
        // source/code truncation is exercised) and the combination exceeds
        // MAX_DIAGNOSTICS_ENTRY_BYTES, without needing to allocate multiple
        // megabytes per field just to prove the same point.
        let mut diagnostic = minimal_diagnostic("x".repeat(MAX_ENTRY_TEXT_BYTES + 1000));
        diagnostic.source = Some("x".repeat(MAX_ENTRY_TEXT_BYTES + 1000));
        diagnostic.code = Some(lsp_types::Code::String(
            "x".repeat(MAX_ENTRY_TEXT_BYTES + 1000),
        ));
        diagnostic.data = Some(serde_json::json!({ "blob": "x".repeat(MAX_ENTRY_TEXT_BYTES) }));
        diagnostic.tags = Some(vec![lsp_types::DiagnosticTag::Unnecessary; 50]);
        diagnostic.related_information = Some(vec![
            lsp_types::DiagnosticRelatedInformation {
                location: lsp_types::Location {
                    uri: uri.clone(),
                    range: Range::default(),
                },
                message: "x".repeat(1000),
            };
            5
        ]);

        cache.store_diagnostics(&test_server(), &uri, Some(1), vec![diagnostic]);

        let stored = &cache.diagnostics(&uri).unwrap().diagnostics;
        assert_eq!(stored.len(), 1);
        let serialized_len = serde_json::to_vec(stored).unwrap().len();
        assert!(
            serialized_len <= MAX_DIAGNOSTICS_ENTRY_BYTES,
            "postcondition must hold even with every field maxed out, got {serialized_len} bytes"
        );
    }

    /// #311 C1 follow-up: exercises `cap_diagnostics_entry_size`'s terminal
    /// fallback directly. `message` is the one field the field-specific
    /// mitigations never touch (they only cover
    /// `source`/`code`/`data`/`code_description`/`related_information`/
    /// `tags`), so an oversized, *untruncated* message -- as it would be if
    /// this private function were ever called without `store_diagnostics`'s
    /// own prior message truncation -- must still be brought under budget
    /// by the terminal step, not left to slip through.
    #[test]
    fn test_cap_diagnostics_entry_size_terminal_fallback_bounds_untruncated_message() {
        let uri: Uri = Uri::from("file:///test.rs");
        let mut diagnostics = vec![minimal_diagnostic(
            "x".repeat(MAX_DIAGNOSTICS_ENTRY_BYTES + 1000),
        )];

        cap_diagnostics_entry_size(&uri, &mut diagnostics);

        assert_eq!(diagnostics.len(), 1);
        assert!(
            message_as_str(&diagnostics[0].message).len()
                <= DIAGNOSTIC_TERMINAL_FALLBACK_MESSAGE_BYTES + 20,
            "terminal fallback must truncate the message itself, got {} bytes",
            message_as_str(&diagnostics[0].message).len()
        );
        let serialized_len = serde_json::to_vec(&diagnostics).unwrap().len();
        assert!(
            serialized_len <= MAX_DIAGNOSTICS_ENTRY_BYTES,
            "postcondition must hold via the terminal fallback, got {serialized_len} bytes"
        );
    }

    /// #311 S5: when no diagnostic carries `data`/`code_description`/
    /// `related_information`/`tags` and the cheap size estimate is already
    /// under budget, nothing should be modified -- the fast path must not
    /// alter content it didn't need to touch.
    #[test]
    fn test_store_diagnostics_cheap_path_leaves_small_diagnostics_untouched() {
        let mut cache = NotificationCache::new();
        let uri: Uri = Uri::from("file:///test.rs");

        let mut diagnostic = minimal_diagnostic("a small, ordinary diagnostic message".to_string());
        diagnostic.source = Some("rustc".to_string());

        cache.store_diagnostics(&test_server(), &uri, Some(1), vec![diagnostic]);

        let stored = &cache.diagnostics(&uri).unwrap().diagnostics;
        assert_eq!(stored.len(), 1);
        assert_eq!(
            stored[0].message,
            lsp_types::Message::String("a small, ordinary diagnostic message".to_string())
        );
        assert_eq!(stored[0].source.as_deref(), Some("rustc"));
    }

    /// #311 S5 follow-up: the critic's exact counterexample. A NUL-heavy
    /// message's *raw* byte length looks small enough for the cheap
    /// estimate to skip the real check, but its *serialized* (JSON-escaped)
    /// size is up to `JSON_ESCAPE_WORST_CASE_FACTOR`x larger -- each NUL
    /// byte costs 6 bytes as `\u0000` once JSON-encoded. Three diagnostics
    /// at exactly `MAX_ENTRY_TEXT_BYTES` of NULs each previously passed the
    /// old raw-length estimate (787,200 bytes, under the 1 MiB cap) while
    /// actually serializing to roughly 4.5 MiB -- letting an entry ~4.5x
    /// over budget skip `fits`/truncation/terminal-fallback entirely.
    #[test]
    fn test_store_diagnostics_cheap_path_escape_safe_for_control_character_heavy_message() {
        let mut cache = NotificationCache::new();
        let uri: Uri = Uri::from("file:///test.rs");

        let nul_heavy_message = "\0".repeat(MAX_ENTRY_TEXT_BYTES);
        let diagnostics: Vec<LspDiagnostic> = (0..3)
            .map(|_| minimal_diagnostic(nul_heavy_message.clone()))
            .collect();

        cache.store_diagnostics(&test_server(), &uri, Some(1), diagnostics);

        let stored = &cache.diagnostics(&uri).unwrap().diagnostics;
        let serialized_len = serde_json::to_vec(stored).unwrap().len();
        assert!(
            serialized_len <= MAX_DIAGNOSTICS_ENTRY_BYTES,
            "escape-heavy content must not let the cheap-estimate fast path skip the real cap, \
             got {serialized_len} bytes"
        );
    }

    #[test]
    fn test_store_diagnostics_replaces_existing() {
        let mut cache = NotificationCache::new();
        let uri: Uri = Uri::from("file:///test.rs");

        cache.store_diagnostics(&test_server(), &uri, Some(1), vec![]);
        assert_eq!(cache.diagnostics_count(), 1);

        cache.store_diagnostics(&test_server(), &uri, Some(2), vec![]);
        assert_eq!(cache.diagnostics_count(), 1);

        let stored = cache.diagnostics(&uri).unwrap();
        assert_eq!(stored.version.map(DocumentVersion::get), Some(2));
    }

    #[test]
    fn test_store_and_get_logs() {
        let mut cache = NotificationCache::new();

        cache.store_log(LogLevel::Error, "error message".to_string());
        cache.store_log(LogLevel::Info, "info message".to_string());

        let logs = cache.logs();
        assert_eq!(logs.len(), 2);
        assert_eq!(logs[0].level, LogLevel::Error);
        assert_eq!(logs[0].message, "error message");
        assert_eq!(logs[1].level, LogLevel::Info);
        assert_eq!(logs[1].message, "info message");
    }

    #[test]
    fn test_logs_max_capacity() {
        let mut cache = NotificationCache::new();

        // Add more than MAX_LOG_ENTRIES
        for i in 0..MAX_LOG_ENTRIES + 10 {
            cache.store_log(LogLevel::Info, format!("message {i}"));
        }

        assert_eq!(cache.logs_count(), MAX_LOG_ENTRIES);

        // Oldest entries should be removed (FIFO)
        let logs = cache.logs();
        assert_eq!(logs.front().unwrap().message, "message 10");
        assert_eq!(
            logs.back().unwrap().message,
            format!("message {}", MAX_LOG_ENTRIES + 9)
        );
    }

    /// #311: `MAX_LOG_ENTRIES` bounds the number of log entries, but not the
    /// size of any one entry -- an oversized message must be truncated
    /// rather than stored verbatim.
    #[test]
    fn test_store_log_truncates_oversized_message() {
        let mut cache = NotificationCache::new();
        let oversized = "a".repeat(MAX_ENTRY_TEXT_BYTES + 100);

        cache.store_log(LogLevel::Info, oversized.clone());

        let stored = &cache.logs()[0].message;
        assert!(stored.len() < oversized.len());
        assert!(stored.ends_with("... (truncated)"));
    }

    #[test]
    fn test_store_log_does_not_truncate_message_at_or_below_limit() {
        let mut cache = NotificationCache::new();
        let message = "a".repeat(MAX_ENTRY_TEXT_BYTES);

        cache.store_log(LogLevel::Info, message.clone());

        assert_eq!(cache.logs()[0].message, message);
    }

    #[test]
    fn test_store_and_get_messages() {
        let mut cache = NotificationCache::new();

        cache.store_message(MessageType::Error, "error msg".to_string());
        cache.store_message(MessageType::Warning, "warning msg".to_string());

        let messages = cache.messages();
        assert_eq!(messages.len(), 2);
        assert_eq!(messages[0].message_type, MessageType::Error);
        assert_eq!(messages[0].message, "error msg");
        assert_eq!(messages[1].message_type, MessageType::Warning);
        assert_eq!(messages[1].message, "warning msg");
    }

    #[test]
    fn test_messages_max_capacity() {
        let mut cache = NotificationCache::new();

        // Add more than MAX_SERVER_MESSAGES
        for i in 0..MAX_SERVER_MESSAGES + 10 {
            cache.store_message(MessageType::Info, format!("message {i}"));
        }

        assert_eq!(cache.messages_count(), MAX_SERVER_MESSAGES);

        // Oldest entries should be removed (FIFO)
        let messages = cache.messages();
        assert_eq!(messages.front().unwrap().message, "message 10");
        assert_eq!(
            messages.back().unwrap().message,
            format!("message {}", MAX_SERVER_MESSAGES + 9)
        );
    }

    /// #311: same per-entry byte cap as `store_log`, applied to server messages.
    #[test]
    fn test_store_message_truncates_oversized_message() {
        let mut cache = NotificationCache::new();
        let oversized = "a".repeat(MAX_ENTRY_TEXT_BYTES + 100);

        cache.store_message(MessageType::Info, oversized.clone());

        let stored = &cache.messages()[0].message;
        assert!(stored.len() < oversized.len());
        assert!(stored.ends_with("... (truncated)"));
    }

    #[test]
    fn test_log_levels() {
        let mut cache = NotificationCache::new();

        cache.store_log(LogLevel::Error, "error".to_string());
        cache.store_log(LogLevel::Warning, "warning".to_string());
        cache.store_log(LogLevel::Info, "info".to_string());
        cache.store_log(LogLevel::Debug, "debug".to_string());

        let logs = cache.logs();
        assert_eq!(logs[0].level, LogLevel::Error);
        assert_eq!(logs[1].level, LogLevel::Warning);
        assert_eq!(logs[2].level, LogLevel::Info);
        assert_eq!(logs[3].level, LogLevel::Debug);
    }

    #[test]
    fn test_message_types() {
        let mut cache = NotificationCache::new();

        cache.store_message(MessageType::Error, "error".to_string());
        cache.store_message(MessageType::Warning, "warning".to_string());
        cache.store_message(MessageType::Info, "info".to_string());
        cache.store_message(MessageType::Log, "log".to_string());

        let messages = cache.messages();
        assert_eq!(messages[0].message_type, MessageType::Error);
        assert_eq!(messages[1].message_type, MessageType::Warning);
        assert_eq!(messages[2].message_type, MessageType::Info);
        assert_eq!(messages[3].message_type, MessageType::Log);
    }

    #[test]
    fn test_timestamp_ordering() {
        let mut cache = NotificationCache::new();

        cache.store_log(LogLevel::Info, "first".to_string());
        std::thread::sleep(std::time::Duration::from_millis(10));
        cache.store_log(LogLevel::Info, "second".to_string());

        let logs = cache.logs();
        assert!(logs[0].timestamp < logs[1].timestamp);
    }

    #[test]
    fn test_store_diagnostics_empty_list() {
        let mut cache = NotificationCache::new();
        let uri: Uri = Uri::from("file:///test.rs");

        let diagnostic = LspDiagnostic {
            range: Range {
                start: Position {
                    line: 0,
                    character: 0,
                },
                end: Position {
                    line: 0,
                    character: 5,
                },
            },
            severity: Some(lsp_types::DiagnosticSeverity::Error),
            message: "test error".to_string().into(),
            code: None,
            source: None,
            code_description: None,
            related_information: None,
            tags: None,
            data: None,
        };

        cache.store_diagnostics(&test_server(), &uri, Some(1), vec![diagnostic]);
        assert_eq!(cache.diagnostics(&uri).unwrap().diagnostics.len(), 1);

        cache.store_diagnostics(&test_server(), &uri, Some(2), vec![]);
        let stored = cache.diagnostics(&uri).unwrap();
        assert_eq!(stored.diagnostics.len(), 0);
        assert_eq!(stored.version.map(DocumentVersion::get), Some(2));
    }

    #[test]
    fn test_store_many_diagnostics_single_file() {
        let mut cache = NotificationCache::new();
        let uri: Uri = Uri::from("file:///test.rs");

        let diagnostics: Vec<LspDiagnostic> = (0..100)
            .map(|i| LspDiagnostic {
                range: Range {
                    start: Position {
                        line: i,
                        character: 0,
                    },
                    end: Position {
                        line: i,
                        character: 10,
                    },
                },
                message: format!("Error {i}").into(),
                severity: Some(lsp_types::DiagnosticSeverity::Error),
                code: None,
                source: None,
                code_description: None,
                related_information: None,
                tags: None,
                data: None,
            })
            .collect();

        cache.store_diagnostics(&test_server(), &uri, Some(1), diagnostics);

        let stored = cache.diagnostics(&uri).unwrap();
        assert_eq!(stored.diagnostics.len(), 100);
    }

    #[test]
    fn test_logs_exact_capacity_boundary() {
        let mut cache = NotificationCache::new();

        for i in 0..MAX_LOG_ENTRIES {
            cache.store_log(LogLevel::Info, format!("message {i}"));
        }
        assert_eq!(cache.logs_count(), MAX_LOG_ENTRIES);

        cache.store_log(LogLevel::Info, "overflow".to_string());
        assert_eq!(cache.logs_count(), MAX_LOG_ENTRIES);
        assert_eq!(cache.logs().front().unwrap().message, "message 1");
    }

    #[test]
    fn test_messages_exact_capacity_boundary() {
        let mut cache = NotificationCache::new();

        for i in 0..MAX_SERVER_MESSAGES {
            cache.store_message(MessageType::Info, format!("message {i}"));
        }
        assert_eq!(cache.messages_count(), MAX_SERVER_MESSAGES);

        cache.store_message(MessageType::Info, "overflow".to_string());
        assert_eq!(cache.messages_count(), MAX_SERVER_MESSAGES);
        assert_eq!(cache.messages().front().unwrap().message, "message 1");
    }

    #[test]
    fn test_diagnostics_max_capacity() {
        let mut cache = NotificationCache::new();

        for i in 0..MAX_DIAGNOSTIC_ENTRIES + 10 {
            let uri: Uri = Uri::from(format!("file:///test{i}.rs"));
            cache.store_diagnostics(&test_server(), &uri, Some(1), vec![]);
        }

        assert_eq!(cache.diagnostics_count(), MAX_DIAGNOSTIC_ENTRIES);

        // Oldest entries should be evicted (FIFO).
        let evicted: Uri = Uri::from("file:///test0.rs");
        assert!(cache.diagnostics(&evicted).is_none());
        let newest: Uri = Uri::from(format!("file:///test{}.rs", MAX_DIAGNOSTIC_ENTRIES + 9));
        assert!(cache.diagnostics(&newest).is_some());
    }

    #[test]
    fn test_diagnostics_replacing_existing_uri_does_not_trigger_eviction() {
        let mut cache = NotificationCache::new();
        let uri: Uri = Uri::from("file:///stable.rs");

        for i in 0..MAX_DIAGNOSTIC_ENTRIES {
            cache.store_diagnostics(
                &test_server(),
                &uri,
                Some(i32::try_from(i).unwrap()),
                vec![],
            );
        }
        assert_eq!(cache.diagnostics_count(), 1);
        assert!(cache.diagnostics(&uri).is_some());
    }

    #[test]
    fn test_diagnostics_republish_refreshes_eviction_order() {
        // #234 S2 / #266 S3 regression: an actively-edited file, republished
        // on every keystroke, must not be evicted ahead of a file that was
        // merely opened once and never touched again.
        let mut cache = NotificationCache::new();
        let actively_edited: Uri = Uri::from("file:///keep.rs");
        cache.store_diagnostics(&test_server(), &actively_edited, Some(1), vec![]);

        // Fill the rest of the cache with untouched entries.
        for i in 0..MAX_DIAGNOSTIC_ENTRIES - 1 {
            let uri: Uri = Uri::from(format!("file:///untouched{i}.rs"));
            cache.store_diagnostics(&test_server(), &uri, Some(1), vec![]);
        }
        assert_eq!(cache.diagnostics_count(), MAX_DIAGNOSTIC_ENTRIES);

        // Republish the actively-edited file -- this must move it to the
        // back of the eviction order, not leave it at its original (oldest)
        // position.
        cache.store_diagnostics(&test_server(), &actively_edited, Some(2), vec![]);

        // One more new URI arrives, exceeding the cap by one: the oldest
        // *untouched* entry must be evicted, not the republished one.
        let overflow: Uri = Uri::from("file:///overflow.rs");
        cache.store_diagnostics(&test_server(), &overflow, Some(1), vec![]);

        assert!(
            cache.diagnostics(&actively_edited).is_some(),
            "republished entry must survive eviction after being refreshed"
        );
        let oldest_untouched: Uri = Uri::from("file:///untouched0.rs");
        assert!(
            cache.diagnostics(&oldest_untouched).is_none(),
            "the oldest never-republished entry must be evicted instead"
        );
        assert!(cache.diagnostics(&overflow).is_some());
    }

    #[test]
    fn test_store_diagnostics_no_version() {
        let mut cache = NotificationCache::new();
        let uri: Uri = Uri::from("file:///test.rs");

        cache.store_diagnostics(&test_server(), &uri, None, vec![]);
        let stored = cache.diagnostics(&uri).unwrap();
        assert_eq!(stored.version, None);
    }

    /// #266/#276: once the *aggregate* cache is full, a noisy server that has
    /// grown far past its fair share must have its own oldest entries
    /// evicted, never a quiet server's, even though both share one
    /// `NotificationCache` and the noisy server was allowed to keep growing
    /// past its static equal share while the aggregate still had room.
    #[test]
    fn test_noisy_server_does_not_evict_quiet_server_entries() {
        let mut cache = NotificationCache::new();
        cache.set_diagnostics_route_count(2);
        let noisy = ServerId::from_static("noisy");
        let quiet = ServerId::from_static("quiet");

        let quiet_uri: Uri = Uri::from("file:///quiet/only_file.rs");
        cache.store_diagnostics(&quiet, &quiet_uri, Some(1), vec![]);

        // Drive the noisy server well past the aggregate cap -- it must be
        // allowed to consume nearly all of it since the quiet server leaves
        // the rest unused (#276), and once the aggregate is full it must
        // only evict its own oldest entries.
        for i in 0..MAX_DIAGNOSTIC_ENTRIES + 50 {
            let uri: Uri = Uri::from(format!("file:///noisy/file{i}.rs"));
            cache.store_diagnostics(&noisy, &uri, Some(1), vec![]);
        }

        assert_eq!(cache.diagnostics_count(), MAX_DIAGNOSTIC_ENTRIES);
        assert!(
            cache.diagnostics(&quiet_uri).is_some(),
            "quiet server's only entry must survive the noisy server's overflow"
        );

        let noisy_first: Uri = Uri::from("file:///noisy/file0.rs");
        assert!(
            cache.diagnostics(&noisy_first).is_none(),
            "noisy server's own oldest entries must be evicted once the aggregate cache is full"
        );
    }

    /// #276: a dominant server must be able to exceed its static equal share
    /// of the budget while other registered diagnostics-route servers are
    /// idle -- eviction is work-conserving and only triggers once the
    /// *aggregate* cache reaches `MAX_DIAGNOSTIC_ENTRIES`, not once a single
    /// server passes `MAX_DIAGNOSTIC_ENTRIES / diagnostics_route_count`.
    #[test]
    fn test_dominant_server_exceeds_equal_share_while_others_idle() {
        let mut cache = NotificationCache::new();
        cache.set_diagnostics_route_count(4);
        let dominant = ServerId::from_static("dominant");

        let equal_share = MAX_DIAGNOSTIC_ENTRIES / 4;
        let more_than_share = equal_share + 100;
        for i in 0..more_than_share {
            let uri: Uri = Uri::from(format!("file:///file{i}.rs"));
            cache.store_diagnostics(&dominant, &uri, Some(1), vec![]);
        }
        assert_eq!(
            cache.diagnostics_count(),
            more_than_share,
            "a dominant server must be able to exceed its static equal share while the aggregate has room"
        );

        // The other three registered servers never write anything, so the
        // dominant server can keep growing all the way to the full budget.
        for i in more_than_share..MAX_DIAGNOSTIC_ENTRIES {
            let uri: Uri = Uri::from(format!("file:///file{i}.rs"));
            cache.store_diagnostics(&dominant, &uri, Some(1), vec![]);
        }
        assert_eq!(cache.diagnostics_count(), MAX_DIAGNOSTIC_ENTRIES);
    }

    /// M1: eviction-target ties (multiple servers holding the same entry
    /// count) must resolve deterministically, not depend on `HashMap`'s
    /// per-process randomized iteration order. This pins the exact winner
    /// rather than only checking repeat-call stability -- stability across
    /// calls would hold trivially even without the fix, since a single
    /// `HashMap` instance's iteration order does not change between calls
    /// within one process; the real risk is a *different* winner on a
    /// *different* process run, which this test can't observe directly, but
    /// the pinned assertion below only passes because the tie-break key
    /// (`(order.len(), id.as_str())`) is unique per server -- no two
    /// distinct `ServerId`s can ever share it, so `max_by_key` never
    /// actually has a tie left to resolve by iteration order.
    #[test]
    fn test_eviction_target_tie_break_is_deterministic() {
        let mut cache = NotificationCache::new();
        cache.set_diagnostics_route_count(1000); // fair share floors at 1

        let a = ServerId::from_static("a");
        let b = ServerId::from_static("b");
        for i in 0..2 {
            let uri: Uri = Uri::from(format!("file:///a/file{i}.rs"));
            cache.store_diagnostics(&a, &uri, Some(1), vec![]);
        }
        for i in 0..2 {
            let uri: Uri = Uri::from(format!("file:///b/file{i}.rs"));
            cache.store_diagnostics(&b, &uri, Some(1), vec![]);
        }

        // `a` and `b` are tied at 2 entries each, both over the floor-1
        // share -- `"b"` sorts after `"a"` lexicographically, so it is the
        // one always picked.
        let writer = ServerId::from_static("writer");
        assert_eq!(cache.server_to_evict_from(&writer), Some(b));
    }

    /// M2: `server_to_evict_from`'s "largest in-share server" fallback is
    /// reachable and correct through the public `store_diagnostics` API,
    /// not just in isolation -- a brand-new server's first write must still
    /// evict something when the aggregate cache is already full purely from
    /// other servers that are each individually within their fair share.
    /// Without this fallback there would be nothing to evict from (the
    /// writer has no entries yet, and no one else exceeds their share) and
    /// the aggregate could grow past `MAX_DIAGNOSTIC_ENTRIES`.
    #[test]
    fn test_new_writer_still_evicts_when_every_existing_server_is_in_share() {
        let mut cache = NotificationCache::new();
        cache.set_diagnostics_route_count(2); // fair share = 500 each

        let a = ServerId::from_static("a");
        let b = ServerId::from_static("b");
        for i in 0..500 {
            let uri: Uri = Uri::from(format!("file:///a/file{i}.rs"));
            cache.store_diagnostics(&a, &uri, Some(1), vec![]);
        }
        for i in 0..500 {
            let uri: Uri = Uri::from(format!("file:///b/file{i}.rs"));
            cache.store_diagnostics(&b, &uri, Some(1), vec![]);
        }
        assert_eq!(cache.diagnostics_count(), MAX_DIAGNOSTIC_ENTRIES);

        // `c` has never written before -- its very first write hits a full,
        // entirely-in-share aggregate.
        let c = ServerId::from_static("c");
        let new_uri: Uri = Uri::from("file:///c/first.rs");
        cache.store_diagnostics(&c, &new_uri, Some(1), vec![]);

        assert_eq!(
            cache.diagnostics_count(),
            MAX_DIAGNOSTIC_ENTRIES,
            "the aggregate cap must still be enforced even when every existing server is within share"
        );
        assert!(cache.diagnostics(&new_uri).is_some());

        // `a` and `b` are tied at 500 entries each; the deterministic
        // tie-break in `server_to_evict_from` picks `b`, so `b`'s oldest
        // entry is the one evicted, not `a`'s.
        let b_oldest: Uri = Uri::from("file:///b/file0.rs");
        assert!(
            cache.diagnostics(&b_oldest).is_none(),
            "the largest in-share server (tie-broken to b) must lose its oldest entry"
        );
        assert!(
            cache
                .diagnostics(&Uri::from("file:///a/file0.rs".to_owned()))
                .is_some(),
            "the other in-share server must be untouched"
        );
    }

    /// Re-publishing diagnostics for a URI under its existing owner must not
    /// count as a new entry against that server's budget.
    #[test]
    fn test_repeated_writes_same_owner_do_not_grow_order_map() {
        let mut cache = NotificationCache::new();
        let server = ServerId::from_static("server");
        let uri: Uri = Uri::from("file:///test.rs");

        let max_version = i32::try_from(MAX_DIAGNOSTIC_ENTRIES).unwrap() + 10;
        for version in 0..max_version {
            cache.store_diagnostics(&server, &uri, Some(version), vec![]);
        }

        assert_eq!(cache.diagnostics_count(), 1);
        let stored = cache.diagnostics(&uri).unwrap();
        assert_eq!(
            stored.version.map(DocumentVersion::get),
            Some(max_version - 1)
        );
    }

    /// If a URI's diagnostics route changes to a different server (e.g.
    /// after a respawn rebind), the entry must move to the new owner's
    /// order map rather than staying attributed to the old one.
    #[test]
    fn test_store_diagnostics_reassigns_ownership() {
        let mut cache = NotificationCache::new();
        let old_owner = ServerId::from_static("old");
        let new_owner = ServerId::from_static("new");
        let uri: Uri = Uri::from("file:///test.rs");

        cache.store_diagnostics(&old_owner, &uri, Some(1), vec![]);
        cache.store_diagnostics(&new_owner, &uri, Some(2), vec![]);

        assert_eq!(cache.diagnostics_count(), 1);
        let stored = cache.diagnostics(&uri).unwrap();
        assert_eq!(stored.version.map(DocumentVersion::get), Some(2));

        // The old owner's order map must no longer reference this URI:
        // filling the old owner's budget with fresh entries must not evict
        // this URI a second time (it's not there to evict) nor corrupt state.
        for i in 0..MAX_DIAGNOSTIC_ENTRIES + 5 {
            let other: Uri = Uri::from(format!("file:///old/file{i}.rs"));
            cache.store_diagnostics(&old_owner, &other, Some(1), vec![]);
        }
        assert!(cache.diagnostics(&uri).is_some());
    }

    /// #290: `diagnostics_owner` is what a cache-only read (e.g.
    /// `get_cached_diagnostics`) uses to resolve the publishing server's
    /// negotiated position encoding, so both branches -- an owner on record
    /// and none -- must behave correctly.
    #[test]
    fn test_diagnostics_owner_returns_publisher_after_store() {
        let mut cache = NotificationCache::new();
        let server = ServerId::from_static("rust");
        let uri: Uri = Uri::from("file:///main.rs");

        cache.store_diagnostics(&server, &uri, Some(1), vec![]);

        assert_eq!(cache.diagnostics_owner(&uri), Some(&server));
    }

    #[test]
    fn test_diagnostics_owner_none_for_untracked_uri() {
        let cache = NotificationCache::new();
        let uri: Uri = Uri::from("file:///never-seen.rs");

        assert_eq!(cache.diagnostics_owner(&uri), None);
    }

    /// Reassigning ownership (see `test_store_diagnostics_reassigns_ownership`
    /// above) must also update `diagnostics_owner`, not just the cached
    /// content -- otherwise a stale owner's encoding would be used to
    /// convert a different server's diagnostics.
    #[test]
    fn test_diagnostics_owner_reflects_reassigned_ownership() {
        let mut cache = NotificationCache::new();
        let old_owner = ServerId::from_static("old");
        let new_owner = ServerId::from_static("new");
        let uri: Uri = Uri::from("file:///test.rs");

        cache.store_diagnostics(&old_owner, &uri, Some(1), vec![]);
        assert_eq!(cache.diagnostics_owner(&uri), Some(&old_owner));

        cache.store_diagnostics(&new_owner, &uri, Some(2), vec![]);
        assert_eq!(cache.diagnostics_owner(&uri), Some(&new_owner));
    }

    /// #266 S2: clearing one server's diagnostics must not disturb another
    /// server's cached entries.
    #[test]
    fn test_clear_server_diagnostics_scopes_to_one_server() {
        let mut cache = NotificationCache::new();
        let crashed = ServerId::from_static("crashed");
        let healthy = ServerId::from_static("healthy");

        let crashed_uri: Uri = Uri::from("file:///crashed/main.py");
        let healthy_uri: Uri = Uri::from("file:///healthy/main.rs");
        cache.store_diagnostics(&crashed, &crashed_uri, Some(1), vec![]);
        cache.store_diagnostics(&healthy, &healthy_uri, Some(1), vec![]);

        cache.clear_server_diagnostics(&crashed);

        assert!(cache.diagnostics(&crashed_uri).is_none());
        assert!(cache.diagnostics(&healthy_uri).is_some());
        assert_eq!(cache.diagnostics_count(), 1);

        // Idempotent / no-op for a server with no (or no longer any) entries.
        cache.clear_server_diagnostics(&crashed);
        assert_eq!(cache.diagnostics_count(), 1);
    }

    /// #359: `mark_push_degraded` must be scoped per server and, once set,
    /// stay set -- there is no "unmark" operation, since only a full mcpls
    /// process restart actually restores push diagnostics for a respawned
    /// server.
    #[test]
    fn test_push_degraded_is_scoped_per_server_and_permanent() {
        let mut cache = NotificationCache::new();
        let degraded = ServerId::from_static("degraded");
        let healthy = ServerId::from_static("healthy");

        assert!(!cache.is_push_degraded(&degraded));
        assert!(!cache.is_push_degraded(&healthy));

        cache.mark_push_degraded(&degraded);

        assert!(cache.is_push_degraded(&degraded));
        assert!(!cache.is_push_degraded(&healthy));

        // Marking again is idempotent.
        cache.mark_push_degraded(&degraded);
        assert!(cache.is_push_degraded(&degraded));
    }

    /// #276: `set_diagnostics_route_count` shrinking a server's fair share
    /// must not retroactively evict any of its already-cached entries --
    /// eviction is work-conserving and only fires once the *aggregate* cache
    /// is full. Once full, though, the shrunk share is what makes that
    /// server the eviction target for a *different* server's write, rather
    /// than the write that actually needed room being rejected or evicting
    /// its own (nonexistent) entries.
    #[test]
    fn test_shrinking_budget_affects_eviction_target_not_existing_entries() {
        let mut cache = NotificationCache::new();
        let server = ServerId::from_static("server");

        for i in 0..MAX_DIAGNOSTIC_ENTRIES {
            let uri: Uri = Uri::from(format!("file:///file{i}.rs"));
            cache.store_diagnostics(&server, &uri, Some(1), vec![]);
        }
        assert_eq!(
            cache.diagnostics_count(),
            MAX_DIAGNOSTIC_ENTRIES,
            "filling to the aggregate cap must not evict anything early"
        );

        // A drastic shrink relative to the entries `server` already holds --
        // must not evict anything by itself.
        cache.set_diagnostics_route_count(4);
        assert_eq!(cache.diagnostics_count(), MAX_DIAGNOSTIC_ENTRIES);

        // A different server's first write, once the aggregate is full,
        // evicts from `server` (now far over its shrunk share) instead.
        let other = ServerId::from_static("other");
        let new_uri: Uri = Uri::from("file:///other/new.rs");
        cache.store_diagnostics(&other, &new_uri, Some(1), vec![]);

        assert_eq!(cache.diagnostics_count(), MAX_DIAGNOSTIC_ENTRIES);
        assert!(cache.diagnostics(&new_uri).is_some());
        let server_oldest: Uri = Uri::from("file:///file0.rs");
        assert!(
            cache.diagnostics(&server_oldest).is_none(),
            "the pre-existing server's oldest entry, now far over its shrunk share, must be evicted"
        );
    }

    /// #283: an external `NotificationCache` consumer that never calls
    /// `set_diagnostics_route_count` must still get fair-share partitioning
    /// once more than one server has written an entry -- the pre-#266
    /// regression this guards against is an unset count silently giving one
    /// server the entire aggregate budget, letting it starve a quiet server.
    #[test]
    fn test_fair_share_applies_by_default_without_explicit_route_count() {
        let mut cache = NotificationCache::new();
        let noisy = ServerId::from_static("noisy");
        let quiet = ServerId::from_static("quiet");

        let quiet_uri: Uri = Uri::from("file:///quiet/only_file.rs");
        cache.store_diagnostics(&quiet, &quiet_uri, Some(1), vec![]);

        // `set_diagnostics_route_count` is deliberately never called here.
        for i in 0..MAX_DIAGNOSTIC_ENTRIES + 50 {
            let uri: Uri = Uri::from(format!("file:///noisy/file{i}.rs"));
            cache.store_diagnostics(&noisy, &uri, Some(1), vec![]);
        }

        assert_eq!(cache.diagnostics_count(), MAX_DIAGNOSTIC_ENTRIES);
        assert!(
            cache.diagnostics(&quiet_uri).is_some(),
            "quiet server's only entry must survive even without ever calling \
             set_diagnostics_route_count"
        );
        let noisy_first: Uri = Uri::from("file:///noisy/file0.rs");
        assert!(
            cache.diagnostics(&noisy_first).is_none(),
            "the noisy server, now auto-derived as one of two servers sharing the budget, \
             must still lose its own oldest entries once over its fair share"
        );
    }

    /// #283: with only one server ever writing, the auto-derived fair-share
    /// count (from `order.len()`) must stay `1`, letting that
    /// server use the whole aggregate budget -- the same as the old default
    /// of `1` when the setter went uncalled, not a regression for the
    /// common single-server case.
    #[test]
    fn test_single_server_gets_full_budget_without_explicit_route_count() {
        let mut cache = NotificationCache::new();

        for i in 0..MAX_DIAGNOSTIC_ENTRIES {
            let uri: Uri = Uri::from(format!("file:///file{i}.rs"));
            cache.store_diagnostics(&test_server(), &uri, Some(1), vec![]);
        }

        assert_eq!(cache.diagnostics_count(), MAX_DIAGNOSTIC_ENTRIES);
    }

    /// #284: when the cache is full and a server's own entry must be
    /// evicted, an entry with an empty (`[]`) diagnostics list -- a file
    /// reported as now clean -- must be evicted ahead of an older entry that
    /// still carries real diagnostics, even though the empty entry is not
    /// that server's strictly-oldest entry.
    #[test]
    fn test_empty_diagnostics_entries_evicted_before_non_empty_ones() {
        let mut cache = NotificationCache::new();
        let server = test_server();

        let important: Uri = Uri::from("file:///important.rs");
        cache.store_diagnostics(
            &server,
            &important,
            Some(1),
            vec![minimal_diagnostic("real error".to_string())],
        );

        // Fill the rest of the budget with empty ("file is clean") entries,
        // all published after `important` and so all newer in eviction
        // order.
        for i in 0..MAX_DIAGNOSTIC_ENTRIES - 1 {
            let uri: Uri = Uri::from(format!("file:///clean{i}.rs"));
            cache.store_diagnostics(&server, &uri, Some(1), vec![]);
        }
        assert_eq!(cache.diagnostics_count(), MAX_DIAGNOSTIC_ENTRIES);

        // One more new URI exceeds the cap: `important` is the strictly
        // oldest entry, but it must survive in favor of the oldest *empty*
        // entry instead.
        let overflow: Uri = Uri::from("file:///overflow.rs");
        cache.store_diagnostics(&server, &overflow, Some(1), vec![]);

        assert!(
            cache.diagnostics(&important).is_some(),
            "a non-empty entry must survive eviction over empty entries, even though it is older"
        );
        let oldest_clean: Uri = Uri::from("file:///clean0.rs");
        assert!(
            cache.diagnostics(&oldest_clean).is_none(),
            "the oldest empty entry must be evicted instead of the older non-empty one"
        );
        assert!(cache.diagnostics(&overflow).is_some());
    }

    /// #284: storing an empty diagnostics list must still create a fully
    /// tracked, cacheable entry -- eviction priority changes which entry is
    /// removed once the cache is full, but does not change what gets stored
    /// in the first place. See the `tracked` field semantics in
    /// `mcp::server::ResourceDiagnosticsResponse` for why callers rely on
    /// this: a `[]` publish for a previously-tracked URI must read back as
    /// "tracked, zero diagnostics", not as untracked.
    #[test]
    fn test_empty_diagnostics_entry_is_still_tracked_until_evicted() {
        let mut cache = NotificationCache::new();
        let uri: Uri = Uri::from("file:///clean.rs");

        cache.store_diagnostics(&test_server(), &uri, Some(1), vec![]);

        let stored = cache.diagnostics(&uri);
        assert!(
            stored.is_some(),
            "an empty-diagnostics entry must still be tracked"
        );
        assert_eq!(stored.unwrap().diagnostics.len(), 0);
    }

    /// #284 S1: an over-share server's own empty ("clean") entry must be
    /// evicted before a *different* over-share server's real diagnostics are
    /// destroyed, even when the fairness-selected victim (the largest
    /// over-share server) itself holds no empty entry of its own.
    #[test]
    fn test_over_share_servers_empty_entry_evicted_before_a_different_servers_real_diagnostic() {
        let mut cache = NotificationCache::new();
        cache.set_diagnostics_route_count(3); // fair share = 333

        let a = ServerId::from_static("a"); // over share, all real diagnostics
        let b = ServerId::from_static("b"); // over share, all empty/clean
        let c = ServerId::from_static("c"); // within share

        for i in 0..500 {
            let uri: Uri = Uri::from(format!("file:///a/file{i}.rs"));
            cache.store_diagnostics(
                &a,
                &uri,
                Some(1),
                vec![minimal_diagnostic(format!("error {i}"))],
            );
        }
        for i in 0..400 {
            let uri: Uri = Uri::from(format!("file:///b/file{i}.rs"));
            cache.store_diagnostics(&b, &uri, Some(1), vec![]);
        }
        for i in 0..100 {
            let uri: Uri = Uri::from(format!("file:///c/file{i}.rs"));
            cache.store_diagnostics(&c, &uri, Some(1), vec![]);
        }
        assert_eq!(cache.diagnostics_count(), MAX_DIAGNOSTIC_ENTRIES);

        // One more write from `a` (the fairness-selected victim, being the
        // largest over-share server) must not destroy any of `a`'s real
        // diagnostics: `b`, also over its share, has an empty entry to give
        // up instead.
        let overflow: Uri = Uri::from("file:///a/overflow.rs");
        cache.store_diagnostics(
            &a,
            &overflow,
            Some(1),
            vec![minimal_diagnostic("overflow error".to_string())],
        );

        for i in 0..500 {
            let uri: Uri = Uri::from(format!("file:///a/file{i}.rs"));
            assert!(
                cache.diagnostics(&uri).is_some(),
                "server a's real diagnostics must all survive; b has an empty entry to lose \
                 instead"
            );
        }
        let b_oldest: Uri = Uri::from("file:///b/file0.rs");
        assert!(
            cache.diagnostics(&b_oldest).is_none(),
            "b's oldest empty entry must be evicted instead of a's real diagnostics"
        );
        assert!(cache.diagnostics(&overflow).is_some());
    }

    /// #284: a URI that transitions non-empty -> empty -> non-empty must not
    /// be treated as still-empty for eviction priority after the second
    /// transition -- emptiness tracking must reflect the *current* state,
    /// not the URI's history.
    #[test]
    fn test_dirty_then_clean_then_dirty_again_updates_emptiness_tracking() {
        let mut cache = NotificationCache::new();
        let server = test_server();
        let uri: Uri = Uri::from("file:///flapping.rs");

        cache.store_diagnostics(
            &server,
            &uri,
            Some(1),
            vec![minimal_diagnostic("first error".to_string())],
        );
        cache.store_diagnostics(&server, &uri, Some(2), vec![]); // now clean
        cache.store_diagnostics(
            &server,
            &uri,
            Some(3),
            vec![minimal_diagnostic("second error".to_string())],
        ); // dirty again

        // Fill the rest of the budget with genuinely empty entries -- if
        // `uri` were still (wrongly) tracked as empty, one of these would be
        // evicted in its place instead of `uri` being left alone.
        for i in 0..MAX_DIAGNOSTIC_ENTRIES - 1 {
            let other: Uri = Uri::from(format!("file:///clean{i}.rs"));
            cache.store_diagnostics(&server, &other, Some(1), vec![]);
        }
        assert_eq!(cache.diagnostics_count(), MAX_DIAGNOSTIC_ENTRIES);

        let overflow: Uri = Uri::from("file:///overflow.rs");
        cache.store_diagnostics(&server, &overflow, Some(1), vec![]);

        let stored = cache.diagnostics(&uri);
        assert!(
            stored.is_some_and(|info| info.diagnostics.len() == 1),
            "the re-dirtied entry must survive and keep its real diagnostic, not be mistaken \
             for an empty entry"
        );
    }

    /// `set_diagnostics_route_count(0)` must clamp to `1`, not panic via
    /// division by zero in `per_server_budget`.
    #[test]
    fn test_set_diagnostics_route_count_zero_clamps_to_one() {
        let mut cache = NotificationCache::new();
        cache.set_diagnostics_route_count(0);

        for i in 0..MAX_DIAGNOSTIC_ENTRIES + 5 {
            let uri: Uri = Uri::from(format!("file:///file{i}.rs"));
            cache.store_diagnostics(&test_server(), &uri, Some(1), vec![]);
        }

        assert_eq!(cache.diagnostics_count(), MAX_DIAGNOSTIC_ENTRIES);
    }

    // Transition logic is unit-tested in `bridge::indexing`; these tests only cover delegation wiring.

    #[test]
    fn test_indexing_state_defaults_unknown() {
        let cache = NotificationCache::new();
        assert_eq!(cache.indexing_state(&test_server()), IndexingState::Unknown);
    }

    #[test]
    fn test_observe_indexing_signal_delegates_to_tracker() {
        let mut cache = NotificationCache::new();
        let server = test_server();
        cache.observe_indexing_signal(
            &server,
            "experimental/serverStatus",
            Some(&serde_json::json!({"quiescent": false})),
        );
        assert_eq!(cache.indexing_state(&server), IndexingState::Loading);
    }

    #[test]
    fn test_reset_indexing_state_delegates_to_tracker() {
        let mut cache = NotificationCache::new();
        let server = test_server();
        cache.observe_indexing_signal(
            &server,
            "experimental/serverStatus",
            Some(&serde_json::json!({"quiescent": false})),
        );
        cache.reset_indexing_state(&server, IndexingReset::Forget);
        assert_eq!(cache.indexing_state(&server), IndexingState::Unknown);
    }

    fn file_uri(path: &str) -> Uri {
        Uri::from(format!("file:///ws/{path}"))
    }

    fn published(source: &str) -> PublishedDiagnosticsUri {
        PublishedDiagnosticsUri::for_test(file_uri(source), file_uri("main.rs"))
    }

    fn diagnostic_at(line: u32, message: &str) -> LspDiagnostic {
        let mut diagnostic = minimal_diagnostic(message.to_owned());
        diagnostic.range.start.line = line;
        diagnostic.range.end.line = line;
        diagnostic
    }

    fn merged(cache: &NotificationCache) -> Option<DiagnosticInfo> {
        cache.diagnostic_sources(&file_uri("main.rs")).merge()
    }

    fn messages(info: &DiagnosticInfo) -> Vec<String> {
        info.diagnostics
            .iter()
            .map(|d| message_as_str(&d.message).to_owned())
            .collect()
    }

    /// The rust-analyzer probe sequence: errors arrive on the alias path and
    /// an empty list on the canonical one.
    #[test]
    fn test_published_alias_errors_survive_empty_canonical_publish() {
        let mut cache = NotificationCache::new();
        let server = test_server();
        let errors = vec![diagnostic_at(1, "e1"), diagnostic_at(2, "e2")];

        cache.store_published_diagnostics(&server, &published("alias.rs"), None, errors);
        cache.store_published_diagnostics(&server, &published("main.rs"), Some(3), vec![]);
        assert_eq!(messages(&merged(&cache).unwrap()), ["e1", "e2"]);

        cache.store_published_diagnostics(&server, &published("main.rs"), Some(4), vec![]);
        assert_eq!(messages(&merged(&cache).unwrap()), ["e1", "e2"]);

        cache.store_published_diagnostics(&server, &published("alias.rs"), None, vec![]);
        assert!(merged(&cache).unwrap().diagnostics.is_empty());
    }

    #[test]
    fn test_published_empty_publish_clears_only_its_own_source() {
        let mut cache = NotificationCache::new();
        let server = test_server();
        cache.store_published_diagnostics(
            &server,
            &published("a1.rs"),
            None,
            vec![diagnostic_at(1, "e1")],
        );
        cache.store_published_diagnostics(
            &server,
            &published("a2.rs"),
            None,
            vec![diagnostic_at(2, "e2")],
        );
        assert_eq!(messages(&merged(&cache).unwrap()), ["e1", "e2"]);

        cache.store_published_diagnostics(&server, &published("a1.rs"), None, vec![]);

        assert_eq!(messages(&merged(&cache).unwrap()), ["e2"]);
    }

    /// Dedup must not depend on duplicates being adjacent after the sort.
    #[test]
    fn test_merge_removes_duplicates_sharing_a_start_with_another_diagnostic() {
        let mut cache = NotificationCache::new();
        let server = test_server();
        let x = diagnostic_at(1, "x");
        let y = diagnostic_at(1, "y");
        cache.store_published_diagnostics(&server, &published("a1.rs"), None, vec![x.clone(), y]);
        cache.store_published_diagnostics(&server, &published("a2.rs"), None, vec![x]);

        assert_eq!(messages(&merged(&cache).unwrap()), ["x", "y"]);
    }

    #[test]
    fn test_merge_orders_by_range_start() {
        let mut cache = NotificationCache::new();
        let server = test_server();
        cache.store_published_diagnostics(
            &server,
            &published("a1.rs"),
            None,
            vec![diagnostic_at(5, "late")],
        );
        cache.store_published_diagnostics(
            &server,
            &published("a2.rs"),
            None,
            vec![diagnostic_at(1, "early")],
        );

        assert_eq!(messages(&merged(&cache).unwrap()), ["early", "late"]);
    }

    #[test]
    fn test_merged_version_is_the_canonical_sources() {
        let mut cache = NotificationCache::new();
        let server = test_server();
        cache.store_published_diagnostics(
            &server,
            &published("main.rs"),
            Some(7),
            vec![diagnostic_at(1, "a")],
        );
        cache.store_published_diagnostics(
            &server,
            &published("alias.rs"),
            None,
            vec![diagnostic_at(2, "b")],
        );
        assert_eq!(
            merged(&cache).unwrap().version.map(DocumentVersion::get),
            Some(7)
        );

        cache.store_published_diagnostics(
            &server,
            &published("main.rs"),
            Some(8),
            vec![diagnostic_at(1, "a")],
        );
        assert_eq!(
            merged(&cache).unwrap().version.map(DocumentVersion::get),
            Some(8)
        );
    }

    #[test]
    fn test_merge_is_bounded_by_the_entry_size_cap() {
        let mut cache = NotificationCache::new();
        let server = test_server();
        let big = "x".repeat(200 * 1024);
        for source in [
            "a1.rs", "a2.rs", "a3.rs", "a4.rs", "a5.rs", "a6.rs", "a7.rs", "a8.rs",
        ] {
            let diagnostics = (0..4)
                .map(|n| diagnostic_at(n, &format!("{source}-{n}-{big}")))
                .collect();
            cache.store_published_diagnostics(&server, &published(source), None, diagnostics);
        }

        let info = merged(&cache).unwrap();

        let bytes = serde_json::to_vec(&info.diagnostics).unwrap().len();
        assert!(bytes <= MAX_DIAGNOSTICS_ENTRY_BYTES, "{bytes} bytes");
    }

    #[test]
    fn test_single_source_is_returned_unchanged() {
        let mut cache = NotificationCache::new();
        cache.store_published_diagnostics(
            &test_server(),
            &published("alias.rs"),
            Some(2),
            vec![diagnostic_at(1, "e")],
        );

        let info = merged(&cache).unwrap();

        assert_eq!(info.uri, file_uri("alias.rs"));
        assert_eq!(info.version.map(DocumentVersion::get), Some(2));
    }

    #[test]
    fn test_ninth_source_is_dropped_without_an_orphan_entry() {
        let mut cache = NotificationCache::new();
        let server = test_server();
        for n in 0..MAX_SOURCES_PER_FILE {
            cache.store_published_diagnostics(
                &server,
                &published(&format!("a{n}.rs")),
                None,
                vec![diagnostic_at(1, "e")],
            );
        }

        cache.store_published_diagnostics(
            &server,
            &published("extra.rs"),
            None,
            vec![diagnostic_at(9, "extra")],
        );

        assert_eq!(cache.diagnostics_count(), MAX_SOURCES_PER_FILE);
        assert!(cache.diagnostics(&file_uri("extra.rs")).is_none());
        assert!(!messages(&merged(&cache).unwrap()).contains(&"extra".to_owned()));
    }

    /// #704: a file whose newer publish was lost reads as lost, not as the
    /// older content or as pending, until the owner publishes it again.
    #[test]
    fn test_lost_publish_replaces_older_entry_with_a_lost_mark() {
        let mut cache = NotificationCache::new();
        let server = test_server();
        let uri = file_uri("a.rs");
        cache.store_diagnostics(&server, &uri, None, vec![diagnostic_at(1, "old")]);

        let changed = cache.record_lost_files(&server, &[DiagnosticsKey::of(&uri)]);

        assert_eq!(changed, [DiagnosticsKey::of(&uri)]);
        assert!(!cache.has_diagnostics(&uri));
        assert_eq!(
            cache.availability(&uri, Some(&server)),
            DiagnosticsAvailability::Evicted
        );
        cache.store_diagnostics(&server, &uri, None, vec![diagnostic_at(2, "new")]);
        assert_eq!(
            cache.availability(&uri, Some(&server)),
            DiagnosticsAvailability::Published
        );
        cache.assert_consistent();
    }

    /// An unnamed loss marks the owner so an unknown file reads as possibly evicted.
    #[test]
    fn test_unnamed_lost_publishes_make_unknown_files_read_evicted() {
        let mut cache = NotificationCache::new();
        let server = test_server();

        cache.record_unnamed_loss(&server);

        assert_eq!(
            cache.availability(&file_uri("unknown.rs"), Some(&server)),
            DiagnosticsAvailability::Evicted
        );
    }

    /// #692: a refused publish is reported as dropped, so nothing is announced for it.
    #[test]
    fn test_a_publish_over_the_source_cap_is_reported_as_dropped() {
        let mut cache = NotificationCache::new();
        let server = test_server();
        for n in 0..MAX_SOURCES_PER_FILE {
            let write = cache.write_published_diagnostics(
                &server,
                &published(&format!("a{n}.rs")),
                None,
                BoundedDiagnostics::new(&file_uri("a.rs"), vec![diagnostic_at(1, "e")]),
            );
            std::assert_matches!(write, PushWrite::Stored { .. });
        }

        let write = cache.write_published_diagnostics(
            &server,
            &published("extra.rs"),
            None,
            BoundedDiagnostics::new(&file_uri("a.rs"), vec![diagnostic_at(9, "extra")]),
        );

        std::assert_matches!(write, PushWrite::Dropped { .. });
    }

    #[test]
    fn test_republishing_an_indexed_source_at_the_cap_is_accepted() {
        let mut cache = NotificationCache::new();
        let server = test_server();
        for n in 0..MAX_SOURCES_PER_FILE {
            cache.store_published_diagnostics(
                &server,
                &published(&format!("a{n}.rs")),
                None,
                vec![],
            );
        }

        cache.store_published_diagnostics(
            &server,
            &published("a0.rs"),
            None,
            vec![diagnostic_at(1, "again")],
        );

        assert_eq!(messages(&merged(&cache).unwrap()), ["again"]);
    }

    #[test]
    fn test_clear_server_diagnostics_prunes_the_source_index() {
        let mut cache = NotificationCache::new();
        let server = test_server();
        cache.store_published_diagnostics(
            &server,
            &published("a1.rs"),
            None,
            vec![diagnostic_at(1, "e")],
        );

        cache.clear_server_diagnostics(&server);

        cache.assert_consistent();
        assert!(cache.files.is_empty());
        assert!(!cache.has_diagnostics(&file_uri("main.rs")));
        assert!(merged(&cache).is_none());
    }

    #[test]
    fn test_eviction_prunes_the_source_index() {
        let mut cache = NotificationCache::new();
        let server = test_server();
        cache.store_published_diagnostics(&server, &published("a1.rs"), None, vec![]);
        for n in 0..MAX_DIAGNOSTIC_ENTRIES {
            let uri = Uri::from(format!("file:///other/{n}.rs"));
            cache.store_diagnostics(&server, &uri, None, vec![]);
        }

        assert!(cache.diagnostics(&file_uri("a1.rs")).is_none());
        cache.assert_consistent();
        assert!(
            !cache
                .files
                .contains_key(&DiagnosticsKey::of(&file_uri("main.rs")))
        );
    }

    #[test]
    fn test_diagnostics_owner_resolves_through_the_source_index() {
        let mut cache = NotificationCache::new();
        let server = test_server();
        cache.store_published_diagnostics(&server, &published("alias.rs"), None, vec![]);

        assert_eq!(cache.diagnostics_owner(&file_uri("main.rs")), Some(&server));
    }

    /// S5: a server fanning one file out over many spellings must not be able
    /// to suppress the canonical publishes.
    #[test]
    fn test_canonical_source_is_admitted_when_aliases_fill_the_cap() {
        let mut cache = NotificationCache::new();
        let server = test_server();
        for n in 0..MAX_SOURCES_PER_FILE {
            cache.store_published_diagnostics(
                &server,
                &published(&format!("a{n}.rs")),
                None,
                vec![diagnostic_at(
                    u32::try_from(n).unwrap(),
                    &format!("alias{n}"),
                )],
            );
        }

        cache.store_published_diagnostics(
            &server,
            &published("main.rs"),
            Some(5),
            vec![diagnostic_at(99, "canonical")],
        );

        let info = merged(&cache).unwrap();
        let shown = messages(&info);
        assert!(shown.contains(&"canonical".to_owned()), "{shown:?}");
        assert!(
            !shown.contains(&"alias0".to_owned()),
            "oldest alias is evicted"
        );
        assert_eq!(shown.len(), MAX_SOURCES_PER_FILE);
        assert_eq!(info.version.map(DocumentVersion::get), Some(5));
        assert_eq!(cache.diagnostics_count(), MAX_SOURCES_PER_FILE);
    }

    #[test]
    fn test_alias_beyond_the_cap_is_still_dropped_when_canonical_is_present() {
        let mut cache = NotificationCache::new();
        let server = test_server();
        cache.store_published_diagnostics(&server, &published("main.rs"), None, vec![]);
        for n in 0..MAX_SOURCES_PER_FILE - 1 {
            cache.store_published_diagnostics(
                &server,
                &published(&format!("a{n}.rs")),
                None,
                vec![],
            );
        }

        cache.store_published_diagnostics(
            &server,
            &published("extra.rs"),
            None,
            vec![diagnostic_at(1, "x")],
        );

        assert!(cache.diagnostics(&file_uri("extra.rs")).is_none());
        assert!(cache.diagnostics(&file_uri("main.rs")).is_some());
    }

    /// The merge must not compare every diagnostic against every other one
    /// sharing its start: 8 sources of 3000 same-start diagnostics each.
    #[test]
    fn test_merge_handles_many_same_start_diagnostics_across_sources() {
        const PER_SOURCE: u32 = 3000;
        let mut cache = NotificationCache::new();
        let server = test_server();
        for source in 0..MAX_SOURCES_PER_FILE {
            let diagnostics = (0..PER_SOURCE)
                .map(|n| diagnostic_at(0, &format!("diagnostic-{n}")))
                .collect();
            cache.store_published_diagnostics(
                &server,
                &published(&format!("a{source}.rs")),
                None,
                diagnostics,
            );
        }

        let info = merged(&cache).unwrap();

        assert_eq!(info.diagnostics.len(), PER_SOURCE as usize);
    }

    /// Diagnostics equal in range and message but differing elsewhere are
    /// distinct and both survive the merge.
    #[test]
    fn test_merge_keeps_diagnostics_that_differ_outside_range_and_message() {
        let mut cache = NotificationCache::new();
        let server = test_server();
        let plain = diagnostic_at(1, "same");
        let mut coded = diagnostic_at(1, "same");
        coded.code = Some(lsp_types::Code::String("E1".to_owned()));
        cache.store_published_diagnostics(&server, &published("a1.rs"), None, vec![plain]);
        cache.store_published_diagnostics(&server, &published("a2.rs"), None, vec![coded]);

        assert_eq!(merged(&cache).unwrap().diagnostics.len(), 2);
    }

    #[test]
    fn test_clear_server_diagnostics_leaves_no_dangling_file_index() {
        let mut cache = NotificationCache::new();
        let (a, b) = (ServerId::from_static("a"), ServerId::from_static("b"));
        cache.store_published_diagnostics(&a, &published("a1.rs"), None, vec![]);
        cache.store_published_diagnostics(
            &b,
            &published("main.rs"),
            None,
            vec![diagnostic_at(1, "e")],
        );

        cache.clear_server_diagnostics(&a);

        cache.assert_consistent();
        assert_eq!(cache.files.len(), 1);
        assert!(cache.diagnostics(&file_uri("main.rs")).is_some());
        assert!(cache.diagnostics(&file_uri("a1.rs")).is_none());
    }

    #[derive(Debug, Clone)]
    enum CacheOp {
        Publish {
            server: u8,
            file: u8,
            alias: Option<u8>,
            empty: bool,
        },
        Clear {
            server: u8,
        },
    }

    fn cache_op() -> impl proptest::strategy::Strategy<Value = CacheOp> {
        use proptest::prelude::*;

        prop_oneof![
            4 => (0..3u8, 0..3u8, proptest::option::of(0..3u8), any::<bool>()).prop_map(
                |(server, file, alias, empty)| CacheOp::Publish { server, file, alias, empty }
            ),
            1 => (0..3u8).prop_map(|server| CacheOp::Clear { server }),
        ]
    }

    proptest::proptest! {
        #[test]
        fn cache_indices_stay_consistent_under_random_operations(
            ops in proptest::collection::vec(cache_op(), 0..60)
        ) {
            let mut cache = NotificationCache::new();
            for op in ops {
                match op {
                    CacheOp::Publish { server, file, alias, empty } => {
                        let canonical = file_uri(&format!("f{file}.rs"));
                        let source = alias.map_or_else(
                            || canonical.clone(),
                            |n| file_uri(&format!("alias{n}.rs")),
                        );
                        let diagnostics = if empty { vec![] } else { vec![diagnostic_at(1, "e")] };
                        cache.store_published_diagnostics(
                            &ServerId::new(format!("s{server}")).unwrap(),
                            &PublishedDiagnosticsUri::for_test(source, canonical),
                            None,
                            diagnostics,
                        );
                    }
                    CacheOp::Clear { server } => {
                        cache.clear_server_diagnostics(&ServerId::new(format!("s{server}")).unwrap());
                    }
                }
                cache.assert_consistent();
            }
        }
    }

    fn first_uri() -> Uri {
        Uri::from("file:///first.rs")
    }

    fn error_diagnostic() -> LspDiagnostic {
        LspDiagnostic {
            severity: Some(lsp_types::DiagnosticSeverity::Error),
            message: "broken".to_owned().into(),
            ..LspDiagnostic::default()
        }
    }

    /// Fills the cache with `MAX_DIAGNOSTIC_ENTRIES` entries: `file:///first.rs`
    /// (empty or not, per `first_empty`) then non-empty fillers.
    fn full_cache(first_empty: bool) -> NotificationCache {
        let mut cache = NotificationCache::new();
        let first: Uri = Uri::from("file:///first.rs");
        let diagnostics = if first_empty {
            vec![]
        } else {
            vec![error_diagnostic()]
        };
        cache.store_diagnostics(&test_server(), &first, None, diagnostics);
        for i in 1..MAX_DIAGNOSTIC_ENTRIES {
            let uri: Uri = Uri::from(format!("file:///filler{i}.rs"));
            cache.store_diagnostics(&test_server(), &uri, None, vec![error_diagnostic()]);
        }
        cache
    }

    fn evict_one(cache: &mut NotificationCache) {
        let overflow: Uri = Uri::from("file:///overflow.rs");
        cache.store_diagnostics(&test_server(), &overflow, None, vec![error_diagnostic()]);
    }

    #[test]
    fn test_evicted_empty_entry_is_listen_replayable() {
        let mut cache = full_cache(true);
        assert!(cache.is_listen_replayable(&first_uri()));
        evict_one(&mut cache);
        assert!(!cache.has_diagnostics(&first_uri()));
        assert!(cache.is_listen_replayable(&first_uri()));
        assert!(!cache.is_listen_replayable(&Uri::from("file:///unrelated.rs")));
    }

    fn write_error(cache: &mut NotificationCache, file: &str) -> PushWrite {
        let uri = Uri::from(file);
        cache.write_published_diagnostics(
            &test_server(),
            &PublishedDiagnosticsUri::for_test(uri.clone(), uri),
            None,
            BoundedDiagnostics::new(&Uri::from(file), vec![error_diagnostic()]),
        )
    }

    /// #649: a push that needs room names the file whose entry it evicted.
    #[test]
    fn test_a_push_reports_the_file_it_evicts() {
        let mut cache = full_cache(false);
        let write = write_error(&mut cache, "file:///overflow.rs");
        assert_eq!(write.evicted(), [DiagnosticsKey::of(&first_uri())]);
        assert!(!cache.has_diagnostics(&first_uri()));
    }

    /// #649: replacing a cached entry, or writing below capacity, evicts nothing.
    #[test]
    fn test_a_push_that_needs_no_room_reports_no_eviction() {
        let mut cache = full_cache(false);
        assert!(
            write_error(&mut cache, "file:///first.rs")
                .evicted()
                .is_empty()
        );
        let mut roomy = NotificationCache::new();
        assert!(write_error(&mut roomy, "file:///a.rs").evicted().is_empty());
    }

    fn route() -> ServerId {
        test_server()
    }

    /// #666: a clean file whose entry was evicted still reads as published
    /// and clean, not as pending.
    #[test]
    fn test_evicted_clean_entry_reads_as_published() {
        let mut cache = full_cache(true);
        assert!(cache.has_diagnostics(&first_uri()));
        evict_one(&mut cache);
        assert!(!cache.has_diagnostics(&first_uri()));
        assert_eq!(
            cache.availability(&first_uri(), Some(&route())),
            DiagnosticsAvailability::Published
        );
    }

    /// #666: a file whose diagnostics were evicted reads as evicted: what the
    /// server said is unknown, which is not the same as nothing published.
    #[test]
    fn test_evicted_non_empty_entry_reads_as_evicted() {
        let mut cache = full_cache(false);
        evict_one(&mut cache);
        assert_eq!(
            cache.availability(&first_uri(), Some(&route())),
            DiagnosticsAvailability::Evicted
        );
    }

    #[test]
    fn test_unpublished_file_reads_as_pending_even_next_to_evictions() {
        let mut cache = full_cache(false);
        evict_one(&mut cache);
        let unseen = Uri::from("file:///never-published.rs");
        assert_eq!(
            cache.availability(&unseen, Some(&route())),
            DiagnosticsAvailability::Pending
        );
        assert_eq!(
            cache.availability(&unseen, None),
            DiagnosticsAvailability::Pending
        );
    }

    /// #666: a respawn forgets what was evicted along with the diagnostics, so
    /// the file reads as pending again until the replacement publishes.
    #[test]
    fn test_clearing_a_server_forgets_its_eviction_marks() {
        let mut cache = full_cache(false);
        evict_one(&mut cache);
        drop(cache.clear_server_diagnostics(&route()));
        assert_eq!(
            cache.availability(&first_uri(), Some(&route())),
            DiagnosticsAvailability::Pending
        );
    }

    #[test]
    fn test_a_new_publish_replaces_the_mark_of_its_file() {
        let mut cache = full_cache(true);
        evict_one(&mut cache);
        let first: Uri = Uri::from("file:///first.rs");
        cache.store_diagnostics(&test_server(), &first, None, vec![error_diagnostic()]);
        assert_eq!(
            cache.availability(&first_uri(), None),
            DiagnosticsAvailability::Published
        );
        assert!(
            cache
                .eviction_marks
                .content(&DiagnosticsKey::of(&first))
                .is_none()
        );
    }

    /// Lost content is never downgraded to clean by a later clean eviction of
    /// the same file.
    #[test]
    fn test_lost_content_survives_a_later_clean_eviction_of_the_file() {
        let mut marks = EvictionMarks::default();
        let file = DiagnosticsKey::of(&first_uri());
        marks.record(file.clone(), route(), EvictedContent::Lost);
        marks.record(file.clone(), route(), EvictedContent::Clean);
        assert_eq!(marks.content(&file), Some(EvictedContent::Lost));
    }

    fn overflowed_after_churn() -> NotificationCache {
        let mut cache = full_cache(false);
        for i in 0..=MAX_EVICTION_MARKS {
            drop(write_error(&mut cache, &format!("file:///churn{i}.rs")));
        }
        assert!(cache.eviction_marks.has_overflowed(&route()));
        cache
    }

    /// #680: the overflow ends with the owner's next accepted push, so a file
    /// forgotten earlier reads as pending again.
    #[test]
    fn test_overflow_ends_with_the_owners_next_accepted_push() {
        let mut cache = NotificationCache::new();
        cache.eviction_marks.overflowed.insert(route());
        let unseen = Uri::from("file:///never-published.rs");
        assert_eq!(
            cache.availability(&unseen, Some(&route())),
            DiagnosticsAvailability::Evicted
        );

        drop(write_error(&mut cache, "file:///fresh.rs"));

        assert!(!cache.eviction_marks.has_overflowed(&route()));
        assert_eq!(
            cache.availability(&unseen, Some(&route())),
            DiagnosticsAvailability::Pending
        );
    }

    /// #680: a pull is a write too, and another server's write leaves the
    /// overflow alone.
    #[test]
    fn test_overflow_ends_with_the_owners_next_accepted_pull_only() {
        let mut cache = NotificationCache::new();
        cache.eviction_marks.overflowed.insert(route());
        let other = ServerId::from_static("other-server");
        cache.store_pulled_for_test(&other, &Uri::from("file:///other.rs"), Vec::new());
        assert!(cache.eviction_marks.has_overflowed(&route()));

        cache.store_pulled_for_test(&route(), &Uri::from("file:///pulled.rs"), Vec::new());
        assert!(!cache.eviction_marks.has_overflowed(&route()));
    }

    /// #680: the clear runs before the write's own evictions, so a write that
    /// evicts into full marks leaves the server overflowed, and one that needs
    /// no room ends it.
    #[test]
    fn test_overflow_clear_precedes_the_evictions_of_the_same_write() {
        let mut cache = overflowed_after_churn();
        drop(write_error(&mut cache, "file:///another-new.rs"));
        assert!(cache.eviction_marks.has_overflowed(&route()));

        drop(write_error(&mut cache, "file:///another-new.rs"));
        assert!(!cache.eviction_marks.has_overflowed(&route()));
        cache.assert_consistent();
    }

    /// #666 eviction pressure: once more files were evicted than the marks
    /// remember, a file without a mark is reported as possibly evicted for the
    /// server that lost marks, and still as pending for any other route.
    #[test]
    fn test_overflowing_the_marks_makes_unmarked_files_read_as_evicted_for_that_server() {
        let mut cache = full_cache(false);
        for i in 0..=MAX_EVICTION_MARKS {
            drop(write_error(&mut cache, &format!("file:///churn{i}.rs")));
        }
        assert!(cache.eviction_marks.has_overflowed(&route()));
        assert!(cache.eviction_marks.by_file.len() <= MAX_EVICTION_MARKS);
        assert!(cache.eviction_marks.order.len() <= MAX_EVICTION_MARKS);
        cache.assert_consistent();

        assert_eq!(
            cache.availability(&first_uri(), Some(&route())),
            DiagnosticsAvailability::Evicted,
            "its mark was the oldest, forgotten"
        );
        let unseen = Uri::from("file:///never-published.rs");
        assert_eq!(
            cache.availability(&unseen, Some(&route())),
            DiagnosticsAvailability::Evicted
        );
        assert_eq!(
            cache.availability(&unseen, Some(&ServerId::from_static("other"))),
            DiagnosticsAvailability::Pending
        );

        drop(cache.clear_server_diagnostics(&route()));
        assert_eq!(
            cache.availability(&unseen, Some(&route())),
            DiagnosticsAvailability::Pending
        );
    }

    #[test]
    fn test_evicted_non_empty_entry_is_not_replayable() {
        let mut cache = full_cache(false);
        evict_one(&mut cache);
        assert!(!cache.has_diagnostics(&first_uri()));
        assert!(!cache.is_listen_replayable(&first_uri()));
    }

    #[test]
    fn test_recached_entry_leaves_the_replay_ring_view() {
        let mut cache = full_cache(true);
        evict_one(&mut cache);
        let first: Uri = Uri::from("file:///first.rs");
        cache.store_diagnostics(&test_server(), &first, None, vec![error_diagnostic()]);
        assert!(cache.has_diagnostics(&first_uri()));
        assert!(!cache.was_recently_evicted(&first_uri(), std::time::Instant::now()));
    }

    #[test]
    fn test_eviction_replay_expires_after_the_window() {
        let mut cache = NotificationCache::new();
        let now = std::time::Instant::now();
        let gone = Uri::from("file:///gone.rs");
        cache.record_empty_eviction(DiagnosticsKey::of(&gone), now);
        assert!(cache.was_recently_evicted(&gone, now + EVICTION_REPLAY_WINDOW));
        assert!(!cache.was_recently_evicted(
            &gone,
            now + EVICTION_REPLAY_WINDOW + std::time::Duration::from_secs(1)
        ));
    }

    #[test]
    fn test_eviction_record_is_bounded_and_keeps_the_newest() {
        let mut cache = NotificationCache::new();
        let now = std::time::Instant::now();
        for i in 0..MAX_RECENT_EVICTIONS + 44 {
            let gone = Uri::from(format!("file:///gone{i}.rs"));
            cache.record_empty_eviction(
                DiagnosticsKey::of(&gone),
                now + std::time::Duration::from_millis(u64::try_from(i).unwrap()),
            );
        }
        assert_eq!(cache.recent_evictions.len(), MAX_RECENT_EVICTIONS);
        let at = now + std::time::Duration::from_secs(1);
        assert!(!cache.was_recently_evicted(&Uri::from("file:///gone0.rs"), at));
        assert!(!cache.was_recently_evicted(&Uri::from("file:///gone43.rs"), at));
        assert!(cache.was_recently_evicted(&Uri::from("file:///gone44.rs"), at));
        let newest = MAX_RECENT_EVICTIONS + 43;
        assert!(cache.was_recently_evicted(&Uri::from(format!("file:///gone{newest}.rs")), at));
    }

    #[test]
    fn test_clearing_a_full_cache_keeps_every_empty_clear_replayable() {
        let mut cache = NotificationCache::new();
        let server = test_server();
        let uris: Vec<Uri> = (0..MAX_DIAGNOSTIC_ENTRIES)
            .map(|i| Uri::from(format!("file:///clean{i}.rs")))
            .collect();
        for uri in &uris {
            cache.store_diagnostics(&server, uri, None, vec![]);
        }

        cache.clear_server_diagnostics(&server);

        assert!(uris.iter().all(|uri| cache.is_listen_replayable(uri)));
    }

    #[test]
    fn test_eviction_order_stays_within_twice_the_record_under_churn() {
        let mut cache = NotificationCache::new();
        let now = std::time::Instant::now();
        let keys: Vec<DiagnosticsKey> = (0..3)
            .map(|i| DiagnosticsKey::of(&Uri::from(format!("file:///hot{i}.rs"))))
            .collect();
        for tick in 0..10_000u64 {
            let key = keys[usize::try_from(tick % 3).unwrap()].clone();
            cache.record_empty_eviction(key, now + std::time::Duration::from_micros(tick));
            let record = &cache.recent_evictions;
            assert!(record.at.len() <= MAX_RECENT_EVICTIONS);
            assert!(record.order.len() <= 2 * record.at.len());
        }
        assert_eq!(cache.recent_evictions.len(), 3);
    }

    #[test]
    fn test_eviction_record_stays_bounded_under_churn_past_the_cap() {
        const KEYS: usize = MAX_RECENT_EVICTIONS + 300;
        let mut cache = NotificationCache::new();
        let now = std::time::Instant::now();
        let keys: Vec<DiagnosticsKey> = (0..KEYS)
            .map(|i| DiagnosticsKey::of(&Uri::from(format!("file:///churn{i}.rs"))))
            .collect();
        for tick in 0..KEYS * 8 {
            let key = keys[tick % KEYS].clone();
            let at = now + std::time::Duration::from_micros(u64::try_from(tick).unwrap());
            cache.record_empty_eviction(key, at);
            let record = &cache.recent_evictions;
            assert!(record.at.len() <= MAX_RECENT_EVICTIONS);
            assert!(record.order.len() <= 2 * record.at.len() + 1);
        }
        assert_eq!(cache.recent_evictions.len(), MAX_RECENT_EVICTIONS);
    }

    #[test]
    fn test_compaction_keeps_the_oldest_first_expiry_order() {
        let mut record = EvictionRecord::default();
        let now = std::time::Instant::now();
        let a = DiagnosticsKey::of(&Uri::from("file:///a.rs"));
        let b = DiagnosticsKey::of(&Uri::from("file:///b.rs"));
        record.record(a.clone(), now);
        record.record(b.clone(), now + std::time::Duration::from_secs(1));
        record.record(a.clone(), now + std::time::Duration::from_secs(2));
        record.record(b.clone(), now + std::time::Duration::from_secs(3));
        record.compact();
        let order: Vec<_> = record.order.iter().map(|(key, _)| key.clone()).collect();
        assert_eq!(order, vec![a, b]);
    }

    #[test]
    fn test_eviction_record_overflow_warns_once_per_window() {
        use tracing_subscriber::layer::SubscriberExt as _;

        let mut record = EvictionRecord::default();
        let now = std::time::Instant::now();
        let captured = CapturedLogs::default();
        let subscriber = tracing_subscriber::registry().with(captured.clone());
        let guard = tracing::subscriber::set_default(subscriber);
        for i in 0..MAX_RECENT_EVICTIONS + 10 {
            let key = DiagnosticsKey::of(&Uri::from(format!("file:///gone{i}.rs")));
            record.record(
                key,
                now + std::time::Duration::from_millis(u64::try_from(i).unwrap()),
            );
        }
        drop(guard);

        let warnings = captured
            .messages()
            .iter()
            .filter(|m| m.contains("diagnostics clears evicted"))
            .count();
        assert_eq!(warnings, 1);
    }

    #[test]
    fn test_eviction_record_deduplicates_and_prunes_expired_entries() {
        let mut cache = NotificationCache::new();
        let now = std::time::Instant::now();
        let a = DiagnosticsKey::of(&Uri::from("file:///a.rs"));
        cache.record_empty_eviction(a.clone(), now);
        cache.record_empty_eviction(a, now);
        assert_eq!(cache.recent_evictions.len(), 1);
        let later = now + EVICTION_REPLAY_WINDOW + std::time::Duration::from_secs(1);
        cache.record_empty_eviction(DiagnosticsKey::of(&Uri::from("file:///b.rs")), later);
        assert_eq!(cache.recent_evictions.len(), 1);
    }

    #[test]
    fn test_alias_eviction_of_an_empty_entry_is_recorded() {
        let mut cache = NotificationCache::new();
        let server = test_server();
        for n in 0..MAX_SOURCES_PER_FILE {
            cache.store_published_diagnostics(
                &server,
                &published(&format!("a{n}.rs")),
                None,
                vec![],
            );
        }
        assert!(cache.recent_evictions.is_empty());

        cache.store_published_diagnostics(
            &server,
            &PublishedDiagnosticsUri::for_test(file_uri("main.rs"), file_uri("main.rs")),
            None,
            vec![diagnostic_at(1, "e")],
        );

        assert!(cache.diagnostics(&file_uri("a0.rs")).is_none());
        assert_eq!(cache.recent_evictions.len(), 1);
        assert!(cache.is_listen_replayable(&file_uri("main.rs")));
    }

    #[test]
    fn test_clearing_a_server_records_its_empty_entries() {
        let mut cache = NotificationCache::new();
        let empty = file_uri("empty.rs");
        let broken = file_uri("broken.rs");
        cache.store_diagnostics(&test_server(), &empty, None, vec![]);
        cache.store_diagnostics(&test_server(), &broken, None, vec![error_diagnostic()]);

        let cleared = cache.clear_server_diagnostics(&test_server());

        assert_eq!(cleared.len(), 2);
        assert!(cache.is_listen_replayable(&empty));
        assert!(!cache.is_listen_replayable(&broken));
    }
}