php-lsp 0.27.0

A PHP Language Server Protocol implementation
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
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
use std::collections::HashSet;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};

use arc_swap::{ArcSwap, ArcSwapOption};

use dashmap::{DashMap, DashSet};
use mir_analyzer::ReferenceIncludes;
use salsa::Setter;
use tower_lsp_server::ls_types::{SemanticToken, Uri};

use crate::db::mir_queries::{LspWorkspace, LspWsFile};
use crate::document::ast::ParsedDoc;
use crate::document::cache_registry::{AnalysisCacheEntry, CacheRegistry};
use crate::index::file_index::FileIndex;
use crate::lang::autoload::Psr4Map;

/// A write invalidated a read and every bounded retry; the client should re-request.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ContentModified;

impl From<ContentModified> for tower_lsp_server::jsonrpc::Error {
    fn from(_: ContentModified) -> Self {
        tower_lsp_server::jsonrpc::Error::new(tower_lsp_server::jsonrpc::ErrorCode::ContentModified)
    }
}

const SNAPSHOT_ATTEMPTS: usize = 3;
/// Consecutive failed passes over one warm-sweep chunk before it is skipped.
const WARM_CHUNK_ATTEMPTS: usize = 5;

/// Files per mir pass: 32 per core, up to 16 cores. A pass fans out across
/// cores, so a small chunk leaves workers idle at its tail and repeats the
/// per-pass setup (on Symfony, 32 files cost 3x the time per file of 256).
fn warm_chunk_size() -> usize {
    32 * std::thread::available_parallelism().map_or(1, |n| n.get().min(16))
}

/// Drives `queue` through `pass` in chunks of `chunk_size`; see [`DocumentStore::run_warm_queue`].
fn run_chunks(
    queue: &[Arc<str>],
    chunk_size: usize,
    cancel: &mir_analyzer::IndexCancel,
    progress: Option<&tokio::sync::mpsc::UnboundedSender<(u32, u32)>>,
    yield_to_interactive: impl Fn(),
    pass: impl Fn(&[Arc<str>]) -> bool,
) -> bool {
    // Chunk size trades sweep throughput against how often the queue reaches
    // a `yield_to_interactive` boundary. Each boundary can sleep up to 500 ms
    // while a request is in flight, so shrinking the chunk multiplies the
    // worst-case stall rather than improving responsiveness.
    let total = queue.len() as u32;
    let mut done: u32 = 0;
    let mut all_settled = true;
    'chunks: for chunk in queue.chunks(chunk_size) {
        if cancel.is_cancelled() {
            all_settled = false;
            break;
        }
        yield_to_interactive();
        // A concurrent write (e.g. another file being ingested) can land
        // mid-chunk and cancel the analysis snapshot, so a failed pass is
        // retried — but only a bounded number of times: a pass that fails
        // without any writer (e.g. a poisoned salsa revision) never succeeds
        // on retry and would pin a core. A skipped chunk leaves the sweep
        // unsettled so completion is not published.
        let mut settled = false;
        for _ in 0..WARM_CHUNK_ATTEMPTS {
            if cancel.is_cancelled() {
                all_settled = false;
                break 'chunks;
            }
            if pass(chunk) {
                settled = true;
                break;
            }
        }
        if settled {
            done = done.saturating_add(chunk.len() as u32);
            if let Some(tx) = progress {
                let _ = tx.send((done, total));
            }
        } else {
            all_settled = false;
        }
    }
    all_settled
}

/// `(file, 0-based line, start column, end column)`.
pub type RefLocation = (Arc<str>, u32, u32, u32);

/// `(implementing class, file, range)`.
pub type MethodImplSite = (Arc<str>, Arc<str>, mir_analyzer::Range);

pub struct DocumentStore {
    /// Per-file caches with unified eviction logic. See [`CacheRegistry`].
    caches: CacheRegistry,

    // ── Salsa-input storage ────────────────────────────────────────────────
    // Phase E4: `DocumentStore` is now a pure salsa-input wrapper. Open-file
    // state (live text, version token, parse-diagnostics cache) lives on
    // `Backend` in its `open_files` map; the set of files tracked by salsa
    // is exactly `source_files.keys()`.
    /// `Uri -> LspWsFile` lookup on the shared mir db. Each `LspWsFile` pairs
    /// mir's `SourceFile` (the shared text input) with the optional warm-start
    /// `cached_index`. Created/updated through the `AnalysisSession`'s
    /// `with_db_mut` under the db write lock; reads run on cheap snapshot clones.
    lsp_ws_files: DashMap<Uri, LspWsFile>,
    /// URIs that have been removed. Re-opening a deleted URI un-deletes it here
    /// and reuses the existing `LspWsFile` handle.
    deleted_uris: DashSet<Uri>,
    /// Set to `true` when the set of tracked files changes (add or remove).
    /// `sync_workspace_files` skips the collect/sort/compare path when this
    /// is `false`, avoiding a lock acquisition on every LSP request.
    workspace_files_dirty: AtomicBool,
    /// Cached result of `workspace_file_paths()`. `None` means stale/never
    /// built — cleared by `mark_workspace_files_dirty` rather than shared
    /// with `workspace_files_dirty` itself, since `sync_workspace_files`
    /// destructively consumes that flag (`swap(false, ..)`) and a second
    /// consumer reading it would race for the same signal.
    workspace_file_paths_cache: ArcSwapOption<Vec<Arc<str>>>,
    /// Diagnostic counter: incremented once per call to
    /// `resolve_reachability_queries`, i.e. once per actual workspace scan
    /// pass — regardless of how many queries are batched into that pass.
    /// Lets tests assert that batching N symbols' reachability narrowing
    /// (e.g. all of one file's code lenses) pays one scan, not N.
    reachability_scan_passes: AtomicU64,
    /// Memoized [`Self::resolve_reachability_queries`] results, keyed on the
    /// query plus [`Self::write_revision`]. Without this, a warm repeat
    /// still pays the O(workspace files) outer loop every call even when
    /// mir's `ClassMentionIndex` avoids the expensive text scan inside it —
    /// cheap per-file work times tens of thousands of files is still
    /// measurable (confirmed via `references_all_kinds` bench: ~1.5-2ms on
    /// a 36k-file workspace, for exactly the query shapes that reach this
    /// function — `class`/`function`/`global constant`/a narrowable
    /// `method` — while shapes answered by a direct index lookup, never
    /// reaching this function at all, stayed sub-0.5ms). Bounded by total
    /// cached FILE entries (`reachability_result_cache_files`), not entry
    /// count, same discipline as mir's own per-file mention cache.
    reachability_result_cache: ReachabilityResultCache,
    /// Sum of `.len()` across every `reachability_result_cache` value.
    reachability_result_cache_files: AtomicU64,
    /// Per-URI lock so concurrent callers computing the same uncached file's
    /// analysis (`cached_analysis_cancellable`) serialize onto one
    /// computation instead of each redoing the full mir pass — e.g. `did_open`'s
    /// diagnostics trigger racing a fast-following hover on a large,
    /// just-opened file. Entries are never removed: bounded by the number of
    /// distinct files ever analyzed, the same order of magnitude as
    /// `lsp_ws_files`.
    analysis_inflight: DashMap<Uri, Arc<Mutex<()>>>,
    /// Diagnostic counter: incremented once per real `FileAnalyzer::analyze`
    /// run in `cached_analysis_cancellable` (never on a cache hit). Lets
    /// tests assert that concurrent callers racing for the same uncached
    /// file's analysis (see `analysis_inflight`) compute it once, not once
    /// per caller.
    analysis_compute_count: AtomicU64,
    /// `LspWorkspace` salsa input on the shared mir db: the project-file scoping
    /// set aggregated by `workspace_index`. Created lazily on first sync (the db
    /// is owned by the lazily-built `AnalysisSession`).
    lsp_workspace: Mutex<Option<LspWorkspace>>,
    /// Shared PSR-4 namespace-to-path map. Shared with `Backend` via `Arc`
    /// so updates from `initialized` (when composer.json is loaded) are
    /// visible here without any additional wiring. `ArcSwap` makes reads
    /// lock-free — a poisoned guard can no longer crash a request handler.
    psr4: Arc<ArcSwap<Psr4Map>>,
    /// `(target PHP version, cached AnalysisSession built for that version)`.
    /// One lock for both — `workspace_php_version()` used to read a separate
    /// `Mutex<PhpVersion>`, so fetching the version and then building/fetching
    /// the session used to take two locks per call; `with_session()`
    /// takes one. `None` only before the first build, or right after
    /// `set_php_version` invalidates it.
    /// mir-analyzer's `AnalysisSession` owns the workspace MirDb, runs Pass-2
    /// analysis, and lazy-loads dependencies via PSR-4. It is single-owner
    /// (`Send`, not `Sync`), so every access — read or write — goes through
    /// this mutex.
    analysis_session: Mutex<(
        mir_analyzer::PhpVersion,
        Option<mir_analyzer::AnalysisSession>,
    )>,
    /// Cache directory shared with the workspace file-index cache. When set,
    /// new `AnalysisSession`s are built with `with_cache_dir` so that stub
    /// parsing results survive server restarts.
    session_cache_dir: OnceLock<std::path::PathBuf>,
    /// User-supplied stub directories (`initializationOptions.stubDirs` /
    /// `.php-lsp.json`). When set, new `AnalysisSession`s are built with
    /// `with_user_stubs` so their `.php` files are registered as the
    /// highest-precedence symbol source alongside the bundled built-ins.
    user_stub_dirs: OnceLock<Vec<std::path::PathBuf>>,
    /// URIs of autoload.files entries from composer.json. These define global
    /// helper functions (e.g. tap, class_uses_recursive in Laravel) that are
    /// not discoverable by namespace walk. Pre-ingested into the AnalysisSession
    /// before each file analysis so mir doesn't emit false UndefinedFunction.
    autoload_uris: std::sync::RwLock<Vec<Uri>>,
    /// Set once the workspace scan's reference-index phase finishes, i.e.
    /// mir's own subtype graph is complete for the workspace. Visibility-derived
    /// scope narrowing that relies on the full subtype set (protected methods)
    /// only applies once this is `true`; before then it falls back to the full
    /// workspace scope so references are never under-reported.
    index_ready: AtomicBool,
    /// Monotonically increasing counter bumped on every actual text write
    /// (including file deletions). Long-running read operations (e.g.
    /// `session_references_to`) capture this value before starting and
    /// cancel themselves if it advances — avoiding stale results and
    /// unbounded retry loops after concurrent edits.
    write_revision: AtomicU64,
    /// Cancel token for the in-flight dependent-diagnostics sweep. A newer
    /// edit's sweep cancels the previous one via [`Self::begin_reanalyze`], so
    /// fast typing preempts stale workspace re-analysis rather than queueing
    /// behind it.
    reanalyze_cancel: Mutex<mir_analyzer::IndexCancel>,
    /// Cancel token for the in-flight analysis warm sweep
    /// ([`Self::warm_analysis_sweep`]); a newer sweep cancels the previous one
    /// via [`Self::begin_warm_sweep`].
    warm_sweep_cancel: Mutex<mir_analyzer::IndexCancel>,
    /// Warm sweeps that ran to completion (not cancelled). Observability only,
    /// surfaced via `$/php-lsp/debugStats` so benches/tests can await warmth.
    warm_sweeps_completed: AtomicU64,
    /// Calls to [`Self::warm_start_indexes`] that actually replayed at least
    /// one file (not the empty-workspace no-op). Observability only, surfaced
    /// via `$/php-lsp/debugStats` so tests can await a runtime-added folder's
    /// warm-start replay instead of guessing a fixed delay.
    warm_start_replays_completed: AtomicU64,
    /// Count of in-flight interactive reads (requests the user is waiting on).
    /// The workspace scan yields at file boundaries while this is non-zero, so
    /// its per-file salsa writes can't starve a request's snapshot into an
    /// endless `Cancelled` retry loop. Advisory only — relaxed ordering.
    interactive_reads: AtomicU64,
}

const SETTLE_BUDGET: std::time::Duration = std::time::Duration::from_millis(50);
pub(crate) const SETTLE_POLL: std::time::Duration = std::time::Duration::from_millis(2);

/// Tracks write-revision polls until the revision stops advancing or
/// [`SETTLE_BUDGET`] elapses.
pub(crate) struct WriteSettle {
    deadline: std::time::Instant,
    rev: u64,
}

impl WriteSettle {
    pub(crate) fn new(rev: u64) -> Self {
        Self {
            deadline: std::time::Instant::now() + SETTLE_BUDGET,
            rev,
        }
    }

    pub(crate) fn settled(&mut self, now: u64) -> bool {
        let quiet = now == std::mem::replace(&mut self.rev, now);
        quiet || std::time::Instant::now() >= self.deadline
    }
}

/// RAII handle marking an interactive read in flight; see
/// [`DocumentStore::interactive_read_guard`].
pub struct InteractiveReadGuard<'a>(&'a AtomicU64);

impl Drop for InteractiveReadGuard<'_> {
    fn drop(&mut self) {
        self.0.fetch_sub(1, Ordering::Relaxed);
    }
}

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

/// Analysis threads need big stacks: deep type-inference recursion on
/// pathological files overflows rayon's 2 MB default, and salsa 0.28's
/// `DependencyGraph::update_transferred_edges` recurses per transferred
/// dependent under contended parallel queries — observed blowing 16 MB on
/// the Laravel fixture (64 MB measured clean over repeated runs; the pages
/// are reserved, not committed). Size the global pool before any parallel
/// analysis runs; build_global fails harmlessly if a pool already exists.
/// Benches/tests driving `AnalysisSession` without a `DocumentStore` must
/// call this themselves — rayon otherwise lazily builds the pool with
/// default stacks on mir's first `par_iter`.
pub fn ensure_rayon_worker_stacks() {
    static RAYON_STACK: OnceLock<()> = OnceLock::new();
    RAYON_STACK.get_or_init(|| {
        let _ = rayon::ThreadPoolBuilder::new()
            .stack_size(64 * 1024 * 1024)
            .build_global();
    });
}

impl DocumentStore {
    pub fn new() -> Self {
        ensure_rayon_worker_stacks();
        DocumentStore {
            caches: CacheRegistry::new(),
            lsp_ws_files: DashMap::new(),
            deleted_uris: DashSet::new(),
            workspace_files_dirty: AtomicBool::new(true),
            workspace_file_paths_cache: ArcSwapOption::from(None),
            reachability_scan_passes: AtomicU64::new(0),
            reachability_result_cache: DashMap::new(),
            reachability_result_cache_files: AtomicU64::new(0),
            analysis_inflight: DashMap::new(),
            analysis_compute_count: AtomicU64::new(0),
            lsp_workspace: Mutex::new(None),
            psr4: Arc::new(ArcSwap::from_pointee(Psr4Map::empty())),
            analysis_session: Mutex::new((mir_analyzer::PhpVersion::LATEST, None)),
            session_cache_dir: OnceLock::new(),
            user_stub_dirs: OnceLock::new(),
            autoload_uris: std::sync::RwLock::new(Vec::new()),
            index_ready: AtomicBool::new(false),
            write_revision: AtomicU64::new(0),
            reanalyze_cancel: Mutex::new(mir_analyzer::IndexCancel::new()),
            warm_sweep_cancel: Mutex::new(mir_analyzer::IndexCancel::new()),
            warm_sweeps_completed: AtomicU64::new(0),
            warm_start_replays_completed: AtomicU64::new(0),
            interactive_reads: AtomicU64::new(0),
        }
    }

