zingolib 7.0.0

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

#![forbid(unsafe_code)]

use super::error::LightClientError;
use super::{LightClient, MixnetPriceFetch};

/// The price run as a speed-priority operation: it races the price census
/// through one Exit Node and settles on the first quote, whichever operator
/// answers.
#[cfg(feature = "nym")]
pub(crate) struct PriceRun {
    /// The pools this run takes its transport from and returns it to.
    pools: std::sync::Arc<crate::mixnet::pools::Pools>,
}

#[cfg(feature = "nym")]
impl crate::mixnet::speed::SpeedPrioritized for PriceRun {
    type Target = zingo_price::PriceSource;
    type Outcome = (
        zingo_price::PriceSource,
        Result<zingo_price::Price, zingo_price::PriceError>,
    );

    fn targets(&self) -> Vec<Self::Target> {
        zingo_price::RACED_SOURCES.to_vec()
    }

    async fn probe(
        &self,
        dial: zingo_netutils::conduit::ConduitDial,
        target: Self::Target,
    ) -> Self::Outcome {
        let outcome = zingo_price::get_source_price(
            target,
            &dial,
            target.url(),
            zingo_price::REQUEST_TIMEOUT,
            zingo_price::CONNECT_TIMEOUT,
        )
        .await;
        (target, outcome)
    }

    fn settled(&self, outcomes: &[Self::Outcome]) -> bool {
        outcomes.iter().any(|(_, outcome)| outcome.is_ok())
    }

    fn answered(&self, outcomes: &[Self::Outcome]) -> bool {
        outcomes.iter().any(|(_, outcome)| outcome.is_ok())
    }

    fn acquire(
        &self,
    ) -> impl std::future::Future<
        Output = Result<
            (crate::mixnet::speed::Member, std::net::SocketAddr),
            crate::mixnet::acquire::TransportError,
        >,
    > + Send {
        // Boot's price fetch runs over the conduit proved for its role, so
        // the first quote costs no birth. A later run finds the conduit
        // spent and births its own client, which keeps priced traffic off
        // the wallet-correlated streams on the standing client.
        let pools = self.pools.clone();
        async move {
            let acquirer = pools
                .acquirer()
                .ok_or(crate::mixnet::acquire::TransportError::NoAcquirer)?;
            let birth = pools
                .conduit_for(crate::mixnet::quartet::Role::PriceFetch, acquirer.as_ref())
                .await?;
            let member = crate::mixnet::speed::Member::new(birth.transport, birth.lease);
            let addr = member
                .addr()
                .ok_or(crate::mixnet::acquire::TransportError::DiedBeforeUse)?;
            Ok((member, addr))
        }
    }

    fn dispose(&self, spent: crate::mixnet::speed::Member) {
        // The quote is a completed round trip, so the exit's proof renews;
        // the client still turns off behind the run, because consecutive
        // fetches must not share a client.
        self.pools.remember(
            spent.node().clone(),
            crate::mixnet::pools::exit_pool::ExitNodeHealthVerdict::EpochProven,
        );
        tokio::spawn(async move {
            spent.retire().await;
        });
    }

    fn abandon(&self, dead: crate::mixnet::speed::Member) {
        self.pools.remember(
            dead.node().clone(),
            crate::mixnet::pools::exit_pool::ExitNodeHealthVerdict::Failed,
        );
        tokio::spawn(async move {
            dead.retire().await;
        });
    }

    fn narrate(&self, phase: crate::mixnet::speed::SpeedProgress) {
        tracing::info!("price run: {phase:?}");
    }
}

/// Replaces the slot's contents under its lock, yielding what it held.
fn swap_slot(
    slot: &std::sync::Arc<std::sync::Mutex<crate::mixnet::MixnetSlot>>,
    next: crate::mixnet::MixnetSlot,
) -> crate::mixnet::MixnetSlot {
    std::mem::replace(&mut *slot.lock().expect("mixnet slot mutex"), next)
}

/// Publishes the slot's settled state into `status`, read under one lock.
fn publish_slot(
    slot: &std::sync::Arc<std::sync::Mutex<crate::mixnet::MixnetSlot>>,
    status: &crate::mixnet::driver::StatusPublisher,
) {
    let guarded = slot.lock().expect("mixnet slot mutex");
    // The evidenced constructor keeps only what the mode offers, so the
    // condemned dip publishes no stale address and a latched death crosses
    // whole for subscribers to render its typed story.
    status.send_replace(crate::mixnet::MixnetStatus::evidenced(
        guarded.mode(),
        guarded.socks5_addr(),
        guarded.exits(),
        guarded.death_report(),
    ));
}

/// Forwards a settled birth's later transitions from its birth channel into
/// the session channel, ending when the client's driver drops its publisher.
fn forward_client_transitions(
    birth_channel: &crate::mixnet::driver::StatusPublisher,
    session: &crate::mixnet::driver::StatusPublisher,
) {
    let mut future_transitions = birth_channel.subscribe();
    let session = std::sync::Arc::clone(session);
    tokio::spawn(async move {
        while future_transitions.changed().await.is_ok() {
            let status = future_transitions.borrow_and_update().clone();
            session.send_replace(status);
        }
    });
}

/// Installs the failover's replacement only while the slot still holds the
/// condemned client whose enable it continues, refusing when consent
/// changed shape mid-birth.
// The Err carries the refused client back to its caller for teardown, one
// move that never rides an error chain, so its size costs nothing.
#[allow(clippy::result_large_err)]
fn install_failover_client(
    slot: &std::sync::Arc<std::sync::Mutex<crate::mixnet::MixnetSlot>>,
    client: crate::mixnet::StandingClient,
) -> Result<crate::mixnet::MixnetSlot, crate::mixnet::StandingClient> {
    let mut guarded = slot.lock().expect("mixnet slot mutex");
    match &*guarded {
        crate::mixnet::MixnetSlot::Attached(current) if current.is_condemned() => Ok(
            std::mem::replace(&mut *guarded, crate::mixnet::MixnetSlot::Attached(client)),
        ),
        _ => Err(client),
    }
}

/// Installs a rotation's replacement only while the slot still holds the
/// healthy client the rotation set out to replace, refusing when a failover
/// or a teardown reached the slot first.
// The exact complement of `install_failover_client`: that path requires a
// condemned incumbent and this one requires an uncondemned one, so a
// rotation and a failover racing the same slot cannot both install.
#[allow(clippy::result_large_err)]
fn install_rotated_client(
    slot: &std::sync::Arc<std::sync::Mutex<crate::mixnet::MixnetSlot>>,
    client: crate::mixnet::StandingClient,
) -> Result<crate::mixnet::MixnetSlot, crate::mixnet::StandingClient> {
    let mut guarded = slot.lock().expect("mixnet slot mutex");
    match &*guarded {
        crate::mixnet::MixnetSlot::Attached(current) if !current.is_condemned() => Ok(
            std::mem::replace(&mut *guarded, crate::mixnet::MixnetSlot::Attached(client)),
        ),
        _ => Err(client),
    }
}

/// Builds the Standing Client a birth installs, its proof deadline set to
/// the earliest feasible ProofAcquisition moment: one epoch from a probed
/// birth's own answer, or the stale observation's original expiry for a
/// trusting birth.
fn standing_client_from_birth(
    birth: crate::mixnet::pools::ProvenBirth,
) -> crate::mixnet::StandingClient {
    use crate::mixnet::pools::Proof;

    let proof = birth.proof;
    let client = crate::mixnet::StandingClient::new(
        birth.transport,
        Some(birth.lease),
        matches!(proof, Proof::Earned { .. }),
    );
    // An inherited proof carries its own deadline, so the watchdog fires
    // when the observation the birth trusted ages out rather than an epoch
    // from now.
    if let Proof::Inherited { proven_until } = proof {
        client.set_proof_deadline(proven_until);
    }
    client
}

/// One ProofAcquisition over the Standing Client: adjudicate `evidence`
/// about its exit, promoting on an answer and, on silence, convicting the
/// exit and running the two-layer failover — Bootstrapping while a
/// replacement births, Died latched when every birth exhausts.
async fn adjudicate_standing_proof(
    slot: std::sync::Arc<std::sync::Mutex<crate::mixnet::MixnetSlot>>,
    pools: std::sync::Arc<crate::mixnet::pools::Pools>,
    status: crate::mixnet::driver::StatusPublisher,
    evidence: zingo_netutils::sentinel::ExitEvidence,
) {
    // Read the client's facts under a brief lock; never hold it across an
    // await.
    let (node, convicted) = {
        let guarded = slot.lock().expect("mixnet slot mutex");
        let crate::mixnet::MixnetSlot::Attached(client) = &*guarded else {
            return;
        };
        if evidence.proves_the_exit() {
            client.note_round_trip();
            let refreshed = client.exit_node().cloned();
            drop(guarded);
            if let Some(node) = refreshed {
                pools.remember(
                    node,
                    crate::mixnet::pools::exit_pool::ExitNodeHealthVerdict::EpochProven,
                );
            }
            publish_slot(&slot, &status);
            return;
        }
        (client.exit_node().cloned(), client.condemn())
    };
    if !convicted {
        // Another adjudication already owns the failover.
        return;
    }
    if let Some(node) = node {
        pools.remember(
            node,
            crate::mixnet::pools::exit_pool::ExitNodeHealthVerdict::Failed,
        );
    }
    // The ruled Bootstrapping dip: the session cannot truthfully claim
    // readiness while the replacement births.
    publish_slot(&slot, &status);
    let Some(acquirer) = pools.acquirer() else {
        // An attached session cannot rebirth locally; the loss surfaces to
        // the host as Died, per the two-layer ruling's exhaustion arm.
        if let crate::mixnet::MixnetSlot::Attached(client) =
            &*slot.lock().expect("mixnet slot mutex")
        {
            client.forsake(zingo_net_diag::NetOpFailure::message(
                zingo_net_diag::NetOpStage::RouteResolution,
                "the attached transport",
                "the exit failed under an attached session, which cannot \
                 rebirth its transport locally",
            ));
        }
        publish_slot(&slot, &status);
        return;
    };
    match pools.acquire_proven(acquirer.as_ref()).await {
        Ok(birth) => {
            let birth_channel = std::sync::Arc::clone(&birth.lifecycle);
            let client = standing_client_from_birth(birth);
            match install_failover_client(&slot, client) {
                Ok(replaced) => {
                    // The replacement's candidate churn stayed on its birth
                    // channel; its settled transitions reach the session's
                    // subscribers from here on.
                    forward_client_transitions(&birth_channel, &status);
                    publish_slot(&slot, &status);
                    if let crate::mixnet::MixnetSlot::Attached(old) = replaced {
                        // The replacement is installed, so the session is
                        // whole; the outgoing client keeps its transport
                        // open only for work already dialed through it.
                        old.retire().await;
                    }
                }
                Err(refused) => {
                    // Consent changed shape mid-birth: the enable this
                    // failover continues is gone, so the replacement dies
                    // unused and its lease recycles.
                    refused.stop().await;
                }
            }
        }
        Err(exhausted) => {
            log::warn!("the standing client's failover exhausted: {exhausted}");
            if let crate::mixnet::MixnetSlot::Attached(client) =
                &*slot.lock().expect("mixnet slot mutex")
            {
                client.forsake(zingo_net_diag::NetOpFailure::from_error(
                    zingo_net_diag::NetOpStage::RouteResolution,
                    "the session's exit census",
                    &exhausted,
                ));
            }
            publish_slot(&slot, &status);
        }
    }
}

