mcpls-core 0.8.0

Core library for MCP to LSP protocol translation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
//! Manual restart of LSP servers on request (`restart_server`).
//!
//! A restart is kill-then-respawn: the old process tree is terminated first,
//! then a replacement is spawned through the same body automatic respawn uses
//! ([`Translator::respawn_locked`]), with the diagnostics pump re-wired so the
//! restarted server returns to live push diagnostics. While the old process is
//! being stopped the server is deregistered and reported as initializing, so
//! concurrent tool calls get a retryable error instead of a dead client.

use std::collections::HashSet;
use std::sync::Arc;
use std::time::Duration;

use futures::StreamExt;
use futures::future::BoxFuture;
use schemars::JsonSchema;
use serde::Serialize;
use tokio::sync::mpsc;
use tokio::task::AbortHandle;

use super::Translator;
use super::respawn::{BackoffPolicy, RespawnConfig};
use super::servers::{Backend, Phase};
use crate::bridge::indexing::IndexingReset;
use crate::bridge::{DiagnosticsKey, IndexingState, NotificationCache};
use crate::config::{LanguageId, ServerId};
use crate::error::{Error, ErrorChain, Result};
use crate::lsp::{ExitGrace, LspNotification};
use crate::redaction::{Redactions, ServerText};
use crate::util::lock_std;

/// Minimum interval between two manual restart attempts of the same server.
const RESTART_COOLDOWN: Duration = Duration::from_secs(5);

/// How long the old server gets to answer `shutdown` on a restart. Short
/// because a server that does not answer is killed anyway and the caller is
/// waiting.
const RESTART_HANDSHAKE_BUDGET: Duration = Duration::from_secs(3);

/// How long a server that did answer `shutdown` may take to exit on its own
/// on a restart (rust-analyzer and jdtls flush caches), before its process
/// tree is killed.
const RESTART_EXIT_GRACE: Duration = crate::lsp::SHUTDOWN_TIMEOUT;

/// Most server ids one request may name.
pub const MAX_RESTART_SERVER_IDS: usize = 64;

/// How many servers one `restart_server` call restarts concurrently.
const RESTART_CONCURRENCY: usize = 4;

/// Longest accepted server id, in bytes.
pub const MAX_SERVER_ID_BYTES: usize = 256;

/// Why a list of server ids was rejected by [`ServerIds::try_new`] or [`ServerIds::parse`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum ServerIdsError {
    /// No ids were given.
    #[error("`servers` must not be empty")]
    Empty,
    /// More than [`MAX_RESTART_SERVER_IDS`] ids were given.
    #[error("`servers` may name at most {MAX_RESTART_SERVER_IDS} servers")]
    TooMany,
    /// An id was empty or whitespace; only [`ServerIds::parse`] returns it.
    #[error("server ids must not be blank")]
    Blank,
    /// An id was longer than [`MAX_SERVER_ID_BYTES`].
    #[error("server ids must be at most {MAX_SERVER_ID_BYTES} bytes")]
    TooLong,
}

/// A non-empty, duplicate-free, bounded list of server ids: at most
/// [`MAX_RESTART_SERVER_IDS`] ids of [`MAX_SERVER_ID_BYTES`] bytes each.
///
/// # Examples
///
/// ```
/// use mcpls_core::bridge::{ServerIds, ServerIdsError};
/// use mcpls_core::config::ServerId;
///
/// let ids = ServerIds::try_new(vec![ServerId::from_static("rust"), ServerId::from_static("rust")]).unwrap();
/// assert_eq!(ids.as_slice().len(), 1);
/// assert_eq!(ServerIds::try_new(Vec::new()), Err(ServerIdsError::Empty));
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ServerIds(Vec<ServerId>);

impl ServerIds {
    /// Build the list, dropping repeated ids.
    ///
    /// # Errors
    ///
    /// [`ServerIdsError`] when `ids` is empty, has more than
    /// [`MAX_RESTART_SERVER_IDS`] entries, or holds an oversized id.
    pub fn try_new(ids: Vec<ServerId>) -> std::result::Result<Self, ServerIdsError> {
        if ids.len() > MAX_RESTART_SERVER_IDS {
            return Err(ServerIdsError::TooMany);
        }
        if ids.iter().any(|id| id.as_str().len() > MAX_SERVER_ID_BYTES) {
            return Err(ServerIdsError::TooLong);
        }
        let mut seen = HashSet::new();
        let unique: Vec<ServerId> = ids
            .into_iter()
            .filter(|id| seen.insert(id.clone()))
            .collect();
        (!unique.is_empty())
            .ok_or(ServerIdsError::Empty)
            .map(|()| Self(unique))
    }

    /// Parse the ids of a request, checking the count, blankness and length
    /// in that order, then drop repeats like [`Self::try_new`].
    ///
    /// # Errors
    ///
    /// [`ServerIdsError`] when `ids` is empty, has more than
    /// [`MAX_RESTART_SERVER_IDS`] entries, or holds a blank or oversized id.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcpls_core::bridge::{ServerIds, ServerIdsError};
    ///
    /// assert_eq!(ServerIds::parse(vec![" ".to_owned()]), Err(ServerIdsError::Blank));
    /// assert_eq!(ServerIds::parse(vec!["rust".to_owned()]).unwrap().as_slice().len(), 1);
    /// ```
    pub fn parse(ids: Vec<String>) -> std::result::Result<Self, ServerIdsError> {
        if ids.len() > MAX_RESTART_SERVER_IDS {
            return Err(ServerIdsError::TooMany);
        }
        let ids = ids
            .into_iter()
            .map(|id| ServerId::new(id).map_err(|_| ServerIdsError::Blank))
            .collect::<std::result::Result<Vec<_>, _>>()?;
        Self::try_new(ids)
    }

    /// The ids, in request order.
    #[must_use]
    pub fn as_slice(&self) -> &[ServerId] {
        &self.0
    }
}

/// Which servers a restart applies to.
///
/// # Examples
///
/// ```
/// use mcpls_core::bridge::{RestartTarget, ServerIds};
/// use mcpls_core::config::ServerId;
///
/// let one = RestartTarget::Servers(ServerIds::try_new(vec![ServerId::from_static("rust")]).unwrap());
/// assert_ne!(one, RestartTarget::All);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RestartTarget {
    /// Every configured server.
    All,
    /// Exactly these servers.
    Servers(ServerIds),
}

/// Why a restart failed.
///
/// [`Self::Refused`] leaves the old process running. Every other reason means
/// the old process is already stopped: the server stays registered as dead,
/// and the next tool call retries the spawn under the normal crash-loop
/// backoff.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case")]
#[non_exhaustive]
pub enum RestartFailure {
    /// Refused before the old process was stopped, which keeps serving.
    ///
    /// Covers every failure of the pre-stop check of the config the
    /// replacement would start from: an untrusted-workspace refusal, and the
    /// planning work itself failing.
    Refused {
        /// Why the restart was refused.
        message: String,
    },
    /// The replacement process could not be started.
    SpawnFailed {
        /// Why the spawn failed.
        message: String,
    },
    /// The replacement started but did not complete the `initialize` handshake.
    InitializeFailed {
        /// Why initialization failed.
        message: String,
    },
    /// mcpls is shutting down, so no replacement was started.
    ShuttingDown,
}

impl RestartFailure {
    fn from_error(error: &Error) -> Self {
        let message = ErrorChain(error).to_string();
        match error {
            Error::ServerNotFound { .. }
            | Error::ServerSpawnFailed { .. }
            | Error::ServerFailedToStart(_) => Self::SpawnFailed { message },
            Error::LspInitFailed { .. }
            | Error::ServerExitedDuringInit { .. }
            | Error::ServerTerminated
            | Error::TaskFailed { .. }
            | Error::StdioCapture(_)
            | Error::Timeout(_)
            | Error::LspServerError(..)
            | Error::LspProtocolError(_)
            | Error::ShutdownTimeout
            | Error::Io(_)
            | Error::Json(_)
            // Spawning a replacement never yields the variants below; they are
            // reported as an initialization failure rather than a new reason.
            | Error::McpServerStart(_)
            | Error::PathToUri(_)
            | Error::HttpBind { .. }
            | Error::InvalidClientPath(_)
            | Error::MalformedPath { .. }
            | Error::DocumentNotFound(_)
            | Error::NoServerForLanguage { .. }
            | Error::NoServerForTool { .. }
            | Error::ServerInitializing { .. }
            | Error::ServerRestarted { .. }
            | Error::SymbolResolution(_)
            | Error::UnknownServers { .. }
            | Error::WorkspaceServersInitializing
            | Error::NoServerConfigured
            | Error::NoServerForWorkspaceTool { .. }
            | Error::ConfigNotFound(_)
            | Error::ConfigInsideWorkspace { .. }
            | Error::Config(_)
            | Error::TomlDe(_)
            | Error::TomlSer(_)
            | Error::NoResolvableListenUris
            | Error::ResourceUri(_)
            | Error::InvalidPositionInput(_)
            | Error::InvalidRangeInput(_)
            | Error::InvalidHierarchyItemInput(_)
            | Error::PositionBeyondDocument { .. }
            | Error::ServerUnavailable { .. }
            | Error::InvalidToolParams(_)
            | Error::FileIo { .. }
            | Error::PathOutsideWorkspace(_)
            | Error::NoWorkspaceRoots(_)
            | Error::DocumentLimitExceeded { .. }
            | Error::SubscriptionLimitReached { .. }
            | Error::ListenStreamsExhausted { .. }
            | Error::ListenFilterTooLarge { .. }
            | Error::FileSizeLimitExceeded { .. }
            | Error::NotARegularFile(_)
            | Error::AllServersFailedToInit { .. }
            | Error::CapabilityNotSupported { .. }
            | Error::WorkspaceIndexing { .. } => Self::InitializeFailed { message },
        }
    }
}