    /// Mark an interactive read (a request the user is waiting on) as in
    /// flight for the guard's lifetime. Background bulk writers poll
    /// [`Self::yield_to_interactive_reads`] between files and pause while any
    /// guard is live, giving the read a write-free window to complete.
    pub fn interactive_read_guard(&self) -> InteractiveReadGuard<'_> {
        self.interactive_reads.fetch_add(1, Ordering::Relaxed);
        InteractiveReadGuard(&self.interactive_reads)
    }

    /// Take an interactive-read guard, wait (bounded ~50 ms) for in-flight
    /// background writes to go quiet, and return the settled write revision.
    ///
    /// For user-facing sweeps that abort when [`Self::write_rev`] advances:
    /// snapshotting the revision this way ensures only genuine user edits —
    /// not the background scan the guard just paused — void the sweep.
    /// Sleeps; call from a blocking thread only.
    pub fn settled_write_rev_guard(&self) -> (InteractiveReadGuard<'_>, u64) {
        let guard = self.interactive_read_guard();
        // Post-scan there is no background write storm to settle; skip the
        // sleep so steady-state requests pay only the guard's atomic inc.
        if !self.is_index_ready() {
            let mut settle = WriteSettle::new(self.write_rev());
            loop {
                std::thread::sleep(SETTLE_POLL);
                if settle.settled(self.write_rev()) {
                    break;
                }
            }
        }
        (guard, self.write_rev())
    }

    /// Pause the calling (background-writer) thread while interactive reads
    /// are in flight, up to 500 ms per call. Bounded so a wedged reader can
    /// only slow the scan, never stop it; callers invoke this per file, so
    /// sustained interactive traffic keeps yielding at each boundary.
    pub fn yield_to_interactive_reads(&self) {
        let mut waited = std::time::Duration::ZERO;
        const STEP: std::time::Duration = std::time::Duration::from_millis(2);
        const MAX: std::time::Duration = std::time::Duration::from_millis(500);
        while self.interactive_reads.load(Ordering::Relaxed) > 0 && waited < MAX {
            std::thread::sleep(STEP);
            waited += STEP;
        }
    }

    /// Install a fresh cancel token for a dependent-diagnostics sweep,
    /// cancelling whichever sweep was previously in flight. Pass the returned
    /// token to `reanalyze_dependents_cancellable`; when a newer edit calls
    /// this again the old token flips and that older sweep stops at its next
    /// file boundary instead of racing this one to publish stale diagnostics.
    pub fn begin_reanalyze(&self) -> mir_analyzer::IndexCancel {
        let fresh = mir_analyzer::IndexCancel::new();
        let mut guard = self.reanalyze_cancel.lock().unwrap();
        guard.cancel();
        *guard = fresh.clone();
        fresh
    }

    /// Install a fresh cancel token for an analysis warm sweep, cancelling any
    /// sweep previously in flight. Mirrors [`Self::begin_reanalyze`] but on a
    /// separate slot: edit-triggered diagnostic sweeps and background warming
    /// must not cancel each other.
    pub fn begin_warm_sweep(&self) -> mir_analyzer::IndexCancel {
        let fresh = mir_analyzer::IndexCancel::new();
        let mut guard = self.warm_sweep_cancel.lock().unwrap();
        guard.cancel();
        *guard = fresh.clone();
        fresh
    }

    /// Drive every workspace file through mir's memoized `analyze_file` query
    /// so later reference/rename requests are memo hits instead of cold
    /// analyses (~20 ms per file on real code — a few hundred candidate files
    /// makes an interactive request take seconds).
    ///
    /// `priority` files (and the files declaring the classes they reference —
    /// the user's working set) are warmed first, so requests against open
    /// files go warm within the sweep's first seconds even on workspaces
    /// where the full sweep takes much longer.
    ///
    /// Background-priority: processes files in small chunks, yielding to
    /// interactive reads at each boundary, and stops at the next boundary once
    /// `cancel` flips. Re-running after edits is cheap — unaffected files
    /// revalidate via salsa without re-analysis. Blocking; call from
    /// `spawn_blocking`.
    pub fn warm_analysis_sweep(&self, priority: &[Uri], cancel: &mir_analyzer::IndexCancel) {
        // Dedicated thread with a generous stack: the serial prepare phase and
        // priority resolution recurse over real-world ASTs whose depth can
        // exceed the default 2 MiB thread stack (debug builds especially).
        // One pathological file must not abort the whole server process.
        std::thread::scope(|s| {
            let _ = std::thread::Builder::new()
                .name("php-lsp-warm-sweep".into())
                .stack_size(64 * 1024 * 1024)
                .spawn_scoped(s, || {
                    let queue = self.sweep_candidate_files(priority);
                    if self.run_warm_queue(&queue, cancel, None) {
                        // The sweep staged each analyzed file's reference
                        // postings into mir's AnalysisCache; persist them so
                        // the next launch's `warm_start_indexes` replays
                        // references index-warm. Flush before publishing
                        // completion — observers of the counter may rely on
                        // the postings being on disk.
                        self.flush_analysis_cache();
                        self.warm_sweeps_completed.fetch_add(1, Ordering::Relaxed);
                    }
                })
                .map(|h| h.join());
        });
    }

    /// Build the sweep's ordered file list: `priority` files and the files
    /// declaring the classes they reference (see [`Self::sweep_priority_files`])
    /// first, then every other tracked file — except vendor files, which the
    /// ambient sweep skips regardless of `indexVendor`. A vendor file that
    /// ends up in `priority` (opened directly, or referenced by an open
    /// project file) is unaffected: the exclusion only applies to the
    /// untargeted bulk-sweep tail, not the front of the queue.
    fn sweep_candidate_files(&self, priority: &[Uri]) -> Vec<Arc<str>> {
        let front: Vec<Arc<str>> = self.sweep_priority_files(priority);
        let front_set: HashSet<&str> = front.iter().map(|f| f.as_ref()).collect();
        front
            .iter()
            .cloned()
            .chain(
                self.lsp_ws_files
                    .iter()
                    .filter(|e| !self.deleted_uris.contains(e.key()))
                    .filter(|e| !is_vendor_uri(e.key()))
                    .map(|e| Arc::<str>::from(e.key().as_str()))
                    .filter(|f| !front_set.contains(f.as_ref())),
            )
            .collect()
    }

    /// Chunked reanalyze of `queue` with the sweep's yield/retry
    /// discipline. Returns `true` only when the whole queue ran to
    /// completion (no cancellation mid-pass) — callers publish completion
    /// (cache flush + `warm_sweeps_completed`) on that basis, so an
    /// observer of the counter can rely on every queued file having
    /// settled; without the retry, a chunk silently skipped has no
    /// guaranteed follow-up, and a caller polling the counter (e.g. a test
    /// waiting for the reference index to be fully warm) can observe
    /// "done" while some files' postings were never written.
    /// `progress`, when given, receives `(settled files, total files)` after
    /// each chunk.
    fn run_warm_queue(
        &self,
        queue: &[Arc<str>],
        cancel: &mir_analyzer::IndexCancel,
        progress: Option<&tokio::sync::mpsc::UnboundedSender<(u32, u32)>>,
    ) -> bool {
        run_chunks(
            queue,
            warm_chunk_size(),
            cancel,
            progress,
            || self.yield_to_interactive_reads(),
            |chunk| self.reanalyze_files(chunk, cancel).is_some(),
        )
    }

    /// The reference-warm phase: one deduped reanalysis queue holding mir's
    /// returned warm-start priority set first, then — when `ambient` — the
    /// project sweep set with `priority` files at its front, so a file in both
    /// is analyzed once rather than twice. Flushes the analysis cache and
    /// counts as a completed warm sweep on full completion.
    ///
    /// Every caller runs this in the background *after* publishing
    /// `indexReady`: it reanalyzes the whole project set, which on a real
    /// workspace costs seconds, and no query needs it to have finished (a
    /// cold file is analyzed on demand). Background-priority: yields to
    /// interactive reads at chunk boundaries, stops at the next boundary
    /// once a newer sweep takes the slot. Blocking; call from
    /// `spawn_blocking`.
    pub fn warm_references_phase(
        &self,
        untrusted: Vec<Arc<str>>,
        priority: &[Uri],
        ambient: bool,
        progress: Option<tokio::sync::mpsc::UnboundedSender<(u32, u32)>>,
    ) {
        // Dedicated thread with a generous stack: the serial prepare phase
        // and priority resolution recurse over real-world ASTs whose depth
        // can exceed the default 2 MiB thread stack (debug builds
        // especially). One pathological file must not abort the whole
        // server process.
        std::thread::scope(|s| {
            let _ = std::thread::Builder::new()
                .name("php-lsp-warm-phase".into())
                .stack_size(64 * 1024 * 1024)
                .spawn_scoped(s, || {
                    self.warm_references_phase_inner(
                        untrusted,
                        priority,
                        ambient,
                        progress.as_ref(),
                    )
                })
                .map(|h| h.join());
        });
    }

    fn warm_references_phase_inner(
        &self,
        untrusted: Vec<Arc<str>>,
        priority: &[Uri],
        ambient: bool,
        progress: Option<&tokio::sync::mpsc::UnboundedSender<(u32, u32)>>,
    ) {
        let mut queue: Vec<Arc<str>> = Vec::with_capacity(untrusted.len());
        let mut seen: HashSet<Arc<str>> = HashSet::new();
        for f in untrusted.iter() {
            if seen.insert(Arc::clone(f)) {
                queue.push(Arc::clone(f));
            }
        }
        if ambient {
            for f in self.sweep_candidate_files(priority) {
                if seen.insert(Arc::clone(&f)) {
                    queue.push(f);
                }
            }
        }
        if queue.is_empty() {
            return;
        }
        let cancel = self.begin_warm_sweep();
        let completed = self.run_warm_queue(&queue, &cancel, progress);
        if !completed {
            return;
        }
        // The phase staged each analyzed file's reference postings into
        // mir's AnalysisCache; persist them so the next launch's
        // `warm_start_indexes` replays them as trusted. Flush before
        // publishing completion — observers of the counter may rely on the
        // postings being on disk.
        self.flush_analysis_cache();
        self.warm_sweeps_completed.fetch_add(1, Ordering::Relaxed);
    }

    /// Persist mir's staged analysis-cache entries (reference postings) to
    /// disk. No-op when nothing changed since the last flush.
    pub fn flush_analysis_cache(&self) {
        self.with_session(|session| session.flush_analysis_cache());
    }

    /// Warm sweeps that ran to completion. See `$/php-lsp/debugStats`.
    pub fn warm_sweeps_completed(&self) -> u64 {
        self.warm_sweeps_completed.load(Ordering::Relaxed)
    }

    pub fn warm_start_replays_completed(&self) -> u64 {
        self.warm_start_replays_completed.load(Ordering::Relaxed)
    }

    /// The sweep's front of the queue: `priority` files themselves plus the
    /// files declaring the classes they reference (type hints, `use` imports,
    /// `new`, `extends`, …) — the set a request against an open file most
    /// likely touches. Resolution goes through the memoized workspace index,
    /// matching only by canonical FQN.
    fn sweep_priority_files(&self, priority: &[Uri]) -> Vec<Arc<str>> {
        if priority.is_empty() {
            return Vec::new();
        }
        let ws = self.get_workspace_index_salsa();
        let mut out: Vec<Arc<str>> = Vec::new();
        let mut seen: HashSet<Arc<str>> = HashSet::new();
        let push = |uri: &Uri, out: &mut Vec<Arc<str>>, seen: &mut HashSet<Arc<str>>| {
            let f: Arc<str> = Arc::from(uri.as_str());
            if seen.insert(Arc::clone(&f)) {
                out.push(f);
            }
        };
        for uri in priority {
            push(uri, &mut out, &mut seen);
        }
        for uri in priority {
            let Some(doc) = self.get_doc_salsa(uri) else {
                continue;
            };
            for fqn in crate::navigation::references::collect_referenced_class_fqns(&doc) {
                if let Some(r) = self.resolve_class_ref_by_fqn(&ws, &fqn)
                    && let Some((decl_uri, _)) = ws.at(r)
                {
                    push(decl_uri, &mut out, &mut seen);
                }
            }
        }
        out
    }

    /// Mark the workspace reference index as fully built. Called by the scan
    /// when its final phase completes (alongside `$/php-lsp/indexReady`).
    pub fn mark_index_ready(&self) {
        // Analyses computed while the scan was still incomplete may have
        // unresolved workspace names.
        self.caches.bump_decl_version();
        self.index_ready.store(true, Ordering::Release);
    }

    /// Whether the workspace reference index has finished building.
    pub fn is_index_ready(&self) -> bool {
        self.index_ready.load(Ordering::Acquire)
    }

    /// Snapshot of the write-revision counter. Long-running reads should
    /// capture this before starting and pass it to cancellable operations;
    /// if the counter advances, those operations abort and return empty rather
    /// than looping indefinitely against a newly-invalidated database.
    pub fn write_rev(&self) -> u64 {
        self.write_revision.load(Ordering::Acquire)
    }

    /// Set the directory used to persist stub-parse and analysis results across
    /// server restarts. Subsequent calls are silently ignored (`OnceLock`
    /// semantics).
    ///
    /// If a session was already built — an early request (e.g. the editor's
    /// restored-buffer `didOpen` racing `initialized`) builds one on demand —
    /// it was pinned in-memory-only: nothing it computes is ever flushed, and
    /// the next launch replays nothing, silently re-paying the whole cold
    /// cost every session. Drop it so the next `analysis_session()` rebuilds
    /// with the cache attached.
    ///
    /// Returns `true` when a session was dropped — the caller must then
    /// re-mirror every currently open buffer (see `drop_session_scoped_state`):
    /// the workspace scan won't do it, since it explicitly skips files that
    /// are already open.
    pub fn set_session_cache_dir(&self, dir: std::path::PathBuf) -> bool {
        if self.session_cache_dir.set(dir).is_err() {
            return false;
        }
        let mut guard = self.analysis_session.lock().unwrap();
        let dropped = guard.1.take().is_some();
        if dropped {
            self.drop_session_scoped_state();
        }
        dropped
    }

    /// Set the user-supplied stub directories (`initializationOptions.stubDirs`).
    /// Subsequent calls are silently ignored (`OnceLock` semantics).
    ///
    /// Same early-session race as [`Self::set_session_cache_dir`]: if a
    /// session was already built without these directories, drop it so the
    /// next `analysis_session()` rebuilds with `with_user_stubs` attached.
    ///
    /// Returns `true` when a session was dropped — same re-mirroring
    /// obligation as `set_session_cache_dir`.
    pub fn set_user_stub_dirs(&self, dirs: Vec<std::path::PathBuf>) -> bool {
        if self.user_stub_dirs.set(dirs).is_err() {
            return false;
        }
        let mut guard = self.analysis_session.lock().unwrap();
        let dropped = guard.1.take().is_some();
        if dropped {
            self.drop_session_scoped_state();
        }
        dropped
    }

    /// Register URIs discovered from composer.json `autoload.files` entries.
    /// These PHP files define global helper functions (e.g. `tap()` in Laravel)
    /// that are not class-resolvable via PSR-4. Clears `analysis_cache` so the
    /// next per-file analysis pre-ingests them into the AnalysisSession before
    /// running mir's FileAnalyzer.
    pub fn set_autoload_uris(&self, uris: Vec<Uri>) {
        *self.autoload_uris.write().unwrap() = uris;
        self.caches.evict_analysis_all();
    }

    /// Build a fresh `AnalysisSession` for `php_version`. The session owns
    /// the shared salsa db and AnalysisCache; lazy-loads vendor files via the
    /// shared PSR-4 map. Built-in stubs are *not* pre-loaded: mir's
    /// `prepare_ast_for_analysis` ingests the stubs each analyzed file
    /// references, and [`crate::types::stub_members`] faults in single stub
    /// files for builtin member/hover lookups. User stub directories (see
    /// [`Self::set_user_stub_dirs`]) are configured on the builder here; mir's
    /// `ingest_file` — called for every mirrored document — is what actually
    /// registers them (and the built-in stubs) as `SourceFile` inputs.
    fn build_session(
        &self,
        php_version: mir_analyzer::PhpVersion,
    ) -> mir_analyzer::AnalysisSession {
        // Hand it the shared PSR-4 map so it can lazy-resolve `UndefinedClass`
        // candidates without us having to mirror every vendor file upfront.
        let resolver: Arc<dyn mir_analyzer::ClassResolver> = self.psr4.load_full();
        // References/implementations are answered from mir's delta-maintained
        // inverted indexes (posting lists + subtype edges), which the session
        // keeps in step with every edit path.
        let mut builder = mir_analyzer::AnalysisSession::new(php_version)
            .with_class_resolver(resolver)
            .with_source_provider(Arc::new(crate::lang::autoload::UriSourceProvider::default()));
        // Must run before `with_cache_dir`: the cache epoch folds in a
        // fingerprint of the user stub set, which `with_cache_dir` only picks
        // up if it's already been configured.
        if let Some(dirs) = self.user_stub_dirs.get()
            && !dirs.is_empty()
        {
            builder = builder.with_user_stubs(Vec::new(), dirs.clone());
        }
        if let Some(dir) = self.session_cache_dir.get() {
            builder = builder.with_cache_dir(dir);
        }
        builder
    }

    /// Run `f` against the `AnalysisSession` for the workspace PHP version,
    /// building it first when none exists yet.
    ///
    /// The version is read under the same lock as the session: a version read
    /// beforehand could be stale and rebuild the session behind
    /// `drop_session_scoped_state`'s back.
    ///
    /// This mutex is the only synchronization for session access and it is
    /// not reentrant: never call back into the store from inside `f`.
    pub fn with_session<R>(&self, f: impl FnOnce(&mut mir_analyzer::AnalysisSession) -> R) -> R {
        let mut guard = self.analysis_session.lock().unwrap();
        let (php_version, session) = &mut *guard;
        let session = session.get_or_insert_with(|| self.build_session(*php_version));
        f(session)
    }

    /// Run `f` on a read snapshot without holding the session lock: the lock
    /// is taken only for `prepare` and the snapshot grab. A write that
    /// cancels `f` retries it on a fresh snapshot, at most
    /// [`SNAPSHOT_ATTEMPTS`] times, then yields [`ContentModified`].
    ///
    /// `f` must not call back into the store: a live snapshot blocks the
    /// next input write, so taking the session lock inside it can deadlock.
    pub fn with_snapshot<R>(
        &self,
        prepare: impl Fn(&mut mir_analyzer::AnalysisSession),
        f: impl Fn(&mir_analyzer::AnalysisSnapshot) -> Result<R, salsa::Cancelled>,
    ) -> Result<R, ContentModified> {
        let _interactive = self.interactive_read_guard();
        self.with_background_snapshot(prepare, f)
    }

    /// [`Self::with_snapshot`] without the interactive-read guard, for
    /// background sweeps that must not stall other background writers.
    fn with_background_snapshot<R>(
        &self,
        prepare: impl Fn(&mut mir_analyzer::AnalysisSession),
        f: impl Fn(&mir_analyzer::AnalysisSnapshot) -> Result<R, salsa::Cancelled>,
    ) -> Result<R, ContentModified> {
        use std::panic::AssertUnwindSafe;
        for _ in 0..SNAPSHOT_ATTEMPTS {
            let snapshot = self.with_session(|session| {
                prepare(session);
                session.snapshot()
            });
            let result = salsa::Cancelled::catch(AssertUnwindSafe(|| f(&snapshot))).and_then(|r| r);
            drop(snapshot);
            if let Ok(value) = result {
                return Ok(value);
            }
        }
        Err(ContentModified)
    }

    /// [`Self::with_snapshot`] for reads that need no preparation and cannot
    /// return `Cancelled` themselves; a cancellation unwinds into the retry.
    pub fn read_snapshot<R>(
        &self,
        f: impl Fn(&mir_analyzer::AnalysisSnapshot) -> R,
    ) -> Result<R, ContentModified> {
        self.with_snapshot(|_| {}, |snap| Ok(f(snap)))
    }

    /// Re-analyze `files` off the session lock, committing their reference
    /// postings. `None` when `cancel` stopped the pass or writes kept
    /// cancelling it.
    pub fn reanalyze_files(
        &self,
        files: &[Arc<str>],
        cancel: &mir_analyzer::IndexCancel,
    ) -> Option<Vec<(Arc<str>, mir_analyzer::FileAnalysis)>> {
        if files.is_empty() || cancel.is_cancelled() {
            return None;
        }
        self.with_background_snapshot(
            |session| {
                session.prepare_for_query(None);
                for file in files {
                    if cancel.is_cancelled() {
                        return;
                    }
                    session.prepare_file_for_analysis(file);
                }
            },
            |snap| snap.reanalyze_files(files, cancel),
        )
        .ok()
        .flatten()
    }

    /// Members of a built-in PHP class from the phpstorm stubs, or `None`
    /// when `fqcn` is not one (or a write kept cancelling the lookup).
    pub fn stub_class_members(&self, fqcn: &str) -> Option<crate::types::type_map::ClassMembers> {
        self.with_snapshot(
            |_| {},
            |snap| crate::types::stub_members::stub_class_members(snap, fqcn),
        )
        .ok()
        .flatten()
    }

    /// mir's class-like for `fqcn`; `None` when unknown or every snapshot attempt was cancelled.
    pub fn find_class_like(&self, fqcn: &str) -> Option<mir_analyzer::db::ClassLike> {
        self.with_snapshot(
            |_| {},
            |snap| snap.find_class_like(fqcn.trim_start_matches('\\')),
        )
        .ok()
        .flatten()
    }

    /// `method` as mir resolves it along `class`'s ancestor chain, then its mixins.
    pub fn find_method_in_chain(
        &self,
        class: &str,
        method: &str,
    ) -> Option<Arc<mir_codebase::definitions::MethodDef>> {
        self.with_snapshot(
            |_| {},
            |snap| snap.find_method_in_chain(class.trim_start_matches('\\'), method),
        )
        .ok()
        .flatten()
        .map(|(_, method)| method)
    }

    /// Current PHP version tracked by the workspace input.
    pub fn workspace_php_version(&self) -> mir_analyzer::PhpVersion {
        self.analysis_session.lock().unwrap().0
    }

    /// Direct parent, interfaces and used traits of `class_fqn` as resolved FQCNs,
    /// via mir's class table. Empty when mir doesn't know the class.
    pub fn class_direct_supertypes(
        &self,
        class_fqn: &str,
    ) -> Result<Vec<Arc<str>>, ContentModified> {
        let class_like = self.with_snapshot(
            |_| {},
            |snap| snap.find_class_like(class_fqn.trim_start_matches('\\')),
        )?;
        let Some(class_like) = class_like else {
            return Ok(Vec::new());
        };
        let mut ordered: Vec<Arc<str>> = class_like.parent().cloned().into_iter().collect();
        ordered.extend(class_like.interfaces().iter().cloned());
        ordered.extend(class_like.extends().iter().cloned());
        for ancestor in class_like.ancestor_fqcns() {
            if !ordered.contains(&ancestor) {
                ordered.push(ancestor);
            }
        }
        Ok(ordered)
    }

    fn subtype_files(&self, class_fqn: &str) -> Result<Vec<Arc<str>>, ContentModified> {
        self.with_snapshot(
            |session| session.prepare_for_query(None),
            |snap| snap.subtype_files(class_fqn, false),
        )
    }

    /// Return the `Arc<ArcSwap<Psr4Map>>` so callers can share it.
    /// `Backend` clones this arc at construction time so writes
    /// (e.g. loading composer.json on `initialized`) are immediately visible
    /// to PSR-4 resolution during analysis without extra plumbing.
    pub fn psr4_arc(&self) -> Arc<ArcSwap<Psr4Map>> {
        Arc::clone(&self.psr4)
    }

    /// Durability for a file's salsa input: vendor files never change within a
    /// session, so salsa can skip re-validating their queries on user edits.
    fn input_durability(uri: &Uri) -> salsa::Durability {
        if uri.as_str().contains("/vendor/") {
            salsa::Durability::HIGH
        } else {
            salsa::Durability::LOW
        }
    }

    /// The `LspWsFile` handle for `uri`, if it is mirrored and not deleted.
    fn lsp_ws_file(&self, uri: &Uri) -> Option<LspWsFile> {
        if self.deleted_uris.contains(uri) {
            return None;
        }
        self.lsp_ws_files.get(uri).map(|e| *e)
    }

    #[cfg(test)]
    fn snapshot_mir_query<R>(&self, f: impl Fn(&mir_analyzer::db::MirDbStorage) -> R) -> R {
        self.snapshot_mir_handle_query(|| Some(()), |db, ()| f(db))
            .expect("unit handle is always present")
    }

    /// Take a cheap snapshot of the shared mir db and run `f` on it with the
    /// salsa input `handle` returns, retrying on `salsa::Cancelled` (raised
    /// when a concurrent writer bumps the revision). Mirrors
    /// [`Self::snapshot_query`] for the converged db. `None` when `handle`
    /// finds none.
    ///
    /// `handle` runs under the session lock together with the snapshot grab,
    /// so a concurrent session rebuild never pairs an old db's handle with
    /// the new db. After [`SNAPSHOT_ATTEMPTS`] cancellations the last attempt
    /// runs under the session lock, which keeps new writers out and
    /// guarantees progress.
    fn snapshot_mir_handle_query<H: Copy, R>(
        &self,
        handle: impl Fn() -> Option<H>,
        f: impl Fn(&mir_analyzer::db::MirDbStorage, H) -> R,
    ) -> Option<R> {
        let _interactive = self.interactive_read_guard();
        self.attempt_mir_handle_query(SNAPSHOT_ATTEMPTS, &handle, &f)
            .unwrap_or_else(|| {
                self.with_session(|session| Some(f(&session.snapshot_db(), handle()?)))
            })
    }

    /// Bounded variant of [`Self::snapshot_mir_handle_query`] for cosmetic,
    /// cursor-triggered reads that must not spin under sustained write pressure.
    /// Returns `None` if a concurrent writer cancels the query `attempts` times
    /// in a row (the caller then falls back to a stale result).
    fn try_snapshot_mir_handle_query<H: Copy, R>(
        &self,
        attempts: usize,
        handle: impl Fn() -> Option<H>,
        f: impl Fn(&mir_analyzer::db::MirDbStorage, H) -> R,
    ) -> Option<R> {
        let _interactive = self.interactive_read_guard();
        self.attempt_mir_handle_query(attempts, &handle, &f)
            .flatten()
    }

    /// Each attempt takes a fresh snapshot under its own brief lock
    /// acquisition: a concurrent writer's salsa `set` holds the mir write lock
    /// and waits for outstanding db handles to drop, while the next
    /// `snapshot_db` needs the read lock — keeping either the clone or the
    /// session lock alive across a retry deadlocks.
    ///
    /// `None` when every attempt was cancelled; `Some(None)` when `handle`
    /// found none.
    fn attempt_mir_handle_query<H: Copy, R>(
        &self,
        attempts: usize,
        handle: &impl Fn() -> Option<H>,
        f: &impl Fn(&mir_analyzer::db::MirDbStorage, H) -> R,
    ) -> Option<Option<R>> {
        use std::panic::AssertUnwindSafe;
        for _ in 0..attempts {
            let (db, h) = self.with_session(|session| (session.snapshot_db(), handle()));
            let Some(h) = h else {
                return Some(None);
            };
            if let Ok(r) = salsa::Cancelled::catch(AssertUnwindSafe(|| f(&db, h))) {
                return Some(Some(r));
            }
        }
        None
    }

    /// Mirror a file's current text into the salsa layer. Creates the
    /// `SourceFile` input on first sight, otherwise updates it through mir's
    /// session write API so mir's own invalidation state stays in sync.
    pub fn mirror_text(&self, uri: &Uri, text: &str) {
        // G2 fast path: compare against the lock-free text cache. When the
        // new text byte-matches what we already mirrored, skip the host
        // mutex entirely. Common during workspace scan + `did_open` for
        // unchanged files, where most threads would otherwise serialise on
        // `host.lock()` just to confirm a no-op.
        if let Some(cached) = self.caches.text_cache.get(uri)
            && **cached == *text
            && !self.deleted_uris.contains(uri)
            && self.lsp_ws_files.contains_key(uri)
        {
            return;
        }
        self.mirror_text_arc(uri, Arc::from(text))
    }

    /// Like [`mirror_text`] but takes an already-allocated `Arc<str>`.
    ///
    /// Callers that already hold an `Arc<str>` (e.g. `ingest_from_doc` reusing
    /// `ParsedDoc::source_arc()`) use this to avoid a second allocation and to
    /// ensure `text_cache` and `parsed_cache` hold the same Arc pointer —
    /// enabling `Arc::ptr_eq` validation in `get_parsed_cached`.
    pub fn mirror_text_arc(&self, uri: &Uri, text_arc: Arc<str>) {
        let dur = Self::input_durability(uri);
        let path: Arc<str> = Arc::from(uri.as_str());
        self.with_session(|session| {
            if let Some(wf) = self.lsp_ws_files.get(uri).map(|e| *e) {
                // A resurrected (previously-deleted) file changes
                // `workspace_file_paths()`'s result set — invalidate its cache.
                // The common case (an edit to an already-live file) hits `None`
                // here and pays nothing extra.
                if self.deleted_uris.remove(uri).is_some() {
                    self.workspace_file_paths_cache.store(None);
                }
                // Fast path: byte-identical text already mirrored — skip the write
                // lock and the revision bump entirely.
                if let Some(cached) = self.caches.text_cache.get(uri)
                    && **cached == *text_arc
                {
                    return;
                }
                session.upsert_source_file(path, text_arc.clone(), dur);
                session.with_db_mut(|db| {
                    // Any text change invalidates a previously-seeded cached index.
                    // Only set when present to avoid a spurious second revision bump.
                    if wf.cached_index(db).is_some() {
                        wf.set_cached_index(db).to(None);
                    }
                });
                self.caches.text_cache.insert(uri.clone(), text_arc);
                // Evict only this file's analysis; cross-file invalidation is handled
                // lazily in `cached_analysis` via the declaration fingerprint.
                self.caches.evict_analysis(uri);
                self.write_revision.fetch_add(1, Ordering::Release);
            } else {
                let sf = session.upsert_source_file(path, text_arc.clone(), dur);
                let wf = session.with_db_mut(|db| LspWsFile::new(db, sf, None));
                self.lsp_ws_files.insert(uri.clone(), wf);
                self.caches.text_cache.insert(uri.clone(), text_arc);
                self.mark_workspace_files_dirty();
                self.write_revision.fetch_add(1, Ordering::Release);
            }
        });
    }

    /// Return the `LspWsFile` handle for a URL, if active (not deleted).
    #[cfg(test)]
    pub fn source_file(&self, uri: &Uri) -> Option<LspWsFile> {
        if self.deleted_uris.contains(uri) {
            return None;
        }
        self.lsp_ws_files.get(uri).map(|e| *e)
    }

    /// Phase K2: pre-seed a `FileIndex` loaded from the on-disk cache onto
    /// the `FileText` input for `uri`. The next `file_index` call for that
    /// file returns the cached index directly, skipping parse + extract.
    ///
    /// Must be called **before** any `file_index(db, sf)` call for this file —
    /// otherwise salsa has already memoized the fresh-parse result and setting
    /// `cached_index` now would only bump the revision without using the cache.
    /// In practice the workspace-scan path seeds immediately after `mirror_text`
    /// and before any query runs.
    ///
    /// Returns `false` when `uri` was not mirrored (caller should mirror
    /// first); returns `true` on success.
    pub fn seed_cached_index(&self, uri: &Uri, index: Arc<FileIndex>) -> bool {
        self.with_session(|session| {
            let Some(wf) = self.lsp_ws_file(uri) else {
                return false;
            };
            session.with_db_mut(|db| wf.set_cached_index(db).to(Some(index)));
            true
        })
    }

    /// Evict the semantic-tokens cache for `uri`. Called by Backend when a
    /// file is closed; diff-based tokens computed against the old revision
    /// are no longer meaningful.
    pub fn evict_token_cache(&self, uri: &Uri) {
        self.caches.evict_tokens(uri);
    }

    /// Return the `FileIndex` for `uri` by running `file_index` on a salsa
    /// snapshot.  Returns `None` when `uri` has not been mirrored.
    ///
    /// Test-only — production code uses the salsa query directly via
    /// `snapshot_query`.
    #[cfg(test)]
    pub fn source_files_len(&self) -> usize {
        self.lsp_ws_files.len()
    }

    #[cfg(test)]
    pub fn snapshot_query_file_index(
        &self,
        uri: &Uri,
    ) -> Option<crate::index::file_index::FileIndex> {
        self.snapshot_mir_handle_query(
            || self.lsp_ws_file(uri),
            |db, wf| (*crate::db::mir_queries::file_index(db, wf).0).clone(),
        )
    }

    /// Register a file in the salsa layer without marking it open.
    ///
    /// Salsa's `parsed_doc` query parses lazily on first read; diagnostics
    /// are populated by `did_open` when the editor actually opens the file.
    pub fn ingest(&self, uri: Uri, text: &str) {
        self.mirror_text(&uri, text);
    }

    /// Index a file using an already-parsed `ParsedDoc`, avoiding a second parse.
    ///
    /// Prefer this over [`ingest`] when the caller already has a `ParsedDoc` (e.g.
    /// after running `DefinitionCollector` during workspace scan). Reuses the
    /// `Arc<str>` already owned by `doc` so that `text_cache` and `SourceFile::text`
    /// share the same pointer — enabling the `Arc::ptr_eq` fast path in
    /// `get_parsed_cached` on the first subsequent salsa query, without an extra
    /// `Arc::from(source)` allocation.
    pub fn ingest_from_doc(&self, uri: Uri, doc: &ParsedDoc) {
        self.mirror_text_arc(&uri, doc.source_arc());
    }

    pub fn remove(&self, uri: &Uri) {
        self.caches.evict(uri);
        // Mark the URI as deleted but keep the `lsp_ws_files` entry so the
        // salsa `LspWsFile`/`SourceFile` handles remain alive. Re-opening the
        // file reuses the same handle instead of calling `LspWsFile::new()`
        // again, which would create a new orphaned salsa input on every
        // delete-reopen cycle. `session.invalidate_file` below already frees
        // the (potentially large) text this handle holds via mir's own
        // `remove_source_file`, so keeping the handle costs only its own
        // small footprint, not the file's content.
        self.deleted_uris.insert(uri.clone());
        self.mark_workspace_files_dirty();
        // Sync workspace files so the deleted file is removed from the salsa
        // `Workspace::files` list and won't appear in workspace symbols etc.
        self.sync_workspace_files();
        // Also evict the file from the `AnalysisSession`'s internal state so
        // workspace symbol queries don't keep returning the deleted file's
        // declarations. Cheap when the session hasn't ingested this file.
        let mut guard = self.analysis_session.lock().unwrap();
        if let Some(session) = guard.1.as_mut() {
            session.invalidate_file(uri.as_str());
            // `file_index` has no LRU cap (unlike `parsed_doc`/`symbol_map`),
            // so without this it would keep holding this file's pre-deletion
            // `FileIndex` (and any seeded on-disk `cached_index`) in memory
            // for the rest of the process's life. Clear the seed and force
            // one recompute against the now-emptied text (`invalidate_file`
            // above already cleared it via mir's `remove_source_file`) to
            // shrink the memo to near-nothing immediately.
            if let Some(wf) = self.lsp_ws_files.get(uri).map(|e| *e) {
                session.with_db_mut(|db| {
                    if wf.cached_index(db).is_some() {
                        wf.set_cached_index(db).to(None);
                    }
                });
                let db = session.snapshot_db();
                let _ = crate::db::mir_queries::file_index(&db, wf);
            }
        }
        self.write_revision.fetch_add(1, Ordering::Release);
    }

    // ── Salsa-backed accessors ─────────────────────────────────────────────
    //
    // Reads run the memoized `parsed_doc` / `file_index` queries, parsing
    // only on first access per revision. These are the production accessors
    // used by every handler.

    /// Salsa-backed parsed document.
    ///
    /// Salsa-backed parsed document for any mirrored file (open or
    /// background-indexed). Returns `None` only when the file is not known
    /// to the store. Callers that want "only if open" should gate on
    /// `Backend::open_files` at the call site (see `Backend::get_doc`).
    pub fn get_doc_salsa(&self, uri: &Uri) -> Option<Arc<ParsedDoc>> {
        self.get_parsed_cached(uri)
    }

    /// Salsa-backed compact symbol index.
    pub fn get_index_salsa(&self, uri: &Uri) -> Option<Arc<FileIndex>> {
        self.snapshot_mir_handle_query(
            || self.lsp_ws_file(uri),
            |db, wf| crate::db::mir_queries::file_index(db, wf).0.clone(),
        )
    }

    /// Salsa-backed pre-computed symbol map (name → Vec<SymbolEntry>).
    /// Memoized per revision: stable files serve from cache in O(1).
    pub fn get_symbol_map_salsa(
        &self,
        uri: &Uri,
    ) -> Option<Arc<crate::types::symbol_map::SymbolMap>> {
        // Symbol map runs on the shared mir db, sharing its memoized `parsed_doc`.
        self.snapshot_mir_handle_query(
            || self.lsp_ws_file(uri),
            |db, wf| {
                let sf = *wf.source(db);
                crate::db::mir_queries::symbol_map(db, sf).0.clone()
            },
        )
    }

    /// Pre-computed symbol maps for every entry in `open_urls` except `uri`.
    pub fn other_symbol_maps(
        &self,
        uri: &Uri,
        open_urls: &[Uri],
    ) -> Vec<(Uri, Arc<crate::types::symbol_map::SymbolMap>)> {
        open_urls
            .iter()
            .filter(|u| *u != uri)
            .filter_map(|u| self.get_symbol_map_salsa(u).map(|m| (u.clone(), m)))
            .collect()
    }

    /// G3: shared implementation for `get_doc_salsa`.
    /// Tries the `parsed_cache` (lock-free) first; validates via
    /// `Arc::ptr_eq` against the G2 `text_cache` so a concurrent writer
    /// that has already committed a new text input cannot be masked by a
    /// stale cache entry. On miss, captures the text Arc and ParsedDoc
    /// together inside a single `snapshot_query`, then publishes both.
    fn get_parsed_cached(&self, uri: &Uri) -> Option<Arc<ParsedDoc>> {
        if let Some(current_text) = self.caches.text_cache.get(uri)
            && let Some(entry) = self.caches.parsed_cache.get(uri)
            && Arc::ptr_eq(&*current_text, &entry.0)
        {
            let doc = entry.1.clone();
            drop(entry);
            self.caches.touch(uri);
            return Some(doc);
        }

        // Parse runs on the shared mir db.
        let (text, doc) = self.snapshot_mir_handle_query(
            || self.lsp_ws_file(uri),
            |db, wf| {
                let sf = *wf.source(db);
                let text = sf.text(db).clone();
                let doc = crate::db::mir_queries::parsed_doc(db, sf).0.clone();
                (text, doc)
            },
        )?;
        self.caches.bump_parse_count();
        self.caches.insert_parsed(uri.clone(), text, doc.clone());
        Some(doc)
    }

    /// Parsed doc for a cosmetic, cursor-triggered read (e.g. `documentHighlight`)
    /// that must stay responsive while the user types. Unlike [`Self::get_doc_salsa`]
    /// it never spins on the `Cancelled` retry loop: it tries the lock-free
    /// `parsed_cache`, then a bounded snapshot parse, and if a concurrent write
    /// stream keeps cancelling it, returns the last-good cached `ParsedDoc`
    /// (possibly one edit stale — invisible for a highlight, unlike a hang).
    /// `None` only when the file has never been parsed.
    pub fn get_doc_snapshot_or_stale(&self, uri: &Uri) -> Option<Arc<ParsedDoc>> {
        if let Some(current_text) = self.caches.text_cache.get(uri)
            && let Some(entry) = self.caches.parsed_cache.get(uri)
            && Arc::ptr_eq(&*current_text, &entry.0)
        {
            let doc = entry.1.clone();
            drop(entry);
            self.caches.touch(uri);
            return Some(doc);
        }

        if let Some((text, doc)) = self.try_snapshot_mir_handle_query(
            3,
            || self.lsp_ws_file(uri),
            |db, wf| {
                let sf = *wf.source(db);
                let text = sf.text(db).clone();
                let doc = crate::db::mir_queries::parsed_doc(db, sf).0.clone();
                (text, doc)
            },
        ) {
            self.caches.bump_parse_count();
            self.caches.insert_parsed(uri.clone(), text, doc.clone());
            return Some(doc);
        }

        self.caches.parsed_cache.get(uri).map(|e| e.1.clone())
    }

    /// Refresh `workspace.files` to mirror the current active file set.
    ///
    /// Skips all work when `workspace_files_dirty` is `false` (the common
    /// case after the workspace scan completes — file-set changes are rare).
    pub fn sync_workspace_files(&self) {
        // Atomically clear the flag.  If it was already false the file set
        // hasn't changed since the last sync; nothing to do.
        if !self.workspace_files_dirty.swap(false, Ordering::AcqRel) {
            return;
        }

        self.with_session(|session| {
            // Collect active (non-deleted) files, sorted by URI for stable ordering.
            let mut entries: Vec<(Arc<str>, LspWsFile)> = self
                .lsp_ws_files
                .iter()
                .filter(|e| !self.deleted_uris.contains(e.key()))
                .map(|e| (Arc::<str>::from(e.key().as_str()), *e.value()))
                .collect();
            entries.sort_unstable_by(|(a, _), (b, _)| a.cmp(b));
            let files: Arc<[LspWsFile]> = entries.iter().map(|(_, wf)| *wf).collect();

            let mut guard = self.lsp_workspace.lock().unwrap();
            session.with_db_mut(|db| match *guard {
                Some(ws) => {
                    ws.set_files(db).to(files);
                }
                None => *guard = Some(LspWorkspace::new(db, files)),
            });
        });
    }

    /// Mark the workspace file set as dirty so the next `sync_workspace_files`
    /// call re-runs the collect/sort/compare path, and invalidate the
    /// `workspace_file_paths()` cache. Exposed for benchmarks that need to
    /// measure the dirty-path cost in isolation.
    pub fn mark_workspace_files_dirty(&self) {
        self.workspace_files_dirty.store(true, Ordering::Release);
        self.workspace_file_paths_cache.store(None);
    }

    /// Update the PHP version tracked by the workspace. Salsa will invalidate
    /// all `semantic_issues` queries so diagnostics are re-evaluated.
    /// Skips the setter when the version hasn't changed to avoid spurious
    /// query invalidation. Returns `true` when the version actually changed —
    /// callers that scan the workspace at runtime (not just at init, before
    /// any file is mirrored) must re-scan every root when this is `true`,
    /// since `drop_session_scoped_state` below empties `lsp_ws_files` and
    /// nothing else repopulates it.
    pub fn set_php_version(&self, version: mir_analyzer::PhpVersion) -> bool {
        {
            let mut guard = self.analysis_session.lock().unwrap();
            if guard.0 == version {
                return false;
            }
            // Clear the cached session too: `with_session` reuses `guard.1`
            // whenever it is set, so leaving the old version's session behind
            // here would silently hand it out under the new version.
            guard.0 = version;
            guard.1 = None;
            // Changing the version selects a different `AnalysisSession` (and
            // thus a different db). In practice the version is set once at
            // init, before any file is mirrored — but a runtime change is
            // possible too (the caller must re-scan in that case, see the
            // `bool` return above).
            self.drop_session_scoped_state();
        }
        true
    }

    /// Discard every piece of state scoped to the current `AnalysisSession`'s
    /// salsa db. MUST accompany anything that causes `analysis_session()` to
    /// hand out a different db (version change, cache-dir attach): the
    /// `LspWsFile` input handles in `lsp_ws_files` index into the *old* db's
    /// tables, and using one against a new db panics with a salsa slot-type
    /// mismatch. The workspace scan re-mirrors on-disk files onto the new
    /// session, but it explicitly skips anything already open in the editor
    /// (so it doesn't clobber live buffer edits with disk content) — callers
    /// whose drop can race an open buffer must re-mirror open files themselves.
    ///
    /// Call with the session lock held, so no reader pairs an old handle with the new db.
    fn drop_session_scoped_state(&self) {
        self.lsp_ws_files.clear();
        *self.lsp_workspace.lock().unwrap() = None;
        self.mark_workspace_files_dirty();
        // Cached FileAnalysis values reference the old session's state.
        self.caches.evict_analysis_all();
    }

    /// Inverted-index reference lookup scoped to `files` (the text-pre-filtered
    /// candidate set): a posting-list read for committed-fresh files plus an
    /// on-demand analyze+commit for stale/uncommitted candidates, so warm
    /// requests are O(results) instead of O(candidates).
    ///
    /// Returns LSP-style 0-based line/column.
    ///
    /// `cancel_rev`: when `Some(rev)`, the query aborts with [`ContentModified`]
    /// if a concurrent write advances the `write_revision` counter past `rev`.
    pub fn indexed_references(
        &self,
        symbol: &mir_analyzer::Name,
        files: &[Arc<str>],
        include_declaration: bool,
        cancel_rev: Option<u64>,
    ) -> Result<Vec<RefLocation>, ContentModified> {
        let stale = || cancel_rev.is_some_and(|rev| self.write_rev() != rev);
        // Scanned before the lock: on a cold workspace this reads file text.
        let candidates = self.with_snapshot(
            |_| {},
            |snap| snap.stale_reference_candidates(symbol, files),
        )?;
        let raw = self.with_snapshot(
            |session| {
                session.prepare_references_query(symbol, &candidates, include_declaration, &stale);
            },
            |snap| {
                if stale() {
                    return Err(salsa::Cancelled::PendingWrite);
                }
                snap.indexed_references_to(
                    symbol,
                    files,
                    include_declaration,
                    ReferenceIncludes::Plain,
                )
            },
        )?;
        Ok(raw
            .into_iter()
            .map(|(file, range)| {
                // Mirror columns are 0-based code points (UTF-16 code units),
                // the same convention used by LSP. We only need to convert
                // mir's 1-based line numbers to 0-based for LSP.
                let line = range.start.line.saturating_sub(1);
                (file, line, range.start.column, range.end.column)
            })
            .collect())
    }

    /// `use`-import lines referencing `symbol`, from mir's `use:` postings.
    /// Read-only lookup with no freshness pass — run [`Self::indexed_references`]
    /// over the same `files` first so uncommitted candidates are analyzed.
    /// Returns `(file_uri, line, col_start, col_end)` tuples like
    /// [`Self::indexed_references`]; the range covers the whole import item.
    pub fn indexed_use_imports(
        &self,
        symbol: &mir_analyzer::Name,
        files: &[Arc<str>],
    ) -> Result<Vec<RefLocation>, ContentModified> {
        let raw = self.with_snapshot(
            |session| session.prepare_for_query(None),
            |snap| snap.indexed_use_import_locations(symbol, files),
        )?;
        Ok(raw
            .into_iter()
            .map(|(file, range)| {
                // mir uses 1-based lines; 0-based columns.
                let line = range.start.line.saturating_sub(1);
                (file, line, range.start.column, range.end.column)
            })
            .collect())
    }

    /// Replay disk-cached reference postings and subtype edges for the whole
    /// mirrored workspace (mir's `warm_start_files`) — a no-op per file
    /// without a content-hash-matching cache entry from a previous run. Call
    /// once after the scan mirrors texts, before the reference-warm phase,
    /// so a returning session starts index-warm. Cheap enough to sit on the
    /// pre-`indexReady` path — it replays cache entries, it does not analyze.
    ///
    /// Returns the subset of replayed files that mir considers worth
    /// prioritizing for follow-up warming. php-lsp treats this as a
    /// performance hint: callers feed the list to the front of
    /// [`Self::warm_references_phase`]'s queue so likely-cold files warm in
    /// the background before the broader ambient sweep, when any, reaches
    /// them.
    pub fn warm_start_indexes(&self) -> Vec<Arc<str>> {
        let files: Vec<(Arc<str>, Arc<str>)> = self
            .lsp_ws_files
            .iter()
            .filter(|e| !self.deleted_uris.contains(e.key()))
            .filter_map(|e| {
                let text = self.caches.text_cache.get(e.key())?;
                Some((Arc::<str>::from(e.key().as_str()), Arc::clone(&text)))
            })
            .collect();
        if files.is_empty() {
            return Vec::new();
        }
        let untrusted = self.with_session(|session| session.warm_start_files(&files));
        self.warm_start_replays_completed
            .fetch_add(1, Ordering::Relaxed);
        untrusted
    }

    /// Candidate file scope for a posting lookup on `symbol`.
    /// Private/protected methods narrow to their visibility scope; everything
    /// else gets the whole workspace. mir gates never-committed candidates on
    /// a symbol-name text mention internally (with PHP's case-insensitive
    /// matching semantics), so a host-side text prefilter would only re-scan
    /// the same bytes with weaker semantics.
    pub(crate) fn reference_candidate_files(&self, symbol: &mir_analyzer::Name) -> Vec<Arc<str>> {
        match symbol {
            mir_analyzer::Name::Method { class, name } => {
                if let Some(urls) = self.method_reference_scope(class, name) {
                    return urls.iter().map(|u| Arc::from(u.as_str())).collect();
                }
            }
            // A class reference always textually resolves the name in the
            // referencing file (import, namespace, or qualified path) —
            // there's no instance-typed-receiver indirection here, so FQN
            // narrowing is always sound. A builtin (stub-resolved) class is
            // additionally never declared in vendor — PHP core/extension
            // types have no user-authored declaration for any file to
            // legitimately "be" — so vendor mentions of it are dependency-
            // internal noise, same call TypeScript makes for `node_modules`
            // usages of `Promise`. A vendor polyfill shadowing the stub makes
            // the class a vendor declaration, so it is not builtin here.
            mir_analyzer::Name::Class(fqcn) => {
                if let Some(files) = self.fqn_reachable_files(std::slice::from_ref(fqcn)) {
                    let builtin = self
                        .with_snapshot(|_| {}, |snap| snap.is_builtin_class(fqcn))
                        .unwrap_or(false);
                    return if builtin {
                        files
                            .into_iter()
                            .filter(|f| !is_vendor_path_str(f))
                            .collect()
                    } else {
                        files
                    };
                }
            }
            // Namespaced functions/constants resolve like class names; an
            // unqualified call to a *global* one (`env()`, `PHP_EOL`) works
            // from any namespace via PHP's global fallback, so FQN
            // reachability can't exclude any file for those. An unqualified
            // *builtin* function is the one case that can still narrow: it's
            // never declared in vendor, so — same reasoning as the builtin
            // class case above — vendor can be dropped outright without an
            // FQN scan.
            mir_analyzer::Name::Function(fqcn) => {
                let trimmed = fqcn.trim_start_matches('\\');
                if trimmed.contains('\\') {
                    if let Some(files) = self.fqn_reachable_files(std::slice::from_ref(fqcn)) {
                        return files;
                    }
                } else if mir_analyzer::is_builtin_function(trimmed) {
                    return self.workspace_file_paths_excluding_vendor();
                }
            }
            // Same split as the function arm: namespaced constants narrow
            // via FQN reachability; an unqualified *builtin* one (`PHP_EOL`)
            // is never declared in vendor, so vendor drops outright.
            mir_analyzer::Name::GlobalConstant(fqcn) => {
                let trimmed = fqcn.trim_start_matches('\\');
                if trimmed.contains('\\') {
                    if let Some(files) = self.fqn_reachable_files(std::slice::from_ref(fqcn)) {
                        return files;
                    }
                } else if mir_analyzer::is_builtin_constant(trimmed) {
                    return self.workspace_file_paths_excluding_vendor();
                }
            }
            _ => {}
        }
        self.workspace_file_paths().to_vec()
    }

    /// Every active workspace file as a mir path (`Arc<str>` of the URI).
    /// The candidate scope handed to mir's queries — mir gates uncommitted
    /// candidates on symbol-name mention internally, so this is always safe.
    ///
    /// Cached behind an `Arc` (invalidated by `mark_workspace_files_dirty`) so
    /// the ~15K-file walk + `Arc<str>` allocation per file only happens once
    /// per workspace-file-set change, not once per caller per request.
    pub fn workspace_file_paths(&self) -> Arc<Vec<Arc<str>>> {
        if let Some(cached) = self.workspace_file_paths_cache.load_full() {
            return cached;
        }
        let files: Arc<Vec<Arc<str>>> = Arc::new(
            self.lsp_ws_files
                .iter()
                .filter(|e| !self.deleted_uris.contains(e.key()))
                .map(|e| Arc::<str>::from(e.key().as_str()))
                .collect(),
        );
        self.workspace_file_paths_cache
            .store(Some(Arc::clone(&files)));
        files
    }

    /// [`Self::workspace_file_paths`] with vendor files dropped — the
    /// narrowed scope for a symbol that's resolved to something builtin
    /// (never declared in vendor), as opposed to the FQN-reachable narrowing
    /// used for project/vendor-defined symbols.
    fn workspace_file_paths_excluding_vendor(&self) -> Vec<Arc<str>> {
        self.workspace_file_paths()
            .iter()
            .filter(|f| !is_vendor_path_str(f))
            .cloned()
            .collect()
    }

    /// Transitive subtypes of `class_fqn` from mir's maintained subtype edge
    /// index, with declaration sites. `include_trait_users` also counts
    /// `use Trait;` composition as a subtype edge (trait-usage lenses); leave
    /// it off for goto-implementation semantics (extends/implements only).
    pub fn indexed_subtype_classes(
        &self,
        class_fqn: &str,
        include_trait_users: bool,
    ) -> Result<Vec<mir_analyzer::SubtypeClassSite>, ContentModified> {
        let files = self.workspace_file_paths();
        self.with_snapshot(
            |session| session.prepare_for_query(None),
            |snap| snap.indexed_subtype_classes(class_fqn, &files, include_trait_users),
        )
    }

    /// [`Self::indexed_subtype_classes`] restricted to subtypes naming
    /// `class_fqn` directly in `extends`/`implements` (or `use`).
    pub fn indexed_direct_subtype_classes(
        &self,
        class_fqn: &str,
        include_trait_users: bool,
    ) -> Result<Vec<mir_analyzer::SubtypeClassSite>, ContentModified> {
        let files = self.workspace_file_paths();
        self.with_snapshot(
            |session| session.prepare_for_query(None),
            |snap| snap.indexed_direct_subtype_classes(class_fqn, &files, include_trait_users),
        )
    }

    /// Concrete implementations of `class_fqn::method` across its subtypes:
    /// `(subtype fqcn, file, name range)` from mir's subtype edge index.
    pub fn indexed_method_implementations(
        &self,
        class_fqn: &str,
        method: &str,
    ) -> Result<Vec<MethodImplSite>, ContentModified> {
        let files = self.workspace_file_paths();
        self.with_snapshot(
            |session| session.prepare_for_query(None),
            |snap| snap.indexed_method_implementations(class_fqn, method, &files),
        )
    }

    /// The complete set of files a `private` method's references can occur in,
    /// or `None` when the search must stay workspace-wide.
    ///
    /// `owner_fqn` is the enclosing class at the cursor; narrowing applies only
    /// when that class *directly declares* `method` (so its `MethodDef`
    /// visibility is authoritative — inherited/call-site lookups fall through to
    /// `None`). A reference to `Class::method` is recorded only where
    /// `analyze_file` resolves an expression to that key, and `analyze_file` is
    /// per-source-file, so a `private` member — resolvable only inside the
    /// declaring class body, which lives in one file — is fully scoped to the
    /// declaring file at any indexing stage.
    ///
    /// A `protected` member is reachable from the declaring class and its
    /// transitive subclasses (`$this->m()`, `parent::m()`, `self::`/`static::`),
    /// all of which live in the declaring file or a subtype file — never outside
    /// the hierarchy in valid PHP. Its scope is therefore the declaring file plus
    /// the transitive subtype files. The complete subtype set is only known once
    /// the workspace reference index finishes, so this narrowing applies only
    /// when [`Self::is_index_ready`]; before then it falls back to `None` (full
    /// workspace scope) so references are never under-reported.
    ///
    /// Classes that compose traits or mixins are excluded — those inline
    /// external resolution context, so a reference could surface in another file.
    pub fn method_reference_scope(&self, owner_fqn: &str, method: &str) -> Option<Vec<Uri>> {
        match self.method_reference_scope_plan(owner_fqn, method) {
            MethodScopePlan::Files(files) => Some(files),
            MethodScopePlan::NeedsScan { fqns, extra_needle } => {
                let files =
                    self.fqn_reachable_files_with_needles(&fqns, &[extra_needle.as_str()])?;
                Some(
                    files
                        .iter()
                        .filter_map(|f| (f).parse::<Uri>().ok())
                        .collect(),
                )
            }
            MethodScopePlan::FullWorkspace => None,
        }
    }

    /// Whether [`Self::reference_candidate_files`] narrows `class::method`'s
    /// scope below the full workspace, without paying for the narrowing scan
    /// itself. A caller that further partitions the candidate set by a
    /// heuristic text mention (references' priority-result streaming) only
    /// has anything to gain when the scope is *not* already narrowed — a
    /// narrowed scope is already the minimal necessary set, so partitioning
    /// it further just re-scans those files' bytes for no benefit.
    pub(crate) fn method_scope_is_narrowed(&self, owner_fqn: &str, method: &str) -> bool {
        !matches!(
            self.method_reference_scope_plan(owner_fqn, method),
            MethodScopePlan::FullWorkspace
        )
    }

    /// Same narrowing decision as [`Self::method_reference_scope`], but stops
    /// short of running the FQN/text-needle scan itself — that scan is the
    /// expensive part (a parallel pass over every workspace file), and a
    /// caller resolving many methods at once (code lens, one call per
    /// declaration in a file) needs to batch it across methods via
    /// [`Self::resolve_reachability_queries`] instead of paying it per call.
    fn method_reference_scope_plan(&self, owner_fqn: &str, method: &str) -> MethodScopePlan {
        use crate::index::file_index::{ClassKind, Visibility};

        let ws = self.get_workspace_index_salsa();
        let owner_fqn = owner_fqn.trim_start_matches('\\');
        let Some(owner_ref) = self.resolve_class_ref_by_fqn(&ws, owner_fqn) else {
            // No project/vendor declaration matches this FQN — a builtin
            // owner (`Closure`, `ReflectionParameter`, ...) always lands
            // here, since PHP core/extension classes have no `FileIndex`
            // entry of their own. Same vendor-exclusion reasoning as the
            // `Name::Class`/builtin-function branches in
            // `reference_candidate_files`: a builtin is never declared in
            // vendor, so vendor's own usages of a builtin-owned method are
            // dependency-internal noise.
            if mir_analyzer::stub_path_for_class(owner_fqn).is_some() {
                return MethodScopePlan::Files(
                    self.workspace_file_paths_excluding_vendor()
                        .iter()
                        .filter_map(|f| f.parse::<Uri>().ok())
                        .collect(),
                );
            }
            return MethodScopePlan::FullWorkspace;
        };
        let Some((decl_uri, decl_class)) = ws.at(owner_ref) else {
            return MethodScopePlan::FullWorkspace;
        };

        // Trait/interface methods, and methods on classes that compose traits or
        // mixins, can be referenced from other files — keep the full scope.
        if !matches!(decl_class.kind, ClassKind::Class | ClassKind::Enum)
            || !decl_class.traits.is_empty()
            || !decl_class.mixins.is_empty()
        {
            return MethodScopePlan::FullWorkspace;
        }

        let Some(method_def) = decl_class
            .methods
            .iter()
            .find(|m| m.name.eq_ignore_ascii_case(method))
        else {
            return MethodScopePlan::FullWorkspace;
        };

        match method_def.visibility {
            Visibility::Private => MethodScopePlan::Files(vec![decl_uri.clone()]),
            Visibility::Protected => {
                if !self.is_index_ready() {
                    return MethodScopePlan::FullWorkspace;
                }
                // Subtype set comes from mir's resolved inheritance graph — it
                // matches subclasses by FQCN, so `extends \Ns\Base` and aliased
                // `use ... as` forms are all found. Falls back to full scope if
                // mir can't resolve the owner.
                let Ok(subtypes) = self.subtype_files(owner_fqn) else {
                    return MethodScopePlan::FullWorkspace;
                };
                let mut files: std::collections::HashSet<Uri> = subtypes
                    .into_iter()
                    .filter_map(|p| p.parse::<Uri>().ok())
                    .collect();
                files.insert(decl_uri.clone());
                MethodScopePlan::Files(files.into_iter().collect())
            }
            // A public *static* method's call sites come in exactly two
            // textual shapes: a resolved class name (`Owner::m()`, inherited
            // `Sub::m()`, `self::`/`static::`/`parent::m()` from inside the
            // hierarchy, aliased `use Owner as X; X::m()` — all covered by
            // owner+subtype FQN reachability) or an *instance* receiver
            // (`$obj::m()`, whose file may never name the class but always
            // contains the member token — covered by the member-name
            // needle). Dynamic member names (`Owner::$m()`) produce no
            // posting at all (verified), so the union is exhaustive. This
            // beats mir's own gate, which only sees bare short names and
            // can't tell this owner apart from an unrelated class sharing
            // its short name. Instance methods stay unnarrowed
            // (`FullWorkspace` below): a typed receiver can hide both the
            // class *and* any distinguishing token cheaper than the member
            // name itself.
            Visibility::Public
                if method_def.is_static || method.eq_ignore_ascii_case("__construct") =>
            {
                if !self.is_index_ready() {
                    return MethodScopePlan::FullWorkspace;
                }
                let Ok(subtypes) = self.indexed_subtype_classes(owner_fqn, false) else {
                    return MethodScopePlan::FullWorkspace;
                };
                let mut fqns: Vec<Arc<str>> = vec![Arc::from(owner_fqn)];
                fqns.extend(subtypes.into_iter().map(|s| s.fqcn));
                // `__construct`'s extra needle is the call-shaped
                // `->__construct` (explicit re-init on a typed receiver),
                // not the bare identifier — that would drag in every file
                // *declaring* a constructor. `new X` sites and
                // `parent::`/`self::`/`static::__construct()` calls need no
                // needle: the former textually resolve an owner/subtype
                // name, the latter live inside hierarchy files, which the
                // subtype closure's namespace rule already admits (unlike
                // mir's own gate, which lacks the closure and keeps a
                // `::__construct` token for the grandchild-`parent::` case).
                let extra_needle = if method.eq_ignore_ascii_case("__construct") {
                    "->__construct".to_string()
                } else {
                    method.to_string()
                };
                MethodScopePlan::NeedsScan { fqns, extra_needle }
            }
            Visibility::Public => MethodScopePlan::FullWorkspace,
        }
    }

    /// Batched form of [`Self::reference_candidate_files`]: resolves the
    /// candidate scope for every symbol in `symbols` while sharing ONE pass
    /// over the workspace for every symbol whose scope needs FQN/text-needle
    /// narrowing (class references, public static methods, constructors),
    /// instead of one pass per symbol.
    ///
    /// Code lens is the motivating caller: a single file's declarations can
    /// produce dozens of reference-count lenses in one request, and each
    /// used to pay its own full `ws.files` scan via
    /// [`Self::fqn_reachable_files_with_needles`] — O(declarations × files)
    /// text scans instead of the one pass this performs.
    ///
    /// Order-preserving: `result[i]` is the scope for `symbols[i]`.
    pub(crate) fn batch_reference_candidate_files(
        &self,
        symbols: &[mir_analyzer::Name],
    ) -> Vec<Vec<Arc<str>>> {
        let mut results: Vec<Option<Vec<Arc<str>>>> = vec![None; symbols.len()];
        let mut queries: Vec<ReachabilityQuery> = Vec::new();
        // queries[k] resolves the scope for symbols[query_targets[k]].
        let mut query_targets: Vec<usize> = Vec::new();

        for (i, symbol) in symbols.iter().enumerate() {
            match symbol {
                mir_analyzer::Name::Method { class, name } => {
                    match self.method_reference_scope_plan(class, name) {
                        MethodScopePlan::Files(urls) => {
                            results[i] = Some(urls.iter().map(|u| Arc::from(u.as_str())).collect());
                        }
                        MethodScopePlan::NeedsScan { fqns, extra_needle } => {
                            queries.push(ReachabilityQuery {
                                kind: ReachabilitySymbolKind::Class,
                                fqns,
                                extra_needles: vec![extra_needle],
                            });
                            query_targets.push(i);
                        }
                        MethodScopePlan::FullWorkspace => {}
                    }
                }
                mir_analyzer::Name::Class(fqcn) => {
                    queries.push(ReachabilityQuery {
                        kind: ReachabilitySymbolKind::Class,
                        fqns: vec![fqcn.clone()],
                        extra_needles: Vec::new(),
                    });
                    query_targets.push(i);
                }
                mir_analyzer::Name::Function(fqcn) | mir_analyzer::Name::GlobalConstant(fqcn)
                    if fqcn.trim_start_matches('\\').contains('\\') =>
                {
                    let kind = match symbol {
                        mir_analyzer::Name::Function(_) => ReachabilitySymbolKind::Function,
                        mir_analyzer::Name::GlobalConstant(_) => {
                            ReachabilitySymbolKind::GlobalConstant
                        }
                        _ => unreachable!(),
                    };
                    queries.push(ReachabilityQuery {
                        kind,
                        fqns: vec![fqcn.clone()],
                        extra_needles: Vec::new(),
                    });
                    query_targets.push(i);
                }
                _ => {}
            }
        }

        if !queries.is_empty()
            && let Some(scanned) = self.resolve_reachability_queries(&queries)
        {
            for (files, target) in scanned.into_iter().zip(query_targets) {
                results[target] = Some(files);
            }
        }

        let fallback = self.workspace_file_paths();
        results
            .into_iter()
            .map(|r| r.unwrap_or_else(|| fallback.as_ref().clone()))
            .collect()
    }

    /// See the `reachability_scan_passes` field's docs. Exposed via
    /// `debugStats` so a protocol-level test can assert a request with many
    /// narrowing-requiring declarations (code lens) pays one scan pass, not
    /// one per declaration.
    pub(crate) fn reachability_scan_passes(&self) -> u64 {
        self.reachability_scan_passes.load(Ordering::Relaxed)
    }

    /// See the `analysis_compute_count` field's docs.
    pub(crate) fn analysis_compute_count(&self) -> u64 {
        self.analysis_compute_count.load(Ordering::Relaxed)
    }

    /// Files that could possibly reference any FQN in `fqns`, narrowed via
    /// PHP's own name-resolution rules rather than bare-word text mention:
    ///
    /// 1. **Namespace rule** — the file's namespace equals the target's, or
    ///    is a `\`-segment prefix of it: `namespace Foo;` reaches
    ///    `Foo\Bar\Baz` through the relative-qualified `Bar\Baz`.
    /// 2. **Import rule** — a `use` of the target itself, an alias of it, or
    ///    any namespace prefix of it (`use Foo\Bar; Bar\Baz::x()`), all
    ///    matched on the import's FQN so aliases come for free.
    /// 3. **Text rule** — the qualified path appears literally in the file
    ///    (`\App\Widget::class` config arrays with no `use` line, or a
    ///    leading-slash-free `App\Widget` from a no-namespace file, where
    ///    qualified names resolve from the root). Matched
    ///    ASCII-case-insensitively — PHP class names are case-insensitive.
    ///
    /// These are the *only* ways PHP resolves a class-like or namespaced
    /// name, so this is exact narrowing grounded in the language's own
    /// resolution order, not a heuristic — unlike mir's own gate, which
    /// only sees bare short names and can't distinguish this owner class
    /// from an unrelated class sharing its short name elsewhere in the
    /// workspace.
    ///
    /// Callers must NOT use this for global-namespace functions/constants
    /// (unqualified calls fall back to the global namespace from *any*
    /// namespace, so no file can be excluded) or for instance members (a
    /// typed receiver can hide the class entirely).
    ///
    /// Returns `None` (full workspace) when the boot scan hasn't finished —
    /// same conservative discipline as the `Protected` branch above — so
    /// references are never under-reported at cold start.
    pub fn fqn_reachable_files(&self, fqns: &[Arc<str>]) -> Option<Vec<Arc<str>>> {
        self.fqn_reachable_files_with_needles(fqns, &[])
    }

    /// [`Self::fqn_reachable_files`] plus files whose text contains any of
    /// `extra_needles` (ASCII-case-insensitive substring, no word bounds).
    /// The union is what makes member-symbol narrowing sound: a static call
    /// through an *instance* receiver (`$obj::make()`) or an explicit
    /// re-init (`$obj->__construct()`) references a member without the file
    /// ever resolving the owner's name, but its text always contains the
    /// call token itself.
    ///
    /// A single-query call through [`Self::resolve_reachability_queries`] —
    /// see that method for the batched form multiple callers share.
    fn fqn_reachable_files_with_needles(
        &self,
        fqns: &[Arc<str>],
        extra_needles: &[&str],
    ) -> Option<Vec<Arc<str>>> {
        let query = ReachabilityQuery {
            kind: ReachabilitySymbolKind::Class,
            fqns: fqns.to_vec(),
            extra_needles: extra_needles.iter().map(|n| n.to_string()).collect(),
        };
        self.resolve_reachability_queries(std::slice::from_ref(&query))
            .map(|mut per_query| per_query.pop().expect("one query in, one result out"))
    }

    /// Resolves many [`Self::fqn_reachable_files_with_needles`]-shaped
    /// queries, memoized per `(query, write_revision)` so a warm repeat
    /// (even for a different needle subset already known to `mention_cache`)
    /// costs a `DashMap` lookup and nothing else.
    ///
    /// This wrapper exists because [`Self::resolve_reachability_queries_uncached`]'s
    /// own `mention_cache` only memoizes the expensive *text scan* — its
    /// outer loop still visits every workspace file to run the cheap
    /// namespace/import checks and a cache lookup, and that "cheap per
    /// file" cost is still measurable multiplied across tens of thousands
    /// of files (confirmed via the `references_all_kinds` bench: ~1.5-2ms
    /// on a 36k-file workspace for query shapes reaching this function,
    /// even on a full `mention_cache` hit). Caching the final result here
    /// skips that loop entirely on a repeat. Queries missing from the cache
    /// are batched into one call to the uncached function (still sharing
    /// one scan pass across every miss, as before).
    fn resolve_reachability_queries(
        &self,
        queries: &[ReachabilityQuery],
    ) -> Option<Vec<Vec<Arc<str>>>> {
        if !self.is_index_ready() {
            return None;
        }
        if queries.is_empty() {
            return Some(Vec::new());
        }
        let revision = self.write_revision.load(Ordering::Acquire);
        let mut out: Vec<Option<Vec<Arc<str>>>> = vec![None; queries.len()];
        let mut miss_queries: Vec<ReachabilityQuery> = Vec::new();
        let mut miss_targets: Vec<usize> = Vec::new();
        for (i, q) in queries.iter().enumerate() {
            match self.reachability_result_cache.get(q) {
                Some(entry) if entry.0 == revision => {
                    out[i] = Some((*entry.1).clone());
                }
                _ => {
                    miss_queries.push(q.clone());
                    miss_targets.push(i);
                }
            }
        }
        if !miss_queries.is_empty() {
            let computed = self.resolve_reachability_queries_uncached(&miss_queries)?;
            let mut cache_files_added = 0u64;
            for (query, result) in miss_queries.into_iter().zip(computed) {
                cache_files_added += result.len() as u64;
                let result = Arc::new(result);
                self.reachability_result_cache
                    .insert(query, (revision, Arc::clone(&result)));
                out[miss_targets.remove(0)] = Some((*result).clone());
            }
            let prior = self
                .reachability_result_cache_files
                .fetch_add(cache_files_added, Ordering::Relaxed);
            const REACHABILITY_RESULT_CACHE_FILE_CAP: u64 = 2_000_000;
            if prior + cache_files_added > REACHABILITY_RESULT_CACHE_FILE_CAP {
                self.reachability_result_cache.clear();
                self.reachability_result_cache_files
                    .store(0, Ordering::Relaxed);
            }
        }
        Some(out.into_iter().map(|o| o.unwrap_or_default()).collect())
    }

    /// Uncached implementation of [`Self::resolve_reachability_queries`],
    /// resolving every query in a single pass over the workspace so N
    /// callers share one scan instead of paying N. Callers should use the
    /// memoizing wrapper.
    ///
    /// The namespace/import checks are cheap in-memory field comparisons and
    /// stay per-query. The qualified-mention fallback is answered by mir's
    /// own `ClassMentionIndex` (`class_mention_scanner`/
    /// `class_mention_answer`/`set_file_class_mentions`) for every needle,
    /// bounded or raw alike — the same persistent per-file mention cache
    /// mir's `indexed_references_to` gate already populates, so a file
    /// scanned by either consumer answers the other for free. A file whose
    /// text and universe-epoch are unchanged since its last scan answers
    /// every needle via a set lookup, no text pass at all. Only a file
    /// that's genuinely edited since its last scan pays the Aho-Corasick
    /// pass, and that pass runs against every currently-known needle in the
    /// universe at once (not just this call's), so the next, differently-
    /// shaped query against that same file is *also* a lookup.
    ///
    /// Returns `None` for every query when the boot scan hasn't finished —
    /// so references are never under-reported at cold start.
    fn resolve_reachability_queries_uncached(
        &self,
        queries: &[ReachabilityQuery],
    ) -> Option<Vec<Vec<Arc<str>>>> {
        use rayon::prelude::*;

        if !self.is_index_ready() {
            return None;
        }
        if queries.is_empty() {
            return Some(Vec::new());
        }
        self.reachability_scan_passes
            .fetch_add(1, Ordering::Relaxed);

        // Per-query targets/namespaces for the cheap checks, plus this
        // query's final needle strings — the exact literal form fed to the
        // universe/scanner (a bare short name carries its `\` prefix).
        let mut per_query_targets: Vec<Vec<&str>> = Vec::with_capacity(queries.len());
        let mut per_query_namespaces: Vec<Vec<Option<&str>>> = Vec::with_capacity(queries.len());
        let mut per_query_needles: Vec<Vec<String>> = Vec::with_capacity(queries.len());

        for q in queries {
            let targets: Vec<&str> = q.fqns.iter().map(|f| f.trim_start_matches('\\')).collect();
            let namespaces: Vec<Option<&str>> = targets
                .iter()
                .map(|t| t.rsplit_once('\\').map(|(ns, _)| ns))
                .collect();
            // Namespaced targets match with or without the leading `\`; a
            // bare global name keeps it (the short name alone would match
            // everything).
            let mut needles: Vec<String> = targets
                .iter()
                .map(|t| {
                    if t.contains('\\') {
                        (*t).to_string()
                    } else {
                        format!("\\{t}")
                    }
                })
                .collect();
            needles.extend(q.extra_needles.iter().cloned());
            per_query_targets.push(targets);
            per_query_namespaces.push(namespaces);
            per_query_needles.push(needles);
        }

        // Every needle is answered by mir's `ClassMentionIndex` — the same
        // persistent per-file mention cache mir's own `indexed_references_to`
        // gate already populates, so a file scanned by either consumer
        // answers the other for free. A needle that's a whole identifier or
        // FQN literal (alphanumeric/underscore/backslash only) gets the
        // stricter, more precise word-boundary match (and is sound: PHP's
        // lexer never places a qualified name flush against another
        // identifier with no separator — `new App\Foo\Bar()` requires that
        // space, `newApp\Foo\Bar` would lex as one invalid token — so the
        // boundary check never under-reports a literal FQN mention in valid
        // source). A needle that isn't a whole identifier (a call token
        // like `->__construct`, whose preceding byte in real usage —
        // `$obj->__construct()` — is itself an identifier character and
        // would otherwise fail that check) is admitted as a raw needle
        // instead, matched with no boundary at all — see
        // `mir_analyzer::db::ClassMentionIndex::add_raw_names`'s doc
        // comment.
        fn needle_needs_raw_match(s: &str) -> bool {
            !s.chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '\\')
        }

        // `snapshot_db` below is dropped before `get_workspace_index_salsa`
        // runs — that function takes its own snapshot internally, and a
        // concurrent writer's `set()` holds mir's write lock waiting for
        // *every* outstanding snapshot to drop while a fresh `snapshot_db`
        // waits for the read lock behind that same writer; keeping this
        // snapshot alive across the call is exactly the deadlock
        // `Self::attempt_mir_handle_query`'s doc comment warns about. The
        // parallel loop below takes its own fresh snapshot instead of
        // reusing this one.
        {
            let mir_db = self.with_session(|session| session.snapshot_db());
            let all_needles = per_query_needles.iter().flatten().map(|s| s.as_str());
            let (raw_needles, bounded_needles): (Vec<&str>, Vec<&str>) =
                all_needles.partition(|n| needle_needs_raw_match(n));
            if !bounded_needles.is_empty() {
                mir_db.add_literal_mention_names(bounded_needles);
            }
            if !raw_needles.is_empty() {
                mir_db.add_raw_mention_needles(raw_needles);
            }
        }

        let ws = self.get_workspace_index_salsa();
        let n = queries.len();
        let workspace_files = self.workspace_file_paths();
        let per_query_import_matches: Vec<std::collections::HashSet<Arc<str>>> = queries
            .iter()
            .map(|q| {
                let symbols: Vec<mir_analyzer::Name> = q
                    .fqns
                    .iter()
                    .map(|fqn| match q.kind {
                        ReachabilitySymbolKind::Class => {
                            mir_analyzer::Name::class(fqn.trim_start_matches('\\').to_string())
                        }
                        ReachabilitySymbolKind::Function => {
                            mir_analyzer::Name::function(fqn.trim_start_matches('\\').to_string())
                        }
                        ReachabilitySymbolKind::GlobalConstant => {
                            mir_analyzer::Name::global_constant(
                                fqn.trim_start_matches('\\').to_string(),
                            )
                        }
                    })
                    .collect();
                let mut matches = std::collections::HashSet::new();
                for symbol in &symbols {
                    let _ = self.indexed_references(symbol, &workspace_files, false, None);
                    matches.extend(
                        self.indexed_use_imports(symbol, &workspace_files)
                            .unwrap_or_default()
                            .into_iter()
                            .map(|(file, _, _, _)| file),
                    );
                }
                matches
            })
            .collect();

        let mir_db = self.with_session(|session| session.snapshot_db());
        let mir_scanner = mir_db.class_mention_scanner();
        let per_query_mir_queries: Vec<Vec<mir_analyzer::db::MentionQuery>> = per_query_needles
            .iter()
            .map(|needles| {
                needles
                    .iter()
                    .filter_map(|n| mir_db.prepare_class_mention_query(n))
                    .collect()
            })
            .collect();
        // For a common short name most of the corpus fails the cheap
        // namespace/import checks and falls through to the mention lookup
        // (or, for a file that's cold or edited since its last scan, the
        // text scan that fills it in) — parallel for the same reason as
        // before: mir's own equivalent gate scan does the same, and a cold
        // query on a 15K-file workspace needs the few-ms parallel pass, not
        // a multi-second sequential one.
        let per_file_matches: Vec<(Arc<str>, Vec<bool>)> = ws
            .files
            .par_iter()
            .map_with(mir_db.clone(), |mir_db, (url, idx)| {
                let file_ns = idx.namespace.as_deref().map(|s| s.trim_start_matches('\\'));
                let mut matched = vec![false; n];
                let mut unresolved: Vec<usize> = Vec::new();
                for qi in 0..n {
                    let ns_match = per_query_namespaces[qi]
                        .iter()
                        .any(|ns| match (file_ns, ns) {
                            (Some(f), Some(t)) => fqn_segment_prefix(f, t),
                            (None, None) => true,
                            // Global-ns files reach namespaced targets only via
                            // the full path (text rule); namespaced files reach
                            // global classes only via `\Name` or an import.
                            _ => false,
                        });
                    if ns_match {
                        matched[qi] = true;
                        continue;
                    }
                    if per_query_import_matches[qi].contains(&Arc::<str>::from(url.as_str())) {
                        matched[qi] = true;
                        continue;
                    }
                    unresolved.push(qi);
                }
                if !unresolved.is_empty()
                    && let Some(text) = self.source_text(url)
                {
                    let url_str = url.as_str();
                    let mut needs_scan = false;
                    for &qi in &unresolved {
                        for q in &per_query_mir_queries[qi] {
                            match mir_db.class_mention_answer(url_str, q, &text) {
                                Some(true) => {
                                    matched[qi] = true;
                                    break;
                                }
                                Some(false) => {}
                                None => {
                                    needs_scan = true;
                                }
                            }
                        }
                    }
                    if needs_scan && let Some(mir_scanner) = &mir_scanner {
                        // Scanned against the *whole* current universe, not
                        // just this call's needles, so a future, differently-
                        // shaped query against this same file is also a
                        // lookup instead of its own fresh scan.
                        let names = mir_scanner.scan(text.as_ref());
                        for &qi in &unresolved {
                            if !matched[qi]
                                && per_query_mir_queries[qi]
                                    .iter()
                                    .any(|q| names.binary_search(&q.name).is_ok())
                            {
                                matched[qi] = true;
                            }
                        }
                        mir_db.set_file_class_mentions(
                            &Arc::<str>::from(url_str),
                            &text,
                            mir_scanner.epoch(),
                            names,
                        );
                    }
                }
                matched
                    .iter()
                    .any(|&m| m)
                    .then(|| (Arc::<str>::from(url.as_str()), matched))
            })
            .flatten()
            .collect();

        let mut out: Vec<Vec<Arc<str>>> = vec![Vec::new(); n];
        for (file, matched) in per_file_matches {
            for (qi, out_files) in out.iter_mut().enumerate() {
                if matched[qi] {
                    out_files.push(file.clone());
                }
            }
        }
        Some(out)
    }

    /// Phase J: salsa-memoized aggregate workspace index.
    ///
    /// Returns the shared `Arc<WorkspaceIndexData>` with the flat
    /// `(Uri, Arc<FileIndex>)` list plus `classes_by_lowercase_name` (for
    /// completion's prefix search). Used by workspace_symbols,
    /// prepare_type_hierarchy, supertypes_of, subtypes_of, and
    /// find_implementations so they don't each rebuild the aggregate per
    /// request. Invalidates automatically when any file's `file_index`
    /// changes. Class/declaration name lookups no longer come from this
    /// aggregate — see `Self::resolve_class_ref`/`class_candidates`/
    /// `declaration_candidate_files`, which query mir's mention index instead.
    pub fn get_workspace_index_salsa(&self) -> Arc<crate::db::workspace_index::WorkspaceIndexData> {
        self.sync_workspace_files();
        self.snapshot_mir_handle_query(
            || *self.lsp_workspace.lock().unwrap(),
            |db, ws| crate::db::mir_queries::workspace_index(db, ws).0.clone(),
        )
        .unwrap_or_else(|| {
            Arc::new(crate::db::workspace_index::WorkspaceIndexData::from_files(
                Vec::new(),
            ))
        })
    }

    /// Total number of real `ParsedDoc` parses served so far (cache misses).
    /// Surfaced via `$/php-lsp/debugStats` so tests can assert the references
    /// read path doesn't parse the whole workspace.
    pub fn parse_count(&self) -> u64 {
        self.caches.parse_count()
    }

    /// Times mir's `RefIndex` was locked on the current session. Reads are
    /// per-key posting lookups and edits commit one file's postings, so this
    /// grows by a small bounded amount per operation — never per candidate.
    /// Surfaced via `$/php-lsp/debugStats` for the stress-test guard.
    pub fn ref_index_lock_count(&self) -> u64 {
        self.with_session(|session| session.ref_index_lock_count())
    }

    /// Diagnostic: mir's `indexed_references_to` memoization hits, surfaced
    /// via `$/php-lsp/debugStats` so a host-side query can be attributed to
    /// the right layer when diagnosing latency.
    pub fn mir_ref_query_cache_hits(&self) -> u64 {
        self.with_session(|session| session.ref_query_cache_hits())
    }

    /// Diagnostic: mir's `indexed_subtype_classes` memoization hits.
    pub fn mir_subtype_query_cache_hits(&self) -> u64 {
        self.with_session(|session| session.subtype_query_cache_hits())
    }

    /// Whether mir's workspace symbol index singleton is populated (warm-start
    /// seed or first sweep). See `DebugStats::workspace_symbol_index_ready`.
    pub fn workspace_symbol_index_ready(&self) -> bool {
        self.with_session(|session| session.workspace_symbol_index_ready())
    }

    /// Executions of mir's tracked O(all-files) symbol-index walk.
    pub fn workspace_index_walks(&self) -> u64 {
        self.with_session(|session| session.workspace_index_walks())
    }

    /// Number of files mirrored into the salsa workspace (open + background
    /// indexed). Surfaced via `$/php-lsp/debugStats` as a denominator for the
    /// per-file cache sizes below — e.g. `text_cache_len` tracking this 1:1
    /// means it's carrying the workspace's working set, not leaking.
    pub fn workspace_file_count(&self) -> u64 {
        self.lsp_ws_files.len() as u64
    }

    /// Entries in the semantic-tokens delta cache. Evicted per-file on
    /// `did_close`; a value that keeps climbing past the number of files
    /// ever opened in the editor means that eviction isn't firing.
    pub fn token_cache_len(&self) -> u64 {
        self.caches.token_cache.len() as u64
    }

    /// Entries in the mirrored-source-text cache. Expected to track
    /// [`Self::workspace_file_count`] — it shares its `Arc<str>` with
    /// salsa's own `SourceFile::text`, so this is a pointer per file, not a
    /// second copy of the workspace's source.
    pub fn text_cache_len(&self) -> u64 {
        self.caches.text_cache.len() as u64
    }

    /// Entries in the read-through `ParsedDoc` cache. Bounded by
    /// `PARSED_CACHE_CAP` via LRU shedding.
    pub fn parsed_cache_len(&self) -> u64 {
        self.caches.parsed_cache.len() as u64
    }

    /// Entries in the per-file `FileAnalysis` cache. Bounded by
    /// `ANALYSIS_CACHE_CAP` via LRU shedding.
    pub fn analysis_cache_len(&self) -> u64 {
        self.caches.analysis_cache.len() as u64
    }

    /// Entries in the owned-`Program` cache. Bounded by
    /// `OWNED_PROGRAM_CACHE_CAP` via LRU shedding.
    pub fn owned_program_cache_len(&self) -> u64 {
        self.caches.owned_program_cache.len() as u64
    }

    /// Entries in the lazily-loaded vendor `FileIndex` cache, populated by
    /// PSR-4 "go to definition" navigation into `vendor/`. Unlike the other
    /// per-file caches above, this one has no LRU cap today — a session with
    /// heavy navigation through a large dependency tree will keep growing
    /// this for the life of the process.
    pub fn vendor_index_cache_len(&self) -> u64 {
        self.caches.vendor_index_cache.len() as u64
    }

    /// Per-file text scans recorded in mir's own `ClassMentionIndex` — the
    /// single shared backend every [`Self::resolve_reachability_queries`]
    /// needle is answered by, whether it's a fully-qualified literal or a
    /// raw call-token needle. The ratio against `reachability_scan_passes`
    /// is the per-file mention cache's hit rate; a warm, unedited repeat
    /// query should bump `reachability_scan_passes` without bumping this at
    /// all.
    pub(crate) fn mir_mention_scans_recorded(&self) -> u64 {
        self.with_session(|session| session.class_mention_stats().scans_recorded)
    }

    /// Return the raw source text for `uri` if it has been mirrored into the
    /// salsa workspace. Used by the references handler to pre-filter session
    /// results by checking whether a file mentions the owning class name.
    pub fn source_text(&self, uri: &Uri) -> Option<Arc<str>> {
        self.caches.text_cache.get(uri).map(|e| Arc::clone(&e))
    }

    /// Cache the semantic tokens computed for a delta response.
    /// `result_id` is an opaque string (a hash of the token data) returned to the client.
    pub fn store_token_cache(&self, uri: &Uri, result_id: String, tokens: Arc<Vec<SemanticToken>>) {
        self.caches.store_token(uri, result_id, tokens);
    }

    /// Return the cached tokens if `result_id` matches the stored one.
    pub fn get_token_cache(&self, uri: &Uri, result_id: &str) -> Option<Arc<Vec<SemanticToken>>> {
        self.caches.get_token(uri, result_id)
    }

    /// Raw semantic issues for a file, computed via mir's session-based
    /// `FileAnalyzer`. The session lazy-loads dependencies via PSR-4 so the
    /// LSP no longer needs to mirror vendor up-front. Callers apply their
    /// own `DiagnosticsConfig` filter via
    /// [`crate::semantic_diagnostics::issues_to_diagnostics`].
    #[tracing::instrument(skip_all)]
    pub fn get_semantic_issues_salsa(&self, uri: &Uri) -> Option<Arc<[mir_issues::Issue]>> {
        let analysis = self.cached_analysis(uri)?;
        let file: Arc<str> = Arc::from(uri.as_str());
        // Workspace-level class issues for this file (circular inheritance,
        // override violations, abstract-method gaps). These are session-wide
        // (a dependency edit changes them without changing this file's bytes),
        // so they are recomputed live rather than cached alongside the
        // per-file body analysis.
        let class_issues = {
            let _s = tracing::debug_span!("session.class_issues_for").entered();
            self.with_snapshot(
                |session| session.prepare_for_query(None),
                |snap| snap.class_issues(std::slice::from_ref(&file)),
            )
            .ok()?
        };
        // `collector_issues` includes raw `ParseError` issues; callers filter
        // those out downstream in `issues_to_diagnostics` (php-lsp already
        // surfaces parse errors as `SyntaxError` diagnostics from its own
        // parser pass), so this returns them unfiltered here.
        let collector_issues = self
            .with_snapshot(
                |_| {},
                |snap| snap.collector_issues(std::slice::from_ref(&file)),
            )
            .ok()?;
        let combined: Vec<mir_issues::Issue> = analysis
            .issues
            .iter()
            .cloned()
            .chain(class_issues)
            .chain(collector_issues)
            .filter(|i| !i.suppressed)
            .collect();
        Some(Arc::from(combined))
    }

    /// Resolve only the codebase symbol identity at `offset` in `uri`.
    ///
    /// This targeted navigation path lets reference queries avoid php-lsp's
    /// retained whole-file [`mir_analyzer::FileAnalysis`] merely to call
    /// `symbol_at(...).kind.to_name()`.
    pub fn mir_name_at(
        &self,
        uri: &Uri,
        offset: u32,
    ) -> Result<Option<mir_analyzer::Name>, ContentModified> {
        let file: Arc<str> = Arc::from(uri.as_str());
        self.with_snapshot(
            |session| session.prepare_for_query(Some(&file)),
            |snap| snap.name_at(&file, offset),
        )
    }

    /// Run (or reuse) mir's per-file body analysis, retaining the full
    /// [`mir_analyzer::FileAnalysis`] — issues **and** resolved symbols — across
    /// requests. Diagnostics read `.issues`; position features call
    /// `.symbol_at(offset)` for the resolved type at a cursor.
    ///
    /// Cache hit when the entry's captured source `Arc` is pointer-equal to the
    /// file's current `doc.source_arc()`. A miss recomputes and overwrites, so
    /// the entry self-evicts on any content edit.
    /// Cache-hit-only variant of [`Self::cached_analysis`]: returns the cached
    /// analysis when the entry is current for the file's text, never computes.
    /// Lets async handlers take the warm path synchronously and reserve
    /// `spawn_blocking` for the cold path (mir Pass 1 + Pass 2 can take
    /// hundreds of ms on large files).
    pub fn cached_analysis_if_fresh(&self, uri: &Uri) -> Option<Arc<mir_analyzer::FileAnalysis>> {
        let doc = self.get_doc_salsa(uri)?;
        let source = doc.source_arc();
        let cur_ver = self.caches.decl_version();
        let analysis = {
            let entry = self.caches.analysis_cache.get(uri)?;
            (Arc::ptr_eq(&entry.source, &source) && entry.decl_version == cur_ver)
                .then(|| entry.analysis.as_ref().map(Arc::clone))??
        };
        self.caches.touch(uri);
        Some(analysis)
    }

    pub fn cached_analysis(&self, uri: &Uri) -> Option<Arc<mir_analyzer::FileAnalysis>> {
        self.cached_analysis_cancellable(uri, &|| false)
    }

    /// Compare `uri`'s current `FileIndex` against its stored declaration
    /// fingerprint. Read-only against the session (`get_index_salsa` takes
    /// its own brief lock via `snapshot_mir_handle_query`) — callers that already
    /// hold the session lock must call this *before* entering `with_session`,
    /// never from inside it: `get_index_salsa` locks the same mutex, and
    /// `std::sync::Mutex` isn't reentrant.
    fn decl_fingerprint_delta(&self, uri: &Uri) -> (bool, Option<Arc<FileIndex>>) {
        let new_index = self.get_index_salsa(uri);
        let old_fp = self
            .caches
            .analysis_cache
            .get(uri)
            .and_then(|e| e.decl_index.as_ref().map(Arc::clone));
        let decl_changed = match (&old_fp, &new_index) {
            (Some(old), Some(new)) => **old != **new,
            (None, Some(new)) => !new.declares_nothing(),
            _ => false,
        };
        (decl_changed, new_index)
    }

    /// Bump php-lsp's analysis-cache generation and refresh the retained
    /// fingerprint entry for a [`Self::decl_fingerprint_delta`] that found a
    /// change. `session` is only needed for `bump_prepare_generation` — the
    /// delta itself must already be computed outside any `with_session` scope
    /// (see that method's doc).
    fn apply_decl_fingerprint(
        &self,
        uri: &Uri,
        session: &mut mir_analyzer::AnalysisSession,
        new_index: &Option<Arc<FileIndex>>,
    ) {
        self.caches.bump_decl_version();
        session.bump_prepare_generation();
        if let Some(source) = self.caches.text_cache.get(uri).map(|t| Arc::clone(&*t)) {
            if let Some(mut entry) = self.caches.analysis_cache.get_mut(uri) {
                entry.source = source;
                entry.decl_index = new_index.as_ref().map(Arc::clone);
                entry.analysis = None;
            } else {
                self.caches.analysis_cache.insert(
                    uri.clone(),
                    AnalysisCacheEntry {
                        source,
                        decl_version: self.caches.decl_version(),
                        decl_index: new_index.as_ref().map(Arc::clone),
                        analysis: None,
                    },
                );
            }
        }
    }

    /// Sync declaration freshness for a file mirrored outside its own
    /// analysis pass. Mir owns resolver/cache invalidation; this protects only
    /// php-lsp's retained [`mir_analyzer::FileAnalysis`] cache, whose entries
    /// are tagged by `decl_version`.
    pub fn sync_analysis_cache_declarations(&self, uri: &Uri) {
        let (decl_changed, new_index) = self.decl_fingerprint_delta(uri);
        if decl_changed {
            self.with_session(|session| self.apply_decl_fingerprint(uri, session, &new_index));
        }
    }

    /// [`Self::cached_analysis`] with an early exit: `should_cancel` is
    /// polled whenever a concurrent salsa write cancels the analysis attempt.
    /// A handler passes its write-revision staleness probe so a request made
    /// obsolete by newer typing stops burning a blocking-pool thread instead
    /// of retrying until the writer pauses — the editor re-requests anyway.
    #[tracing::instrument(skip_all)]
    pub fn cached_analysis_cancellable(
        &self,
        uri: &Uri,
        should_cancel: &(dyn Fn() -> bool + Sync),
    ) -> Option<Arc<mir_analyzer::FileAnalysis>> {
        // Need the parsed doc both for the analyzer and as the cache key.
        let doc = self.get_doc_salsa(uri)?;
        let source = doc.source_arc();

        if let Some(hit) = self.cached_analysis_if_fresh(uri) {
            return Some(hit);
        }

        // Serialize concurrent callers analyzing the SAME uncached file onto
        // one computation instead of each redoing the full mir pass — e.g.
        // `did_open`'s diagnostics trigger racing a fast-following hover on a
        // large just-opened file (tower-lsp's default concurrency runs up to
        // 4 in-flight LSP messages at once, so this genuinely happens). Other
        // files never contend: the lock is per-URI.
        let inflight = Arc::clone(
            self.analysis_inflight
                .entry(uri.clone())
                .or_insert_with(|| Arc::new(Mutex::new(())))
                .value(),
        );
        // Guards `()`: a panicked analysis must not wedge this URI forever.
        let _inflight_guard = inflight
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);

        // Re-check now that we hold the per-URI lock: whoever we waited on
        // may have just populated the cache. `cur_ver` becomes the freshness
        // tag on OUR insert below, so re-fetching it here (rather than reusing
        // a value captured before we waited) reflects what was actually true
        // right before we started computing, not before we started waiting.
        if let Some(hit) = self.cached_analysis_if_fresh(uri) {
            return Some(hit);
        }
        let cur_ver = self.caches.decl_version();

        let file: Arc<str> = Arc::from(uri.as_str());

        let source_map = php_rs_parser::source_map::SourceMap::new(doc.source());
        let owned_program = if let Some(cached) = self.caches.owned_program_cache.get(uri)
            && Arc::ptr_eq(&cached.0, &source)
        {
            Arc::clone(&cached.1)
        } else {
            let prog = Arc::new(php_ast::owned::to_owned_program(doc.program()));
            self.caches.shed_stale(
                &self.caches.owned_program_cache,
                crate::document::cache_registry::OWNED_PROGRAM_CACHE_CAP,
            );
            self.caches
                .owned_program_cache
                .insert(uri.clone(), (Arc::clone(&source), Arc::clone(&prog)));
            prog
        };

        // autoload.files helpers (e.g. Laravel's tap()) must be ingested so mir sees their functions.
        let autoload_texts: Vec<(Arc<str>, Arc<str>)> = {
            let autoload_uris = self.autoload_uris.read().unwrap().clone();
            autoload_uris
                .iter()
                .filter_map(|auri| {
                    self.caches
                        .text_cache
                        .get(auri)
                        .map(|t| (Arc::from(auri.as_str()), Arc::clone(&*t)))
                })
                .collect()
        };
        // Bare same-namespace / use-imported class refs aren't resolved by mir's priority_index_for_ast; preload them.
        let class_fqns = crate::navigation::references::collect_referenced_class_fqns(&doc);

        // Re-ingesting on a retry would overwrite a newer edit with `source`,
        // so a superseded attempt skips the write and fails fast.
        let superseded = std::cell::Cell::new(false);
        let analysis = self.with_snapshot(
            |session| {
                let text_changed = self
                    .caches
                    .text_cache
                    .get(uri)
                    .is_none_or(|t| !Arc::ptr_eq(&t, &source));
                if text_changed || should_cancel() {
                    superseded.set(true);
                    return;
                }
                session.ingest_file(file.clone(), source.clone());
                for (afile, atext) in &autoload_texts {
                    session.ingest_file(afile.clone(), atext.clone());
                }
                for fqcn in &class_fqns {
                    let _ = session.load_class(fqcn);
                }
                session.prepare_for_query(Some(&file));
            },
            |snap| {
                if superseded.get() {
                    return Err(salsa::Cancelled::PendingWrite);
                }
                snap.analyze(file.clone(), doc.source(), &owned_program, &source_map)
            },
        );
        let analysis = Arc::new(analysis.ok()?);
        self.analysis_compute_count.fetch_add(1, Ordering::Relaxed);
        // Keep php-lsp's retained FileAnalysis cache coherent with declaration
        // changes discovered while analyzing this file. Mir owns its own
        // invalidation; this protects only php-lsp's in-memory analysis_cache.
        // `decl_fingerprint_delta` takes its own brief session lock, so it
        // must run outside any `with_session` scope.
        let (decl_changed, decl_index) = self.decl_fingerprint_delta(uri);
        if decl_changed {
            self.with_session(|session| self.apply_decl_fingerprint(uri, session, &decl_index));
        }
        let ver = cur_ver + u64::from(decl_changed);
        self.caches.shed_stale(
            &self.caches.analysis_cache,
            crate::document::cache_registry::ANALYSIS_CACHE_CAP,
        );
        self.caches.touch(uri);
        self.caches.analysis_cache.insert(
            uri.clone(),
            AnalysisCacheEntry {
                source,
                decl_version: ver,
                decl_index,
                analysis: Some(Arc::clone(&analysis)),
            },
        );
        Some(analysis)
    }

    /// Returns `(uri, doc)` for files currently open in the editor.
    ///
    /// Resolve `open_urls` (from `Backend::open_urls()`) to parsed docs.
    /// Files not mirrored in the salsa layer are filtered out silently.
    pub fn docs_for(&self, open_urls: &[Uri]) -> Vec<(Uri, Arc<ParsedDoc>)> {
        open_urls
            .iter()
            .filter_map(|u| self.get_doc_salsa(u).map(|d| (u.clone(), d)))
            .collect()
    }

    /// Parsed docs for every entry in `open_urls` except `uri`.
    pub fn other_docs(&self, uri: &Uri, open_urls: &[Uri]) -> Vec<(Uri, Arc<ParsedDoc>)> {
        open_urls
            .iter()
            .filter(|u| *u != uri)
            .filter_map(|u| self.get_doc_salsa(u).map(|d| (u.clone(), d)))
            .collect()
    }

    /// Borrow-scoped access to the aggregate `(Uri, Arc<FileIndex>)` slice,
    /// avoiding per-call cloning of the workspace-wide vector.
    pub fn with_all_indexes<R>(&self, f: impl FnOnce(&[(Uri, Arc<FileIndex>)]) -> R) -> R {
        f(&self.get_workspace_index_salsa().files)
    }

    /// Store a lazily-loaded vendor `FileIndex` in the session cache.
    /// Only call this for files that are not part of the normal workspace scan
    /// (i.e. vendor files loaded on-demand by PSR-4 navigation).
    pub fn cache_vendor_index(&self, uri: Uri, index: Arc<FileIndex>) {
        self.caches.vendor_index_cache.insert(uri, index);
    }

    /// Retrieve a previously cached vendor `FileIndex`.
    pub fn get_vendor_index(&self, uri: &Uri) -> Option<Arc<FileIndex>> {
        self.caches
            .vendor_index_cache
            .get(uri)
            .map(|e| Arc::clone(&*e))
    }

    /// Parses only the workspace files whose raw text
    /// mentions at least one of `needles` as a whole identifier
    /// (ASCII-case-insensitive — PHP class names are case-insensitive). Used
    /// by callers scanning for a class/interface *declaration* by name (e.g.
    /// "implement missing methods"), where the needle set is small and a miss
    /// guarantees the file declares none of them.
    ///
    /// Answered from mir's persistent per-file `ClassMentionIndex` — the
    /// same cache the reference/subtype gates and
    /// [`Self::resolve_reachability_queries`] populate — so a file scanned
    /// here answers later reference queries for free, and vice versa. Text
    /// comes from this store's own mirror (`source_text`), same as before;
    /// `class_mention_answer` validates cache freshness against it, so a
    /// file whose mirror diverges from mir's copy is simply rescanned.
    pub fn docs_for_scan_mentioning(&self, needles: &[String]) -> Vec<(Uri, Arc<ParsedDoc>)> {
        if needles.is_empty() {
            return Vec::new();
        }
        // Scoped so the mir snapshot drops before `get_doc_salsa` below —
        // same writer-starvation discipline as
        // `resolve_reachability_queries_uncached`.
        let urls: Vec<Uri> = {
            let mir_db = self.with_session(|session| session.snapshot_db());
            mir_db.add_literal_mention_names(needles.iter().map(|s| s.as_str()));
            let queries: Vec<mir_analyzer::db::MentionQuery> = needles
                .iter()
                .filter_map(|n| mir_db.prepare_class_mention_query(n))
                .collect();
            if queries.is_empty() {
                return Vec::new();
            }
            let scanner = mir_db.class_mention_scanner();
            self.lsp_ws_files
                .iter()
                .filter(|e| !self.deleted_uris.contains(e.key()))
                .filter(|e| {
                    let Some(text) = self.source_text(e.key()) else {
                        return false;
                    };
                    let url_str = e.key().as_str();
                    let mut unanswered = false;
                    for q in &queries {
                        match mir_db.class_mention_answer(url_str, q, &text) {
                            Some(true) => return true,
                            Some(false) => {}
                            None => unanswered = true,
                        }
                    }
                    if !unanswered {
                        return false;
                    }
                    let Some(scanner) = &scanner else {
                        // Defensive only: the needles were admitted above,
                        // so the universe (and scanner) can't be empty.
                        return needles
                            .iter()
                            .any(|n| crate::text::contains_ascii_case_insensitive(&text, n));
                    };
                    let names = scanner.scan(text.as_ref());
                    let hit = queries.iter().any(|q| names.binary_search(&q.name).is_ok());
                    mir_db.set_file_class_mentions(
                        &Arc::<str>::from(url_str),
                        &text,
                        scanner.epoch(),
                        names,
                    );
                    hit
                })
                .map(|e| e.key().clone())
                .collect()
        };
        urls.into_iter()
            .filter_map(|u| self.get_doc_salsa(&u).map(|d| (u, d)))
            .collect()
    }

    /// Subset of `files` (mir paths) mentioning `short_name` as a whole
    /// identifier, ASCII-case-insensitive, via mir's shared per-file mention
    /// cache, scanned off the session lock. A file mir doesn't know is
    /// omitted; if writes keep cancelling the scan, every file is returned.
    pub fn files_mentioning_short_name(
        &self,
        files: &[Arc<str>],
        short_name: &str,
    ) -> Vec<Arc<str>> {
        self.with_snapshot(
            |_| {},
            |snap| snap.files_mentioning_any(files, &[short_name]),
        )
        .unwrap_or_else(|_| files.to_vec())
    }

    /// Candidate files that may *declare* something named `name` anywhere in
    /// the workspace (function/class/method/property/constant/enum-case),
    /// narrowed via mir's persistent per-file mention cache instead of an
    /// eagerly-rebuilt `name → [DeclRef]` map. A miss means no file's text
    /// contains `name` at all, so nothing declares it either — same
    /// necessary-not-sufficient contract as `files_mentioning_short_name`;
    /// callers must still verify the candidate actually declares `name` (via
    /// its own `FileIndex`/AST), same as they always have. Unlike an eagerly
    /// rebuilt map, an edit to file X only invalidates X's own cached mention
    /// set, not the whole workspace's.
    pub fn declaration_candidate_files(
        &self,
        wi: &crate::db::workspace_index::WorkspaceIndexData,
        name: &str,
    ) -> Vec<Uri> {
        self.files_mentioning_short_name(&wi.file_paths, name)
            .iter()
            .filter_map(|p| p.parse::<Uri>().ok())
            .collect()
    }

    fn definition_location(&self, name: &mir_analyzer::Name) -> Option<mir_types::Location> {
        self.with_snapshot(|_| {}, |snap| snap.definition_of_cached(name))
            .ok()?
            .ok()
    }

    /// O(1) resolution of a *known* FQN to its declaring class, via mir's own
    /// incrementally-maintained FQN→location index (`definition_of_cached`,
    /// backed by the same singleton `all_classes()`/`workspace_classes` read
    /// from — no rebuild-from-scratch, no per-call scan over every workspace
    /// file). No php-lsp-side duplicate structure involved. Use this whenever
    /// the caller already has a resolved FQN, not just a bare short name
    /// needing disambiguation; falls back to `None` (never wrong, just not
    /// fast) when mir hasn't loaded/committed the class yet.
    pub fn class_ref_by_fqn(
        &self,
        wi: &crate::db::workspace_index::WorkspaceIndexData,
        fqn: &str,
    ) -> Option<crate::db::workspace_index::ClassRef> {
        let trimmed = fqn.trim_start_matches('\\');
        let name = mir_analyzer::Name::Class(Arc::from(trimmed));
        let loc = self.definition_location(&name)?;
        let &file_idx = wi.path_to_file_idx.get(loc.file.as_ref())?;
        let (_, idx) = wi.files.get(file_idx as usize)?;
        let class_idx = idx
            .classes
            .iter()
            .position(|c| c.fqn.trim_start_matches('\\').eq_ignore_ascii_case(trimmed))?;
        Some(crate::db::workspace_index::ClassRef {
            file: file_idx,
            class: class_idx as u32,
        })
    }

    /// Resolve a *known* FQN to its declaring class. This is the default
    /// lookup path for callers that already resolved imports/aliases or are
    /// following a semantic symbol carrying an FQN.
    pub fn resolve_class_ref_by_fqn(
        &self,
        wi: &crate::db::workspace_index::WorkspaceIndexData,
        fqn: &str,
    ) -> Option<crate::db::workspace_index::ClassRef> {
        self.class_ref_by_fqn(wi, fqn)
    }

    /// O(1) resolution of a known FQN to its declaring global function via
    /// mir's incrementally-maintained definition index. As with
    /// [`Self::class_ref_by_fqn`], validate the result against the current
    /// workspace snapshot before returning its compact index back-pointer.
    pub fn function_ref_by_fqn(
        &self,
        wi: &crate::db::workspace_index::WorkspaceIndexData,
        fqn: &str,
    ) -> Option<crate::db::workspace_index::FunctionRef> {
        let trimmed = fqn.trim_start_matches('\\');
        let name = mir_analyzer::Name::function(trimmed.to_string());
        let loc = self.definition_location(&name)?;
        let &file_idx = wi.path_to_file_idx.get(loc.file.as_ref())?;
        let (_, idx) = wi.files.get(file_idx as usize)?;
        let function_idx = idx
            .functions
            .iter()
            .position(|function| function.fqn.trim_start_matches('\\') == trimmed)?;
        Some(crate::db::workspace_index::FunctionRef {
            file: file_idx,
            function: function_idx as u32,
        })
    }

    /// O(candidates) replacement for the old `decls_by_name`-backed linear
    /// scan: find a declaration named `word` anywhere in the workspace,
    /// optionally excluding one file (the current document, which the
    /// caller has already searched with accurate AST ranges), via
    /// [`Self::declaration_candidate_files`] + the same per-file check
    /// `goto_declaration_from_index` uses.
    pub fn find_declaration(
        &self,
        wi: &crate::db::workspace_index::WorkspaceIndexData,
        word: &str,
        exclude: Option<&Uri>,
    ) -> Option<tower_lsp_server::ls_types::Location> {
        let bare = crate::text::strip_variable_sigil(word);
        let exclude = exclude.map(|u| u.as_str());
        self.files_mentioning_short_name(&wi.file_paths, word)
            .into_iter()
            .filter(|p| exclude != Some(p.as_ref()))
            .find_map(|p| {
                let &file_idx = wi.path_to_file_idx.get(p.as_ref())?;
                let (uri, _) = wi.files.get(file_idx as usize)?;
                let doc = self.get_doc_salsa(uri)?;
                crate::navigation::declaration::any_declaration_in_doc(uri, &doc, word, bare)
            })
    }

    /// Files whose `use` imports include the class `fqn` (leading `\` ignored
    /// — PHP names are case-insensitive), from mir's `use:` postings. The
    /// candidate scope for `use`-line rewrites on file rename/delete: only
    /// importers can carry such a line.
    pub fn files_importing(&self, fqn: &str) -> Vec<Uri> {
        let symbol = mir_analyzer::Name::class(fqn.trim_start_matches('\\').to_string());
        let files = self.reference_candidate_files(&symbol);
        // `use:` postings are read-only lookups; warm the candidate set first
        // so cold/uncommitted files commit their current import postings.
        let _ = self.indexed_references(&symbol, &files, false, None);
        self.indexed_use_imports(&symbol, &files)
            .unwrap_or_default()
            .into_iter()
            .filter_map(|(file, _, _, _)| file.parse::<Uri>().ok())
            .collect::<std::collections::HashSet<_>>()
            .into_iter()
            .collect()
    }
}