/// Runs one ProofAcquisition end to end: the arbiter Sentinel exchange
/// dialed into the Standing Client's tunnel, then the adjudication.
async fn run_proof_acquisition(
    slot: std::sync::Arc<std::sync::Mutex<crate::mixnet::MixnetSlot>>,
    pools: std::sync::Arc<crate::mixnet::pools::Pools>,
    status: crate::mixnet::driver::StatusPublisher,
) {
    let socks5 = {
        let guarded = slot.lock().expect("mixnet slot mutex");
        match &*guarded {
            crate::mixnet::MixnetSlot::Attached(client) if !client.is_condemned() => {
                match client.proxy().socks5_addr() {
                    Some(addr) => addr,
                    None => return,
                }
            }
            _ => return,
        }
    };
    let evidence =
        zingo_netutils::sentinel::probe_sentinel(socks5, zingo_netutils::time::SENTINEL_BUDGET)
            .await;
    adjudicate_standing_proof(slot, pools, status, evidence).await;
}

/// The expiry watchdog: sleeps until the Standing Client's proof deadline,
/// fires a new ProofAcquisition at that earliest feasible moment, follows
/// replacement clients in the slot until the slot empties, and parks on the
/// status channel whenever an acquisition leaves a lapsed deadline
/// unadvanced.
async fn standing_proof_watchdog(
    slot: std::sync::Arc<std::sync::Mutex<crate::mixnet::MixnetSlot>>,
    pools: std::sync::Arc<crate::mixnet::pools::Pools>,
    status: crate::mixnet::driver::StatusPublisher,
) {
    let mut wake = status.subscribe();
    loop {
        let deadline = {
            let guarded = slot.lock().expect("mixnet slot mutex");
            match &*guarded {
                crate::mixnet::MixnetSlot::Attached(client) => client.proof_deadline(),
                _ => return,
            }
        };
        tokio::time::sleep_until(tokio::time::Instant::from_std(deadline)).await;
        let due = {
            let guarded = slot.lock().expect("mixnet slot mutex");
            match &*guarded {
                crate::mixnet::MixnetSlot::Attached(client) => {
                    // A round trip may have moved the deadline while we
                    // slept; only a still-lapsed proof is due.
                    client.proof_deadline() <= std::time::Instant::now()
                }
                _ => return,
            }
        };
        if due {
            run_proof_acquisition(slot.clone(), pools.clone(), status.clone()).await;
            // Mark the channel seen before the progress read, so an install
            // landing after the read still wakes the park below.
            wake.borrow_and_update();
            let advanced = {
                let guarded = slot.lock().expect("mixnet slot mutex");
                match &*guarded {
                    crate::mixnet::MixnetSlot::Attached(client) => {
                        client.proof_deadline() > deadline
                    }
                    _ => return,
                }
            };
            // An acquisition that could not act — a condemned client
            // mid-failover, a forsaken exhaustion, an address-less proxy —
            // left the lapsed deadline in place, and re-arming on it would
            // spin a core until vacate: park until the slot's next
            // published transition instead.
            if !advanced && wake.changed().await.is_err() {
                return;
            }
        }
    }
}

/// One rotation, make-before-break: prove a replacement while the incumbent
/// still serves, install it, then retire the incumbent once the work already
/// dialed through it drains (ADR 0048).
async fn hand_off_standing_client<A>(
    slot: &std::sync::Arc<std::sync::Mutex<crate::mixnet::MixnetSlot>>,
    pools: &std::sync::Arc<crate::mixnet::pools::Pools>,
    status: &crate::mixnet::driver::StatusPublisher,
    acquirer: &A,
) where
    A: crate::mixnet::acquire::TransportAcquirable + ?Sized,
{
    // The replacement births on its own channel and nothing publishes until
    // it is installed, so a rotation is never visible as a bootstrap: the
    // incumbent is serving throughout.
    let birth = match pools.acquire_proven(acquirer).await {
        Ok(birth) => birth,
        Err(exhausted) => {
            // A rotation that cannot prove a replacement is a no-op. The
            // incumbent is healthy, so keeping it costs only the bounded
            // exposure this rotation meant to end.
            log::warn!(
                "a rotation found no proven replacement, so the session keeps its client: {exhausted}"
            );
            return;
        }
    };
    let birth_channel = std::sync::Arc::clone(&birth.lifecycle);
    let client = standing_client_from_birth(birth);
    match install_rotated_client(slot, client) {
        Ok(replaced) => {
            forward_client_transitions(&birth_channel, status);
            publish_slot(slot, status);
            if let crate::mixnet::MixnetSlot::Attached(old) = replaced {
                old.retire().await;
            }
        }
        Err(refused) => {
            // A failover or a teardown reached the slot while the
            // replacement was proving, so the client it would have replaced
            // is already gone; the replacement dies unused and its lease
            // recycles.
            refused.stop().await;
        }
    }
}

/// The rotation watchdog: draws a cadence, waits out the platform's verdict
/// on affording a bootstrap, hands the session to a replacement, and repeats
/// until the slot empties.
async fn standing_rotation_watchdog(
    slot: std::sync::Arc<std::sync::Mutex<crate::mixnet::MixnetSlot>>,
    pools: std::sync::Arc<crate::mixnet::pools::Pools>,
    status: crate::mixnet::driver::StatusPublisher,
) {
    // Asked once before any waiting, so a platform that will never rotate
    // holds no sleeping task for the session's life.
    if let Some(acquirer) = pools.acquirer()
        && matches!(
            crate::mixnet::acquire::TransportAcquirable::rotation_verdict(acquirer.as_ref()),
            crate::mixnet::acquire::RotationVerdict::Never
        )
    {
        return;
    }
    loop {
        // The generator is scoped so no non-Send handle crosses the await.
        let cadence = {
            let mut entropy = rand::rng();
            crate::mixnet::acquire::rotation_interval(&mut entropy)
        };
        tokio::time::sleep(cadence).await;

        let acquirer = loop {
            if !matches!(
                &*slot.lock().expect("mixnet slot mutex"),
                crate::mixnet::MixnetSlot::Attached(_)
            ) {
                return;
            }
            let Some(acquirer) = pools.acquirer() else {
                // An attached session births nothing locally, so it also
                // rotates nothing.
                return;
            };
            // Asked at the moment of acting rather than when the cadence was
            // drawn, because the battery and the foreground state the host
            // weighs are the ones it has now.
            match crate::mixnet::acquire::TransportAcquirable::rotation_verdict(acquirer.as_ref()) {
                crate::mixnet::acquire::RotationVerdict::Now => break acquirer,
                crate::mixnet::acquire::RotationVerdict::Defer(after) => {
                    tokio::time::sleep(after).await
                }
                // A platform can rule rotation out mid-session, and the
                // ruling holds for the rest of it.
                crate::mixnet::acquire::RotationVerdict::Never => return,
            }
        };
        hand_off_standing_client(&slot, &pools, &status, acquirer.as_ref()).await;
    }
}

impl LightClient {
    /// Take whatever transport the slot holds and shut it down, leaving the
    /// `Unattached` that a failed enable also deliberately leaves behind: a
    /// failure must not silently reinstate a prior `SwitchedOff`. The
    /// transmit policy is not this method's to touch.
    pub(super) async fn vacate_mixnet_slot(&mut self) {
        self.exit_pools.clear_acquirer();
        // Boot's unspent conduits go with the session: a teardown before
        // their jobs took them must leave no proxy behind.
        for conduit in self.exit_pools.drain_conduits() {
            conduit.transport.stop().await;
        }
        for watchdog in [&mut self.standing_watchdog, &mut self.rotation_watchdog] {
            if let Some(watchdog) = watchdog.take() {
                watchdog.abort();
            }
        }
        if let Some(acquisition) = self
            .proof_acquisition
            .lock()
            .expect("the proof-acquisition slot is never poisoned")
            .take()
        {
            acquisition.abort();
        }
        if let crate::mixnet::MixnetSlot::Attached(client) =
            swap_slot(&self.mixnet_slot, crate::mixnet::MixnetSlot::Unattached)
        {
            // Stopping the Standing Client recycles its exit's lease by
            // drop after the transport is gone.
            client.stop().await;
        }
    }

    /// Starts the expiry and rotation watchdogs for a freshly installed
    /// Standing Client, replacing any predecessors.
    fn arm_standing_watchdog(&mut self) {
        for watchdog in [&mut self.standing_watchdog, &mut self.rotation_watchdog] {
            if let Some(watchdog) = watchdog.take() {
                watchdog.abort();
            }
        }
        self.standing_watchdog = Some(tokio::spawn(standing_proof_watchdog(
            self.mixnet_slot.clone(),
            self.exit_pools.clone(),
            std::sync::Arc::clone(&self.mixnet_status),
        )));
        // Both watchdogs follow the slot rather than a client, so a rotation
        // or a failover installing a replacement re-arms neither.
        self.rotation_watchdog = Some(tokio::spawn(standing_rotation_watchdog(
            self.mixnet_slot.clone(),
            self.exit_pools.clone(),
            std::sync::Arc::clone(&self.mixnet_status),
        )));
    }

    /// Raises the suspicion that the Standing Client's exit is dead,
    /// spawning a ProofAcquisition whose arbiter probe adjudicates it.
    pub(crate) fn note_standing_exit_suspicion(&self) {
        let mut held = self
            .proof_acquisition
            .lock()
            .expect("the proof-acquisition slot is never poisoned");
        // Single flight: a running acquisition already owns the adjudication,
        // and tracking the handle lets a vacate abort it, so a consent
        // revoked mid-birth is never raced by an untracked task.
        if held.as_ref().is_some_and(|task| !task.is_finished()) {
            return;
        }
        *held = Some(tokio::spawn(run_proof_acquisition(
            self.mixnet_slot.clone(),
            self.exit_pools.clone(),
            std::sync::Arc::clone(&self.mixnet_status),
        )));
    }

    /// ```
    /// use zingolib::config::{ClientConfig, WalletConfig};
    /// use zingolib::lightclient::LightClient;
    /// use zingolib::mixnet::{Indicator, TransportError};
    ///
    /// tokio::runtime::Runtime::new().unwrap().block_on(async {
    ///     let wallet_dir = tempfile::tempdir().unwrap();
    ///     let config = ClientConfig::builder()
    ///         .set_wallet_dir(wallet_dir.path().to_path_buf())
    ///         .set_wallet_config(WalletConfig::MnemonicPhrase {
    ///             mnemonic_phrase: "abandon abandon abandon abandon abandon \
    ///                 abandon abandon abandon abandon abandon abandon abandon \
    ///                 abandon abandon abandon abandon abandon abandon abandon \
    ///                 abandon abandon abandon abandon art"
    ///                 .to_string(),
    ///             no_of_accounts: std::num::NonZeroU32::new(1).unwrap(),
    ///             birthday: 2_000_000,
    ///             wallet_settings: Default::default(),
    ///         })
    ///         .build()
    ///         .unwrap();
    ///     let mut client = LightClient::new(config, true).await.unwrap();
    ///
    ///     // Enabling births the standing client from the binary at the
    ///     // given path; a binary that cannot run refuses typed at the
    ///     // first step (the exit-directory discovery), and the failed
    ///     // enable leaves Unattached — a refusal, never nakednet.
    ///     let missing = std::path::Path::new("/nonexistent/nym-proxy");
    ///     let refused = client.enable_mixnet(missing).await;
    ///     assert!(matches!(
    ///         refused,
    ///         Err(TransportError::DiscoverySpawn(_))
    ///     ));
    ///     assert_eq!(client.read_mixnet_indicator(), Indicator::Unattached);
    /// });
    /// ```
    pub async fn enable_mixnet(
        &mut self,
        binary_path: &std::path::Path,
    ) -> Result<(), crate::mixnet::acquire::TransportError> {
        self.enable_mixnet_from(std::sync::Arc::new(
            crate::mixnet::acquire::Acquirer::Spawned(crate::mixnet::acquire::SpawnedBinary::at(
                binary_path.to_path_buf(),
            )),
        ))
        .await
    }