/// What happened to one server in a restart request.
///
/// # Examples
///
/// ```
/// use mcpls_core::bridge::RestartOutcome;
///
/// let value = serde_json::to_value(RestartOutcome::Throttled { retry_in_ms: 1500 }).unwrap();
/// assert_eq!(value["status"], "throttled");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
#[serde(tag = "status", rename_all = "snake_case")]
#[non_exhaustive]
pub enum RestartOutcome {
    /// The server runs a freshly initialized process.
    Restarted {
        /// Another restart of this server finished while the request waited, so none was repeated.
        coalesced: bool,
        /// Indexing readiness of the new process.
        indexing_state: IndexingState,
        /// Push diagnostics for this server are still not live. A restart
        /// clears this; it stays set if a crash respawn raced in afterwards
        /// and restarting again is needed.
        push_notifications_degraded: bool,
    },
    /// The restart failed; see [`RestartFailure`].
    Failed {
        /// Why it failed.
        reason: RestartFailure,
    },
    /// The server was restarted too recently; retry after `retry_in_ms`.
    Throttled {
        /// Milliseconds until a restart is allowed again.
        retry_in_ms: u64,
    },
    /// The server has not finished its initial startup; retry shortly.
    Initializing,
    /// The server never started (or failed at startup), so there is no
    /// process to restart. Fix the cause and restart mcpls.
    NotRunning {
        /// Why the server is not running.
        message: String,
    },
}

impl RestartOutcome {
    /// The outcome for a server that is not registered, or whose process is gone.
    pub(crate) fn not_running(id: &ServerId) -> Self {
        Self::NotRunning {
            message: format!("LSP server '{id}' is not running"),
        }
    }
}

/// Whether a restart request ran the restart itself or found it done already.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RestartRun {
    /// This request stopped the old process and started the replacement.
    Performed,
    /// Another restart of the same server finished while this request waited.
    Coalesced,
}

/// One server's entry in a [`RestartServerResult`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
pub struct ServerRestartEntry {
    /// The server this entry reports on.
    pub server_id: ServerId,
    /// What happened to it.
    #[serde(flatten)]
    pub outcome: RestartOutcome,
}

/// Result of a restart request: one entry per targeted server, sorted by id.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
pub struct RestartServerResult {
    /// Per-server outcomes.
    pub servers: Vec<ServerRestartEntry>,
}

/// Count of manual restarts completed for one server.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(super) struct RestartGeneration(u64);

impl RestartGeneration {
    const fn bump(&mut self) {
        self.0 = self.0.saturating_add(1);
    }
}

/// The two notification lanes of a freshly spawned server.
#[derive(Debug)]
pub struct NotificationReceivers {
    /// Diagnostics, log and `showMessage` lane.
    pub(crate) notifications: crate::lsp::NotificationInbox,
    /// `$/progress` and unrecognized notifications lane.
    pub(crate) lifecycle: mpsc::Receiver<LspNotification>,
    /// The `tsserver` path mcpls pinned for this server, so the lifecycle lane
    /// can warn when the server reports it did not take effect.
    pub(crate) pinned_tsserver: Option<std::path::PathBuf>,
}

impl NotificationReceivers {
    /// The receivers a pump drains for a spawned server's `lanes`.
    pub(crate) fn new(
        lanes: crate::lsp::ServerLanes,
        pinned_tsserver: Option<std::path::PathBuf>,
    ) -> Self {
        let crate::lsp::ServerLanes {
            notifications,
            lifecycle,
        } = lanes;
        Self {
            notifications,
            lifecycle,
            pinned_tsserver,
        }
    }
}

/// How a respawned server's notifications are consumed.
#[derive(Clone, Copy)]
pub(super) enum NotificationRouting<'a> {
    /// Drain and discard the notification lane; the diagnostics-route server
    /// is flagged push-degraded (automatic crash respawn).
    Discard,
    /// Re-wire the diagnostics pump (manual restart).
    Pump(&'a dyn NotificationWiring),
}

/// Whether a server's `publishDiagnostics` pushes are the ones the cache
/// keeps for its language -- see #174 section 8.
///
/// The role is re-evaluated whenever a server settles: a catch-all that
/// registered as `Secondary` becomes `Authoritative` when the explicit
/// diagnostics server for its language fails afterwards. Pushes the catch-all
/// made while it was `Secondary` are not replayed; the cache fills with its
/// next publish for each file (the next `didOpen`/`didChange`). A file nobody
/// opens may never get one, since only the disk sweep sends `didSave`, and
/// only for changed files of a server with a subscribed file.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiagnosticsRole {
    /// The server is the language's diagnostics route: its pushes are cached
    /// and subscribers are notified.
    Authoritative,
    /// Another server owns the language's diagnostics (or none does): pushes
    /// are skipped so they cannot overwrite or spuriously notify about the
    /// owner's entries.
    Secondary,
}

/// Whether a server's push diagnostics are live or discarded after a cache reset.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum PushDelivery {
    /// The replacement's pushes are cached again (manual restart re-wired the pump).
    Live,
    /// Pushes are not cached; the server is flagged push-degraded.
    Degraded,
}

/// Drops what a stopped or replaced server left in `cache`: its indexing
/// state per `indexing`, and, for the diagnostics-route server only, its
/// cached diagnostics, then updates its push-degraded flag per `push`.
/// Returns the cleared keys so subscribers can be told to re-read them.
pub(super) fn reset_server_cache(
    cache: &mut NotificationCache,
    id: &ServerId,
    indexing: IndexingReset,
    role: DiagnosticsRole,
    push: PushDelivery,
) -> Vec<DiagnosticsKey> {
    cache.reset_indexing_state(id, indexing);
    if role != DiagnosticsRole::Authoritative {
        return Vec::new();
    }
    let cleared = cache.clear_server_diagnostics(id);
    match push {
        PushDelivery::Live => cache.clear_push_degraded(id),
        PushDelivery::Degraded => cache.mark_push_degraded(id),
    }
    cleared
}

impl DiagnosticsRole {
    /// The role of a server that is, or is not, the language's diagnostics route.
    pub(crate) const fn from_route(is_diagnostics_route: bool) -> Self {
        if is_diagnostics_route {
            Self::Authoritative
        } else {
            Self::Secondary
        }
    }
}

/// The part of notification handling that lives in `serve_with`'s scope
/// (shutdown token, subscription registry) and so cannot be built by the
/// translator itself.
pub trait NotificationWiring: std::fmt::Debug + Send + Sync {
    /// Start a diagnostics pump over `receivers` for `id`, returning a handle
    /// that stops it. A panicking pump must mark `id` push-degraded.
    fn spawn_pump(
        &self,
        id: ServerId,
        receivers: NotificationReceivers,
        role: DiagnosticsRole,
    ) -> AbortHandle;

    /// Tell subscribers of the resources behind the `cleared` cache keys to
    /// re-read them: after a server's entries were cleared, and after a pull
    /// write evicted other files' entries.
    fn publish_invalidated<'a>(&'a self, cleared: &'a [DiagnosticsKey]) -> BoxFuture<'a, ()>;

    /// Whether any session holds a subscription at all, so a caller can skip
    /// work that only matters to subscribers. Defaults to `true`, which only
    /// forgoes the saving.
    fn has_subscriptions(&self) -> BoxFuture<'_, bool> {
        Box::pin(async { true })
    }

    /// Tell subscribers of the resource behind `file`, the canonical URI of a
    /// tracked file, that a `textDocument/diagnostic` report changed what a
    /// read of it returns.
    fn publish_changed<'a>(&'a self, file: &'a lsp_types::Uri) -> BoxFuture<'a, ()>;
}

/// Keeps restarts reporting `initializing` until dropped, so an init panic,
/// task abort or early return can never leave the flag set.
#[derive(Debug)]
pub struct StartupGuard<'a>(&'a Translator);

impl Drop for StartupGuard<'_> {
    fn drop(&mut self) {
        lock_std(&self.0.phase).finish_startup();
    }
}

/// A server taken out of its slot for termination, restored on every exit
/// path (error, early return, panic, cancelled future).
struct Deregistered<'a> {
    translator: &'a Translator,
    id: ServerId,
    backend: Option<Backend>,
}

impl<'a> Deregistered<'a> {
    /// Marks `id` restarting while taking its backend, in one step, so no
    /// caller ever finds it in neither state (which would read as a missing
    /// server).
    fn take(translator: &'a Translator, id: &ServerId) -> Option<Self> {
        let backend = lock_std(&translator.servers).take_for_restart(id)?;
        let held = Self {
            translator,
            id: id.clone(),
            backend: Some(backend),
        };
        held.backend
            .as_ref()
            .is_some_and(|backend| backend.server().is_some())
            .then_some(held)
    }

    /// Stop the held server. Termination errors (a wedged server times out)
    /// are not fatal.
    async fn terminate(&mut self) {
        let Some(backend) = self.backend.as_mut() else {
            return;
        };
        backend.client().mark_restarted(self.id.clone());
        let Some(server) = backend.server_mut() else {
            return;
        };
        let stopped = server
            .terminate(
                RESTART_HANDSHAKE_BUDGET,
                ExitGrace::IfAnswered(RESTART_EXIT_GRACE),
            )
            .await;
        if let Err(error) = stopped {
            tracing::warn!(id = %self.id, error = %ErrorChain(&error), "old LSP server did not stop cleanly; continuing with restart");
        }
    }