/// `prefix` equals `whole` or is a `\`-segment-aligned prefix of it,
/// ASCII-case-insensitively (PHP name semantics). `"Foo\Bar"` is a segment
/// prefix of `"Foo\Bar\Baz"` but `"Foo\Ba"` is not.
fn fqn_segment_prefix(prefix: &str, whole: &str) -> bool {
    let (p, w) = (prefix.as_bytes(), whole.as_bytes());
    w.len() >= p.len()
        && w[..p.len()].eq_ignore_ascii_case(p)
        && (w.len() == p.len() || w[p.len()] == b'\\')
}

/// `uri`'s path has a `vendor` component, e.g. `file:///proj/vendor/acme/Lib.php`
/// or the nested-monorepo `file:///proj/packages/api/vendor/x/Y.php`. URI
/// paths are always `/`-separated regardless of platform, so a plain
/// component split is enough — no OS path handling needed.
fn is_vendor_uri(uri: &Uri) -> bool {
    is_vendor_path_str(uri.path().as_str())
}

/// [`is_vendor_uri`] on a raw URI/path string, for callers already holding
/// one (e.g. the `Arc<str>` candidate lists `reference_candidate_files`
/// deals in) instead of a parsed [`Uri`].
fn is_vendor_path_str(s: &str) -> bool {
    s.split('/').any(|seg| seg == "vendor")
}