    /// ```
    /// use zingolib::config::{ClientConfig, WalletConfig};
    /// use zingolib::lightclient::LightClient;
    /// use zingolib::mixnet::acquire::{HostRefusal, HostedTransport, ProxyHosting, RotationVerdict};
    /// use zingolib::mixnet::{ExitNodeId, Indicator, TransportError};
    ///
    /// // A host that declines every request, standing in for the platform
    /// // that owns the proxy where subprocesses are forbidden.
    /// struct DecliningHost;
    ///
    /// impl ProxyHosting for DecliningHost {
    ///     fn discover_exit_nodes(&self) -> Result<Vec<ExitNodeId>, HostRefusal> {
    ///         Err(HostRefusal::Declined {
    ///             detail: "the platform is in low-power mode".to_string(),
    ///         })
    ///     }
    ///
    ///     fn start_transport(
    ///         &self,
    ///         _clutch: &[ExitNodeId],
    ///     ) -> Result<HostedTransport, HostRefusal> {
    ///         Err(HostRefusal::Declined {
    ///             detail: "the platform is in low-power mode".to_string(),
    ///         })
    ///     }
    ///
    ///     // Low power is exactly when a platform declines to spend a
    ///     // bootstrap, so this host holds whatever it has.
    ///     fn rotation_verdict(&self) -> RotationVerdict {
    ///         RotationVerdict::Defer(zingolib::mixnet::mixnet_timing().client_rotation_max)
    ///     }
    /// }
    ///
    /// tokio::runtime::Runtime::new().unwrap().block_on(async {
    ///     let wallet_dir = tempfile::tempdir().unwrap();
    ///     let config = ClientConfig::builder()
    ///         .set_wallet_dir(wallet_dir.path().to_path_buf())
    ///         .set_wallet_config(WalletConfig::MnemonicPhrase {
    ///             mnemonic_phrase: "abandon abandon abandon abandon abandon \
    ///                 abandon abandon abandon abandon abandon abandon abandon \
    ///                 abandon abandon abandon abandon abandon abandon abandon \
    ///                 abandon abandon abandon abandon art"
    ///                 .to_string(),
    ///             no_of_accounts: std::num::NonZeroU32::new(1).unwrap(),
    ///             birthday: 2_000_000,
    ///             wallet_settings: Default::default(),
    ///         })
    ///         .build()
    ///         .unwrap();
    ///     let mut client = LightClient::new(config, true).await.unwrap();
    ///
    ///     // The standing client births from the host instead of a spawned
    ///     // binary; the host's refusal surfaces typed and the failed
    ///     // enable leaves Unattached — a refusal, never nakednet.
    ///     let refused = client
    ///         .enable_mixnet_via_host(DecliningHost)
    ///         .await;
    ///     assert!(matches!(
    ///         refused,
    ///         Err(TransportError::HostRefused(HostRefusal::Declined { .. }))
    ///     ));
    ///     assert_eq!(client.read_mixnet_indicator(), Indicator::Unattached);
    /// });
    /// ```
    pub async fn enable_mixnet_via_host(
        &mut self,
        host: impl crate::mixnet::acquire::ProxyHosting,
    ) -> Result<(), crate::mixnet::acquire::TransportError> {
        self.enable_mixnet_from(std::sync::Arc::new(
            crate::mixnet::acquire::Acquirer::Hosted(
                crate::mixnet::acquire::HostedProvider::owned_by(host),
            ),
        ))
        .await
    }

    /// Enables Mixnet Mode over `acquirer` by birthing the session's
    /// standing Proven Client — the same trust-or-probe birth every client
    /// gets — narrating on the session channel as the slot owner while the
    /// birth runs on its own channel, holding only the bound exit's lease,
    /// and leaving any failure `Unattached`.
    ///
    /// The enable is the user's consent to the mixnet from the moment it
    /// is asked for, so the transmit policy moves to
    /// [`TransmitPolicy::Mixnet`](crate::mixnet::TransmitPolicy) before the
    /// birth starts: a send during the bootstrap refuses as `Bootstrapping`
    /// rather than travelling a nakednet route the user has just turned
    /// away from. A failed enable restores the policy the user had before,
    /// so a session that chose nakednet keeps sending there after an
    /// attempt that did not take, and a session that never chose it keeps
    /// refusing.
    async fn enable_mixnet_from(
        &mut self,
        acquirer: std::sync::Arc<crate::mixnet::acquire::Acquirer>,
    ) -> Result<(), crate::mixnet::acquire::TransportError> {
        let policy_before = self.transmit_policy();
        self.set_transmit_policy(crate::mixnet::TransmitPolicy::Mixnet);
        self.vacate_mixnet_slot().await;
        // The slot owner alone speaks on the session channel: one
        // Bootstrapping for the whole enable, the settled state after it,
        // and never a candidate's churn.
        self.mixnet_status
            .send_replace(crate::mixnet::MixnetStatus {
                mode: crate::mixnet::Indicator::Bootstrapping,
                socks5_addr: None,
                exits: Vec::new(),
                bootstrap_detail: None,
                death: None,
            });
        // Boot proves four exits at once and assigns each a role in the
        // order it confirms (ADR 0045). The IndexerClient's birth becomes
        // the session's standing client; the other three are held for the
        // jobs boot gives them and stop when those jobs end.
        match crate::mixnet::quartet::prove_quartet(&self.exit_pools, acquirer.as_ref()).await {
            Ok(quartet) => {
                let birth = quartet.indexer;
                // The three unspent conduits go to the exit authority, where
                // the job each role names takes its own without a birth.
                for (role, conduit) in [
                    (crate::mixnet::quartet::Role::IndexerSweep, quartet.sweep),
                    (crate::mixnet::quartet::Role::PriceFetch, quartet.price),
                    (crate::mixnet::quartet::Role::Spare, quartet.spare),
                ] {
                    self.exit_pools.hold_conduit(role, conduit);
                }
                // The Standing Client's later transitions — above all
                // Died — must still reach the session's subscribers.
                forward_client_transitions(&birth.lifecycle, &self.mixnet_status);
                let client = standing_client_from_birth(birth);
                let superseded = swap_slot(
                    &self.mixnet_slot,
                    crate::mixnet::MixnetSlot::Attached(client),
                );
                debug_assert!(matches!(superseded, crate::mixnet::MixnetSlot::Unattached));
                self.exit_pools.set_acquirer(acquirer);
                self.arm_standing_watchdog();
                // The settled slot publishes last so subscribers read the
                // attached state whole.
                self.publish_mixnet_slot_state();
                Ok(())
            }
            Err(error) => {
                // A failed enable leaves Unattached rather than a prior
                // SwitchedOff, and hands the policy back to the user's
                // earlier choice; subscribers must see the settled state.
                self.set_transmit_policy(policy_before);
                self.publish_mixnet_slot_state();
                Err(error)
            }
        }
    }

    /// Records a completed round trip carried by the Standing Client,
    /// promoting stale proof to earned Ready and refreshing the exit's
    /// EpochProven observation.
    pub(crate) fn note_standing_round_trip(&self) {
        let promoted_node = {
            let guarded = self.mixnet_slot.lock().expect("mixnet slot mutex");
            match &*guarded {
                crate::mixnet::MixnetSlot::Attached(client) if client.note_round_trip() => {
                    Some(client.exit_node().cloned())
                }
                _ => None,
            }
        };
        if let Some(node) = promoted_node {
            if let Some(node) = node {
                self.exit_pools.remember(
                    node,
                    crate::mixnet::pools::exit_pool::ExitNodeHealthVerdict::EpochProven,
                );
            }
            // Subscribers watching the session channel see the promotion.
            self.publish_mixnet_slot_state();
        }
    }

    /// ```
    /// use zingolib::config::{ClientConfig, WalletConfig};
    /// use zingolib::lightclient::LightClient;
    /// use zingolib::mixnet::{ExitNodeId, Indicator, MixnetProxyError};
    ///
    /// tokio::runtime::Runtime::new().unwrap().block_on(async {
    ///     let wallet_dir = tempfile::tempdir().unwrap();
    ///     let config = ClientConfig::builder()
    ///         .set_wallet_dir(wallet_dir.path().to_path_buf())
    ///         .set_wallet_config(WalletConfig::MnemonicPhrase {
    ///             mnemonic_phrase: "abandon abandon abandon abandon abandon \
    ///                 abandon abandon abandon abandon abandon abandon abandon \
    ///                 abandon abandon abandon abandon abandon abandon abandon \
    ///                 abandon abandon abandon abandon art"
    ///                 .to_string(),
    ///             no_of_accounts: std::num::NonZeroU32::new(1).unwrap(),
    ///             birthday: 2_000_000,
    ///             wallet_settings: Default::default(),
    ///         })
    ///         .build()
    ///         .unwrap();
    ///     let mut client = LightClient::new(config, true).await.unwrap();
    ///
    ///     // An unparseable address refuses typed, leaving Unattached.
    ///     let refused = client.attach_mixnet("not-an-address", &[]).await;
    ///     assert!(matches!(
    ///         refused,
    ///         Err(MixnetProxyError::InvalidAddress { .. })
    ///     ));
    ///     assert_eq!(client.read_mixnet_indicator(), Indicator::Unattached);
    ///
    ///     // Empty `exits` refuses typed before anything is dialed.
    ///     let exitless = client.attach_mixnet("127.0.0.1:9", &[]).await;
    ///     assert!(matches!(exitless, Err(MixnetProxyError::NoExits)));
    ///
    ///     // A well-formed endpoint installs as the Standing Client, and
    ///     // readiness is validated asynchronously: the call returns before
    ///     // any probe, so the mode is not yet Ready.
    ///     let host_drawn = ExitNodeId::parse("host-drawn-exit").unwrap();
    ///     client
    ///         .attach_mixnet("127.0.0.1:9", std::slice::from_ref(&host_drawn))
    ///         .await
    ///         .unwrap();
    ///     assert_ne!(client.read_mixnet_indicator(), Indicator::Ready);
    ///
    ///     // A later attach vacates the standing transport first, so its
    ///     // failure leaves Unattached rather than the prior client.
    ///     client.attach_mixnet("not-an-address", &[]).await.unwrap_err();
    ///     assert_eq!(client.read_mixnet_indicator(), Indicator::Unattached);
    /// });
    /// ```
    ///
    /// Like every enable, the attach is the user's consent to the mixnet
    /// from the moment it is asked for: the transmit policy moves to
    /// [`TransmitPolicy::Mixnet`](crate::mixnet::TransmitPolicy) before the
    /// attach, so a send while the readiness gate runs refuses as
    /// `Bootstrapping` rather than leaking. A refused attach restores the
    /// policy the user had before.
    pub async fn attach_mixnet(
        &mut self,
        socks5_addr: &str,
        exits: &[crate::mixnet::ExitNodeId],
    ) -> Result<(), crate::mixnet::MixnetProxyError> {
        let policy_before = self.transmit_policy();
        self.set_transmit_policy(crate::mixnet::TransmitPolicy::Mixnet);
        self.vacate_mixnet_slot().await;
        let attached = socks5_addr
            .parse()
            .map_err(|_| crate::mixnet::MixnetProxyError::InvalidAddress {
                addr: socks5_addr.to_string(),
            })
            .and_then(|socks5_addr| {
                crate::mixnet::MixnetProxy::attach(
                    socks5_addr,
                    exits,
                    std::sync::Arc::clone(&self.mixnet_status),
                )
            });
        match attached {
            Ok(proxy) => {
                // The mobile host drew the attached endpoint's exit outside
                // this session's Exit Pool, so the Standing Client holds no
                // exit_reservation.
                // The attach readiness gate earns the proof end to end, so
                // the hosted Standing Client is born probed.
                let superseded = swap_slot(
                    &self.mixnet_slot,
                    crate::mixnet::MixnetSlot::Attached(crate::mixnet::StandingClient::new(
                        proxy, None, true,
                    )),
                );
                debug_assert!(matches!(superseded, crate::mixnet::MixnetSlot::Unattached));
                self.arm_standing_watchdog();
                Ok(())
            }
            Err(error) => {
                // A refused attach leaves Unattached rather than a prior
                // SwitchedOff, and hands the policy back to the user's
                // earlier choice; subscribers must see the settled state.
                self.set_transmit_policy(policy_before);
                self.publish_mixnet_slot_state();
                Err(error)
            }
        }
    }