    /// Put the held backend back; idempotent.
    fn restore(&mut self) {
        if let Some(backend) = self.backend.take() {
            let refused = lock_std(&self.translator.servers).restore(&self.id, backend);
            if refused.is_some() {
                tracing::warn!(id = %self.id, "restored server dropped: its slot was settled meanwhile");
            }
            drop(refused);
        }
    }
}

impl Drop for Deregistered<'_> {
    fn drop(&mut self) {
        self.restore();
    }
}

impl Translator {
    /// Restart the servers named by `target`, each independently.
    ///
    /// The old process tree is stopped (graceful `shutdown`/`exit` bounded by
    /// the LSP shutdown deadline, then the whole process group is killed) and a
    /// replacement is spawned and initialized from the server's existing
    /// config. Requests in flight on the old process fail with a retryable
    /// [`Error::ServerRestarted`]; documents are re-opened on the new process
    /// on next access. Servers not named are untouched. Restarts of the same
    /// server are serialized, and a request that queued behind another restart
    /// of the same server is reported as coalesced.
    ///
    /// # Errors
    ///
    /// [`Error::UnknownServers`] when `target` names a server that is not
    /// configured; nothing is restarted then. Per-server failures are reported
    /// in the result, not as errors.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use mcpls_core::bridge::{RestartTarget, Translator};
    ///
    /// # async fn run(translator: &Translator) -> mcpls_core::error::Result<()> {
    /// let result = translator.restart_servers(RestartTarget::All).await?;
    /// for entry in &result.servers {
    ///     println!("{}: {:?}", entry.server_id, entry.outcome);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn restart_servers(&self, target: RestartTarget) -> Result<RestartServerResult> {
        let known = self.known_server_ids();
        let ids = match target {
            RestartTarget::All => known,
            RestartTarget::Servers(requested) => {
                let unknown: Vec<ServerId> = requested
                    .as_slice()
                    .iter()
                    .filter(|id| !known.contains(id))
                    .cloned()
                    .collect();
                if !unknown.is_empty() {
                    return Err(Error::UnknownServers {
                        unknown,
                        configured: known,
                    });
                }
                requested.0
            }
        };

        // Snapshotted for every id up front: ids queued behind the
        // concurrency limit must not observe a restart of their own request.
        let requests: Vec<(ServerId, RestartGeneration)> = ids
            .into_iter()
            .map(|id| {
                let generation = self.restart_generation(&id);
                (id, generation)
            })
            .collect();
        let mut servers: Vec<ServerRestartEntry> = futures::stream::iter(requests)
            .map(|(id, generation)| async move {
                let outcome = Box::pin(self.restart_one(&id, generation)).await;
                ServerRestartEntry {
                    server_id: id,
                    outcome,
                }
            })
            .buffer_unordered(RESTART_CONCURRENCY)
            .collect()
            .await;
        servers.sort_by(|a, b| a.server_id.as_str().cmp(b.server_id.as_str()));
        Ok(RestartServerResult { servers })
    }

    /// Every server a restart may address: registered, still expected, or
    /// failed at startup. Sorted by id.
    fn known_server_ids(&self) -> Vec<ServerId> {
        let mut ids: Vec<ServerId> = lock_std(&self.servers).ids().cloned().collect();
        ids.sort_by(|a, b| a.as_str().cmp(b.as_str()));
        ids
    }

    fn restart_generation(&self, id: &ServerId) -> RestartGeneration {
        lock_std(&self.servers)
            .get(id)
            .map_or_default(|slot| slot.restart.generation)
    }

    /// Install how restarted servers get their diagnostics pump back.
    ///
    /// Called once, before the first server settles, so each initial pump is
    /// registered with [`Self::set_notification_task`] as its server
    /// registers; a repeat call keeps the first wiring. Restarts stay blocked
    /// until startup has settled (see [`Self::begin_startup`]).
    pub(crate) fn install_wiring(&self, wiring: Arc<dyn NotificationWiring>) {
        if self.wiring.set(wiring).is_err() {
            tracing::debug!("notification wiring already installed");
        }
    }

    /// Record the task consuming `id`'s notification lanes, so a restart can
    /// stop it before starting its replacement.
    pub(crate) fn set_notification_task(&self, id: &ServerId, handle: AbortHandle) {
        if let Some(slot) = lock_std(&self.servers).get_mut(id) {
            slot.notification_task = Some(handle);
        }
    }

    /// Take the task consuming `id`'s notification lanes out of its slot.
    pub(super) fn take_notification_task(&self, id: &ServerId) -> Option<AbortHandle> {
        lock_std(&self.servers)
            .get_mut(id)
            .and_then(|slot| slot.notification_task.take())
    }

    /// Declare that the initial server startup is still settling; restarts
    /// report `initializing` until the returned guard is dropped, because routes
    /// (and so diagnostics roles) still change while servers settle; a restarted
    /// pump follows those changes through the shared role registry.
    pub(crate) fn begin_startup(&self) -> StartupGuard<'_> {
        lock_std(&self.phase).begin_startup();
        StartupGuard(self)
    }

    /// Declare that shutdown has begun; no restart starts a server after this.
    pub(crate) fn begin_shutdown(&self) {
        lock_std(&self.phase).begin_shutdown();
    }

    fn is_shutting_down(&self) -> bool {
        *lock_std(&self.phase) == Phase::ShuttingDown
    }

    /// The cooldown still to wait before `id` may be restarted again.
    fn restart_cooldown_remaining(&self, id: &ServerId) -> Option<Duration> {
        let last = lock_std(&self.servers).get(id)?.restart.last_attempt?;
        let elapsed = self.clock.now().saturating_duration_since(last);
        RESTART_COOLDOWN.checked_sub(elapsed)
    }

    async fn restarted_outcome(&self, id: &ServerId, run: RestartRun) -> RestartOutcome {
        let (indexing_state, push_notifications_degraded) = match &self.notification_cache {
            Some(cache) => {
                let cache = cache.lock().await;
                (cache.indexing_state(id), cache.is_push_degraded(id))
            }
            None => (IndexingState::Unknown, false),
        };
        RestartOutcome::Restarted {
            coalesced: run == RestartRun::Coalesced,
            indexing_state,
            push_notifications_degraded,
        }
    }

    /// The notification wiring a restart of `id` needs, or why it cannot be
    /// restarted right now, in classification order: shutting down, never
    /// started or failed to start, init panicked, startup still settling or not
    /// yet wired, then the cooldown.
    fn restart_permit(
        &self,
        id: &ServerId,
    ) -> std::result::Result<&Arc<dyn NotificationWiring>, RestartOutcome> {
        let phase = *lock_std(&self.phase);
        if phase == Phase::ShuttingDown {
            return Err(RestartOutcome::Failed {
                reason: RestartFailure::ShuttingDown,
            });
        }
        let not_running = {
            let servers = lock_std(&self.servers);
            let outcome = servers
                .server(id)
                .is_none()
                .then(|| match servers.failure(id) {
                    Some(failure) => RestartOutcome::NotRunning {
                        message: Error::ServerFailedToStart(Box::new(failure.clone())).to_string(),
                    },
                    None if servers.is_expected(id) => RestartOutcome::Initializing,
                    None => RestartOutcome::not_running(id),
                });
            drop(servers);
            outcome
        };
        if let Some(outcome) = not_running {
            return Err(outcome);
        }
        if phase == Phase::InitPanicked {
            return Err(RestartOutcome::NotRunning {
                message: "startup was interrupted by a panic, so servers cannot be restarted; restart mcpls".to_string(),
            });
        }
        let wiring = match (phase, self.wiring.get()) {
            (Phase::Settling, _) | (_, None) => return Err(RestartOutcome::Initializing),
            (_, Some(wiring)) => wiring,
        };
        self.restart_cooldown_remaining(id)
            .map_or(Ok(wiring), |remaining| {
                Err(RestartOutcome::Throttled {
                    retry_in_ms: u64::try_from(remaining.as_millis()).unwrap_or(u64::MAX),
                })
            })
    }

    async fn restart_one(&self, id: &ServerId, seen: RestartGeneration) -> RestartOutcome {
        let lock = self.respawn_lock(id);
        let _serialized = lock.lock().await;

        if self.restart_generation(id) != seen {
            return self.restarted_outcome(id, RestartRun::Coalesced).await;
        }
        let wiring = match self.restart_permit(id) {
            Ok(wiring) => wiring,
            Err(outcome) => return outcome,
        };

        let running = lock_std(&self.servers)
            .server(id)
            .map(|server| server.init_config().clone());
        let Some(running) = running else {
            return RestartOutcome::not_running(id);
        };
        let vetted = match running.for_respawn().await {
            Ok(vetted) => vetted,
            Err(error) => {
                tracing::warn!(%id, error = %ErrorChain(&error), "LSP server restart refused");
                return RestartOutcome::Failed {
                    reason: RestartFailure::Refused {
                        message: ErrorChain(&error).to_string(),
                    },
                };
            }
        };

        // A refusal stopped nothing, so it must not start the restart cooldown.
        self.note_restart_attempt(id);
        tracing::info!(%id, "restarting LSP server on request");

        let Some(mut old) = Deregistered::take(self, id) else {
            return RestartOutcome::not_running(id);
        };
        let language_id = vetted.server_config().language_id.clone();
        old.terminate().await;
        drop(old);

        if self.is_shutting_down() {
            self.invalidate_stopped_server(id, &language_id).await;
            return RestartOutcome::Failed {
                reason: RestartFailure::ShuttingDown,
            };
        }
        let respawned = self
            .respawn_locked(
                id,
                RespawnConfig::Vetted(vetted),
                BackoffPolicy::Bypass,
                NotificationRouting::Pump(wiring.as_ref()),
            )
            .await;
        // Counted from completion too, so a slow restart cannot be chained at once.
        self.note_restart_attempt(id);
        if let Err(error) = respawned {
            tracing::warn!(%id, error = %ErrorChain(&error), "LSP server restart failed");
            self.invalidate_stopped_server(id, &language_id).await;
            return RestartOutcome::Failed {
                reason: RestartFailure::from_error(&error),
            };
        }

        if self.is_shutting_down() {
            self.discard_registered(id).await;
            return RestartOutcome::Failed {
                reason: RestartFailure::ShuttingDown,
            };
        }
        if let Some(slot) = lock_std(&self.servers).get_mut(id) {
            slot.restart.generation.bump();
        }
        tracing::info!(%id, "LSP server restarted");
        self.restarted_outcome(id, RestartRun::Performed).await
    }

    fn note_restart_attempt(&self, id: &ServerId) {
        if let Some(slot) = lock_std(&self.servers).get_mut(id) {
            slot.restart.last_attempt = Some(self.clock.now());
        }
    }

    /// The old process is gone and no replacement runs: drop what it cached
    /// and say so, so its diagnostics are never served as live.
    async fn invalidate_stopped_server(&self, id: &ServerId, language_id: &LanguageId) {
        // Best effort: the old pump goes first, and an aborted task stops at its
        // next await, so it cannot re-cache what the dead server buffered
        // once the cache below is cleared.
        if let Some(pump) = self.take_notification_task(id) {
            pump.abort();
            tokio::task::yield_now().await;
        }
        let cleared = match &self.notification_cache {
            Some(cache) => {
                let mut cache = cache.lock().await;
                reset_server_cache(
                    &mut cache,
                    id,
                    IndexingReset::Forget,
                    DiagnosticsRole::from_route(self.is_diagnostics_route(language_id, id)),
                    PushDelivery::Degraded,
                )
            }
            None => Vec::new(),
        };
        if let Some(wiring) = self.wiring.get() {
            wiring.publish_invalidated(&cleared).await;
        }
    }

    /// Shut down and deregister the server just registered under `id`, after
    /// shutdown began while its replacement was starting.
    async fn discard_registered(&self, id: &ServerId) {
        let server = lock_std(&self.servers).remove_server(id);
        if let Some(server) = server
            && let Err(error) = server.shutdown().await
        {
            tracing::warn!(%id, error = %ErrorChain(&error), "replacement LSP server shutdown failed");
        }
    }
}