/// The narrowing decision for a method's reference scope, computed without
/// running the expensive part (the FQN/text-needle workspace scan) so a
/// batch caller can pool that scan across many methods.
enum MethodScopePlan {
    /// Fully resolved already — no workspace scan needed at all (private:
    /// the declaring file alone; protected: the declaring file plus its
    /// resolved subtype set).
    Files(Vec<Uri>),
    /// A public static method or constructor: resolvable to the declaring
    /// class's FQN-reachable files unioned with files matching one extra
    /// text needle. This is the case a batch caller pools.
    NeedsScan {
        fqns: Vec<Arc<str>>,
        extra_needle: String,
    },
    /// No narrowing possible (instance methods, an unresolvable owner, or
    /// the boot scan hasn't finished) — full workspace scope.
    FullWorkspace,
}

/// One [`DocumentStore::resolve_reachability_queries`] request: the target
/// FQNs for the namespace/import rules, plus raw text needles matched the
/// same way (ASCII-case-insensitive substring).
#[derive(Clone, PartialEq, Eq, Hash)]
struct ReachabilityQuery {
    kind: ReachabilitySymbolKind,
    fqns: Vec<Arc<str>>,
    extra_needles: Vec<String>,
}

#[derive(Clone, Copy, PartialEq, Eq, Hash)]
enum ReachabilitySymbolKind {
    Class,
    Function,
    GlobalConstant,
}