    /// Disable Mixnet Mode — the deliberate, per-session choice that alone
    /// reaches [`Indicator::SwitchedOff`](crate::mixnet::Indicator) — shutting
    /// down any running transport. A transport act only: the transmit
    /// policy is untouched, so where a send travels afterwards is the
    /// policy's answer, and the mixnet-only surfaces refuse.
    pub async fn disable_mixnet(&mut self) {
        // Revoked consent stops every networking act this session started:
        // the health sweep's survey halts with the standing transport.
        self.abort_health_sweep().await;
        self.vacate_mixnet_slot().await;
        swap_slot(&self.mixnet_slot, crate::mixnet::MixnetSlot::SwitchedOff);
        self.publish_mixnet_slot_state();
    }

    /// Publish the slot's current state into the session status channel,
    /// called only after a slot transition settles — never mid-replacement —
    /// so subscribers see deliberate states and not the transient unattached
    /// between a vacate and its successor.
    pub(super) fn publish_mixnet_slot_state(&self) {
        publish_slot(&self.mixnet_slot, &self.mixnet_status);
    }

    /// The driver entry a session calls at its go-online moment, which under
    /// [`MixnetStartPolicy::ForcedOn`](crate::mixnet::MixnetStartPolicy)
    /// provisions the transport by `strategy` (the bundled binary spawned
    /// from the consumer's platform hints, or an attach to a mobile-platform-hosted
    /// endpoint) and blocks until the standing client is born proven, under
    /// [`MixnetStartPolicy::OptedOutThisSession`](crate::mixnet::MixnetStartPolicy)
    /// records the startup opt-out as the explicit act that reaches switched
    /// off and sets the transmit policy to
    /// [`TransmitPolicy::Nakednet`](crate::mixnet::TransmitPolicy), so the
    /// session's sends travel over the indexer (ADR 0024, consent at start),
    /// returns any provisioning failure typed while leaving the mode
    /// unattached — refusal, never a silent nakednet — and never respawns on
    /// its own, recovery staying explicit through
    /// [`Indicator::needs_recovery`](crate::mixnet::Indicator::needs_recovery).
    pub async fn start_mixnet_session(
        &mut self,
        strategy: crate::mixnet::ProvisionStrategy<'_>,
        policy: crate::mixnet::MixnetStartPolicy,
    ) -> Result<(), crate::mixnet::acquire::TransportError> {
        match policy {
            crate::mixnet::MixnetStartPolicy::OptedOutThisSession => {
                self.disable_mixnet().await;
                // The opt-out is the user's explicit nakednet consent for
                // this session, so it is the one production act that sets
                // the policy. The price fetch stays mixnet-only regardless.
                self.set_transmit_policy(crate::mixnet::TransmitPolicy::Nakednet);
                Ok(())
            }
            crate::mixnet::MixnetStartPolicy::ForcedOn => match strategy {
                crate::mixnet::ProvisionStrategy::Spawn(hints) => {
                    let path = crate::mixnet::provision::resolve_proxy_path(&hints);
                    log::info!("mixnet session start: spawning nym-proxy at {path}");
                    // The go-online moment is a user act: someone is waiting.
                    self.enable_mixnet(std::path::Path::new(&path)).await
                }
                crate::mixnet::ProvisionStrategy::Attach { socks5_addr, exits } => self
                    .attach_mixnet(socks5_addr, exits)
                    .await
                    .map_err(crate::mixnet::acquire::TransportError::from),
            },
        }
    }

    /// Subscribe to Mixnet Mode — the receiving half of the session's one
    /// status channel — whose keep-only-latest push delivers a typed
    /// [`MixnetStatus`](crate::mixnet::MixnetStatus) snapshot on every
    /// transition, in a receiver independent of this client borrow that
    /// survives enable/disable cycles.
    pub fn subscribe_mixnet_status(
        &self,
    ) -> tokio::sync::watch::Receiver<crate::mixnet::MixnetStatus> {
        self.mixnet_status.subscribe()
    }

    pub fn read_mixnet_indicator(&self) -> crate::mixnet::Indicator {
        self.mixnet_slot.lock().expect("mixnet slot mutex").mode()
    }

    /// The local SOCKS5 address while Mixnet Mode is ready.
    pub fn mixnet_socks5_addr(&self) -> Option<std::net::SocketAddr> {
        self.mixnet_slot
            .lock()
            .expect("mixnet slot mutex")
            .socks5_addr()
    }

    /// The session's conduit while a transport is attached.
    pub fn mixnet_conduit(&self) -> Option<crate::mixnet::MixnetConduit> {
        self.mixnet_slot
            .lock()
            .expect("mixnet slot mutex")
            .conduit()
    }

    /// Switch Mixnet Mode on for a chain-mock test, with the slot reporting
    /// [`Indicator::Ready`](crate::mixnet::Indicator) at `socks5_addr` while
    /// no child, watcher, or probe stands behind it, so the test walks the
    /// same fail-closed route resolver and escalation orchestration a live
    /// Ready session does and the transmit path submits over the mock
    /// indexer's channel without ever dialing the address.
    #[cfg(any(test, feature = "testutils"))]
    pub async fn switch_on_mixnet_for_tests(&mut self, socks5_addr: std::net::SocketAddr) {
        self.attach_mixnet_for_tests(socks5_addr, true).await;
    }

    /// Switch Mixnet Mode on over the SOCKS5 relay at `socks5_addr`, with real mixnet arms.
    #[cfg(any(test, feature = "testutils"))]
    pub async fn switch_on_mixnet_through_for_tests(&mut self, socks5_addr: std::net::SocketAddr) {
        self.attach_mixnet_for_tests(socks5_addr, false).await;
    }

    #[cfg(any(test, feature = "testutils"))]
    async fn attach_mixnet_for_tests(
        &mut self,
        socks5_addr: std::net::SocketAddr,
        mock_arms: bool,
    ) {
        self.vacate_mixnet_slot().await;
        swap_slot(
            &self.mixnet_slot,
            crate::mixnet::MixnetSlot::AttachedForTests {
                socks5_addr,
                conduit: crate::mixnet::MixnetConduit::over(socks5_addr),
                mock_arms,
            },
        );
        // Every slot transition publishes (the one-shared-watch invariant),
        // the stand-in included.
        self.publish_mixnet_slot_state();
        // The stand-in carries the enable's consent act.
        self.set_transmit_policy(crate::mixnet::TransmitPolicy::Mixnet);
    }

    /// The proxy's latest bootstrap progress line while Mixnet Mode is
    /// bootstrapping, so a user interface can narrate the connect race.
    pub fn mixnet_bootstrap_detail(&self) -> Option<String> {
        self.mixnet_slot
            .lock()
            .expect("mixnet slot mutex")
            .proxy()
            .and_then(|proxy| proxy.bootstrap_detail())
    }

    /// Why the transport died, while Mixnet Mode is
    /// [`Indicator::Died`](crate::mixnet::Indicator) and the watcher held a
    /// typed cause: the [`zingo_net_diag::NetOpFailure`] record naming the
    /// stage, the target, and the cause chain as a vector, so a `died`
    /// verdict carries *why* without anyone parsing prose.
    pub fn mixnet_death_detail(&self) -> Option<zingo_net_diag::NetOpFailure> {
        self.mixnet_slot
            .lock()
            .expect("mixnet slot mutex")
            .proxy()
            .and_then(|proxy| proxy.death_detail())
    }

    /// The latched death read whole — its moment and, when the watcher held
    /// one, its typed cause — while Mixnet Mode is
    /// [`Indicator::Died`](crate::mixnet::Indicator) and `None` in every
    /// other mode, the moment distinguishing a stale latch from a fresh one
    /// through [`crate::mixnet::DeathReport::age`].
    pub fn mixnet_death_report(&self) -> Option<crate::mixnet::DeathReport> {
        self.mixnet_slot
            .lock()
            .expect("mixnet slot mutex")
            .proxy()
            .and_then(|proxy| proxy.death_report())
    }

    /// Resolve the route of a mixnet-only surface (price-fetch, the liveness
    /// probe): the session's conduit while Mixnet Mode is
    /// [`Indicator::Ready`](crate::mixnet::Indicator::Ready), a typed
    /// refusal in every other state. The transmit policy has no say here.
    pub fn mixnet_only_route(
        &self,
    ) -> Result<crate::mixnet::MixnetConduit, crate::mixnet::MixnetNotReady> {
        crate::mixnet::resolve_mixnet_only_route(
            self.read_mixnet_indicator(),
            self.mixnet_conduit(),
        )
    }

    /// Resolve the route of a transmission under the session's
    /// [`TransmitPolicy`](crate::mixnet::TransmitPolicy): nakednet at once
    /// under the nakednet policy, and under the mixnet policy the conduit
    /// or the refusal [`Self::mixnet_only_route`] would give.
    pub fn send_route(&self) -> Result<crate::mixnet::MixnetRoute, crate::mixnet::MixnetNotReady> {
        crate::mixnet::resolve_send_route(
            self.transmit_policy(),
            self.read_mixnet_indicator(),
            self.mixnet_conduit(),
        )
    }

    /// The session's transmit policy, readable so a consumer can show the
    /// current mode.
    pub fn transmit_policy(&self) -> crate::mixnet::TransmitPolicy {
        if self
            .transmit_over_mixnet
            .load(std::sync::atomic::Ordering::Acquire)
        {
            crate::mixnet::TransmitPolicy::Mixnet
        } else {
            crate::mixnet::TransmitPolicy::Nakednet
        }
    }

    /// Set the session's transmit policy. Takes effect on the next route
    /// resolution, so a transmission already in flight keeps the route it
    /// resolved. Never persisted: every session starts under
    /// [`TransmitPolicy::Mixnet`](crate::mixnet::TransmitPolicy).
    pub fn set_transmit_policy(&self, policy: crate::mixnet::TransmitPolicy) {
        self.transmit_over_mixnet.store(
            policy == crate::mixnet::TransmitPolicy::Mixnet,
            std::sync::atomic::Ordering::Release,
        );
    }