impl ServerText for RestartFailure {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        match self {
            Self::Refused { message }
            | Self::SpawnFailed { message }
            | Self::InitializeFailed { message } => {
                redactions.redact_in_place(message);
            }
            Self::ShuttingDown => {}
        }
    }
}

impl ServerText for RestartOutcome {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        match self {
            Self::Restarted {
                coalesced: _,
                indexing_state: _,
                push_notifications_degraded: _,
            }
            | Self::Throttled { retry_in_ms: _ }
            | Self::Initializing => {}
            Self::Failed { reason } => reason.redact_server_text(redactions),
            Self::NotRunning { message } => redactions.redact_in_place(message),
        }
    }
}

impl ServerText for ServerRestartEntry {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            server_id: _,
            outcome,
        } = self;
        outcome.redact_server_text(redactions);
    }
}

impl ServerText for RestartServerResult {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self { servers } = self;
        servers.redact_server_text(redactions);
    }
}

#[cfg(test)]
mod tests {
    use std::assert_matches;

    use super::*;

    #[test]
    fn server_ids_drop_repeats_keep_order_and_reject_empty() {
        let ids = ServerIds::try_new(vec![
            ServerId::from_static("b"),
            ServerId::from_static("a"),
            ServerId::from_static("b"),
        ])
        .unwrap();
        assert_eq!(
            ids.as_slice(),
            [ServerId::from_static("b"), ServerId::from_static("a")]
        );
        assert_eq!(ServerIds::try_new(Vec::new()), Err(ServerIdsError::Empty));
        let ids = |count: usize| {
            (0..count)
                .map(|i| ServerId::new(format!("s{i}")).unwrap())
                .collect()
        };
        assert!(ServerIds::try_new(ids(MAX_RESTART_SERVER_IDS)).is_ok());
        assert_eq!(
            ServerIds::try_new(ids(MAX_RESTART_SERVER_IDS + 1)),
            Err(ServerIdsError::TooMany)
        );
        assert_eq!(
            ServerIds::parse(vec![" ".to_owned()]),
            Err(ServerIdsError::Blank)
        );
        assert_eq!(
            ServerIds::try_new(vec![
                ServerId::new("x".repeat(MAX_SERVER_ID_BYTES + 1)).unwrap()
            ]),
            Err(ServerIdsError::TooLong)
        );
        assert_eq!(
            ServerIds::parse(vec![" ".to_owned(); MAX_RESTART_SERVER_IDS + 1]),
            Err(ServerIdsError::TooMany)
        );
        assert_eq!(
            ServerIds::parse(vec!["x".repeat(MAX_SERVER_ID_BYTES + 1), " ".to_owned()]),
            Err(ServerIdsError::Blank)
        );
    }

    #[test]
    fn a_refusal_serializes_with_its_own_kind() {
        let refused = RestartFailure::Refused {
            message: "no".to_string(),
        };
        assert_eq!(
            serde_json::to_value(refused).unwrap(),
            serde_json::json!({"kind": "refused", "message": "no"})
        );
    }

    #[test]
    fn restart_entry_flattens_the_outcome_next_to_the_server_id() {
        let entry = ServerRestartEntry {
            server_id: ServerId::from_static("rust"),
            outcome: RestartOutcome::Failed {
                reason: RestartFailure::SpawnFailed {
                    message: "gone".to_string(),
                },
            },
        };
        assert_eq!(
            serde_json::to_value(entry).unwrap(),
            serde_json::json!({
                "server_id": "rust",
                "status": "failed",
                "reason": {"kind": "spawn_failed", "message": "gone"},
            })
        );
    }

    #[test]
    fn spawn_errors_map_to_spawn_failed_and_the_rest_to_initialize_failed() {
        let not_found = Error::ServerNotFound {
            command: crate::config::ServerCommand::from_static("x"),
            io: std::io::Error::from(std::io::ErrorKind::NotFound),
        };
        assert_matches!(
            RestartFailure::from_error(&not_found),
            RestartFailure::SpawnFailed { .. }
        );
        assert_matches!(
            RestartFailure::from_error(&Error::Timeout(Duration::from_secs(5))),
            RestartFailure::InitializeFailed { .. }
        );
    }

    #[test]
    fn restart_failure_keeps_the_os_cause() {
        let spawn = Error::ServerSpawnFailed {
            command: crate::config::ServerCommand::from_static("x"),
            source: std::io::Error::new(std::io::ErrorKind::PermissionDenied, "permission denied"),
        };
        let RestartFailure::SpawnFailed { message } = RestartFailure::from_error(&spawn) else {
            panic!("expected SpawnFailed");
        };
        assert_eq!(message, "failed to spawn LSP server 'x': permission denied");
    }

    /// #815: a refusal stops nothing, so it must not start the restart
    /// cooldown. Needs no process: the refusal is the argument recheck, whose
    /// trigger (an executable file named `tool.exe` in the workspace) holds on
    /// every host.
    #[tokio::test]
    async fn test_refused_restart_leaves_the_cooldown_untouched() {
        use tokio::sync::Mutex;
        use tokio_util::sync::CancellationToken;

        use crate::bridge::translator::clock::{Clock, FakeClock};
        use crate::bridge::{NotificationCache, WorkspaceRoots};
        use crate::config::{LanguageId, ToolRouter};
        use crate::mcp::SubscriptionRegistry;
        use crate::runtime::pump::{DiagnosticsRoles, PumpShared, PumpWiring};

        let dir = tempfile::TempDir::new().unwrap();
        let tool = dir.path().join("tool.exe");
        std::fs::write(&tool, "").unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt as _;
            std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap();
        }
        let roots = WorkspaceRoots::from_paths(&[dir.path().to_path_buf()]).unwrap();

        let id = ServerId::from_static("rust");
        let cache = Arc::new(Mutex::new(NotificationCache::new()));
        let clock = Arc::new(FakeClock::new());
        let mut translator = Translator::new()
            .with_router(ToolRouter::catch_all([(
                id.clone(),
                LanguageId::from_static("rust"),
            )]))
            .with_notification_cache(Arc::clone(&cache))
            .with_clock(Arc::clone(&clock) as Arc<dyn Clock>);
        translator.set_workspace_roots(roots.clone());
        translator.register_server_complete(crate::lsp::fake_lsp_server_with_config(
            crate::config::LspServerConfig::rust_analyzer(),
        ));
        translator.install_wiring(Arc::new(PumpWiring::new(
            PumpShared {
                roles: DiagnosticsRoles::default(),
                notification_cache: cache,
                subs: SubscriptionRegistry::new(),
                workspace_roots: translator.workspace_roots.clone(),
            },
            CancellationToken::new(),
        )));

        let init = lock_std(&translator.servers)
            .server_mut(&id)
            .unwrap()
            .init_config()
            .clone();
        let command = init.server_config().command.server_command().clone();
        let mut init = init.with_trust(crate::lsp::SpawnTrust::Untrusted(
            crate::lsp::vetting::UntrustedVetting::new(roots, command),
        ));
        init.server_config_mut().args =
            crate::config::ServerArgs::new([tool.to_string_lossy().into_owned()]).unwrap();
        lock_std(&translator.servers)
            .server_mut(&id)
            .unwrap()
            .set_init_config(init);

        let result = translator
            .restart_servers(RestartTarget::All)
            .await
            .unwrap();