/// Memoized [`DocumentStore::resolve_reachability_queries`] results: query
/// -> `(write_revision computed at, resolved file list)`. See the field doc
/// on `DocumentStore::reachability_result_cache`.
type ReachabilityResultCache = DashMap<ReachabilityQuery, (u64, Arc<Vec<Arc<str>>>)>;

#[cfg(test)]
mod tests {
    #[test]
    fn warm_chunk_that_never_settles_is_skipped_after_bounded_attempts() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        let queue: Vec<Arc<str>> = (0..70).map(|i| Arc::from(format!("f{i}.php"))).collect();
        let cancel = mir_analyzer::IndexCancel::new();
        let calls = AtomicUsize::new(0);
        let settled = run_chunks(
            &queue,
            32,
            &cancel,
            None,
            || {},
            |chunk| {
                calls.fetch_add(1, Ordering::Relaxed);
                // Only the middle chunk (files 32..64) always fails.
                chunk[0].as_ref() != "f32.php"
            },
        );
        assert!(!settled, "a skipped chunk must leave the sweep unsettled");
        // Two healthy chunks once each, plus the failing one bounded.
        assert_eq!(calls.load(Ordering::Relaxed), 2 + WARM_CHUNK_ATTEMPTS);
    }

    #[test]
    fn warm_chunk_retries_until_a_transient_failure_clears() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        let queue: Vec<Arc<str>> = vec![Arc::from("a.php")];
        let cancel = mir_analyzer::IndexCancel::new();
        let calls = AtomicUsize::new(0);
        let settled = run_chunks(
            &queue,
            32,
            &cancel,
            None,
            || {},
            |_| calls.fetch_add(1, Ordering::Relaxed) >= 2,
        );
        assert!(settled);
        assert_eq!(calls.load(Ordering::Relaxed), 3);
    }

    use super::*;

    #[test]
    fn write_settle_waits_for_a_quiet_revision() {
        let mut settle = WriteSettle::new(1);
        assert!(!settle.settled(2));
        assert!(!settle.settled(3));
        assert!(settle.settled(3));
    }

    fn uri(path: &str) -> Uri {
        format!("file://{path}").parse::<Uri>().unwrap()
    }

    /// Phase E4: open-file state lives on `Backend`, not `DocumentStore`.
    /// Tests that need to simulate "file is open" just mirror the text into
    /// the salsa input — the open/closed distinction is enforced by the
    /// caller (Backend) in production.
    fn open(store: &DocumentStore, u: Uri, text: String) {
        store.mirror_text(&u, &text);
    }

    // Spawn a thread that calls `yield_to_interactive_reads` and hands back
    // the elapsed time it spent waiting. It signals `ready` right before
    // entering the call, so the caller can block on that signal instead of
    // guessing how long thread start-up takes — a fixed sleep here would
    // race the thread scheduler, and that race is exactly what made this
    // test flaky under load (e.g. Windows CI runners have much coarser and
    // less predictable thread-spawn latency than Linux/macOS).
    fn spawn_yield_waiter(
        store: &Arc<DocumentStore>,
    ) -> (
        std::sync::mpsc::Receiver<()>,
        std::thread::JoinHandle<std::time::Duration>,
    ) {
        let (ready_tx, ready_rx) = std::sync::mpsc::channel();
        let store = Arc::clone(store);
        let handle = std::thread::spawn(move || {
            ready_tx.send(()).unwrap();
            let t = std::time::Instant::now();
            store.yield_to_interactive_reads();
            t.elapsed()
        });
        (ready_rx, handle)
    }

    #[test]
    fn scan_writers_yield_while_interactive_reads_are_in_flight() {
        let store = Arc::new(DocumentStore::new());

        // No guard: returns immediately.
        let t = std::time::Instant::now();
        store.yield_to_interactive_reads();
        assert!(t.elapsed() < std::time::Duration::from_millis(200));

        // Guard held on another thread: the writer waits until it drops.
        // We only start the hold timer once the waiter has confirmed it's
        // about to poll, so the guard can never be dropped before the
        // writer starts waiting on it.
        let guard = store.interactive_read_guard();
        let (ready_rx, waiter) = spawn_yield_waiter(&store);
        ready_rx.recv().unwrap();
        const HOLD: std::time::Duration = std::time::Duration::from_millis(60);
        std::thread::sleep(HOLD);
        drop(guard);
        let waited = waiter.join().unwrap();
        assert!(
            waited >= HOLD,
            "writer should have paused at least as long as the read guard was held (waited {waited:?})"
        );

        // Guard fully released: nested guards count correctly.
        let g1 = store.interactive_read_guard();
        let g2 = store.interactive_read_guard();
        drop(g1);
        let (ready_rx, waiter) = spawn_yield_waiter(&store);
        ready_rx.recv().unwrap();
        const HOLD2: std::time::Duration = std::time::Duration::from_millis(30);
        std::thread::sleep(HOLD2);
        drop(g2);
        let waited = waiter.join().unwrap();
        assert!(
            waited >= HOLD2,
            "writer should have paused while the nested read guard was held (waited {waited:?})"
        );
        store.yield_to_interactive_reads(); // all guards dropped — no wait
    }

    #[test]
    fn index_registers_file_in_salsa() {
        let store = DocumentStore::new();
        store.ingest(uri("/lib.php"), "<?php\nfunction lib_fn() {}");
        let idx = store.get_index_salsa(&uri("/lib.php")).unwrap();
        assert_eq!(idx.functions.len(), 1);
        assert_eq!(&*idx.functions[0].name, "lib_fn");
    }

    #[test]
    fn remove_hides_file_from_index() {
        let store = DocumentStore::new();
        let u = uri("/lib.php");
        store.ingest(u.clone(), "<?php");
        store.remove(&u);
        assert!(store.get_index_salsa(&u).is_none());
    }

    #[test]
    fn remove_frees_mir_source_text() {
        let store = DocumentStore::new();
        let u = uri("/lib.php");
        let big_text = format!("<?php\n{}", "// pad\n".repeat(1000));
        store.ingest(u.clone(), &big_text);

        let sf = store.with_session(|session| session.lookup_source_file(u.as_str()).unwrap());
        let len_before = store.snapshot_mir_query(|db| sf.text(db).len());
        assert!(len_before > 1000, "sanity: source text should be mirrored");

        store.remove(&u);

        let len_after = store.snapshot_mir_query(|db| sf.text(db).len());
        assert_eq!(
            len_after, 0,
            "remove() must free mir's SourceFile text, not just hide the file from indexes"
        );
    }

    #[test]
    fn remove_shrinks_file_index_memo() {
        let store = DocumentStore::new();
        let u = uri("/lib.php");
        store.ingest(u.clone(), "<?php\nclass BigClassBeforeDelete {}\n");

        let wf = store.lsp_ws_files.get(&u).map(|e| *e).unwrap();
        let idx_before =
            store.snapshot_mir_query(|db| crate::db::mir_queries::file_index(db, wf).0.clone());
        assert_eq!(
            idx_before.classes.len(),
            1,
            "sanity: class should be indexed"
        );

        store.remove(&u);

        let idx_after =
            store.snapshot_mir_query(|db| crate::db::mir_queries::file_index(db, wf).0.clone());
        assert!(
            idx_after.classes.is_empty(),
            "remove() must shrink file_index's memo (no LRU cap, unlike parsed_doc/symbol_map) \
             against the emptied text, not hold the pre-deletion FileIndex forever"
        );
    }

    #[test]
    fn remove_and_reopen_reuses_source_file_handle() {
        let store = DocumentStore::new();
        let u = uri("/lib.php");
        store.ingest(u.clone(), "<?php");
        let ft_before = store.source_file(&u).unwrap();
        store.remove(&u);
        assert!(
            store.source_file(&u).is_none(),
            "deleted file should be hidden"
        );
        store.mirror_text(&u, "<?php");
        let ft_after = store.source_file(&u).unwrap();
        assert!(
            ft_before == ft_after,
            "reopen must reuse the same FileText handle"
        );
    }

    #[test]
    fn delete_reopen_churn_does_not_amplify_salsa_inputs() {
        let store = DocumentStore::new();
        let uris: Vec<Uri> = (0..20).map(|i| uri(&format!("/churn/f{i}.php"))).collect();
        for u in &uris {
            store.ingest(u.clone(), "<?php class A {}");
        }
        let count_before = store.source_files_len();
        for _ in 0..10 {
            for u in &uris {
                store.remove(u);
            }
            for u in &uris {
                store.ingest(u.clone(), "<?php class A {}");
            }
        }
        assert_eq!(
            store.source_files_len(),
            count_before,
            "delete-reopen cycles must not create new salsa inputs (L1-B regression guard)"
        );
    }

    #[test]
    fn warm_analysis_sweep_preserves_reference_results() {
        let store = DocumentStore::new();
        store.ingest(
            uri("/svc.php"),
            "<?php\nnamespace App;\nclass Svc { public function run(): void {} }",
        );
        store.ingest(
            uri("/caller.php"),
            "<?php\nnamespace App;\nclass Caller {\n    private Svc $s;\n    public function go(): void { $this->s->run(); }\n}",
        );
        let sym = mir_analyzer::Name::method("App\\Svc", "run");
        let files: Vec<Arc<str>> = [uri("/svc.php"), uri("/caller.php")]
            .iter()
            .map(|u| Arc::from(u.as_str()))
            .collect();
        let cold = store.indexed_references(&sym, &files, false, None).unwrap();
        assert_eq!(cold.len(), 1, "caller.php references Svc::run once");
        expect_test::expect![[r#"
            [
                (
                    "file:///caller.php",
                    4,
                    43,
                    46,
                ),
            ]
        "#]]
        .assert_debug_eq(&cold);

        let cancel = store.begin_warm_sweep();
        store.warm_analysis_sweep(&[], &cancel);
        let warm = store.indexed_references(&sym, &files, false, None).unwrap();
        assert_eq!(cold, warm, "sweep must not change reference results");

        // An edit after the sweep is still picked up (memos revalidate).
        store.ingest(
            uri("/caller.php"),
            "<?php\nnamespace App;\nclass Caller {\n    private Svc $s;\n    public function go(): void { $this->s->run(); $this->s->run(); }\n}",
        );
        let cancel = store.begin_warm_sweep();
        store.warm_analysis_sweep(&[], &cancel);
        let after_edit = store.indexed_references(&sym, &files, false, None).unwrap();
        assert_eq!(after_edit.len(), 2, "re-sweep must see the new reference");
        expect_test::expect![[r#"
            [
                (
                    "file:///caller.php",
                    4,
                    43,
                    46,
                ),
                (
                    "file:///caller.php",
                    4,
                    60,
                    63,
                ),
            ]
        "#]]
        .assert_debug_eq(&after_edit);
    }

    #[test]
    fn sweep_priority_puts_open_files_and_their_dependencies_first() {
        let store = DocumentStore::new();
        store.ingest(
            uri("/a.php"),
            "<?php\nnamespace App;\nclass A { public function go(B $b): void {} }",
        );
        store.ingest(uri("/b.php"), "<?php\nnamespace App;\nclass B {}");
        store.ingest(uri("/unrelated.php"), "<?php\nnamespace App;\nclass C {}");
        store.mark_index_ready();

        let front = store.sweep_priority_files(&[uri("/a.php")]);
        let front: Vec<&str> = front.iter().map(|f| f.as_ref()).collect();
        assert_eq!(
            front,
            vec![uri("/a.php").as_str(), uri("/b.php").as_str()],
            "open file first, then the files declaring its referenced classes"
        );
    }

    #[test]
    fn sweep_candidate_files_excludes_vendor_from_the_ambient_tail() {
        let store = DocumentStore::new();
        store.ingest(
            uri("/vendor/acme/Lib.php"),
            "<?php\nnamespace Acme;\nclass Lib {}",
        );
        store.ingest(uri("/src/Own.php"), "<?php\nnamespace App;\nclass Own {}");
        store.mark_index_ready();

        let files = store.sweep_candidate_files(&[]);
        let files: Vec<&str> = files.iter().map(|f| f.as_ref()).collect();
        assert!(
            !files.contains(&uri("/vendor/acme/Lib.php").as_str()),
            "vendor file must not be in the ambient (non-priority) sweep list: {files:?}"
        );
        assert!(
            files.contains(&uri("/src/Own.php").as_str()),
            "non-vendor file must still be in the ambient sweep list: {files:?}"
        );
    }

    #[test]
    fn sweep_candidate_files_still_includes_an_explicitly_prioritized_vendor_file() {
        let store = DocumentStore::new();
        store.ingest(
            uri("/vendor/acme/Lib.php"),
            "<?php\nnamespace Acme;\nclass Lib {}",
        );
        store.mark_index_ready();

        // Opening the vendor file directly makes it a priority target, which
        // bypasses the ambient-sweep vendor exclusion.
        let files = store.sweep_candidate_files(&[uri("/vendor/acme/Lib.php")]);
        let files: Vec<&str> = files.iter().map(|f| f.as_ref()).collect();
        assert!(
            files.contains(&uri("/vendor/acme/Lib.php").as_str()),
            "an explicitly opened/prioritized vendor file must still be warmed: {files:?}"
        );
    }

    #[test]
    fn is_vendor_uri_matches_top_level_and_nested_vendor_dirs_only() {
        assert!(is_vendor_uri(&uri("/proj/vendor/acme/Lib.php")));
        assert!(is_vendor_uri(&uri(
            "/proj/packages/api/vendor/acme/Lib.php"
        )));
        assert!(!is_vendor_uri(&uri("/proj/src/Vendored/Lib.php")));
        assert!(!is_vendor_uri(&uri("/proj/src/VendorLib.php")));
    }

    #[test]
    fn warm_analysis_sweep_stops_on_cancel() {
        let store = DocumentStore::new();
        for i in 0..40 {
            store.ingest(
                uri(&format!("/f{i}.php")),
                "<?php\nclass A { public function m(): int { return 1; } }",
            );
        }
        let cancel = store.begin_warm_sweep();
        cancel.cancel();
        // Pre-cancelled token: returns without analyzing (must not hang/panic).
        store.warm_analysis_sweep(&[], &cancel);
        // A newer sweep's token supersedes the old one.
        let old = store.begin_warm_sweep();
        let _new = store.begin_warm_sweep();
        assert!(old.is_cancelled());
    }

    #[test]
    fn all_indexes_includes_every_mirrored_file() {
        let store = DocumentStore::new();
        open(&store, uri("/a.php"), "<?php\nfunction a() {}".to_string());
        store.ingest(uri("/b.php"), "<?php\nfunction b() {}");
        let mut uris: Vec<String> = store.with_all_indexes(|indexes| {
            indexes
                .iter()
                .map(|(u, _)| u.as_str().to_string())
                .collect()
        });
        uris.sort();
        assert_eq!(
            uris,
            vec![
                uri("/a.php").as_str().to_string(),
                uri("/b.php").as_str().to_string()
            ]
        );
    }

    #[test]
    fn other_docs_excludes_current_uri() {
        let store = DocumentStore::new();
        let ua = uri("/a.php");
        let ub = uri("/b.php");
        open(&store, ua.clone(), "<?php\nfunction a() {}".to_string());
        open(&store, ub.clone(), "<?php\nfunction b() {}".to_string());
        let open_urls = vec![ua.clone(), ub.clone()];
        let others = store.other_docs(&ua, &open_urls);
        assert_eq!(others.len(), 1);
        assert_eq!(others[0].0.as_str(), ub.as_str());
    }

    #[test]
    fn evict_token_cache_removes_entry() {
        let store = DocumentStore::new();
        let u = uri("/a.php");
        open(&store, u.clone(), "<?php".to_string());
        store.store_token_cache(&u, "id1".to_string(), Arc::new(vec![]));
        assert!(store.get_token_cache(&u, "id1").is_some());
        store.evict_token_cache(&u);
        assert!(store.get_token_cache(&u, "id1").is_none());
    }

    #[test]
    fn vendor_index_cache_evicted_on_remove() {
        let store = DocumentStore::new();
        let u = uri("/vendor/acme/lib.php");
        store.ingest(u.clone(), "<?php\nclass Lib {}");
        let idx = store.get_index_salsa(&u).unwrap();
        store.cache_vendor_index(u.clone(), idx.clone());
        let cached = store.get_vendor_index(&u).unwrap();
        assert!(
            Arc::ptr_eq(&idx, &cached),
            "get_vendor_index must return the exact FileIndex that was cached"
        );
        store.remove(&u);
        assert!(store.get_vendor_index(&u).is_none());
    }

    /// A repeat reachability query against unchanged files must not re-scan
    /// any of them. `fqn_reachable_files` has no raw `extra_needles`, so
    /// it's answered by mir's `ClassMentionIndex` (see
    /// `resolve_reachability_queries_uncached`'s doc comment) —
    /// `mir_mention_scans_recorded` (bumped only on an actual text scan
    /// inside that index) proves this directly rather than inferring it
    /// from timing.
    #[test]
    fn reachability_repeat_query_hits_mention_cache() {
        let store = DocumentStore::new();
        for i in 0..5 {
            open(
                &store,
                uri(&format!("/Other/Noise{i}.php")),
                format!(
                    "<?php\nnamespace Other{i};\nclass N{i} {{ public function run() {{ return new \\App\\Owner(); }} }}\n"
                ),
            );
        }
        store.mark_index_ready();

        let target: Arc<str> = Arc::from("App\\Owner");
        let first = store
            .fqn_reachable_files(std::slice::from_ref(&target))
            .expect("index is ready");
        assert_eq!(
            first.len(),
            5,
            "every noise file textually mentions the target"
        );
        let scans_after_first = store.mir_mention_scans_recorded();
        assert!(
            scans_after_first > 0,
            "cold query must scan the noise files' text at least once"
        );

        let second = store
            .fqn_reachable_files(&[target])
            .expect("index is ready");
        assert_eq!(second.len(), 5);
        assert_eq!(
            store.mir_mention_scans_recorded(),
            scans_after_first,
            "identical repeat query must not re-scan any file's text"
        );
    }

    /// A needle admitted into the universe *after* a file was last scanned
    /// must still be found on that file — the per-file `epoch` check must
    /// force a rescan rather than answering from a mention-set that
    /// predates the needle. Without this, mir's `ClassMentionIndex`'s
    /// "append-only, lazily grown" design would silently under-report
    /// references to any symbol first queried after another symbol already
    /// warmed the cache for the same file.
    #[test]
    fn reachability_new_needle_still_finds_previously_scanned_file() {
        let store = DocumentStore::new();
        open(
            &store,
            uri("/Other/Multi.php"),
            "<?php\nnamespace Other;\nclass Multi { public function run() {\n    new \\App\\First();\n    new \\App\\Second();\n} }\n"
                .to_string(),
        );
        store.mark_index_ready();

        // First query only asks about `First` — this forces a scan of
        // Multi.php's text, caching its mention-set at an epoch that
        // includes `First` but not yet `Second`.
        let first_hits = store
            .fqn_reachable_files(&[Arc::from("App\\First")])
            .expect("index is ready");
        assert_eq!(first_hits.len(), 1);

        // Second query: a brand-new needle never admitted before.
        // Multi.php's cached entry predates it.
        let second_hits = store
            .fqn_reachable_files(&[Arc::from("App\\Second")])
            .expect("index is ready");
        assert_eq!(
            second_hits.len(),
            1,
            "a needle admitted after a file's last scan must still be found on that file"
        );
    }

    /// An edit that adds a new mention must not be served from a stale
    /// cache entry — `Arc::ptr_eq` against the cached `text` must detect
    /// the change and force a fresh scan.
    #[test]
    fn reachability_cache_invalidates_on_edit() {
        let store = DocumentStore::new();
        let target: Arc<str> = Arc::from("App\\Owner");
        let noise = uri("/Other/Noise.php");
        open(
            &store,
            noise.clone(),
            "<?php\nnamespace Other;\nclass Noise {}\n".to_string(),
        );
        store.mark_index_ready();

        let before = store
            .fqn_reachable_files(std::slice::from_ref(&target))
            .expect("index is ready");
        assert!(before.is_empty(), "file does not mention the target yet");

        open(
            &store,
            noise,
            "<?php\nnamespace Other;\nclass Noise { public function run() { return new \\App\\Owner(); } }\n"
                .to_string(),
        );

        let after = store
            .fqn_reachable_files(&[target])
            .expect("index is ready");
        assert_eq!(
            after.len(),
            1,
            "an edit that adds a mention must not be served from a stale cache entry"
        );
    }

    /// A repeat query must not even enter `resolve_reachability_queries_uncached`
    /// — `mention_cache` (proven above) only skips the text scan *inside*
    /// that function, but its outer per-file loop still runs on every call
    /// unless the result itself is cached. `reachability_scan_passes` (bumped
    /// only inside the uncached function) staying flat on the second call
    /// proves the whole function was skipped, not just its scan.
    #[test]
    fn reachability_repeat_query_skips_uncached_function_entirely() {
        let store = DocumentStore::new();
        for i in 0..5 {
            open(
                &store,
                uri(&format!("/Other/Noise{i}.php")),
                format!(
                    "<?php\nnamespace Other{i};\nclass N{i} {{ public function run() {{ return new \\App\\Owner(); }} }}\n"
                ),
            );
        }
        store.mark_index_ready();

        let target: Arc<str> = Arc::from("App\\Owner");
        store
            .fqn_reachable_files(std::slice::from_ref(&target))
            .expect("index is ready");
        let passes_after_first = store.reachability_scan_passes();
        assert!(
            passes_after_first > 0,
            "cold query must run the uncached function at least once"
        );

        store
            .fqn_reachable_files(&[target])
            .expect("index is ready");
        assert_eq!(
            store.reachability_scan_passes(),
            passes_after_first,
            "identical repeat query must be answered entirely from the result cache"
        );
    }

    /// `batch_reference_candidate_files` can mix a bounded needle-less query
    /// (`Name::Class`, an FQN literal) and a raw-needle query (`__construct`,
    /// whose extra needle is the no-word-bound call token `->__construct`)
    /// in the SAME call — both answered by mir's `ClassMentionIndex`, which
    /// admits and scans both needle shapes in one pass (see
    /// `resolve_reachability_queries_uncached`'s doc comment). `UsesBoth.php`
    /// calls `$obj->__construct()` on an untyped parameter — it never
    /// textually mentions `Owner` at all, so it must surface only via the
    /// raw needle, never via the class query, proving the two needle shapes
    /// don't cross-pollute each other's results when batched together.
    #[test]
    fn batch_reference_candidate_files_mixes_raw_and_bounded_needles() {
        let store = DocumentStore::new();
        open(
            &store,
            uri("/App/Owner.php"),
            "<?php\nnamespace App;\nclass Owner { public function __construct() {} }\n".to_string(),
        );
        open(
            &store,
            uri("/Other/UsesBoth.php"),
            "<?php\nnamespace Other;\nclass UsesBoth { public function run($obj) { $obj->__construct(); } }\n"
                .to_string(),
        );
        store.mark_index_ready();

        let symbols = vec![
            mir_analyzer::Name::Class(Arc::from("App\\Owner")),
            mir_analyzer::Name::Method {
                class: Arc::from("App\\Owner"),
                name: Arc::from("__construct"),
            },
        ];
        let scopes = store.batch_reference_candidate_files(&symbols);
        assert_eq!(scopes.len(), 2);
        let class_scope: Vec<&str> = scopes[0].iter().map(|f| f.as_ref()).collect();
        let method_scope: Vec<&str> = scopes[1].iter().map(|f| f.as_ref()).collect();
        assert!(
            !class_scope.iter().any(|f| f.contains("UsesBoth")),
            "the class query must not pick up a file that never mentions the FQN: {class_scope:?}"
        );
        assert!(
            method_scope.iter().any(|f| f.contains("UsesBoth")),
            "the raw `->__construct` needle must find the call site: {method_scope:?}"
        );
    }

    #[test]
    fn index_populates_file_index_with_symbols() {
        let store = DocumentStore::new();
        store.ingest(uri("/a.php"), "<?php\nfunction hello() {}");
        let idx = store.get_index_salsa(&uri("/a.php")).unwrap();
        assert_eq!(idx.functions.len(), 1);
        assert_eq!(&*idx.functions[0].name, "hello");
    }

    #[test]
    fn open_populates_file_index_with_symbols() {
        let store = DocumentStore::new();
        open(&store, uri("/a.php"), "<?php\nclass Foo {}".to_string());
        let idx = store.get_index_salsa(&uri("/a.php")).unwrap();
        assert_eq!(idx.classes.len(), 1);
        assert_eq!(&*idx.classes[0].name, "Foo");
    }

    // ── Mirror invariants ────────────────────────────────────────────────
    //
    // Every mutation path that changes file text must keep the salsa layer
    // consistent. These tests walk a set-edit-reopen cycle and assert that
    // the salsa-derived `FileIndex` reflects the latest text at each step.

    fn names_of(idx: &FileIndex) -> Vec<String> {
        let mut out: Vec<String> = idx.classes.iter().map(|c| c.name.to_string()).collect();
        out.extend(idx.functions.iter().map(|f| f.name.to_string()));
        out.sort();
        out
    }

    fn salsa_index_names(store: &DocumentStore, url: &Uri) -> Vec<String> {
        store
            .snapshot_query_file_index(url)
            .map(|idx| names_of(&idx))
            .unwrap_or_default()
    }

    #[test]
    fn mirror_tracks_repeated_edits() {
        let store = DocumentStore::new();
        let u = uri("/mirror.php");

        open(&store, u.clone(), "<?php\nclass A {}".to_string());
        assert_eq!(salsa_index_names(&store, &u), vec!["A".to_string()]);

        open(
            &store,
            u.clone(),
            "<?php\nclass A {}\nclass B {}".to_string(),
        );
        assert_eq!(
            salsa_index_names(&store, &u),
            vec!["A".to_string(), "B".to_string()]
        );

        open(&store, u.clone(), "<?php\nfunction greet() {}".to_string());
        assert_eq!(salsa_index_names(&store, &u), vec!["greet".to_string()]);
    }

    #[test]
    fn mirror_tracks_ingest_and_ingest_from_doc() {
        let store = DocumentStore::new();

        // Background `index(url, text)` path.
        let u1 = uri("/bg1.php");
        store.ingest(u1.clone(), "<?php\nclass Bg1 {}");
        assert_eq!(salsa_index_names(&store, &u1), vec!["Bg1".to_string()]);

        // `ingest_from_doc(url, &doc)` path (workspace-scan Phase 2).
        let u2 = uri("/bg2.php");
        let doc = crate::analysis::diagnostics::parse_document_no_diags(
            "<?php\nclass Bg2 {}\nfunction f() {}",
        );
        store.ingest_from_doc(u2.clone(), &doc);
        assert_eq!(
            salsa_index_names(&store, &u2),
            vec!["Bg2".to_string(), "f".to_string()]
        );
    }

    /// G3: confirms the `parsed_cache` actually hits — two consecutive
    /// `get_doc_salsa` calls on unchanged text return the same `Arc`
    /// (pointer equality), and an edit forces a miss that produces a
    /// different `Arc`.
    /// parsed_cache must stay bounded — inserting more than
    /// `PARSED_CACHE_CAP` unique URLs must not cause unbounded growth.
    /// Eviction is probabilistic, so we only assert the bound, not which
    /// Seeding a cached index for a URL that was never mirrored is a no-op
    /// (returns `false`) — avoids silently allocating SourceFiles outside
    /// `mirror_text`'s control.
    #[test]
    fn seed_cached_index_noops_for_unknown_uri() {
        let store = DocumentStore::new();
        let u = uri("/never_mirrored.php");
        let index = Arc::new(crate::index::file_index::FileIndex::default());
        assert!(!store.seed_cached_index(&u, index));
    }

    /// entries survive.
    #[test]
    fn parsed_cache_stays_bounded_under_many_inserts() {
        let store = DocumentStore::new();
        use crate::document::cache_registry::PARSED_CACHE_CAP;
        let overflow = PARSED_CACHE_CAP + 100;
        for i in 0..overflow {
            let u = uri(&format!("/cap/file{i}.php"));
            store.ingest(u.clone(), "<?php\nclass A {}");
            // Force a parsed_cache insert via get_doc_salsa.
            let _ = store.get_doc_salsa(&u);
        }
        assert!(
            store.caches.parsed_cache.len() <= PARSED_CACHE_CAP,
            "parsed_cache grew to {} entries (cap {})",
            store.caches.parsed_cache.len(),
            PARSED_CACHE_CAP
        );
    }

    /// The shed is recency-based: an entry touched right before overflow (an
    /// open file being edited) must survive a sweep of cold inserts, while
    /// untouched cold entries are the ones dropped.
    #[test]
    fn parsed_cache_shed_keeps_recently_used_entries() {
        let store = DocumentStore::new();
        use crate::document::cache_registry::PARSED_CACHE_CAP;

        let hot = uri("/cap/hot.php");
        store.ingest(hot.clone(), "<?php\nclass Hot {}");
        let _ = store.get_doc_salsa(&hot);

        // Fill to just below the cap with cold entries, then re-touch the hot
        // file so it is the most recently used entry at shed time.
        for i in 0..(PARSED_CACHE_CAP - 2) {
            let u = uri(&format!("/cap/cold{i}.php"));
            store.ingest(u.clone(), "<?php\nclass A {}");
            let _ = store.get_doc_salsa(&u);
        }
        let _ = store.get_doc_salsa(&hot);

        // Overflow: this insert triggers the shed of the LRU half.
        let trigger = uri("/cap/trigger.php");
        store.ingest(trigger.clone(), "<?php\nclass T {}");
        let _ = store.get_doc_salsa(&trigger);

        assert!(
            store.caches.parsed_cache.contains_key(&hot),
            "recently-touched entry must survive the recency shed"
        );
        assert!(
            store.caches.parsed_cache.len() <= PARSED_CACHE_CAP,
            "cache must stay bounded after the shed"
        );
    }

    /// `analysis_cache` must stay bounded when many distinct files are
    /// analyzed across a session (multi-hour usage previously grew it
    /// without limit).
    #[test]
    fn analysis_cache_stays_bounded_under_many_files() {
        use crate::document::cache_registry::ANALYSIS_CACHE_CAP;
        let store = DocumentStore::new();
        let overflow = ANALYSIS_CACHE_CAP + 16;
        for i in 0..overflow {
            let u = uri(&format!("/acap/file{i}.php"));
            store.ingest(u.clone(), "<?php\nfunction f() { return 1; }");
            let _ = store.cached_analysis(&u);
        }
        assert!(
            store.caches.analysis_cache.len() <= ANALYSIS_CACHE_CAP,
            "analysis_cache grew to {} entries (cap {})",
            store.caches.analysis_cache.len(),
            ANALYSIS_CACHE_CAP
        );
    }

    #[test]
    fn get_doc_salsa_cache_hits_across_calls() {
        let store = DocumentStore::new();
        let u = uri("/g3_cache.php");
        open(&store, u.clone(), "<?php\nclass G3 {}".to_string());

        let a = store.get_doc_salsa(&u).unwrap();
        let b = store.get_doc_salsa(&u).unwrap();
        assert!(
            Arc::ptr_eq(&a, &b),
            "parsed_cache hit should yield the same Arc across calls"
        );

        open(&store, u.clone(), "<?php\nclass G3b {}".to_string());
        let c = store.get_doc_salsa(&u).unwrap();
        assert!(
            !Arc::ptr_eq(&a, &c),
            "edit should invalidate the parsed_cache entry"
        );
    }

    #[test]
    fn get_doc_salsa_returns_some_for_mirrored_files() {
        // Phase E4: `get_doc_salsa` no longer gates on open-state. The
        // open/closed distinction now lives on `Backend::get_doc`.
        let store = DocumentStore::new();
        let u = uri("/e4_doc.php");
        store.ingest(u.clone(), "<?php\nclass P {}");
        let doc = store.get_doc_salsa(&u).unwrap();
        match &doc.program().stmts[0].kind {
            php_ast::StmtKind::Class(c) => {
                assert_eq!(c.name.and_then(|n| n.as_str()), Some("P"))
            }
            other => panic!("expected a class declaration, got {other:?}"),
        }
    }

    #[test]
    fn get_doc_snapshot_or_stale_matches_salsa_on_settled_buffer() {
        let store = DocumentStore::new();
        let u = uri("/stale_settled.php");
        open(&store, u.clone(), "<?php\nclass S {}".to_string());
        let fresh = store.get_doc_salsa(&u).unwrap();
        let stale = store.get_doc_snapshot_or_stale(&u).unwrap();
        assert!(
            Arc::ptr_eq(&fresh, &stale),
            "on a settled buffer the stale-tolerant accessor must serve the cached parse"
        );
    }

    /// WS1: the cursor-triggered highlight accessor must stay responsive under a
    /// sustained write stream — never spin (the deadline join hangs if it does)
    /// and always yield a fresh or last-good parse for an open file.
    #[test]
    fn get_doc_snapshot_or_stale_stays_responsive_under_writes() {
        use std::sync::Arc;
        use std::thread;
        use std::time::{Duration, Instant};

        let store = Arc::new(DocumentStore::new());
        let urls: Vec<Uri> = (0..8).map(|i| uri(&format!("/hl{i}.php"))).collect();
        for (i, u) in urls.iter().enumerate() {
            open(&store, u.clone(), format!("<?php\nclass H{i} {{}}"));
            // Warm the parse cache so the stale fallback always has a last-good doc.
            assert!(store.get_doc_salsa(u).is_some());
        }

        let deadline = Instant::now() + Duration::from_millis(400);
        let mut handles = Vec::new();

        {
            let store = Arc::clone(&store);
            let urls = urls.clone();
            handles.push(thread::spawn(move || {
                let mut rev = 0u32;
                while Instant::now() < deadline {
                    for u in &urls {
                        store.mirror_text(u, &format!("<?php\nclass H {{}}\n// rev {rev}"));
                    }
                    rev += 1;
                }
            }));
        }

        for _ in 0..4 {
            let store = Arc::clone(&store);
            let urls = urls.clone();
            handles.push(thread::spawn(move || {
                while Instant::now() < deadline {
                    for u in &urls {
                        assert!(
                            store.get_doc_snapshot_or_stale(u).is_some(),
                            "open file must resolve to a fresh or stale parse, never None"
                        );
                    }
                }
            }));
        }

        for h in handles {
            h.join()
                .expect("stale accessor must not panic or spin under concurrent writes");
        }
    }

    /// WS1 A/B measurement (not a pass/fail guard): compares the old unbounded
    /// `get_doc_salsa` against the new bounded `get_doc_snapshot_or_stale` under
    /// an identical continuous write stream. Run explicitly:
    /// `cargo test --lib ws1_ab_latency -- --ignored --nocapture`.
    #[test]
    #[ignore = "timing measurement; run with --ignored --nocapture"]
    fn ws1_ab_latency_under_write_pressure() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicBool, Ordering};
        use std::thread;
        use std::time::{Duration, Instant};

        // A large file: each parse is long enough that a concurrent write can
        // cancel it mid-flight — the condition under which the unbounded retry
        // actually spins (a tiny file parses faster than the writer's gap).
        fn big_source(rev: u32) -> String {
            let mut s = String::from("<?php\nclass Big {\n");
            for i in 0..3000 {
                s.push_str(&format!(
                    "    public function m{i}(int $a, string $b): int {{ return $a + {i}; }}\n"
                ));
            }
            s.push_str(&format!("}}\n// rev {rev}\n"));
            s
        }

        fn measure(
            store: &Arc<DocumentStore>,
            url: &Uri,
            writers: usize,
            label: &str,
            call: impl Fn(&DocumentStore, &Uri) -> bool,
        ) {
            let stop = Arc::new(AtomicBool::new(false));
            let mut writer_handles = Vec::new();
            for w in 0..writers {
                let store = Arc::clone(store);
                let url = url.clone();
                let stop = Arc::clone(&stop);
                writer_handles.push(thread::spawn(move || {
                    let mut rev = (w as u32) * 1_000_000;
                    while !stop.load(Ordering::Relaxed) {
                        store.mirror_text(&url, &big_source(rev));
                        rev = rev.wrapping_add(1);
                    }
                }));
            }
            thread::sleep(Duration::from_millis(30)); // let the writers get hot

            let n = 100usize;
            let mut max = Duration::ZERO;
            let mut total = Duration::ZERO;
            for _ in 0..n {
                let t = Instant::now();
                let ok = call(store, url);
                let dt = t.elapsed();
                assert!(ok, "{label}: accessor returned None");
                max = max.max(dt);
                total += dt;
            }
            stop.store(true, Ordering::Relaxed);
            for h in writer_handles {
                h.join().unwrap();
            }
            println!(
                "{label}: {n} calls, {writers} writers — max {:>10.3?}, mean {:>10.3?}",
                max,
                total / n as u32
            );
        }

        let store = Arc::new(DocumentStore::new());
        let url = uri("/perf_big.php");
        open(&store, url.clone(), big_source(0));
        assert!(store.get_doc_salsa(&url).is_some()); // warm the cache

        for writers in [2usize, 4] {
            measure(
                &store,
                &url,
                writers,
                "NEW get_doc_snapshot_or_stale",
                |s, u| s.get_doc_snapshot_or_stale(u).is_some(),
            );
            measure(
                &store,
                &url,
                writers,
                "OLD get_doc_salsa (unbounded)  ",
                |s, u| s.get_doc_salsa(u).is_some(),
            );
        }
    }

    #[test]
    fn get_salsa_accessors_return_none_for_unknown_uri() {
        let store = DocumentStore::new();
        let u = uri("/never-seen.php");
        assert!(store.get_doc_salsa(&u).is_none());
        assert!(store.get_index_salsa(&u).is_none());
    }

    /// Phase E1: concurrent readers and writers must not deadlock, panic, or
    /// return stale data. Writers briefly bump inputs while readers are
    /// running on cloned snapshots; any `salsa::Cancelled` raised on the
    /// reader side must be caught and retried by `snapshot_query`.
    ///
    /// The salsa surface (`get_doc_salsa`, `get_index_salsa`) is protected by
    /// `snapshot_query`'s last-resort host-lock fallback.
    #[test]
    fn concurrent_reads_and_writes_do_not_panic() {
        use std::sync::Arc;
        use std::thread;
        use std::time::{Duration, Instant};

        let store = Arc::new(DocumentStore::new());
        let urls: Vec<Uri> = (0..8).map(|i| uri(&format!("/f{i}.php"))).collect();
        for (i, u) in urls.iter().enumerate() {
            open(&store, u.clone(), format!("<?php\nclass C{i} {{}}"));
        }

        let deadline = Instant::now() + Duration::from_millis(400);
        let mut handles = Vec::new();

        // Writer thread: keep bumping every file's text.
        {
            let store = Arc::clone(&store);
            let urls = urls.clone();
            handles.push(thread::spawn(move || {
                let mut rev = 0u32;
                while Instant::now() < deadline {
                    for u in &urls {
                        let text = format!("<?php\nclass C{{}}\n// rev {rev}");
                        store.mirror_text(u, &text);
                    }
                    rev += 1;
                }
            }));
        }

        // Reader threads: hammer the salsa accessors.
        for _ in 0..4 {
            let store = Arc::clone(&store);
            let urls = urls.clone();
            handles.push(thread::spawn(move || {
                while Instant::now() < deadline {
                    for u in &urls {
                        let _ = store.get_doc_salsa(u);
                        let _ = store.get_index_salsa(u);
                    }
                    // Codebase and references live in the session, not salsa.
                    // Concurrent-read smoke is limited to the
                    // remaining salsa surface (parsed_doc, file_index).
                }
            }));
        }

        for h in handles {
            h.join().expect("no panic under concurrent read/write");
        }
    }

    /// PSR-4 lazy-loading: `get_semantic_issues_salsa` must not emit
    /// `UndefinedClass` for a class that is PSR-4-resolvable on disk, even
    /// when the dependency file is not yet in `source_files`.
    #[test]
    fn psr4_lazy_load_suppresses_undefined_class() {
        let tmp = tempfile::tempdir().unwrap();

        // Write Entity.php to disk (not mirrored into the store).
        std::fs::create_dir_all(tmp.path().join("src/Model")).unwrap();
        std::fs::write(
            tmp.path().join("src/Model/Entity.php"),
            "<?php\nnamespace App\\Model;\nclass Entity {}\n",
        )
        .unwrap();

        // Write composer.json so Psr4Map::load can build the map.
        std::fs::write(
            tmp.path().join("composer.json"),
            r#"{"autoload":{"psr-4":{"App\\":"src/"}}}"#,
        )
        .unwrap();

        let store = DocumentStore::new();

        // Inject a PSR-4 map pointing at the tmp dir.
        store
            .psr4
            .store(Arc::new(crate::lang::autoload::Psr4Map::load(tmp.path())));

        // Mirror the consuming file (Entity not yet in source_files).
        // Uses Entity as a parameter type hint — the analyzer resolves these
        // through use statements, so this exercises the full PSR-4 lazy-load path.
        let handler_url = Uri::from_file_path(tmp.path().join("src/Service/Handler.php")).unwrap();
        store.mirror_text(
            &handler_url,
            "<?php\nnamespace App\\Service;\nuse App\\Model\\Entity;\nfunction handle(Entity $e): Entity { return $e; }\n",
        );

        let issues = store.get_semantic_issues_salsa(&handler_url).unwrap();
        let undef: Vec<_> = issues
            .iter()
            .filter(|i| matches!(i.kind, mir_issues::IssueKind::UndefinedClass { .. }))
            .collect();
        assert!(
            undef.is_empty(),
            "PSR-4 lazy-loading must prevent UndefinedClass for App\\Model\\Entity; got: {undef:?}"
        );
    }

    /// Issue #243 repro: a PSR-0-autoloaded vendor class (PEAR-style, e.g.
    /// `Legacy_Service`) must lazy-load the same way PSR-4 classes do.
    #[test]
    fn psr0_lazy_load_suppresses_undefined_class_243_repro() {
        let tmp = tempfile::tempdir().unwrap();

        std::fs::create_dir_all(tmp.path().join("vendor/legacy/src/Legacy")).unwrap();
        std::fs::write(
            tmp.path().join("vendor/legacy/src/Legacy/Service.php"),
            "<?php\n\nclass Legacy_Service\n{\n    public function name(): string\n    {\n        return 'legacy';\n    }\n}\n",
        )
        .unwrap();

        std::fs::write(
            tmp.path().join("composer.json"),
            r#"{"autoload":{"psr-0":{"Legacy_":"vendor/legacy/src/"}}}"#,
        )
        .unwrap();

        let store = DocumentStore::new();
        store
            .psr4
            .store(Arc::new(crate::lang::autoload::Psr4Map::load(tmp.path())));

        let repro_url = Uri::from_file_path(tmp.path().join("repro.php")).unwrap();
        store.mirror_text(
            &repro_url,
            "<?php\n\n$service = new Legacy_Service();\necho $service->name();\n",
        );

        let issues = store.get_semantic_issues_salsa(&repro_url).unwrap();
        let undef: Vec<_> = issues
            .iter()
            .filter(|i| matches!(i.kind, mir_issues::IssueKind::UndefinedClass { .. }))
            .collect();
        assert!(
            undef.is_empty(),
            "PSR-0 lazy-loading must prevent UndefinedClass for Legacy_Service; got: {undef:?}"
        );
    }

    /// Regression (found while investigating issue #242, root cause is
    /// distinct from it — not fixed by the `is_index_ready` gate):
    /// `cached_analysis_if_fresh` is keyed on php-lsp's retained analysis-cache
    /// generation. A newly mirrored file still has to sync that generation so
    /// consumers analyzed before the dependency existed do not keep a stale
    /// `UndefinedClass` analysis.
    #[test]
    fn cached_analysis_invalidated_by_new_dependency_file() {
        let store = DocumentStore::new();
        let consumer_uri = uri("/app.php");
        let dep_uri = uri("/Mage.php");

        // Consumer references Mage before Mage exists anywhere in the store —
        // correctly flagged, and this analysis gets cached.
        store.mirror_text(&consumer_uri, "<?php\n\nnew Mage();\n");
        let issues = store.get_semantic_issues_salsa(&consumer_uri).unwrap();
        assert!(
            issues
                .iter()
                .any(|i| matches!(i.kind, mir_issues::IssueKind::UndefinedClass { .. })),
            "sanity check: Mage must be reported missing before it exists"
        );

        // Mage now becomes known to the store — exactly what a workspace
        // scan or a `didChangeWatchedFiles` CREATED event does.
        store.mirror_text(&dep_uri, "<?php\nclass Mage {}\n");
        store.sync_analysis_cache_declarations(&dep_uri);

        // Consumer's diagnostics should now resolve cleanly.
        let issues = store.get_semantic_issues_salsa(&consumer_uri).unwrap();
        assert!(
            !issues
                .iter()
                .any(|i| matches!(i.kind, mir_issues::IssueKind::UndefinedClass { .. })),
            "Mage now exists, but consumer.php's cached analysis was never \
             invalidated: {issues:?}"
        );
    }

    /// The same staleness, reached by the initial workspace scan path: a file
    /// opened while the scan is still running must not keep the memo it left
    /// behind against a partial index.
    #[test]
    fn cached_analysis_invalidated_by_finished_scan() {
        let store = DocumentStore::new();
        let consumer_uri = uri("/app.php");
        let dep_uri = uri("/Mage.php");

        store.mirror_text(&consumer_uri, "<?php\n\nnew Mage();\n");
        let issues = store.get_semantic_issues_salsa(&consumer_uri).unwrap();
        assert!(
            issues
                .iter()
                .any(|i| matches!(i.kind, mir_issues::IssueKind::UndefinedClass { .. })),
            "sanity check: Mage must be reported missing before the scan reaches it"
        );

        // The scan reaches Mage.php and then finishes. `mirror_text` alone is
        // what `index::workspace_scan` does with every file it reads.
        store.mirror_text(&dep_uri, "<?php\nclass Mage {}\n");
        store.mark_index_ready();

        let issues = store.get_semantic_issues_salsa(&consumer_uri).unwrap();
        assert!(
            !issues
                .iter()
                .any(|i| matches!(i.kind, mir_issues::IssueKind::UndefinedClass { .. })),
            "the finished scan did not invalidate app.php's analysis: {issues:?}"
        );
    }

    /// Issue #191 regression: workspace-wide scans (find-references, rename,
    /// call-hierarchy) must not re-parse closed/indexed files on repeated
    /// invocations. Once a file's `ParsedDoc` has been produced, subsequent
    /// repeated `get_doc_salsa` calls must hit the cache and return the same
    /// `Arc<ParsedDoc>` (pointer equality), proving no re-parse occurred.
    ///
    /// The cache layers protecting this are:
    ///   1. `parsed_cache` (cap [`PARSED_CACHE_CAP`]) — read-through, validated
    ///      via `Arc::ptr_eq` on the text Arc.
    ///   2. salsa `parsed_doc` memo (`lru = 2048`) — second line of defense
    ///      when `parsed_cache` evicts.
    ///
    /// Together they keep every workspace-scan op O(N) memo lookups, never
    /// O(N) parses, for any workspace whose file count fits the cap.
    #[test]
    fn repeated_doc_lookups_do_not_reparse_indexed_files() {
        let store = DocumentStore::new();
        const N: usize = 50;
        for i in 0..N {
            let u = uri(&format!("/scan/file{i}.php"));
            store.ingest(u, &format!("<?php\nclass C{i} {{}}\nfunction f{i}() {{}}"));
        }

        let scan = || -> Vec<(Uri, Arc<ParsedDoc>)> {
            (0..N)
                .map(|i| {
                    let u = uri(&format!("/scan/file{i}.php"));
                    let d = store.get_doc_salsa(&u).unwrap();
                    (u, d)
                })
                .collect()
        };
        let first = scan();
        let second = scan();
        assert_eq!(first.len(), N);
        assert_eq!(second.len(), N);

        let by_url_first: std::collections::HashMap<Uri, Arc<ParsedDoc>> =
            first.into_iter().collect();
        for (u, doc2) in second {
            let doc1 = by_url_first
                .get(&u)
                .expect("second scan returned a URL the first didn't");
            assert!(
                Arc::ptr_eq(doc1, &doc2),
                "{u:?} re-parsed across lookups — \
                 cache (parsed_cache + salsa parsed_doc memo) failed to hit"
            );
        }

        // Editing one file's text must invalidate just that file's entry,
        // not the rest. This locks in self-eviction via Arc::ptr_eq on text.
        let edited_url = uri("/scan/file0.php");
        let pre_edit = store.get_doc_salsa(&edited_url).unwrap();
        store.ingest(edited_url.clone(), "<?php\nclass C0Edited {}");
        let post_edit = store.get_doc_salsa(&edited_url).unwrap();
        assert!(
            !Arc::ptr_eq(&pre_edit, &post_edit),
            "edited file must produce a fresh ParsedDoc"
        );
        for i in 1..N {
            let u = uri(&format!("/scan/file{i}.php"));
            let original = by_url_first.get(&u).unwrap();
            let after = store.get_doc_salsa(&u).unwrap();
            assert!(
                Arc::ptr_eq(original, &after),
                "{u:?} should not have re-parsed because of an unrelated edit"
            );
        }
    }

    /// Incremental analysis cache: a body-only edit to file A (no declaration
    /// changes) must not bump `decl_version`, so file B's cached analysis
    /// survives. A declaration edit MUST bump the version so B's entry goes
    /// stale.
    #[test]
    fn body_only_edit_does_not_invalidate_sibling_analysis_cache() {
        let store = DocumentStore::new();
        let ua = uri("/ic_a.php");
        let ub = uri("/ic_b.php");

        // Analyze both files to establish their fingerprints.
        open(
            &store,
            ua.clone(),
            "<?php\nfunction a() { return 1; }".to_string(),
        );
        open(
            &store,
            ub.clone(),
            "<?php\nfunction b() { return 2; }".to_string(),
        );
        let _ = store.cached_analysis(&ua).unwrap();
        let analysis_b_first = store.cached_analysis(&ub).unwrap();
        let ver_after_warm = store.caches.decl_version();

        // Body-only edit to A: same function name, different body -> FileIndex unchanged.
        store.mirror_text(&ua, "<?php\nfunction a() { return 999; }");
        let _ = store.cached_analysis(&ua);
        let ver_after_body_edit = store.caches.decl_version();
        assert_eq!(
            ver_after_warm, ver_after_body_edit,
            "body-only edit must not bump decl_version"
        );

        // B's cached entry should still be valid (ptr-eq source AND same version).
        let analysis_b_second = store.cached_analysis_if_fresh(&ub);
        assert!(
            analysis_b_second.is_some(),
            "B's analysis should hit cache after body-only edit to A"
        );
        assert!(
            Arc::ptr_eq(&analysis_b_first, &analysis_b_second.unwrap()),
            "B's analysis should be the identical Arc (no re-analysis)"
        );

        // Declaration edit to A: rename the function -> FileIndex changes.
        store.mirror_text(&ua, "<?php\nfunction a_renamed() { return 999; }");
        let _ = store.cached_analysis(&ua);
        let ver_after_decl_edit = store.caches.decl_version();
        assert!(
            ver_after_decl_edit > ver_after_body_edit,
            "declaration edit must bump decl_version (was {ver_after_body_edit}, now {ver_after_decl_edit})"
        );

        // B's entry is now stale — cached_analysis_if_fresh must return None.
        let analysis_b_stale = store.cached_analysis_if_fresh(&ub);
        assert!(
            analysis_b_stale.is_none(),
            "B's analysis should be stale after A's declaration changed"
        );
    }

    /// snapshot_query must complete without panic when a concurrent writer
    /// races the snapshot. The single-retry-then-lock logic should handle this
    /// correctly: the lock-held fallback guarantees progress.
    #[test]
    fn snapshot_query_survives_concurrent_writes() {
        use std::sync::Arc;
        use std::thread;
        use std::time::{Duration, Instant};

        let store = Arc::new(DocumentStore::new());
        let u = uri("/sq_test.php");
        open(
            &store,
            u.clone(),
            "<?php\nfunction f(): int { return 1; }".to_string(),
        );

        let deadline = Instant::now() + Duration::from_millis(200);
        let mut handles = Vec::new();

        // Writer: keep bumping the file text to trigger salsa::Cancelled.
        {
            let store = Arc::clone(&store);
            let u = u.clone();
            handles.push(thread::spawn(move || {
                let mut rev = 0u32;
                while Instant::now() < deadline {
                    store.mirror_text(&u, &format!("<?php\nfunction f(): int {{ return {rev}; }}"));
                    rev += 1;
                }
            }));
        }

        // Reader: hammer snapshot_query via get_doc_salsa.
        for _ in 0..4 {
            let store = Arc::clone(&store);
            let u = u.clone();
            handles.push(thread::spawn(move || {
                while Instant::now() < deadline {
                    let _ = store.get_doc_salsa(&u);
                    let _ = store.get_index_salsa(&u);
                }
            }));
        }

        for h in handles {
            h.join()
                .expect("no panic in snapshot_query under concurrent writes");
        }
    }

    /// Concurrent callers racing to analyze the SAME uncached file (e.g.
    /// `did_open`'s diagnostics trigger vs. a fast-following hover, which
    /// tower-lsp's default concurrency genuinely allows) must serialize onto
    /// one `FileAnalyzer::analyze` run and all observe its identical result
    /// — not each redo the full analysis independently.
    #[test]
    fn concurrent_callers_share_one_analysis_computation() {
        use std::sync::{Arc, Barrier};
        use std::thread;

        let store = Arc::new(DocumentStore::new());
        let u = uri("/inflight_test.php");
        open(
            &store,
            u.clone(),
            "<?php\nfunction f(): int { return 1; }".to_string(),
        );

        const N: usize = 8;
        let barrier = Arc::new(Barrier::new(N));
        let handles: Vec<_> = (0..N)
            .map(|_| {
                let store = Arc::clone(&store);
                let u = u.clone();
                let barrier = Arc::clone(&barrier);
                thread::spawn(move || {
                    barrier.wait();
                    store.cached_analysis(&u)
                })
            })
            .collect();
        let results: Vec<_> = handles
            .into_iter()
            .map(|h| h.join().expect("no panic in cached_analysis"))
            .collect();

        assert_eq!(
            store.analysis_compute_count(),
            1,
            "{N} concurrent callers analyzing the same uncached file must compute once, not {N} times"
        );
        let first = results[0].clone().expect("analysis must succeed");
        for r in &results {
            let r = r.as_ref().expect("analysis must succeed");
            assert!(
                Arc::ptr_eq(&first, r),
                "every caller must observe the identical analysis Arc, not its own copy"
            );
        }
    }

    /// Manual perf diagnostic (`cargo test --release -- --ignored --nocapture
    /// diagnostic_coalescing_cpu_time_ms`): N threads race `cached_analysis`
    /// for the same uncached, moderately expensive file. `computations`
    /// (from `analysis_compute_count`) is the direct proof of the fix: it
    /// must stay at 1 regardless of N. `wall_ms` is secondary color — without
    /// the per-URI lock, N threads each independently running the full
    /// analyze pass genuinely in parallel can contend for the same cores/
    /// caches and degrade wall time as N grows past the core count; with the
    /// lock, added threads just wait on the one real computation.
    #[test]
    #[ignore]
    fn diagnostic_coalescing_cpu_time_ms() {
        use std::sync::{Arc, Barrier};
        use std::thread;
        use std::time::Instant;

        let mut src = "<?php\nclass Big {\n".to_string();
        for m in 0..200 {
            src.push_str(&format!(
                "    public function m{m}(int $x): int {{ $y = $x * {m} + strlen((string)$x); return $y > 0 ? $y : -$y; }}\n"
            ));
        }
        src.push_str("}\n");

        for &nthreads in &[1usize, 4, 8, 16, 32] {
            let store = Arc::new(DocumentStore::new());
            let u = uri("/coalesce_bench.php");
            open(&store, u.clone(), src.clone());

            let barrier = Arc::new(Barrier::new(nthreads));
            let wall_start = Instant::now();
            let handles: Vec<_> = (0..nthreads)
                .map(|_| {
                    let store = Arc::clone(&store);
                    let u = u.clone();
                    let barrier = Arc::clone(&barrier);
                    thread::spawn(move || {
                        barrier.wait();
                        let _ = store.cached_analysis(&u);
                    })
                })
                .collect();
            for h in handles {
                h.join().unwrap();
            }
            let wall_ms = wall_start.elapsed().as_secs_f64() * 1000.0;
            eprintln!(
                "threads={nthreads:>3}  computations={:>3}  wall_ms={wall_ms:>8.3}",
                store.analysis_compute_count()
            );
        }
    }

    /// Manual perf diagnostic (`cargo test --release -- --ignored --nocapture
    /// diagnostic_batch_vs_per_symbol_scan_ms`), not a CI-run assertion:
    /// isolates the pure scan-count effect of `batch_reference_candidate_files`
    /// vs M independent `reference_candidate_files` calls, excluding the
    /// surrounding `code_lenses()`/`indexed_references` cost entirely — this
    /// measures scope narrowing alone. See `benches/code_lens_scaling.rs` for
    /// the end-to-end request-level number.
    #[test]
    #[ignore]
    fn diagnostic_batch_vs_per_symbol_scan_ms() {
        use std::time::Instant;
        let num_methods = 100usize;
        for &n_noise in &[500usize, 1500, 3000, 8000] {
            let store = DocumentStore::new();
            let owner = "App\\Service";
            let mut src = "<?php\nnamespace App;\nclass Service {\n".to_string();
            for m in 0..num_methods {
                src.push_str(&format!(
                    "    public static function alpha{m}(): void {{}}\n"
                ));
            }
            src.push_str("}\n");
            store.ingest(("file:///synth/Service.php").parse::<Uri>().unwrap(), &src);
            for i in 0..n_noise {
                let u = format!("file:///synth/N{i}.php").parse::<Uri>().unwrap();
                let t = format!(
                    "<?php\nnamespace Other{i};\nclass N{i} {{ public function run(){{}} }}\n"
                );
                store.ingest(u, &t);
            }
            store.mark_index_ready();

            let mut symbols = vec![mir_analyzer::Name::class(owner)];
            for m in 0..num_methods {
                symbols.push(mir_analyzer::Name::method(owner, &format!("alpha{m}")));
            }

            let t = Instant::now();
            for s in &symbols {
                std::hint::black_box(store.reference_candidate_files(s));
            }
            let per_symbol_ms = t.elapsed().as_secs_f64() * 1000.0;

            let t = Instant::now();
            std::hint::black_box(store.batch_reference_candidate_files(&symbols));
            let batch_ms = t.elapsed().as_secs_f64() * 1000.0;

            eprintln!(
                "n_noise={n_noise:>6}  symbols={:>4}  per_symbol_ms={per_symbol_ms:>10.3}  batch_ms={batch_ms:>10.3}  speedup={:>6.2}x",
                symbols.len(),
                per_symbol_ms / batch_ms
            );
        }
    }

    /// Manual perf diagnostic (`cargo test --release -- --ignored --nocapture
    /// diagnostic_priority_scan_avoided_cost_ms`): measures the cost of
    /// `handle_references`'s priority-partition owner-mention scan
    /// (`navigation.rs`) run over an already-narrowed candidate scope — the
    /// exact cost `method_scope_is_narrowed` now lets the handler skip
    /// entirely for private/protected/static methods. The scope size here
    /// models a protected method's subtype-closure narrowing (the case where
    /// a widely-subclassed base class makes the "narrowed" scope non-trivial).
    #[test]
    #[ignore]
    fn diagnostic_priority_scan_avoided_cost_ms() {
        use std::time::Instant;

        let store = DocumentStore::new();
        let owner_short = "Owner";
        for &n in &[10usize, 100, 1000, 3000] {
            let mut files: Vec<Arc<str>> = Vec::with_capacity(n);
            for i in 0..n {
                let u = format!("file:///synth/S{i}.php").parse::<Uri>().unwrap();
                let t = format!(
                    "<?php\nclass S{i} extends Owner {{\n\
                     \x20   public function run(): void {{\n\
                     \x20       parent::process();\n\
                     \x20   }}\n\
                     }}\n"
                );
                store.ingest(u.clone(), &t);
                files.push(Arc::<str>::from(u.as_str()));
            }

            let t0 = Instant::now();
            use rayon::prelude::*;
            let matched: Vec<Arc<str>> = files
                .par_iter()
                .filter(|f| {
                    (f.as_ref())
                        .parse::<Uri>()
                        .ok()
                        .and_then(|u| store.source_text(&u))
                        .is_some_and(|txt| {
                            crate::text::contains_ascii_case_insensitive(&txt, owner_short)
                        })
                })
                .cloned()
                .collect();
            let avoided_ms = t0.elapsed().as_secs_f64() * 1000.0;
            eprintln!(
                "narrowed_scope_files={n:>5}  avoided_scan_ms={avoided_ms:>9.4}  matched={}  (new code: 0.000ms — skipped entirely)",
                matched.len()
            );
        }
    }

    /// Manual perf diagnostic (`cargo test --release -- --ignored --nocapture
    /// diagnostic_laravel_scan_blocking_vs_spawn_blocking`): demonstrates the
    /// actual effect of moving `handle_references`'s Laravel string-key scan
    /// (`navigation.rs`) into `spawn_blocking`. On a single-worker-thread
    /// runtime, a CPU-bound scan with no `.await` points inside it hogs that
    /// one worker until it completes — a concurrently-spawned trivial task
    /// can't run until the scan yields. `spawn_blocking` moves the scan to a
    /// separate thread, freeing the worker immediately.
    #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
    #[ignore]
    async fn diagnostic_laravel_scan_blocking_vs_spawn_blocking() {
        use std::time::Instant;

        fn run_scan_inline(store: &DocumentStore, n: usize) -> usize {
            let mut count = 0;
            for i in 0..n {
                let u = format!("file:///synth/F{i}.php").parse::<Uri>().unwrap();
                if store
                    .source_text(&u)
                    .is_some_and(|t| t.contains("APP_NAME_0"))
                    && let Some(doc) = store.get_doc_salsa(&u)
                {
                    let _ = crate::laravel::find_call_sites(&doc, &["env"], "APP_NAME_0");
                    count += 1;
                }
            }
            count
        }

        let store = Arc::new(DocumentStore::new());
        let n = 30_000usize;
        for i in 0..n {
            let u = format!("file:///synth/F{i}.php").parse::<Uri>().unwrap();
            let t = format!("<?php\n$x = env('APP_NAME_{i}');\n");
            store.ingest(u, &t);
        }

        // Both scenarios spawn the scan AND a trivial task as separate
        // `tokio::spawn`ed tasks — the same relationship real tower-lsp
        // request handlers have (each dispatched request is its own spawned
        // task on the shared worker pool), unlike driving the scan inline in
        // this test function's own body (which `#[tokio::test]` runs via
        // `block_on` on the harness thread, not a pool worker, and so
        // wouldn't actually contend with `tokio::spawn`ed tasks at all).

        // OLD shape: scan task runs the work inline, no yield points inside.
        let spawn_time = Instant::now();
        let store_c = Arc::clone(&store);
        let scan_handle = tokio::spawn(async move { run_scan_inline(&store_c, n) });
        let (tx, rx) = tokio::sync::oneshot::channel();
        tokio::spawn(async move {
            let _ = tx.send(Instant::now());
        });
        let matched = scan_handle.await.unwrap();
        let scan_ms = spawn_time.elapsed().as_secs_f64() * 1000.0;
        let trivial_ran_at = rx.await.unwrap();
        let trivial_delay_ms = trivial_ran_at.duration_since(spawn_time).as_secs_f64() * 1000.0;
        eprintln!(
            "OLD (inline on the request's own task):  scan_ms={scan_ms:>8.3}  matched={matched:>4}  concurrent_trivial_task_delay_ms={trivial_delay_ms:>8.3}"
        );

        // NEW shape: scan task hands the work to spawn_blocking and awaits it.
        let spawn_time = Instant::now();
        let store_c = Arc::clone(&store);
        let scan_handle = tokio::spawn(async move {
            tokio::task::spawn_blocking(move || run_scan_inline(&store_c, n))
                .await
                .unwrap()
        });
        let (tx, rx) = tokio::sync::oneshot::channel();
        tokio::spawn(async move {
            let _ = tx.send(Instant::now());
        });
        let matched = scan_handle.await.unwrap();
        let scan_ms = spawn_time.elapsed().as_secs_f64() * 1000.0;
        let trivial_ran_at = rx.await.unwrap();
        let trivial_delay_ms = trivial_ran_at.duration_since(spawn_time).as_secs_f64() * 1000.0;
        eprintln!(
            "NEW (via spawn_blocking):                scan_ms={scan_ms:>8.3}  matched={matched:>4}  concurrent_trivial_task_delay_ms={trivial_delay_ms:>8.3}"
        );
    }

    /// When a sibling file's declaration changes (bumping decl_version), the
    /// owned_program_cache entry for the unchanged file B should be reused
    /// rather than deep-cloned again. We verify this via Arc pointer equality.
    #[test]
    fn owned_program_cache_reused_after_sibling_declaration_change() {
        let store = DocumentStore::new();
        let ua = uri("/prog_a.php");
        let ub = uri("/prog_b.php");

        open(
            &store,
            ua.clone(),
            "<?php\nfunction alpha(): void {}".to_string(),
        );
        open(
            &store,
            ub.clone(),
            "<?php\nfunction beta(): void {}".to_string(),
        );

        // Warm both analysis caches and populate owned_program_cache for both files.
        let _ = store.cached_analysis(&ua);
        let _ = store.cached_analysis(&ub);

        // Capture B's owned_program Arc before the sibling edit.
        let prog_b_first = store
            .caches
            .owned_program_cache
            .get(&ub)
            .map(|e| Arc::clone(&e.1))
            .expect("B's owned_program should be cached after first analysis");

        // Declaration change to A: bumps decl_version, invalidating all cached_analysis entries.
        store.mirror_text(&ua, "<?php\nfunction alpha_renamed(): void {}");
        // Re-analyze A to trigger the decl_version bump.
        let _ = store.cached_analysis(&ua);

        // Now re-analyze B. Its source is unchanged, so owned_program_cache must hit.
        let _ = store.cached_analysis(&ub);

        let prog_b_second = store
            .caches
            .owned_program_cache
            .get(&ub)
            .map(|e| Arc::clone(&e.1))
            .expect("B's owned_program should still be cached after sibling edit");

        assert!(
            Arc::ptr_eq(&prog_b_first, &prog_b_second),
            "B's owned_program Arc should be identical (cache hit) after sibling declaration change"
        );
    }

    /// write_rev() increments on each real text write (identical text is a no-op).
    #[test]
    fn write_rev_increments_on_write() {
        let store = DocumentStore::new();
        let u = uri("/rev_test.php");
        let before = store.write_rev();
        store.mirror_text(&u, "<?php echo 1;");
        let after_first = store.write_rev();
        assert!(after_first > before, "first write must bump the revision");
        // Identical text must NOT bump the revision (fast path).
        store.mirror_text(&u, "<?php echo 1;");
        assert_eq!(
            store.write_rev(),
            after_first,
            "identical text must not bump the revision"
        );
        // Different text must bump again.
        store.mirror_text(&u, "<?php echo 2;");
        assert!(
            store.write_rev() > after_first,
            "changed text must bump the revision"
        );
    }

    /// A write after the captured revision makes a references query answer
    /// `ContentModified` instead of a stale result.
    #[test]
    fn stale_cancel_rev_yields_content_modified() {
        let store = DocumentStore::new();
        let u = uri("/stale.php");
        store.mirror_text(&u, "<?php\nfunction target() {}\ntarget();\n");
        let rev = store.write_rev();
        store.mirror_text(&u, "<?php\nfunction target() {}\ntarget();\ntarget();\n");
        let files = [Arc::<str>::from(u.as_str())];
        let name = mir_analyzer::Name::function("target".to_string());
        assert_eq!(
            store.indexed_references(&name, &files, true, Some(rev)),
            Err(ContentModified)
        );
    }

    /// begin_reanalyze() cancels the previously-issued sweep token so a newer
    /// edit preempts an in-flight dependent walk, and hands back a fresh token.
    #[test]
    fn begin_reanalyze_cancels_previous_token() {
        let store = DocumentStore::new();
        let first = store.begin_reanalyze();
        assert!(!first.is_cancelled(), "a fresh token starts un-cancelled");
        let second = store.begin_reanalyze();
        assert!(
            first.is_cancelled(),
            "issuing a new token must cancel the previous in-flight sweep"
        );
        assert!(
            !second.is_cancelled(),
            "the newly-issued token must itself be un-cancelled"
        );
    }

    /// A session built before the cache dir is known (an editor's
    /// restored-buffer `didOpen` racing `initialized`) must be rebuilt with
    /// the cache attached when the dir arrives — not stay pinned
    /// in-memory-only for the server's lifetime.
    #[test]
    fn set_session_cache_dir_rebuilds_pinned_session() {
        let store = DocumentStore::new();
        // Force-build the early, cache-less session.
        store.with_session(|_| ());
        let dir = tempfile::tempdir().unwrap();
        let dropped = store.set_session_cache_dir(dir.path().to_path_buf());
        assert!(
            dropped,
            "the cache-less early session must be dropped and rebuilt"
        );
        // Force the rebuild so the cache dir actually opens on disk.
        store.with_session(|_| ());
        assert!(
            dir.path().join("stubs").exists(),
            "the rebuilt session must have opened the on-disk stub cache"
        );
    }

    /// Same rebuild-on-race guarantee as `set_session_cache_dir`, for
    /// `set_user_stub_dirs`.
    #[test]
    fn set_user_stub_dirs_rebuilds_pinned_session() {
        let store = DocumentStore::new();
        // Force-build the early, stub-dir-less session.
        store.with_session(|_| ());
        let dir = tempfile::tempdir().unwrap();
        let dropped = store.set_user_stub_dirs(vec![dir.path().to_path_buf()]);
        assert!(
            dropped,
            "the stub-dir-less early session must be dropped and rebuilt"
        );
    }

    /// A class defined only in a `stubDirs` directory must resolve — without
    /// `UndefinedClass` — from a *different* file than whichever one happened
    /// to trigger the session's lazy stub load, proving the stub is
    /// registered as a real, session-wide symbol rather than something
    /// scoped to the triggering file.
    #[test]
    fn user_stub_directory_class_resolves_across_files() {
        let stubs_dir = tempfile::tempdir().unwrap();
        std::fs::write(
            stubs_dir.path().join("Container.php"),
            "<?php\nclass Container {\n    public function get(string $id): mixed { return null; }\n}\n",
        )
        .unwrap();

        let store = DocumentStore::new();
        store.set_user_stub_dirs(vec![stubs_dir.path().to_path_buf()]);

        // First file has nothing to do with the stub; only primes the session.
        let a = uri("/stub_cross_file_a.php");
        store.mirror_text(&a, "<?php\necho 1;\n");
        let _ = store.get_semantic_issues_salsa(&a);

        // Second, unrelated file references the stub-defined class.
        let b = uri("/stub_cross_file_b.php");
        store.mirror_text(&b, "<?php\n$c = new Container();\n$c->get('x');\n");
        let issues = store.get_semantic_issues_salsa(&b).unwrap();
        let undef: Vec<_> = issues
            .iter()
            .filter(|i| matches!(i.kind, mir_issues::IssueKind::UndefinedClass { .. }))
            .collect();
        assert!(
            undef.is_empty(),
            "Container must resolve from the stubDirs directory in a file that \
             didn't trigger the load itself; got: {undef:?}"
        );
    }

    /// write_rev() increments when a file is removed.
    #[test]
    fn write_rev_increments_on_remove() {
        let store = DocumentStore::new();
        let u = uri("/rev_remove.php");
        store.mirror_text(&u, "<?php class A {}");
        let before = store.write_rev();
        store.remove(&u);
        assert!(store.write_rev() > before, "remove must bump the revision");
    }

    /// Session rebuilds racing reads and writes never hand an old db's
    /// `LspWsFile`/`LspWorkspace` handle to the new db.
    #[test]
    fn session_rebuild_racing_handle_users_does_not_panic() {
        use mir_analyzer::PhpVersion;
        let store = Arc::new(DocumentStore::new());
        let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let workers: Vec<_> = (0..4)
            .map(|t| {
                let (store, stop) = (Arc::clone(&store), Arc::clone(&stop));
                std::thread::spawn(move || {
                    let mut n = 0u32;
                    while !stop.load(Ordering::Relaxed) {
                        let u = uri(&format!("/race_{t}_{}.php", n % 8));
                        store.mirror_text(&u, &format!("<?php\nclass Race{t}_{n} {{}}\n"));
                        let _ = store.get_doc_salsa(&u);
                        let _ = store.get_index_salsa(&u);
                        let _ = store.get_symbol_map_salsa(&u);
                        let _ = store.get_workspace_index_salsa();
                        n += 1;
                    }
                })
            })
            .collect();
        for i in 0..200 {
            let version = if i % 2 == 0 {
                PhpVersion::LATEST
            } else {
                PhpVersion::new(8, 1)
            };
            store.set_php_version(version);
        }
        stop.store(true, Ordering::Relaxed);
        for w in workers {
            w.join().expect("worker panicked");
        }
    }

    /// mir keys a vendor class it loads on demand by the same URI the scan
    /// later mirrors the file under, so the two share one mir file.
    #[test]
    fn class_ref_by_fqn_resolves_on_demand_loaded_vendor_class() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(tmp.path().join("vendor/acme/src")).unwrap();
        let base_src = "<?php\nnamespace Acme;\nclass Base { public function hello(): void {} }\n";
        std::fs::write(tmp.path().join("vendor/acme/src/Base.php"), base_src).unwrap();
        std::fs::write(
            tmp.path().join("composer.json"),
            r#"{"autoload":{"psr-4":{"Acme\\":"vendor/acme/src/"}}}"#,
        )
        .unwrap();

        let store = DocumentStore::new();
        store
            .psr4
            .store(Arc::new(crate::lang::autoload::Psr4Map::load(tmp.path())));

        let app = Uri::from_file_path(tmp.path().join("src/App.php")).unwrap();
        store.mirror_text(
            &app,
            "<?php\nnamespace App;\nuse Acme\\Base;\nclass App extends Base {}\n",
        );
        let _ = store.get_semantic_issues_salsa(&app);

        let base = Uri::from_file_path(tmp.path().join("vendor/acme/src/Base.php")).unwrap();
        let base_class = mir_analyzer::Name::Class(Arc::from("Acme\\Base"));
        let loaded = store
            .definition_location(&base_class)
            .expect("Acme\\Base must load on demand");
        assert_eq!(loaded.file.as_ref(), base.as_str());

        let edited = "<?php\nnamespace Acme;\n\nclass Base { public function hello(): void {} }\n";
        store.mirror_text(&base, edited);
        let moved = store.definition_location(&base_class).unwrap();
        assert_eq!(moved.file.as_ref(), base.as_str());
        assert_eq!(
            moved.line, 4,
            "the mirrored text must replace the on-demand copy"
        );

        let wi = store.get_workspace_index_salsa();
        let class_ref = store
            .class_ref_by_fqn(&wi, "Acme\\Base")
            .expect("on-demand loaded vendor class must resolve");
        assert_eq!(wi.files[class_ref.file as usize].0, base);
    }
}