    /// Runs the mixnet liveness probe — concurrent `GetLightdInfo` calls
    /// through the session's SOCKS5 proxy, each appending its outcome to the
    /// cross-session indexer history — against `target`, or against every
    /// Destination when `target` is `None`, with no nakednet leg and a
    /// refusal while the mixnet transport is not ready.
    pub async fn probe_destinations(
        &self,
        target: Option<http::Uri>,
        timeout: std::time::Duration,
    ) -> Result<Vec<crate::mixnet::probe::MixnetProbe>, crate::lightclient::error::LightClientError>
    {
        // The guard lives for the whole probe, so the conduit counts this
        // work as outstanding until every leg has finished.
        let dial = self.mixnet_only_route()?.dial();
        let socks5_addr = dial.socks5();
        if let Some(uri) = &target
            && !crate::mixnet::probe::probe_eligible(uri)
        {
            return Err(
                crate::lightclient::error::LightClientError::IneligibleProbeTarget(uri.clone()),
            );
        }
        let targets: Vec<http::Uri> = target
            .map_or_else(
                || {
                    self.destination_servers
                        .registry_reachable(crate::destination::servers::Transport::Mixnet)
                },
                |uri| vec![uri],
            )
            .into_iter()
            .filter(crate::mixnet::probe::probe_eligible)
            .collect();
        let history = self.indexer_history.clone();
        let probes = futures::future::join_all(targets.iter().map(|indexer| {
            crate::mixnet::probe::probe_indexer(indexer, socks5_addr, timeout, &history)
        }))
        .await;
        // Any answered probe is a completed round trip through the Standing
        // Client, promoting stale proof to earned; a wave nobody answered
        // raises the suspicion the standing exit is dead, and the arbiter
        // probe adjudicates.
        if probes.iter().any(|probe| probe.leg.outcome.is_ok()) {
            self.note_standing_round_trip();
        } else if !probes.is_empty() {
            self.note_standing_exit_suspicion();
        }
        Ok(probes)
    }

    /// Update and return the current ZEC price in USD by racing the price
    /// sources through the tunnel and taking the first answer. Mixnet-only
    /// (ADR 0011, amendment 2026-09-11): a ready mixnet carries it, every
    /// other state refuses with a typed
    /// [`MixnetNotReady`](crate::mixnet::MixnetNotReady), and the transmit
    /// policy has no effect.
    pub async fn update_current_price(&self) -> Result<MixnetPriceFetch, LightClientError> {
        let dispatched = std::time::Instant::now();
        let conduit = self.mixnet_only_route()?;
        let dial = conduit.dial();
        let socks5_addr = dial.socks5();

        let run = PriceRun {
            pools: self.exit_pools.clone(),
        };

        let (outcomes, via_socks5) = if self.exit_pools.acquirer().is_some() {
            let (outcomes, spent) = crate::mixnet::speed::run_speed_prioritized(&run)
                .await
                .map_err(crate::wallet::error::PriceError::Speed)?;
            let dial = spent
                .addr()
                .map(|addr| addr.to_string())
                .unwrap_or_default();
            crate::mixnet::speed::SpeedPrioritized::dispose(&run, spent);
            (outcomes, dial)
        } else {
            let conduit = zingo_netutils::conduit::MixnetConduit::over(socks5_addr);
            match crate::mixnet::speed::run_wave(&run, &conduit).await {
                crate::mixnet::speed::WaveEnd::Settled(outcomes)
                | crate::mixnet::speed::WaveEnd::Exhausted(outcomes) => {
                    (outcomes, socks5_addr.to_string())
                }
            }
        };
        let raced =
            zingo_price::first_quote(outcomes).map_err(crate::wallet::error::PriceError::from)?;
        Ok(MixnetPriceFetch {
            usd: raced.price.price_usd,
            source: raced.source,
            round_trip: dispatched.elapsed(),
            route: crate::lightclient::PriceFetchRoute::Mixnet { via_socks5 },
        })
    }
}

#[cfg(test)]
mod tests {

    mod price_fetch_contract {
        //! The price-fetch error contract: every failure reaches the API
        //! as a typed [`LightClientError`], and a nakednet leg runs only
        //! with consent. Route refusals pair with `mixnet::route`'s tests;
        //! transport-leg failures are pinned in `zingo-price`.
        use crate::lightclient::LightClient;
        use crate::lightclient::error::LightClientError;
        use crate::testutils::synthetic_wallet::SyntheticWalletBuilder;

        fn wallet() -> crate::wallet::LightWallet {
            SyntheticWalletBuilder::new(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED).build()
        }

        /// A never-enabled mixnet is a typed refusal, never a nakednet
        /// fallback: the fresh client is `Unattached` (absence is not
        /// consent, ADR 0011 amendment 2026-07-28), and the route pre-flight
        /// runs before any network object is built, so no packet leaves the
        /// process.
        #[tokio::test]
        async fn an_unattached_mixnet_is_a_typed_refusal() {
            let client = LightClient::new_for_test(wallet()).await;

            let error = client
                .update_current_price()
                .await
                .expect_err("no transport was ever enabled, so the mixnet fetch must refuse");
            assert!(
                matches!(
                    error,
                    LightClientError::MixnetNotReady(crate::mixnet::MixnetNotReady::Unattached)
                ),
                "the refusal must be typed, not prose: {error}"
            );
        }

        /// The price fetch is mixnet-only (ADR 0011, amendment 2026-09-11):
        /// a switched-off transport refuses it as the unattached one does,
        /// with no nakednet leg.
        #[tokio::test]
        async fn switched_off_mode_refuses_the_price_fetch() {
            let mut client = LightClient::new_for_test(wallet()).await;
            client.disable_mixnet().await;

            let error = client
                .update_current_price()
                .await
                .expect_err("a switched-off transport must refuse the price fetch");
            assert!(
                matches!(
                    error,
                    LightClientError::MixnetNotReady(crate::mixnet::MixnetNotReady::Unattached)
                ),
                "the refusal must be typed, not prose: {error}"
            );
        }

        /// The transmit policy is a send-only input, so the
        /// nakednet policy never opens a nakednet leg for the price fetch.
        /// Falsified if the fetch under the nakednet policy does anything
        /// but refuse on an unattached transport.
        #[tokio::test]
        async fn the_nakednet_policy_never_reaches_the_price_fetch() {
            let client = LightClient::new_for_test(wallet()).await;
            client.set_transmit_policy(crate::mixnet::TransmitPolicy::Nakednet);

            let error = client
                .update_current_price()
                .await
                .expect_err("the transmit policy must not consent to a nakednet price fetch");
            assert!(
                matches!(
                    error,
                    LightClientError::MixnetNotReady(crate::mixnet::MixnetNotReady::Unattached)
                ),
                "the refusal must be typed, not prose: {error}"
            );
        }

        /// A deliberate disable on a fresh, never-enabled client lands
        /// SwitchedOff rather than Unattached, and both resolvers read it
        /// as a missing transport.
        #[tokio::test]
        async fn disable_before_any_enable_lands_switched_off() {
            let mut client = LightClient::new_for_test(wallet()).await;
            assert_eq!(
                client.read_mixnet_indicator(),
                crate::mixnet::Indicator::Unattached
            );

            client.disable_mixnet().await;

            assert_eq!(
                client.read_mixnet_indicator(),
                crate::mixnet::Indicator::SwitchedOff
            );
            assert_eq!(
                client.mixnet_only_route().err(),
                Some(crate::mixnet::MixnetNotReady::Unattached)
            );
            assert_eq!(
                client.send_route().err(),
                Some(crate::mixnet::MixnetNotReady::Unattached)
            );
        }
    }

    mod transmit_policy {
        //! The session's transmit policy (ADR 0011, amendment 2026-09-11):
        //! the consumer's per-session choice of where a transaction
        //! travels, readable, flippable through `&self`, and reaching the
        //! send route alone. The state by policy matrix is pinned in
        //! `mixnet::route`; these pin the client's wiring of it.
        use crate::lightclient::LightClient;
        use crate::mixnet::{MixnetNotReady, MixnetRoute, TransmitPolicy};
        use crate::testutils::synthetic_wallet::SyntheticWalletBuilder;

        fn wallet() -> crate::wallet::LightWallet {
            SyntheticWalletBuilder::new(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED).build()
        }

        #[tokio::test]
        async fn every_session_starts_under_the_mixnet_policy() {
            let client = LightClient::new_for_test(wallet()).await;
            assert_eq!(client.transmit_policy(), TransmitPolicy::Mixnet);
        }

        #[tokio::test]
        async fn the_policy_flips_while_the_client_runs_and_reads_back() {
            let client = LightClient::new_for_test(wallet()).await;
            client.set_transmit_policy(TransmitPolicy::Nakednet);
            assert_eq!(client.transmit_policy(), TransmitPolicy::Nakednet);
            client.set_transmit_policy(TransmitPolicy::Mixnet);
            assert_eq!(client.transmit_policy(), TransmitPolicy::Mixnet);
        }

        /// The nakednet policy routes a send at once, on a client whose
        /// transport was never enabled.
        #[tokio::test]
        async fn the_nakednet_policy_routes_a_send_over_an_unattached_transport() {
            let client = LightClient::new_for_test(wallet()).await;
            assert_eq!(client.send_route(), Err(MixnetNotReady::Unattached));

            client.set_transmit_policy(TransmitPolicy::Nakednet);

            assert_eq!(client.send_route(), Ok(MixnetRoute::Nakednet));
        }

        /// A flip back to the mixnet policy restores the refusal, so the
        /// policy is read at resolution time and never latched.
        #[tokio::test]
        async fn flipping_back_to_the_mixnet_policy_restores_the_refusal() {
            let client = LightClient::new_for_test(wallet()).await;
            client.set_transmit_policy(TransmitPolicy::Nakednet);
            assert_eq!(client.send_route(), Ok(MixnetRoute::Nakednet));

            client.set_transmit_policy(TransmitPolicy::Mixnet);

            assert_eq!(client.send_route(), Err(MixnetNotReady::Unattached));
        }
    }

    mod consent_holds {
        //! Revoked consent stops every networking act the session started
        //! (findings 2 and 9 of the 2026-08-14 PR #2695 review).
        use crate::lightclient::LightClient;
        use crate::mixnet::ExitNodeId;
        use crate::testutils::synthetic_wallet::SyntheticWalletBuilder;

        fn wallet() -> crate::wallet::LightWallet {
            SyntheticWalletBuilder::new(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED).build()
        }

        /// A Standing Client over an attach to `addr`, for slot tests.
        fn attached_client(addr: std::net::SocketAddr) -> crate::mixnet::StandingClient {
            let proxy = crate::mixnet::MixnetProxy::attach(
                addr,
                &[ExitNodeId::from("exit-alpha")],
                crate::mixnet::status_publisher(),
            )
            .expect("the attach accepts a bound exit");
            crate::mixnet::StandingClient::new(proxy, None, true)
        }

        /// HYPOTHESIS: disabling the mixnet halts the health sweep, so the
        /// consent revocation stops the census probing the session started.
        /// Falsified if the sweep's task survives the disable.
        #[tokio::test]
        async fn disable_mixnet_halts_the_health_sweep() {
            let mut client = LightClient::new_for_test(wallet()).await;
            let (held_tx, cancelled_rx) = tokio::sync::oneshot::channel::<()>();
            let sweep = tokio::spawn(async move {
                let _held = held_tx;
                std::future::pending::<()>().await
            });
            *client
                .health_sweep
                .lock()
                .expect("the health-sweep slot is never poisoned") = Some(sweep);

            client.disable_mixnet().await;

            assert!(
                client
                    .health_sweep
                    .lock()
                    .expect("the health-sweep slot is never poisoned")
                    .is_none(),
                "the disable takes and halts the sweep"
            );
            assert!(
                cancelled_rx.await.is_err(),
                "the sweep task was cancelled, not left surveying"
            );
        }