        assert_matches!(
            &result.servers[0].outcome,
            RestartOutcome::Failed {
                reason: RestartFailure::Refused { .. }
            },
            "{result:?}"
        );
        assert_eq!(translator.restart_cooldown_remaining(&id), None);
    }

    #[cfg(unix)]
    mod restart_tests {
        use std::fs;
        use std::path::{Path, PathBuf};

        use tempfile::TempDir;
        use tokio::sync::Mutex;
        use tokio_util::sync::CancellationToken;

        use super::*;
        use crate::bridge::translator::clock::{Clock, FakeClock};
        use crate::bridge::translator::testing::{
            stub_server_config, write_crash_after_init_script, write_protocol_server_script,
            write_responder_script, write_slow_exit_server_script,
        };
        use crate::bridge::{NotificationCache, WorkspaceRoots};
        use crate::config::{LanguageId, ServerCommand, ToolRouter};
        use crate::error::{ServerSpawnFailure, StartupFailure};
        use crate::mcp::SubscriptionRegistry;
        use crate::runtime::pump::{PumpShared, PumpWiring};

        struct Fixture {
            translator: Arc<Translator>,
            cache: Arc<Mutex<NotificationCache>>,
            clock: Arc<FakeClock>,
            id: ServerId,
            dir: TempDir,
        }

        fn server_ids(names: &[&str]) -> RestartTarget {
            RestartTarget::Servers(
                ServerIds::try_new(names.iter().map(|n| ServerId::new(*n).unwrap()).collect())
                    .unwrap(),
            )
        }

        async fn fixture(dir: TempDir, script: &Path, wired: bool) -> Fixture {
            let id = ServerId::from_static("rust");
            let cache = Arc::new(Mutex::new(NotificationCache::new()));
            let clock = Arc::new(FakeClock::new());
            let mut translator = Translator::new()
                .with_router(ToolRouter::catch_all([(
                    id.clone(),
                    LanguageId::from_static("rust"),
                )]))
                .with_notification_cache(Arc::clone(&cache))
                .with_clock(clock.clone());
            translator.set_workspace_roots(
                WorkspaceRoots::from_paths(&[dir.path().to_path_buf()]).unwrap(),
            );

            let crate::lsp::SpawnedServer { server, lanes } =
                crate::lsp::LspServer::spawn(stub_server_config("rust", script))
                    .await
                    .unwrap();
            let receivers = NotificationReceivers::new(lanes, None);
            translator.register_server_complete(server);

            let wiring = PumpWiring::new(
                PumpShared {
                    roles: crate::runtime::pump::DiagnosticsRoles::default(),
                    notification_cache: Arc::clone(&cache),
                    subs: SubscriptionRegistry::new(),
                    workspace_roots: translator.workspace_roots.clone(),
                },
                CancellationToken::new(),
            );
            let pump = wiring.spawn_pump(id.clone(), receivers, DiagnosticsRole::Authoritative);
            translator.set_notification_task(&id, pump);
            if wired {
                translator.install_wiring(Arc::new(wiring));
            }
            Fixture {
                translator: Arc::new(translator),
                cache,
                clock,
                id,
                dir,
            }
        }

        async fn protocol_fixture(publish: Option<&str>) -> (Fixture, PathBuf) {
            let dir = TempDir::new().unwrap();
            let log = dir.path().join("server.log");
            let script = write_protocol_server_script(dir.path(), &log, publish);
            (fixture(dir, &script, true).await, log)
        }

        fn read_log(log: &Path) -> String {
            fs::read_to_string(log).unwrap_or_default()
        }

        fn only_outcome(result: &RestartServerResult) -> &RestartOutcome {
            assert_eq!(result.servers.len(), 1, "{result:?}");
            &result.servers[0].outcome
        }

        impl Fixture {
            fn root(&self) -> &Path {
                self.dir.path()
            }

            #[cfg(unix)]
            fn vet_arguments_against(&self, boundary: WorkspaceRoots, tool: &Path) {
                let init = lock_std(&self.translator.servers)
                    .server_mut(&self.id)
                    .unwrap()
                    .init_config()
                    .clone();
                let command = init.server_config().command.server_command().clone();
                let mut init = init.with_trust(crate::lsp::SpawnTrust::Untrusted(
                    crate::lsp::vetting::UntrustedVetting::new(boundary, command),
                ));
                let args = init.server_config_mut();
                args.args = crate::config::ServerArgs::new(
                    args.args
                        .iter()
                        .cloned()
                        .chain([tool.to_string_lossy().into_owned()]),
                )
                .unwrap();
                lock_std(&self.translator.servers)
                    .server_mut(&self.id)
                    .unwrap()
                    .set_init_config(init);
            }

            fn registered(&self) -> bool {
                let servers = lock_std(&self.translator.servers);
                servers.server(&self.id).is_some() && servers.client(&self.id).is_some()
            }

            fn expected(&self) -> bool {
                lock_std(&self.translator.servers).is_expected(&self.id)
            }

            fn is_dead(&self) -> bool {
                lock_std(&self.translator.servers)
                    .server_mut(&self.id)
                    .unwrap()
                    .is_dead()
                    .unwrap()
            }

            async fn wait_until_deregistered(&self) {
                tokio::time::timeout(Duration::from_secs(5), async {
                    while !self.expected() {
                        tokio::time::sleep(Duration::from_millis(10)).await;
                    }
                })
                .await
                .expect("the restart must deregister the server");
            }
        }

        #[tokio::test]
        async fn test_restart_replaces_the_process_after_a_graceful_stop() {
            let (fx, log) = protocol_fixture(None).await;

            let result = fx
                .translator
                .restart_servers(RestartTarget::All)
                .await
                .unwrap();

            assert_matches!(
                only_outcome(&result),
                RestartOutcome::Restarted {
                    coalesced: false,
                    ..
                },
                "{result:?}"
            );
            let log = read_log(&log);
            assert_eq!(log.matches("started").count(), 2, "{log}");
            assert!(log.contains(r#""method":"shutdown""#), "{log}");
            assert!(log.contains(r#""method":"exit""#), "{log}");
            assert!(fx.registered() && !fx.expected() && !fx.is_dead());
        }

        /// Regression test for #736: a restart refused by the argument recheck
        /// is decided before the running server is stopped.
        #[cfg(unix)]
        #[tokio::test]
        async fn test_restart_refused_by_the_argument_recheck_keeps_the_old_server_running() {
            use std::os::unix::fs::PermissionsExt as _;

            let (fx, log) = protocol_fixture(None).await;
            let workspace = fx.root().join("ws");
            fs::create_dir_all(&workspace).unwrap();
            let tool = workspace.join("tool");
            fs::write(&tool, "").unwrap();
            fx.vet_arguments_against(WorkspaceRoots::from_paths(&[workspace]).unwrap(), &tool);
            fx.translator
                .restart_servers(RestartTarget::All)
                .await
                .unwrap();
            fx.clock.advance(RESTART_COOLDOWN + Duration::from_secs(1));
            fs::set_permissions(&tool, fs::Permissions::from_mode(0o755)).unwrap();

            let result = fx
                .translator
                .restart_servers(RestartTarget::All)
                .await
                .unwrap();

            let RestartOutcome::Failed {
                reason: RestartFailure::Refused { message },
            } = only_outcome(&result)
            else {
                panic!("expected a refused restart, got {result:?}");
            };
            assert!(
                message.contains("executable inside the workspace"),
                "{message}"
            );
            let log = read_log(&log);
            assert_eq!(log.matches("started").count(), 2, "{log}");
            assert!(fx.registered() && !fx.expected() && !fx.is_dead());
        }

        /// A refusal stops nothing, so it must not start the restart cooldown.
        #[cfg(unix)]
        #[tokio::test]
        async fn test_refused_restart_does_not_start_the_cooldown() {
            use std::os::unix::fs::PermissionsExt as _;

            let (fx, _log) = protocol_fixture(None).await;
            let workspace = fx.root().join("ws");
            fs::create_dir_all(&workspace).unwrap();
            let tool = workspace.join("tool");
            fs::write(&tool, "").unwrap();
            fx.vet_arguments_against(WorkspaceRoots::from_paths(&[workspace]).unwrap(), &tool);
            fx.translator
                .restart_servers(RestartTarget::All)
                .await
                .unwrap();
            fx.clock.advance(RESTART_COOLDOWN + Duration::from_secs(1));
            fs::set_permissions(&tool, fs::Permissions::from_mode(0o755)).unwrap();
            let refused = fx
                .translator
                .restart_servers(RestartTarget::All)
                .await
                .unwrap();
            assert_matches!(
                only_outcome(&refused),
                RestartOutcome::Failed {
                    reason: RestartFailure::Refused { .. }
                },
                "{refused:?}"
            );

            fs::set_permissions(&tool, fs::Permissions::from_mode(0o644)).unwrap();
            let retried = fx
                .translator
                .restart_servers(RestartTarget::All)
                .await
                .unwrap();

            assert_matches!(
                only_outcome(&retried),
                RestartOutcome::Restarted { .. },
                "{retried:?}"
            );
        }

        #[tokio::test]
        async fn test_restart_of_a_wedged_server_completes_despite_the_terminate_error() {
            let dir = TempDir::new().unwrap();
            let script = write_responder_script(dir.path(), 600);
            let fx = fixture(dir, &script, true).await;

            let result = fx
                .translator
                .restart_servers(RestartTarget::All)
                .await
                .unwrap();

            assert_matches!(
                only_outcome(&result),
                RestartOutcome::Restarted { .. },
                "{result:?}"
            );
            assert!(fx.registered() && !fx.expected() && !fx.is_dead());
        }

        #[tokio::test]
        async fn test_cancelled_restart_restores_the_registry() {
            let dir = TempDir::new().unwrap();
            let script = write_responder_script(dir.path(), 600);
            let fx = fixture(dir, &script, true).await;

            let translator = Arc::clone(&fx.translator);
            let task =
                tokio::spawn(async move { translator.restart_servers(RestartTarget::All).await });
            fx.wait_until_deregistered().await;
            assert!(!fx.registered());

            task.abort();
            assert!(task.await.unwrap_err().is_cancelled());

            assert!(fx.registered() && !fx.expected());
        }

        #[tokio::test]
        async fn test_restart_of_a_startup_failed_server_reports_not_running() {
            let id = ServerId::from_static("rust");
            let translator = Translator::new().with_router(ToolRouter::catch_all([(
                id.clone(),
                LanguageId::from_static("rust"),
            )]));
            translator.record_startup_failures(&[ServerSpawnFailure {
                server_id: id.clone(),
                language_id: LanguageId::from_static("rust"),
                command: ServerCommand::from_static("missing"),
                reason: StartupFailure::InitTaskPanicked,
            }]);
            translator.rebind_router(&HashSet::new());
            translator.clear_expected_servers();

            let result = translator
                .restart_servers(server_ids(&["rust"]))
                .await
                .unwrap();

            assert_matches!(
                only_outcome(&result),
                RestartOutcome::NotRunning { .. },
                "{result:?}"
            );
        }

        #[tokio::test]
        async fn test_restart_all_reports_a_refused_server_as_not_running() {
            let config = crate::config::LspServerConfig::rust_analyzer();
            let translator =
                Translator::new().with_router(ToolRouter::from_configs([&config]).unwrap());
            translator.record_refusals(&[ServerSpawnFailure {
                server_id: config.id(),
                language_id: config.language_id.clone(),
                command: config.command.server_command().clone(),
                reason: StartupFailure::RefusedUntrustedWorkspace(
                    crate::error::UntrustedRefusal::NotAllowed { builtin: None },
                ),
            }]);

            let result = translator
                .restart_servers(RestartTarget::All)
                .await
                .unwrap();

            let outcome = only_outcome(&result);
            assert_matches!(
                outcome,
                RestartOutcome::NotRunning { message } if message.contains("--allow-server rust"),
                "{result:?}"
            );
        }

        #[tokio::test]
        async fn test_restart_of_a_settled_server_while_startup_settles_reports_initializing() {
            let dir = TempDir::new().unwrap();
            let log = dir.path().join("server.log");
            let script = write_protocol_server_script(dir.path(), &log, None);
            let fx = fixture(dir, &script, true).await;
            let startup = fx.translator.begin_startup();

            let during = fx
                .translator
                .restart_servers(server_ids(&["rust"]))
                .await
                .unwrap();
            assert_eq!(*only_outcome(&during), RestartOutcome::Initializing);

            drop(startup);
            let after = fx
                .translator
                .restart_servers(server_ids(&["rust"]))
                .await
                .unwrap();
            assert_matches!(
                only_outcome(&after),
                RestartOutcome::Restarted { .. },
                "{after:?}"
            );
        }

        #[tokio::test]
        async fn test_restart_permit_classifies_in_order() {
            let id = ServerId::from_static("rust");
            let translator = Translator::new();
            assert_matches!(
                translator.restart_permit(&id),
                Err(RestartOutcome::NotRunning { .. })
            );

            translator.set_expected_servers(HashSet::from([id.clone()]));
            assert_matches!(
                translator.restart_permit(&id),
                Err(RestartOutcome::Initializing)
            );

            translator.clear_expected_servers();
            translator.record_startup_failures(&[ServerSpawnFailure {
                server_id: id.clone(),
                language_id: crate::config::LanguageId::from_static("rust"),
                command: ServerCommand::from_static("missing"),
                reason: StartupFailure::InitTaskPanicked,
            }]);
            assert_matches!(
                translator.restart_permit(&id),
                Err(RestartOutcome::NotRunning { .. })
            );

            let config = crate::config::LspServerConfig::rust_analyzer();
            let running = Translator::new();
            running
                .register_server_complete(crate::lsp::fake_lsp_server_with_config(config.clone()));
            let rid = config.id();
            assert_matches!(
                running.restart_permit(&rid),
                Err(RestartOutcome::Initializing)
            );

            lock_std(&running.phase).init_panicked();
            assert_matches!(
                running.restart_permit(&rid),
                Err(RestartOutcome::NotRunning { .. })
            );

            running.begin_shutdown();
            assert_matches!(
                running.restart_permit(&rid),
                Err(RestartOutcome::Failed {
                    reason: RestartFailure::ShuttingDown
                })
            );
        }

        #[test]
        fn test_dropping_the_startup_guard_clears_the_flag() {
            let translator = Translator::new();
            let startup = translator.begin_startup();
            assert_eq!(*lock_std(&translator.phase), Phase::Settling);
            drop(startup);
            assert_eq!(*lock_std(&translator.phase), Phase::Settled);
        }

        #[tokio::test]
        async fn test_restart_of_a_startup_failed_server_while_startup_settles_reports_not_running()
        {
            let id = ServerId::from_static("rust");
            let translator = Translator::new().with_router(ToolRouter::catch_all([(
                id.clone(),
                LanguageId::from_static("rust"),
            )]));
            translator.record_startup_failures(&[ServerSpawnFailure {
                server_id: id,
                language_id: LanguageId::from_static("rust"),
                command: ServerCommand::from_static("missing"),
                reason: StartupFailure::InitTaskPanicked,
            }]);
            let _startup = translator.begin_startup();

            let result = translator
                .restart_servers(server_ids(&["rust"]))
                .await
                .unwrap();

            assert_matches!(
                only_outcome(&result),
                RestartOutcome::NotRunning { .. },
                "{result:?}"
            );
        }

        #[tokio::test]
        async fn test_restart_of_a_still_expected_server_reports_initializing() {
            let id = ServerId::from_static("rust");
            let translator = Translator::new().with_router(ToolRouter::catch_all([(
                id.clone(),
                LanguageId::from_static("rust"),
            )]));
            translator.set_expected_servers(HashSet::from([id]));

            let result = translator
                .restart_servers(server_ids(&["rust"]))
                .await
                .unwrap();

            assert_eq!(*only_outcome(&result), RestartOutcome::Initializing);
        }

        #[tokio::test]
        async fn test_restart_before_the_wiring_is_installed_reports_initializing() {
            let dir = TempDir::new().unwrap();
            let log = dir.path().join("server.log");
            let script = write_protocol_server_script(dir.path(), &log, None);
            let fx = fixture(dir, &script, false).await;

            let result = fx
                .translator
                .restart_servers(RestartTarget::All)
                .await
                .unwrap();

            assert_eq!(*only_outcome(&result), RestartOutcome::Initializing);
            assert_eq!(read_log(&log).matches("started").count(), 1);
            assert!(fx.registered());
        }

        #[tokio::test]
        async fn test_restart_rejects_unknown_ids_and_restarts_nothing() {
            let (fx, log) = protocol_fixture(None).await;

            let err = fx
                .translator
                .restart_servers(server_ids(&["rust", "nope"]))
                .await
                .unwrap_err();

            let Error::UnknownServers {
                unknown,
                configured,
            } = err
            else {
                panic!("expected UnknownServers, got {err:?}");
            };
            assert_eq!(unknown, [ServerId::from_static("nope")]);
            assert_eq!(configured, [ServerId::from_static("rust")]);
            assert_eq!(read_log(&log).matches("started").count(), 1);
        }

        #[tokio::test]
        async fn test_restart_is_throttled_until_the_cooldown_elapses() {
            let (fx, _log) = protocol_fixture(None).await;
            let first = fx
                .translator
                .restart_servers(RestartTarget::All)
                .await
                .unwrap();
            assert_matches!(only_outcome(&first), RestartOutcome::Restarted { .. });

            let second = fx
                .translator
                .restart_servers(RestartTarget::All)
                .await
                .unwrap();
            let RestartOutcome::Throttled { retry_in_ms } = only_outcome(&second) else {
                panic!("expected Throttled, got {second:?}");
            };
            assert!((1..=5000).contains(retry_in_ms));

            fx.clock.advance(RESTART_COOLDOWN + Duration::from_secs(1));
            let third = fx
                .translator
                .restart_servers(RestartTarget::All)
                .await
                .unwrap();
            assert_matches!(only_outcome(&third), RestartOutcome::Restarted { .. });
        }

        #[tokio::test]
        async fn test_concurrent_restarts_of_one_server_coalesce() {
            let (fx, log) = protocol_fixture(None).await;

            let (a, b) = tokio::join!(
                fx.translator.restart_servers(RestartTarget::All),
                fx.translator.restart_servers(RestartTarget::All),
            );

            let outcomes = [a.unwrap(), b.unwrap()];
            let coalesced = outcomes
                .iter()
                .filter(|result| {
                    matches!(
                        only_outcome(result),
                        RestartOutcome::Restarted {
                            coalesced: true,
                            ..
                        }
                    )
                })
                .count();
            assert_eq!(coalesced, 1, "{outcomes:?}");
            assert_eq!(read_log(&log).matches("started").count(), 2);
        }

        #[tokio::test]
        async fn test_restart_clears_degradation_and_keeps_the_early_diagnostics_push() {
            let dir = TempDir::new().unwrap();
            let file = dunce::canonicalize(dir.path()).unwrap().join("main.rs");
            fs::write(&file, "fn main() {}").unwrap();
            let uri = crate::bridge::try_path_to_uri(&file).unwrap();
            let log = dir.path().join("server.log");
            let script = write_protocol_server_script(dir.path(), &log, Some(uri.as_ref()));
            let fx = fixture(dir, &script, true).await;
            {
                let mut cache = fx.cache.lock().await;
                cache.mark_push_degraded(&fx.id);
                cache.clear_server_diagnostics(&fx.id);
            }

            let result = fx
                .translator
                .restart_servers(RestartTarget::All)
                .await
                .unwrap();

            assert_matches!(
                only_outcome(&result),
                RestartOutcome::Restarted {
                    push_notifications_degraded: false,
                    ..
                },
                "{result:?}"
            );
            tokio::time::timeout(Duration::from_secs(5), async {
                while !fx.cache.lock().await.has_diagnostics(&uri) {
                    tokio::time::sleep(Duration::from_millis(20)).await;
                }
            })
            .await
            .expect("the diagnostics pushed during the new handshake must reach the cache");
        }

        #[tokio::test]
        async fn test_restart_fails_requests_in_flight_with_server_restarted() {
            let (fx, _log) = protocol_fixture(None).await;
            let client = lock_std(&fx.translator.servers).client(&fx.id).unwrap();
            let in_flight = tokio::spawn(async move {
                client
                    .request::<_, serde_json::Value>(
                        "textDocument/hover",
                        serde_json::json!({}),
                        Duration::from_secs(30),
                    )
                    .await
            });
            tokio::time::sleep(Duration::from_millis(300)).await;

            fx.translator
                .restart_servers(RestartTarget::All)
                .await
                .unwrap();

            let failed = tokio::time::timeout(Duration::from_secs(5), in_flight)
                .await
                .expect("the in-flight request must fail promptly")
                .unwrap();
            assert_matches!(&failed, Err(Error::ServerRestarted { server_id }) if *server_id == fx.id, "{failed:?}");
        }

        #[tokio::test]
        async fn test_restart_during_shutdown_starts_nothing() {
            let (fx, log) = protocol_fixture(None).await;
            fx.translator.begin_shutdown();

            let result = fx
                .translator
                .restart_servers(RestartTarget::All)
                .await
                .unwrap();

            assert_eq!(
                *only_outcome(&result),
                RestartOutcome::Failed {
                    reason: RestartFailure::ShuttingDown
                }
            );
            assert_eq!(read_log(&log).matches("started").count(), 1);
            assert!(fx.registered());
        }

        #[tokio::test]
        async fn test_shutdown_beginning_while_the_old_server_stops_prevents_the_respawn() {
            let dir = TempDir::new().unwrap();
            let script = write_responder_script(dir.path(), 600);
            let fx = fixture(dir, &script, true).await;

            let translator = Arc::clone(&fx.translator);
            let task =
                tokio::spawn(async move { translator.restart_servers(RestartTarget::All).await });
            fx.wait_until_deregistered().await;
            fx.translator.begin_shutdown();

            let result = task.await.unwrap().unwrap();

            assert_eq!(
                *only_outcome(&result),
                RestartOutcome::Failed {
                    reason: RestartFailure::ShuttingDown
                }
            );
            assert!(fx.registered() && !fx.expected() && fx.is_dead());
        }

        #[tokio::test]
        async fn test_failed_replacement_leaves_the_server_registered_and_reports_spawn_failed() {
            let dir = TempDir::new().unwrap();
            let log = dir.path().join("server.log");
            let script = write_protocol_server_script(dir.path(), &log, None);
            let fx = fixture(dir, &script, true).await;
            let mut broken = stub_server_config("rust", &script);
            broken.server_config_mut().command =
                ServerCommand::from_static("mcpls-test-missing-server").into();
            lock_std(&fx.translator.servers)
                .server_mut(&fx.id)
                .unwrap()
                .set_init_config(broken);

            let result = fx
                .translator
                .restart_servers(RestartTarget::All)
                .await
                .unwrap();

            assert_matches!(
                only_outcome(&result),
                RestartOutcome::Failed {
                    reason: RestartFailure::SpawnFailed { .. }
                },
                "{result:?}"
            );
            assert!(fx.registered() && !fx.expected() && fx.is_dead());
        }

        #[tokio::test]
        async fn test_take_leaves_the_server_expected_in_the_same_step_and_restore_runs_it_again() {
            let config = crate::config::LspServerConfig::rust_analyzer();
            let id = config.id();
            let translator = Translator::new();
            translator.register_server_complete(crate::lsp::fake_lsp_server_with_config(config));

            let held = Deregistered::take(&translator, &id).unwrap();
            {
                let servers = lock_std(&translator.servers);
                assert!(
                    servers.is_expected(&id),
                    "the id must never be in neither state"
                );
                assert!(servers.server(&id).is_none());
                drop(servers);
            }
            drop(held);

            let servers = lock_std(&translator.servers);
            assert!(!servers.is_expected(&id));
            assert!(servers.server(&id).is_some());
            drop(servers);
        }

        /// Six servers, two overlapping `All` requests: ids queued behind the
        /// concurrency limit must snapshot their generation up front, so each
        /// server is restarted exactly once and the other request coalesces.
        #[tokio::test]
        async fn test_overlapping_requests_over_more_than_four_servers_restart_each_once() {
            let dir = TempDir::new().unwrap();
            let cache = Arc::new(Mutex::new(NotificationCache::new()));
            let mut translator = Translator::new().with_notification_cache(Arc::clone(&cache));
            translator.set_workspace_roots(
                WorkspaceRoots::from_paths(&[dir.path().to_path_buf()]).unwrap(),
            );
            let wiring = PumpWiring::new(
                PumpShared {
                    roles: crate::runtime::pump::DiagnosticsRoles::default(),
                    notification_cache: Arc::clone(&cache),
                    subs: SubscriptionRegistry::new(),
                    workspace_roots: translator.workspace_roots.clone(),
                },
                CancellationToken::new(),
            );
            let mut logs = Vec::new();
            for index in 0..6 {
                let name = format!("s{index}");
                let log = dir.path().join(format!("{name}.log"));
                let script_dir = dir.path().join(&name);
                fs::create_dir(&script_dir).unwrap();
                let script = write_protocol_server_script(&script_dir, &log, None);
                let crate::lsp::SpawnedServer { server, lanes } =
                    crate::lsp::LspServer::spawn(stub_server_config(&name, &script))
                        .await
                        .unwrap();
                let receivers = NotificationReceivers::new(lanes, None);
                translator.register_server_complete(server);
                let id = ServerId::new(name.as_str()).unwrap();
                let pump = wiring.spawn_pump(id.clone(), receivers, DiagnosticsRole::Secondary);
                translator.set_notification_task(&id, pump);
                logs.push(log);
            }
            translator.install_wiring(Arc::new(wiring));

            let (a, b) = tokio::join!(
                translator.restart_servers(RestartTarget::All),
                translator.restart_servers(RestartTarget::All),
            );
            let (a, b) = (a.unwrap(), b.unwrap());

            assert_eq!((a.servers.len(), b.servers.len()), (6, 6));
            for (first, second) in a.servers.iter().zip(&b.servers) {
                let coalesced = |entry: &ServerRestartEntry| match entry.outcome {
                    RestartOutcome::Restarted { coalesced, .. } => coalesced,
                    ref other => panic!("{}: unexpected outcome {other:?}", entry.server_id),
                };
                assert_ne!(
                    coalesced(first),
                    coalesced(second),
                    "{}: exactly one request restarts it",
                    first.server_id
                );
            }
            for log in logs {
                assert_eq!(read_log(&log).matches("started").count(), 2, "{log:?}");
            }
        }

        #[tokio::test]
        async fn test_an_automatic_respawn_does_not_count_towards_coalescing() {
            let dir = TempDir::new().unwrap();
            let script = write_crash_after_init_script(dir.path());
            let fx = fixture(dir, &script, true).await;
            tokio::time::timeout(Duration::from_secs(3), async {
                while !fx.is_dead() {
                    tokio::time::sleep(Duration::from_millis(20)).await;
                }
            })
            .await
            .expect("the seed server crashes after initialize");
            let before = fx.translator.restart_generation(&fx.id);
            fx.translator.respawn_if_dead(&fx.id).await.unwrap();
            assert_eq!(fx.translator.restart_generation(&fx.id), before);

            let result = fx
                .translator
                .restart_servers(RestartTarget::All)
                .await
                .unwrap();

            assert_matches!(
                only_outcome(&result),
                RestartOutcome::Restarted {
                    coalesced: false,
                    ..
                },
                "{result:?}"
            );
        }

        #[tokio::test]
        async fn test_an_unregistered_server_is_never_throttled() {
            let id = ServerId::from_static("rust");
            let clock = Arc::new(FakeClock::new());
            let translator = Translator::new().with_clock(clock.clone());
            translator.set_expected_servers(HashSet::from([id.clone()]));
            lock_std(&translator.servers)
                .get_mut(&id)
                .unwrap()
                .restart
                .last_attempt = Some(clock.now());
            let starting = translator
                .restart_servers(server_ids(&["rust"]))
                .await
                .unwrap();
            assert_eq!(*only_outcome(&starting), RestartOutcome::Initializing);

            translator.clear_expected_servers();
            translator.record_startup_failures(&[ServerSpawnFailure {
                server_id: id,
                language_id: LanguageId::from_static("rust"),
                command: ServerCommand::from_static("missing"),
                reason: StartupFailure::InitTaskPanicked,
            }]);
            let failed = translator
                .restart_servers(server_ids(&["rust"]))
                .await
                .unwrap();
            assert_matches!(
                only_outcome(&failed),
                RestartOutcome::NotRunning { .. },
                "{failed:?}"
            );
        }

        #[tokio::test]
        async fn test_restart_after_an_init_panic_without_wiring_reports_not_running() {
            let dir = TempDir::new().unwrap();
            let log = dir.path().join("server.log");
            let script = write_protocol_server_script(dir.path(), &log, None);
            let fx = fixture(dir, &script, false).await;
            fx.translator.settle_after_init_panic(&[]).await;

            let result = fx
                .translator
                .restart_servers(RestartTarget::All)
                .await
                .unwrap();

            assert_matches!(
                only_outcome(&result),
                RestartOutcome::NotRunning { .. },
                "{result:?}"
            );
        }

        #[tokio::test]
        async fn test_restart_after_an_init_panic_with_wiring_installed_reports_not_running() {
            let dir = TempDir::new().unwrap();
            let log = dir.path().join("server.log");
            let script = write_protocol_server_script(dir.path(), &log, None);
            let fx = fixture(dir, &script, true).await;
            fx.translator.settle_after_init_panic(&[]).await;

            let result = fx
                .translator
                .restart_servers(RestartTarget::All)
                .await
                .unwrap();

            assert_matches!(
                only_outcome(&result),
                RestartOutcome::NotRunning { .. },
                "{result:?}"
            );
        }

        #[tokio::test]
        async fn test_a_failed_restart_invalidates_the_stopped_servers_cached_diagnostics() {
            let dir = TempDir::new().unwrap();
            let file = dunce::canonicalize(dir.path()).unwrap().join("main.rs");
            fs::write(&file, "fn main() {}").unwrap();
            let uri = crate::bridge::try_path_to_uri(&file).unwrap();
            let log = dir.path().join("server.log");
            let script = write_protocol_server_script(dir.path(), &log, Some(uri.as_ref()));
            let fx = fixture(dir, &script, true).await;
            tokio::time::timeout(Duration::from_secs(5), async {
                while !fx.cache.lock().await.has_diagnostics(&uri) {
                    tokio::time::sleep(Duration::from_millis(20)).await;
                }
            })
            .await
            .expect("the seed server's diagnostics reach the cache");
            let mut broken = stub_server_config("rust", &script);
            broken.server_config_mut().command =
                ServerCommand::from_static("mcpls-test-missing-server").into();
            lock_std(&fx.translator.servers)
                .server_mut(&fx.id)
                .unwrap()
                .set_init_config(broken);

            let result = fx
                .translator
                .restart_servers(RestartTarget::All)
                .await
                .unwrap();

            assert_matches!(only_outcome(&result), RestartOutcome::Failed { .. });
            let (stale, degraded) = {
                let cache = fx.cache.lock().await;
                (cache.has_diagnostics(&uri), cache.is_push_degraded(&fx.id))
            };
            assert!(!stale, "stale diagnostics must go");
            assert!(degraded);
            assert!(
                lock_std(&fx.translator.servers)
                    .get(&fx.id)
                    .is_none_or(|slot| slot.notification_task.is_none()),
                "the dead server's pump handle must be dropped"
            );
        }

        #[tokio::test]
        async fn test_cooldown_counts_from_the_completion_of_a_slow_restart() {
            let dir = TempDir::new().unwrap();
            let script = write_responder_script(dir.path(), 600);
            let fx = fixture(dir, &script, true).await;
            let translator = Arc::clone(&fx.translator);
            let restart =
                tokio::spawn(async move { translator.restart_servers(RestartTarget::All).await });
            fx.wait_until_deregistered().await;
            fx.clock.advance(Duration::from_secs(30));

            restart.await.unwrap().unwrap();
            let again = fx
                .translator
                .restart_servers(RestartTarget::All)
                .await
                .unwrap();

            assert_matches!(
                only_outcome(&again),
                RestartOutcome::Throttled { .. },
                "{again:?}"
            );
        }

        #[tokio::test]
        async fn test_a_request_queued_behind_a_discarded_restart_is_not_reported_coalesced() {
            let dir = TempDir::new().unwrap();
            let script = write_responder_script(dir.path(), 600);
            let fx = fixture(dir, &script, true).await;
            let (first_tx, second_tx) = (Arc::clone(&fx.translator), Arc::clone(&fx.translator));
            let first =
                tokio::spawn(async move { first_tx.restart_servers(RestartTarget::All).await });
            fx.wait_until_deregistered().await;
            let second =
                tokio::spawn(async move { second_tx.restart_servers(RestartTarget::All).await });
            tokio::time::sleep(Duration::from_millis(100)).await;
            fx.translator.begin_shutdown();

            for result in [
                first.await.unwrap().unwrap(),
                second.await.unwrap().unwrap(),
            ] {
                assert_eq!(
                    *only_outcome(&result),
                    RestartOutcome::Failed {
                        reason: RestartFailure::ShuttingDown
                    }
                );
            }
        }

        /// A server that answered `shutdown` but needs longer than the
        /// handshake budget to exit is not killed at the budget.
        #[tokio::test]
        async fn test_a_healthy_server_slow_to_exit_is_not_killed_at_the_handshake_budget() {
            let dir = TempDir::new().unwrap();
            let log = dir.path().join("server.log");
            let delay = u32::try_from(RESTART_HANDSHAKE_BUDGET.as_secs()).unwrap() + 1;
            let script = write_slow_exit_server_script(dir.path(), &log, delay);
            let fx = fixture(dir, &script, true).await;

            let result = fx
                .translator
                .restart_servers(RestartTarget::All)
                .await
                .unwrap();

            assert_matches!(
                only_outcome(&result),
                RestartOutcome::Restarted { .. },
                "{result:?}"
            );
            assert!(
                read_log(&log).contains("exiting"),
                "the old server must have exited by itself, not been killed"
            );
        }

        #[tokio::test]
        async fn test_restart_recovers_a_crashed_server() {
            let dir = TempDir::new().unwrap();
            let script = write_crash_after_init_script(dir.path());
            let fx = fixture(dir, &script, true).await;
            tokio::time::timeout(Duration::from_secs(3), async {
                while !fx.is_dead() {
                    tokio::time::sleep(Duration::from_millis(20)).await;
                }
            })
            .await
            .expect("the seed server crashes after initialize");

            let result = fx
                .translator
                .restart_servers(RestartTarget::All)
                .await
                .unwrap();

            assert_matches!(
                only_outcome(&result),
                RestartOutcome::Restarted { .. },
                "{result:?}"
            );
        }

        /// #667: right after a restart of a server that reported readiness
        /// before, the result says `loading` and a gated call holds until the
        /// replacement's own signal arrives instead of reading an empty index.
        #[tokio::test]
        async fn test_restart_of_a_signalling_server_gates_until_its_signal() {
            let (fx, _log) = protocol_fixture(None).await;
            fx.cache.lock().await.observe_indexing_signal(
                &fx.id,
                "experimental/serverStatus",
                Some(&serde_json::json!({"quiescent": true})),
            );

            let result = fx
                .translator
                .restart_servers(RestartTarget::All)
                .await
                .unwrap();
            assert_matches!(
                only_outcome(&result),
                RestartOutcome::Restarted {
                    indexing_state: IndexingState::Loading,
                    ..
                },
                "{result:?}"
            );

            let translator = Arc::clone(&fx.translator);
            let id = fx.id.clone();
            let gated = tokio::spawn(async move { translator.wait_for_indexing_ready(&id).await });
            tokio::time::sleep(Duration::from_millis(150)).await;
            assert!(!gated.is_finished(), "the gate must hold before the signal");

            fx.cache.lock().await.observe_indexing_signal(
                &fx.id,
                "experimental/serverStatus",
                Some(&serde_json::json!({"quiescent": true})),
            );
            tokio::time::timeout(Duration::from_secs(5), gated)
                .await
                .expect("the gate releases once the replacement is ready")
                .unwrap()
                .unwrap();
        }

        /// #667: a server that never reported a signal is restarted without a
        /// gate (no new fixed delay).
        #[tokio::test]
        async fn test_restart_of_a_silent_server_reports_unknown() {
            let (fx, _log) = protocol_fixture(None).await;

            let result = fx
                .translator
                .restart_servers(RestartTarget::All)
                .await
                .unwrap();

            assert_matches!(
                only_outcome(&result),
                RestartOutcome::Restarted {
                    indexing_state: IndexingState::Unknown,
                    ..
                },
                "{result:?}"
            );
            fx.translator.wait_for_indexing_ready(&fx.id).await.unwrap();
        }
    }
}

#[cfg(test)]
mod server_text_tests {
    use super::*;

    #[test]
    fn test_restart_messages_are_redacted() {
        let secret = "SuperSecretValue123";
        let set = Redactions::new([("API_TOKEN".to_owned(), secret.to_owned())]);
        let mut result = RestartServerResult {
            servers: vec![
                ServerRestartEntry {
                    server_id: ServerId::from_static("a"),
                    outcome: RestartOutcome::Failed {
                        reason: RestartFailure::SpawnFailed {
                            message: format!("spawn {secret}"),
                        },
                    },
                },
                ServerRestartEntry {
                    server_id: ServerId::from_static("b"),
                    outcome: RestartOutcome::Failed {
                        reason: RestartFailure::InitializeFailed {
                            message: format!("init {secret}"),
                        },
                    },
                },
                ServerRestartEntry {
                    server_id: ServerId::from_static("c"),
                    outcome: RestartOutcome::NotRunning {
                        message: format!("gone {secret}"),
                    },
                },
            ],
        };

        result.redact_server_text(&set);

        let json = serde_json::to_string(&result).unwrap();
        assert!(!json.contains(secret), "{json}");
        assert_eq!(json.matches("[redacted:API_TOKEN]").count(), 3, "{json}");
    }
}