        /// HYPOTHESIS: a failover's replacement installs only while the slot
        /// still holds the condemned client whose enable it continues, so a
        /// consent revoked mid-birth is never reversed. Falsified if the
        /// install overwrites a SwitchedOff slot.
        #[tokio::test]
        async fn a_switched_off_slot_refuses_the_failover_client() {
            let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
                .await
                .expect("bind an ephemeral port");
            let addr = listener.local_addr().expect("local addr");
            let slot = std::sync::Arc::new(std::sync::Mutex::new(
                crate::mixnet::MixnetSlot::SwitchedOff,
            ));

            let Err(refused) = super::super::install_failover_client(&slot, attached_client(addr))
            else {
                panic!("a switched-off slot must refuse the continuation");
            };
            refused.stop().await;

            assert!(
                matches!(
                    &*slot.lock().expect("mixnet slot mutex"),
                    crate::mixnet::MixnetSlot::SwitchedOff
                ),
                "the revoked consent stands"
            );
        }

        /// HYPOTHESIS: the install succeeds exactly when the slot holds the
        /// condemned client the failover replaces, yielding the superseded
        /// slot for teardown. Falsified if a condemned slot refuses.
        #[tokio::test]
        async fn a_condemned_slot_accepts_the_failover_client() {
            let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
                .await
                .expect("bind an ephemeral port");
            let addr = listener.local_addr().expect("local addr");
            let old = attached_client(addr);
            old.condemn();
            let slot = std::sync::Arc::new(std::sync::Mutex::new(
                crate::mixnet::MixnetSlot::Attached(old),
            ));

            let Ok(superseded) =
                super::super::install_failover_client(&slot, attached_client(addr))
            else {
                panic!("the condemned slot must accept its continuation");
            };
            if let crate::mixnet::MixnetSlot::Attached(old) = superseded {
                old.stop().await;
            }

            assert!(
                matches!(
                    &*slot.lock().expect("mixnet slot mutex"),
                    crate::mixnet::MixnetSlot::Attached(client) if !client.is_condemned()
                ),
                "the replacement stands in the slot"
            );
        }

        /// HYPOTHESIS: a rotation installs over the healthy incumbent it set
        /// out to replace, which is the one client no other path can
        /// replace, and yields it for retirement. Falsified if a healthy
        /// slot refuses the hand-off.
        #[tokio::test]
        async fn a_healthy_slot_accepts_the_rotated_client() {
            let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
                .await
                .expect("bind an ephemeral port");
            let addr = listener.local_addr().expect("local addr");
            let slot = std::sync::Arc::new(std::sync::Mutex::new(
                crate::mixnet::MixnetSlot::Attached(attached_client(addr)),
            ));

            let Ok(superseded) = super::super::install_rotated_client(&slot, attached_client(addr))
            else {
                panic!("a healthy slot must accept its rotation");
            };
            let crate::mixnet::MixnetSlot::Attached(outgoing) = superseded else {
                panic!("the rotation yields the incumbent it replaced");
            };
            outgoing.retire().await;

            assert!(
                matches!(
                    &*slot.lock().expect("mixnet slot mutex"),
                    crate::mixnet::MixnetSlot::Attached(client) if !client.is_condemned()
                ),
                "the replacement stands in the slot"
            );
        }

        /// HYPOTHESIS: rotation and failover are exact complements over the
        /// slot, so a client is replaceable by one path and never by both.
        /// Falsified if a condemned client accepts a rotation or a healthy
        /// one accepts a failover, either of which lets a rotation and a
        /// failover both install over the same incumbent.
        #[tokio::test]
        async fn rotation_and_failover_never_claim_the_same_incumbent() {
            let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
                .await
                .expect("bind an ephemeral port");
            let addr = listener.local_addr().expect("local addr");

            let healthy = std::sync::Arc::new(std::sync::Mutex::new(
                crate::mixnet::MixnetSlot::Attached(attached_client(addr)),
            ));
            let Err(refused) =
                super::super::install_failover_client(&healthy, attached_client(addr))
            else {
                panic!("a healthy incumbent has no failover to continue");
            };
            refused.stop().await;

            let condemned_client = attached_client(addr);
            condemned_client.condemn();
            let condemned = std::sync::Arc::new(std::sync::Mutex::new(
                crate::mixnet::MixnetSlot::Attached(condemned_client),
            ));
            let Err(refused) =
                super::super::install_rotated_client(&condemned, attached_client(addr))
            else {
                panic!("a condemned incumbent is the failover's to replace, not a rotation's");
            };
            refused.stop().await;
        }

        /// HYPOTHESIS: a rotation refuses a slot whose consent was revoked
        /// mid-birth, exactly as a failover does, so neither reinstates a
        /// transport the user switched off. Falsified if the install
        /// overwrites a SwitchedOff slot.
        #[tokio::test]
        async fn a_switched_off_slot_refuses_the_rotated_client() {
            let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
                .await
                .expect("bind an ephemeral port");
            let addr = listener.local_addr().expect("local addr");
            let slot = std::sync::Arc::new(std::sync::Mutex::new(
                crate::mixnet::MixnetSlot::SwitchedOff,
            ));

            let Err(refused) = super::super::install_rotated_client(&slot, attached_client(addr))
            else {
                panic!("a switched-off slot must refuse the rotation");
            };
            refused.stop().await;

            assert!(
                matches!(
                    &*slot.lock().expect("mixnet slot mutex"),
                    crate::mixnet::MixnetSlot::SwitchedOff
                ),
                "the revoked consent stands"
            );
        }

        /// How long a watchdog that must not wait is given to retire.
        const IMMEDIATE_RETIREMENT: std::time::Duration = std::time::Duration::from_millis(50);

        /// HYPOTHESIS: a platform that rules rotation out retires the
        /// watchdog rather than parking it on a cadence whose answer cannot
        /// change, so a desktop session holds no sleeping task for its
        /// whole life. Falsified if the watchdog waits out a rotation
        /// interval before reading a verdict it could have read at once.
        #[tokio::test]
        async fn a_platform_that_never_rotates_retires_the_watchdog() {
            let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
                .await
                .expect("bind an ephemeral port");
            let addr = listener.local_addr().expect("local addr");
            let slot = std::sync::Arc::new(std::sync::Mutex::new(
                crate::mixnet::MixnetSlot::Attached(attached_client(addr)),
            ));
            let pools = crate::mixnet::pools::Pools::new();
            // The desktop acquirer is the production Never, and its verdict
            // is answered without the binary ever being spawned.
            pools.set_acquirer(std::sync::Arc::new(
                crate::mixnet::acquire::Acquirer::Spawned(
                    crate::mixnet::acquire::SpawnedBinary::at("nym-proxy".into()),
                ),
            ));

            let watchdog = tokio::spawn(super::super::standing_rotation_watchdog(
                slot,
                pools,
                crate::mixnet::status_publisher(),
            ));
            tokio::time::timeout(IMMEDIATE_RETIREMENT, watchdog)
                .await
                .expect("a Never verdict retires the watchdog before any cadence elapses")
                .expect("the watchdog runs to completion");
        }

        /// An acquirer whose every birth refuses, so a rotation exhausts.
        struct BirthlessAcquirer;

        impl crate::mixnet::acquire::TransportAcquirable for BirthlessAcquirer {
            async fn discover(
                &self,
            ) -> Result<std::collections::HashSet<ExitNodeId>, crate::mixnet::acquire::TransportError>
            {
                Ok(std::collections::HashSet::new())
            }

            async fn acquire(
                &self,
                _clutch: &[ExitNodeId],
                _publisher: crate::mixnet::driver::StatusPublisher,
            ) -> Result<crate::mixnet::MixnetProxy, crate::mixnet::acquire::TransportError>
            {
                Err(crate::mixnet::acquire::TransportError::NotReady {
                    budget: zingo_netutils::time::NYM_LIFECYCLE_TIMEOUT,
                })
            }

            fn rotation_verdict(&self) -> crate::mixnet::acquire::RotationVerdict {
                crate::mixnet::acquire::RotationVerdict::Now
            }
        }

        /// HYPOTHESIS: make-before-break means a rotation that cannot prove
        /// a replacement is a no-op, so the session keeps its service and
        /// publishes no transition at all. Falsified if a failed rotation
        /// leaves the slot empty or dips the mode, either of which turns a
        /// privacy measure into an outage.
        #[tokio::test]
        async fn a_rotation_without_a_replacement_keeps_the_incumbent() {
            let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
                .await
                .expect("bind an ephemeral port");
            let addr = listener.local_addr().expect("local addr");
            let slot = std::sync::Arc::new(std::sync::Mutex::new(
                crate::mixnet::MixnetSlot::Attached(attached_client(addr)),
            ));
            let pools = crate::mixnet::pools::Pools::new();
            let status = crate::mixnet::status_publisher();
            let mut watching = status.subscribe();
            watching.borrow_and_update();

            super::super::hand_off_standing_client(&slot, &pools, &status, &BirthlessAcquirer)
                .await;

            assert!(
                matches!(
                    &*slot.lock().expect("mixnet slot mutex"),
                    crate::mixnet::MixnetSlot::Attached(client) if !client.is_condemned()
                ),
                "a rotation that cannot prove a replacement must keep the client it has"
            );
            assert!(
                !watching
                    .has_changed()
                    .expect("the channel outlives the test"),
                "a failed rotation is invisible: the incumbent never stopped serving"
            );
        }
    }

    mod expiry_watchdog_parks {
        //! The watchdog's progress discipline (finding 3 of the 2026-08-14
        //! PR #2695 review): an acquisition that cannot advance a lapsed
        //! proof deadline parks the watchdog on the status channel instead
        //! of spinning it against a deadline nothing will move.
        use crate::mixnet::ExitNodeId;

        /// How long the test observes the armed watchdog for starvation.
        const PARK_OBSERVATION: std::time::Duration = std::time::Duration::from_millis(50);

        /// A Standing Client over an attach to `addr`, for slot tests.
        fn attached_client(addr: std::net::SocketAddr) -> crate::mixnet::StandingClient {
            let proxy = crate::mixnet::MixnetProxy::attach(
                addr,
                &[ExitNodeId::from("exit-alpha")],
                crate::mixnet::status_publisher(),
            )
            .expect("the attach accepts a bound exit");
            crate::mixnet::StandingClient::new(proxy, None, true)
        }

        /// HYPOTHESIS: a lapsed deadline the acquisition cannot advance — a
        /// condemned client mid-failover — parks the watchdog awaiting the
        /// slot's next published transition. Falsified if the watchdog's
        /// hot loop starves this current-thread runtime, so the sleep below
        /// never completes and the test dies by timeout.
        #[tokio::test]
        async fn a_stalled_acquisition_parks_the_watchdog() {
            let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
                .await
                .expect("bind an ephemeral port");
            let addr = listener.local_addr().expect("local addr");
            let client = attached_client(addr);
            client.condemn();
            client.set_proof_deadline(std::time::Instant::now());
            let slot = std::sync::Arc::new(std::sync::Mutex::new(
                crate::mixnet::MixnetSlot::Attached(client),
            ));
            let pools = crate::mixnet::pools::Pools::new();
            let status = crate::mixnet::status_publisher();

            let watchdog = tokio::spawn(super::super::standing_proof_watchdog(
                slot.clone(),
                pools,
                status,
            ));

            tokio::time::sleep(PARK_OBSERVATION).await;
            assert!(
                !watchdog.is_finished(),
                "the parked watchdog still guards the slot"
            );
            watchdog.abort();
        }
    }

    mod birth_channel_isolation {
        //! The birth-channel rule (finding 3 of the PR #2705 review): a
        //! birth's candidate lifecycle belongs to the birth's own channel,
        //! and the session channel speaks only for the slot.
        use std::sync::{Arc, Mutex};

        use crate::lightclient::LightClient;
        use crate::mixnet::{ExitNodeId, Indicator, MixnetStatus};
        use crate::testutils::synthetic_wallet::SyntheticWalletBuilder;

        fn wallet() -> crate::wallet::LightWallet {
            SyntheticWalletBuilder::new(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED).build()
        }

        /// The exit this harness announces as bound, and the first the
        /// quartet assigns.
        const HARNESS_EXIT: &str = "exit-alpha";

        /// Every exit this harness discovers. Boot proves a quartet, so a
        /// population smaller than [`quartet::QUARTET_SIZE`] cannot fill
        /// the roles and the enable refuses.
        const HARNESS_CENSUS: [&str; crate::mixnet::quartet::QUARTET_SIZE] =
            [HARNESS_EXIT, "exit-beta", "exit-gamma", "exit-delta"];

        /// Yields granted after a publication so a subscriber on another
        /// worker observes it before the watch channel coalesces.
        const ANNOUNCEMENT_YIELDS: usize = 8;

        /// HYPOTHESIS: during an enable the session channel narrates the
        /// slot owner's Bootstrapping and never a candidate's Ready, so a
        /// subscriber cannot observe a client the slot does not hold.
        /// Falsified if any Ready reaches the session channel mid-enable.
        #[tokio::test(flavor = "multi_thread")]
        async fn the_enable_narrates_without_relaying_candidates() {
            let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
                .await
                .expect("bind an ephemeral port");
            let addr = listener.local_addr().expect("local addr");
            let mut client = LightClient::new_for_test(wallet()).await;
            for exit in HARNESS_CENSUS {
                client.exit_pools.remember(
                    ExitNodeId::from(exit),
                    crate::mixnet::pools::exit_pool::ExitNodeHealthVerdict::EpochProven,
                );
            }
            let mut feed = client.subscribe_mixnet_status();
            let seen: Arc<Mutex<Vec<MixnetStatus>>> = Arc::default();
            let sink = Arc::clone(&seen);
            // The collector must be parked on the channel before the enable
            // begins, or coalescing hides the transients it exists to catch.
            let (started_tx, started_rx) = tokio::sync::oneshot::channel();
            let collector = tokio::spawn(async move {
                started_tx.send(()).expect("the test task is waiting");
                while feed.changed().await.is_ok() {
                    let status = feed.borrow_and_update().clone();
                    sink.lock().expect("collector mutex").push(status);
                }
            });
            started_rx.await.expect("the collector starts");

            client
                .enable_mixnet_from(std::sync::Arc::new(
                    crate::mixnet::acquire::Acquirer::Announcing(
                        crate::mixnet::acquire::AnnouncingAcquirer {
                            socks5_addr: addr,
                            census: HARNESS_CENSUS
                                .iter()
                                .map(|id| ExitNodeId::from(*id))
                                .collect(),
                            yields: ANNOUNCEMENT_YIELDS,
                            // The harness pins the client it scripts, so a
                            // rotation must never replace it mid-test.
                            rotation: crate::mixnet::acquire::RotationVerdict::Never,
                        },
                    ),
                ))
                .await
                .expect("the trusted birth settles the enable");

            for _ in 0..ANNOUNCEMENT_YIELDS {
                tokio::task::yield_now().await;
            }
            collector.abort();
            let seen = seen.lock().expect("collector mutex");
            assert!(
                seen.iter().all(|status| status.mode != Indicator::Ready),
                "no candidate Ready reaches the session channel: {seen:?}"
            );
            // A watch channel promises the latest state, not every event, so
            // the narration clause asserts only what any subscriber is
            // guaranteed: whatever it observes first is the slot owner's
            // plain Bootstrapping, never a candidate's detailed one.
            if let Some(first) = seen.first() {
                assert_eq!(
                    first.mode,
                    Indicator::Bootstrapping,
                    "the channel's first mid-enable state is the slot owner's"
                );
                assert_eq!(
                    first.bootstrap_detail, None,
                    "the narration is the slot owner's, never a candidate's"
                );
            }
        }
    }

    mod death_story {
        //! A latched death reaches subscribers with its typed cause (finding
        //! F6 of the PR #2705 review, item 2 of the 2026-08-14 split).
        use crate::mixnet::{ExitNodeId, Indicator};

        /// HYPOTHESIS: a forsaken Standing Client's Died reaches the status
        /// channel carrying the exhaustion's typed story, so a consumer
        /// renders the cause and never a bare "died". Falsified if the
        /// published death is None.
        #[tokio::test]
        async fn a_forsaken_client_publishes_its_death_story() {
            let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
                .await
                .expect("bind an ephemeral port");
            let addr = listener.local_addr().expect("local addr");
            let birth_channel = crate::mixnet::status_publisher();
            let proxy = crate::mixnet::MixnetProxy::attach(
                addr,
                &[ExitNodeId::from("exit-alpha")],
                birth_channel,
            )
            .expect("the attach accepts a bound exit");
            let client = crate::mixnet::StandingClient::new(proxy, None, true);
            let exhausted = crate::mixnet::acquire::TransportError::NoProvenExit {
                probed: crate::mixnet::pools::MAX_PROVING_BIRTHS,
                budget: zingo_netutils::time::SENTINEL_BUDGET,
            };
            client.forsake(zingo_net_diag::NetOpFailure::from_error(
                zingo_net_diag::NetOpStage::RouteResolution,
                "the session's exit census",
                &exhausted,
            ));
            let slot = std::sync::Arc::new(std::sync::Mutex::new(
                crate::mixnet::MixnetSlot::Attached(client),
            ));

            let session = crate::mixnet::status_publisher();
            super::super::publish_slot(&slot, &session);

            let published = session.subscribe().borrow().clone();
            assert_eq!(published.mode, Indicator::Died, "forsaken latches Died");
            let death = published
                .death
                .expect("the published death carries its report");
            let detail = death.detail.expect("the report holds the typed cause");
            assert!(
                detail
                    .cause_chain
                    .iter()
                    .any(|layer| layer.contains("no proven exit")),
                "the exhaustion's own words reach the subscriber: {detail:?}"
            );
        }
    }

    mod session_driver_contract {
        //! The session driver's contract (ADR 0024, decision 2).
        //!
        //! The driver entry is the one call a session makes at its go-online
        //! moment; these tests pin its consent-at-start semantics, its typed
        //! refusal on a failed provisioning, the push delivery of every
        //! transition through the session's one status channel, and the
        //! Died-only recovery predicate.
        use crate::lightclient::LightClient;
        use crate::testutils::synthetic_wallet::SyntheticWalletBuilder;

        fn wallet() -> crate::wallet::LightWallet {
            SyntheticWalletBuilder::new(zingo_test_vectors::seeds::HOSPITAL_MUSEUM_SEED).build()
        }

        /// HYPOTHESIS: a failed enable hands the session back as the user
        /// had it: from `SwitchedOff` under the nakednet policy, a failed
        /// `attach_mixnet` lands `Unattached` and publishes it, and the
        /// policy is `Nakednet` again, so the user who chose nakednet keeps
        /// sending there after an enable that did not take. Falsified if
        /// the mode remains `SwitchedOff` or the policy ends elsewhere.
        #[tokio::test]
        async fn a_failed_attach_restores_the_policy_the_user_had() {
            let mut client = LightClient::new_for_test(wallet()).await;
            client.disable_mixnet().await;
            client.set_transmit_policy(crate::mixnet::TransmitPolicy::Nakednet);
            let subscriber = client.subscribe_mixnet_status();

            client
                .attach_mixnet("not-an-address", &[])
                .await
                .expect_err("an unparseable mobile platform address must fail the attach");

            assert_eq!(
                client.read_mixnet_indicator(),
                crate::mixnet::Indicator::Unattached
            );
            assert_eq!(
                subscriber.borrow().mode,
                crate::mixnet::Indicator::Unattached,
                "subscribers must see the settled state"
            );
            assert_eq!(
                client.transmit_policy(),
                crate::mixnet::TransmitPolicy::Nakednet,
                "a failed enable must hand the policy back"
            );
            assert_eq!(
                client.send_route(),
                Ok(crate::mixnet::MixnetRoute::Nakednet),
                "the user who chose nakednet keeps sending there"
            );
        }

        /// HYPOTHESIS: the enable is the mixnet consent from the moment it
        /// is asked for, so a send during the bootstrap refuses rather than
        /// travelling the nakednet route the user just turned away from.
        /// Attaches to a refusing localhost port from a nakednet session:
        /// the attach is accepted, the readiness gate runs, and the send
        /// route reads `Bootstrapping` while it does. Falsified if the send
        /// route yields nakednet at any point after the attach.
        #[tokio::test]
        async fn a_send_during_the_bootstrap_refuses_rather_than_leak() {
            let mut client = LightClient::new_for_test(wallet()).await;
            client.set_transmit_policy(crate::mixnet::TransmitPolicy::Nakednet);
            assert_eq!(
                client.send_route(),
                Ok(crate::mixnet::MixnetRoute::Nakednet)
            );

            client
                .attach_mixnet(
                    "127.0.0.1:9",
                    &[crate::mixnet::ExitNodeId::from("exit-alpha")],
                )
                .await
                .expect("a well-formed address and a named exit attach");

            assert_eq!(
                client.transmit_policy(),
                crate::mixnet::TransmitPolicy::Mixnet,
                "the attach itself is the consent, before readiness"
            );
            assert!(
                matches!(
                    client.send_route(),
                    Err(crate::mixnet::MixnetNotReady::Bootstrapping
                        | crate::mixnet::MixnetNotReady::Died)
                ),
                "a send after the attach must refuse until the gate settles, got {:?}",
                client.send_route()
            );
            client.go_offline().await;
        }

        /// HYPOTHESIS: a failed enable on a session that never chose
        /// nakednet keeps refusing sends: the default `Mixnet` policy
        /// stands and the slot is `Unattached`. Falsified if the failure
        /// opens a nakednet send.
        #[tokio::test]
        async fn a_failed_attach_without_a_nakednet_choice_still_refuses() {
            let mut client = LightClient::new_for_test(wallet()).await;

            client
                .attach_mixnet("not-an-address", &[])
                .await
                .expect_err("an unparseable mobile platform address must fail the attach");

            assert_eq!(
                client.send_route(),
                Err(crate::mixnet::MixnetNotReady::Unattached)
            );
        }

        /// HYPOTHESIS: a runtime enable after the startup opt-out brings
        /// sends back to the mixnet: the policy the opt-out set to
        /// `Nakednet` is `Mixnet` again once the enable settles. Falsified
        /// if a ready transport is paired with a nakednet send route.
        #[tokio::test]
        async fn enabling_after_the_opt_out_routes_sends_over_the_mixnet() {
            let mut client = LightClient::new_for_test(wallet()).await;
            client
                .start_mixnet_session(
                    crate::mixnet::ProvisionStrategy::Spawn(
                        crate::mixnet::provision::SpawnHints::default(),
                    ),
                    crate::mixnet::MixnetStartPolicy::OptedOutThisSession,
                )
                .await
                .expect("the opt-out provisions nothing and cannot fail");
            assert_eq!(
                client.transmit_policy(),
                crate::mixnet::TransmitPolicy::Nakednet
            );

            let socks5_addr = crate::mocks::transmission::MOCK_SOCKS5_ADDR;
            client.attach_mixnet_for_tests(socks5_addr, true).await;

            assert!(client.read_mixnet_indicator().is_ready());
            assert_eq!(
                client.transmit_policy(),
                crate::mixnet::TransmitPolicy::Mixnet
            );
            assert!(
                matches!(
                    client.send_route(),
                    Ok(crate::mixnet::MixnetRoute::Mixnet(_))
                ),
                "a ready transport after an enable must carry the sends"
            );
        }

        /// The driver entry honors the startup opt-out (ADR 0024, consent
        /// at start): OptedOutThisSession lands SwitchedOff without
        /// provisioning anything — the strategy is never exercised — sets
        /// the transmit policy to nakednet so sends still travel, and the
        /// transition reaches subscribers through the session channel.
        #[tokio::test]
        async fn the_driver_records_the_startup_opt_out_and_publishes_it() {
            let mut client = LightClient::new_for_test(wallet()).await;
            let subscriber = client.subscribe_mixnet_status();
            assert_eq!(
                subscriber.borrow().mode,
                crate::mixnet::Indicator::Unattached,
                "the channel opens in the ground state"
            );
            assert_eq!(
                client.transmit_policy(),
                crate::mixnet::TransmitPolicy::Mixnet,
                "the session starts under the mixnet policy"
            );

            client
                .start_mixnet_session(
                    // A hint set that resolves to no real binary: the
                    // opt-out branch must never try to spawn it.
                    crate::mixnet::ProvisionStrategy::Spawn(
                        crate::mixnet::provision::SpawnHints::default(),
                    ),
                    crate::mixnet::MixnetStartPolicy::OptedOutThisSession,
                )
                .await
                .expect("the opt-out provisions nothing and cannot fail");

            assert_eq!(
                client.read_mixnet_indicator(),
                crate::mixnet::Indicator::SwitchedOff
            );
            assert_eq!(
                subscriber.borrow().mode,
                crate::mixnet::Indicator::SwitchedOff,
                "the slot transition must reach subscribers"
            );
            assert_eq!(
                client.transmit_policy(),
                crate::mixnet::TransmitPolicy::Nakednet,
                "the opt-out is the session's nakednet consent"
            );
            assert_eq!(
                client.send_route(),
                Ok(crate::mixnet::MixnetRoute::Nakednet),
                "an opted-out session must still transmit"
            );
            assert_eq!(
                client.mixnet_only_route().err(),
                Some(crate::mixnet::MixnetNotReady::Unattached),
                "the opt-out never opens a nakednet price fetch"
            );
        }

        /// A forced-on attach to a malformed address fails typed and leaves
        /// Unattached — refusal, never nakednet — and publishes the settled
        /// state so a subscriber cannot be left staring at a stale mode.
        #[tokio::test]
        async fn a_failed_forced_on_start_publishes_unattached() {
            let mut client = LightClient::new_for_test(wallet()).await;
            let subscriber = client.subscribe_mixnet_status();

            let error = client
                .start_mixnet_session(
                    crate::mixnet::ProvisionStrategy::Attach {
                        socks5_addr: "not-a-socket-address",
                        exits: &[],
                    },
                    crate::mixnet::MixnetStartPolicy::ForcedOn,
                )
                .await
                .expect_err("a malformed attach address must refuse");
            assert!(matches!(
                error,
                crate::mixnet::acquire::TransportError::Proxy(
                    crate::mixnet::MixnetProxyError::InvalidAddress { .. }
                )
            ));

            assert_eq!(
                client.read_mixnet_indicator(),
                crate::mixnet::Indicator::Unattached
            );
            assert_eq!(
                subscriber.borrow().mode,
                crate::mixnet::Indicator::Unattached,
                "the failed start's settled state must reach subscribers"
            );
        }

        /// The attached transport's lifecycle reaches subscribers end to
        /// end: a forced-on attach to a refusing localhost port publishes
        /// bootstrapping, then died with the typed readiness failure — all
        /// pushed, never polled. A deliberate disable afterwards publishes
        /// SwitchedOff and, because stop() awaits the aborted watcher, no
        /// stale death can be published over it.
        #[tokio::test]
        async fn attach_lifecycle_and_disable_reach_subscribers_in_order() {
            let mut client = LightClient::new_for_test(wallet()).await;
            let mut subscriber = client.subscribe_mixnet_status();

            client
                .start_mixnet_session(
                    // Port 9 (discard) refuses: readiness fails fast and
                    // the driver lands Died.
                    crate::mixnet::ProvisionStrategy::Attach {
                        socks5_addr: "127.0.0.1:9",
                        exits: &[crate::mixnet::ExitNodeId::from("host-bound-exit")],
                    },
                    crate::mixnet::MixnetStartPolicy::ForcedOn,
                )
                .await
                .expect("a well-formed address attaches");

            let died = subscriber
                .wait_for(|status| status.mode == crate::mixnet::Indicator::Died)
                .await
                .expect("the publisher outlives the wait")
                .clone();
            assert!(
                died.death.and_then(|report| report.detail).is_some(),
                "an attach readiness failure must publish its typed cause"
            );

            client.disable_mixnet().await;
            assert_eq!(
                subscriber.borrow_and_update().mode,
                crate::mixnet::Indicator::SwitchedOff
            );
            tokio::task::yield_now().await;
            assert!(
                !subscriber.has_changed().expect("the publisher is alive"),
                "no stale transport publication may follow the deliberate disable"
            );
        }

        /// HYPOTHESIS: the test-only mixnet switch takes an already parsed
        /// socket address, so the contract is checked by the compiler and no
        /// external harness can abort inside it on a placeholder string.
        /// Falsified if the helper still takes text and parses within.
        #[tokio::test]
        async fn the_test_switch_takes_a_typed_socket_address() {
            let mut client = LightClient::new_for_test(wallet()).await;
            let socks5_addr = crate::mocks::transmission::MOCK_SOCKS5_ADDR;

            client.switch_on_mixnet_for_tests(socks5_addr).await;

            assert_eq!(
                client.mixnet_socks5_addr(),
                Some(socks5_addr),
                "the slot reports the very address the caller handed it"
            );
        }

        /// The recovery predicate is Died only: the ground state carries no
        /// online intent (a wallet may never have consented to
        /// connectivity), switched off is consent revocation's territory,
        /// and the live states need no repair. Exhaustive over ALL so a new
        /// state must take a position.
        #[test]
        fn the_recovery_predicate_is_died_only() {
            for mode in crate::mixnet::Indicator::ALL {
                assert_eq!(
                    mode.needs_recovery(),
                    matches!(mode, crate::mixnet::Indicator::Died),
                    "{mode} must {}need recovery",
                    if matches!(mode, crate::mixnet::Indicator::Died) {
                        ""
                    } else {
                        "not "
                    }
                );
            }
        }
    }
}

#[cfg(test)]
mod proof_acquisition {
    //! The ProofAcquisition contract: the arbiter's evidence promotes or
    //! convicts the Standing Client's exit, the conviction runs the
    //! two-layer failover, and the expiry watchdog fires a new
    //! ProofAcquisition the moment the proof stops being epoch-fresh.

    use super::{adjudicate_standing_proof, standing_proof_watchdog};
    use crate::mixnet::pools::exit_pool::Reservation;
    use crate::mixnet::{Indicator, MixnetSlot, StandingClient};

    fn slot_with(born_probed: bool, exit: &str) -> std::sync::Arc<std::sync::Mutex<MixnetSlot>> {
        let proxy = crate::mixnet::MixnetProxy::ready_for_slot_tests(
            "127.0.0.1:9".parse().expect("the test address parses"),
            vec![crate::mixnet::ExitNodeId::from(exit)],
        );
        std::sync::Arc::new(std::sync::Mutex::new(MixnetSlot::Attached(
            StandingClient::new(
                proxy,
                Some(Reservation::dangling_for_test(exit)),
                born_probed,
            ),
        )))
    }

    /// HYPOTHESIS: an answered arbiter probe promotes stale proof to
    /// earned Ready and refreshes the exit's EpochProven observation.
    /// Falsified if an answer convicts, demotes, or writes nothing.
    #[tokio::test]
    async fn an_answer_promotes_and_refreshes_the_observation() {
        let slot = slot_with(false, "exit-answers");
        let pools = crate::mixnet::pools::Pools::new();
        let status = crate::mixnet::status_publisher();

        adjudicate_standing_proof(
            slot.clone(),
            pools.clone(),
            std::sync::Arc::clone(&status),
            zingo_netutils::sentinel::evidence_of(Some(64), 900),
        )
        .await;

        assert_eq!(slot.lock().unwrap().mode(), Indicator::Ready);
        assert!(
            pools.exits.lock().unwrap().epoch_proven(
                &crate::mixnet::ExitNodeId::from("exit-answers"),
                std::time::Instant::now()
            ),
            "the answer refreshes the exit's EpochProven observation"
        );
        assert_eq!(status.borrow().mode, Indicator::Ready);
    }

    /// HYPOTHESIS: a silent arbiter probe convicts the exit, and with no
    /// acquirer to rebirth from the failover exhausts into a latched Died,
    /// published to subscribers, with the conviction remembered. Falsified
    /// if silence leaves readiness standing or the conviction unwritten.
    #[tokio::test]
    async fn silence_convicts_and_a_rebirthless_failover_latches_died() {
        let slot = slot_with(true, "exit-silent");
        let pools = crate::mixnet::pools::Pools::new();
        let status = crate::mixnet::status_publisher();

        adjudicate_standing_proof(
            slot.clone(),
            pools.clone(),
            std::sync::Arc::clone(&status),
            zingo_netutils::sentinel::ExitEvidence::Silent,
        )
        .await;

        assert_eq!(slot.lock().unwrap().mode(), Indicator::Died);
        assert!(
            pools.exits.lock().unwrap().epoch_failed(
                &crate::mixnet::ExitNodeId::from("exit-silent"),
                std::time::Instant::now()
            ),
            "the conviction reaches the NodeHealthIndex"
        );
        assert_eq!(status.borrow().mode, Indicator::Died);
    }

    /// HYPOTHESIS: when the proof deadline lapses, the expiry watchdog
    /// fires a new ProofAcquisition at that earliest feasible moment: the
    /// arbiter probe runs against the tunnel (refused here, so silent),
    /// the exit is convicted, and the rebirthless failover latches Died —
    /// all without any operation touching the client. Falsified if expiry
    /// passes unnoticed.
    #[tokio::test(start_paused = true)]
    async fn expiry_fires_a_proof_acquisition_unprompted() {
        let slot = slot_with(true, "exit-expired");
        if let MixnetSlot::Attached(client) = &*slot.lock().unwrap() {
            client.set_proof_deadline(std::time::Instant::now());
        }
        let pools = crate::mixnet::pools::Pools::new();
        let status = crate::mixnet::status_publisher();
        let mut watcher = status.subscribe();

        let watchdog = tokio::spawn(standing_proof_watchdog(
            slot.clone(),
            pools.clone(),
            std::sync::Arc::clone(&status),
        ));
        watcher
            .wait_for(|published| published.mode == Indicator::Died)
            .await
            .expect("the watchdog publishes the exhausted failover");
        watchdog.abort();

        assert!(
            pools.exits.lock().unwrap().epoch_failed(
                &crate::mixnet::ExitNodeId::from("exit-expired"),
                std::time::Instant::now()
            ),
            "the unprompted ProofAcquisition convicted the lapsed exit"
        );
    }
}