orbit-link 0.6.8

Named reusable duplex sessions between members of an Orbit fleet.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
//! One bounded mailbox per fleet node: many writers, the lane's owner reads.
//!
//! Every node has a lane. An edge worker writes an exchange header into the
//! lane of the service worker it picked; that worker reads its own lane and
//! nobody else's. Replies travel the same way in the other direction, which is
//! why one table serves both — a node is either an edge or a service
//! worker, so its lane only ever receives one kind of frame.
//!
//! ## A full lane refuses
//!
//! `orbit_core::Ring` is a fan-out log and overwrites: `slot = counter %
//! capacity`, unconditionally, with no `Result` to refuse through. Correct for
//! telemetry, fatal here — an overwritten request is a request that vanished
//! while its caller waited. A writer that finds this lane full gets
//! [`Error::InboxFull`] and the caller answers 503.
//!
//! ## Producer-owned admission and publication
//!
//! A full-width turn identifies each physical slot's reuse. Its claim names
//! one bounded producer intent and moves FREE -> RESERVED -> COMMITTED or
//! CANCELLED. Helpers may admit a reservation but never read partial bytes.
//! The FIFO reader acquires COMMITTED before copying, skips CANCELLED, then
//! publishes next turn, FREE and head in that order. A slow live producer can
//! still hold the FIFO head; recovery never infers death from elapsed time.
//!
//! Writes contain no ownership lock, new syscall or polling wait. Segment
//! lifecycle code holds producer registrations with kernel locks and performs
//! exact-generation recovery only after those holds can be acquired.

#[cfg(unix)]
use std::io;
use std::sync::atomic::{AtomicU8, AtomicU32, AtomicU64, Ordering};

use orbit_core::process::ProcessOwner;

#[path = "inbox/claims.rs"]
pub(crate) mod claims;
use claims::{CANCELLED, COMMITTED};

use super::{Error, Result};

/// Marks a mapped region as this layout, so a segment left by a different
/// shape is recognised rather than read as garbage.
pub(crate) const INBOX_MAGIC: u32 = 0x4f54_5849; // "OTXI"

/// The layout's own version, separate from the geometry. Geometry changes are
/// caught by Orbit, which refuses a segment sized differently from the code's;
/// this catches a change that keeps the size and moves the meaning.
///
/// 13: a receiver's capacity row declares how many of its window's slots run
/// at once; the rest are the receiver's own queue.
///
/// 12: a receiver's capacity row counts the admission slots it holds, so a
/// full receiver refuses a reservation in one load.
///
/// 11: a producer registration carries a waiting word, and a reader that
/// frees one of its records rings it.
///
/// 10: the owner's growth policy and a coalesced pressure word in the table
/// header, in what was padding.
///
/// 9: atomic live-bound policy and retiring admission window.
///
/// 8: receiver-owned work reservations and capacity-change interests.
///
/// 7: producer registry, owned claims and monotonic consumer handoff.
///
/// 6: an interest table follows the watchers, one entry per lane and per
/// watcher slot, and a watcher carries a role.
///
/// 5: a directory-watcher table follows the lanes. Being woken when the
/// directory moves no longer requires holding a lane, so a process that serves
/// nothing (a master) can watch it too.
///
/// 4: a lane carries a reactor-listener word for descriptor-native async wake.
///
/// 3: a claimed lane's owner holds the lane's lock for as long as it lives, so
/// a lane whose lock can be taken belongs to a process that is gone. A build
/// before it holds no lock and would read as dead, so the two never share a
/// table.
pub(crate) const INBOX_VERSION: u32 = 13;

/// An owner's declared growth: never fewer than `min` workers, never more
/// than `max`, `step` added per pressure episode. What a worker is, and how
/// one starts, is the owner's or its supervisor's.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct GrowthPolicy {
    pub min: u16,
    pub max: u16,
    pub step: u16,
}

/// A lane taken back from a process that is gone.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Reclaimed {
    pub lane: usize,
    /// The incarnation its body streams are stamped with.
    pub incarnation: u64,
    pub pid: u32,
}

/// Longest service name a lane can advertise. Long enough for the names
/// a site route already uses; a longer one is a configuration error, not a
/// truncation.
pub const LANE_NAME_MAX: usize = 47;

/// Longest role tag a lane can carry: `asgi`, `php`, `edge`. A word, not a
/// description.
pub const LANE_ROLE_MAX: usize = 8;

/// Copy a role out of shared memory into a fixed buffer and ask `accept`.
fn accept_role(
    role: &[u8; LANE_ROLE_MAX],
    role_len: &AtomicU8,
    accept: impl FnOnce(&str) -> bool,
) -> bool {
    let len = role_len.load(Ordering::Acquire) as usize;
    if len == 0 || len > LANE_ROLE_MAX {
        return false;
    }
    let mut copy = [0u8; LANE_ROLE_MAX];
    // SAFETY: `role` is a mapped field of `LANE_ROLE_MAX` bytes and `len` is
    // within it; the bytes are copied before they are interpreted.
    copy[..len].copy_from_slice(unsafe {
        std::slice::from_raw_parts(role.as_ptr(), len)
    });
    std::str::from_utf8(&copy[..len]).is_ok_and(accept)
}

/// Per-lane state, in two cache lines on purpose.
///
/// The first line is written on every frame — reservation, read position, the
/// wake word. The second is written once when a process claims the lane and
/// read only when an edge is choosing a target. Keeping them apart means the
/// choosing side can read identity without touching the line the hot counters
/// live on.
#[repr(C, align(64))]
pub(crate) struct LaneHeader {
    /// Next position a writer may claim. Writers CAS this; nobody else writes
    /// it.
    pub(crate) reserve: AtomicU64,
    /// Next position the owner will read. Only the owner writes it.
    pub(crate) read: AtomicU64,
    /// How many live consumers serve this lane. A writer that finds zero
    /// refuses rather than filling a mailbox nobody empties.
    pub(crate) consumers: AtomicU32,
    /// Bumped on every commit: the word a parked reader waits on.
    pub(crate) changes: AtomicU32,
    /// The incarnation of the process that owns this lane. A consumer count
    /// left behind by a dead process is stale, and shared memory outlives the
    /// process that wrote it.
    pub(crate) incarnation: AtomicU64,
    pub(crate) waiters: AtomicU32,
    /// Set while the lane's Tokio receiver is waiting on its named socket.
    /// A writer clears it before ringing that socket, so concurrent writes
    /// coalesce into one reactor wake.
    pub(crate) reactor: AtomicU32,
    pub(crate) epoch: AtomicU64,
    initialized: AtomicU32,
    /// A capable reader stamps its exact inbox epoch here after setup.
    paired_bodies_epoch: AtomicU32,

    // ── second line: identity, written once per claim ──────────────────
    /// Which service this lane serves.
    ///
    /// A fleet may hold several — an edge belongs to exactly one fleet, so
    /// every service it reaches is in that fleet with it. The name lives
    /// here rather than in a table of its own: identity, presence and
    /// incarnation are one fact about a lane and want one place, and a
    /// separate table would be a second thing to keep true.
    ///
    /// Read as bytes under the lane's own ordering: a claim publishes the
    /// length last, so a reader that sees a length sees the bytes before it.
    pub(crate) service: [u8; LANE_NAME_MAX],
    pub(crate) service_len: AtomicU8,
    /// The process that holds this lane.
    ///
    /// Written for the operator, not for the protocol: nothing here routes by
    /// it. It is what answers "is this lane a live process or something a
    /// crashed one left behind", which the rest of the header cannot say — a
    /// consumer count is a claim, and a claim outlives the process that made
    /// it.
    ///
    /// Zero means the owner did not say. That is what every lane written
    /// before this field existed reports, and it is why the layout version
    /// stays where it is: the bytes were padding and padding was zeroed, so no
    /// reader of either build misreads the other's.
    ///
    /// A hint, not proof. A process id can be reused, so "alive" can name a
    /// different process; turning death into a 502 needs the death itself, not
    /// this.
    pub(crate) pid: AtomicU32,
    /// What serves the name: `asgi`, `php`, `edge`.
    ///
    /// The name is the only address, so two roles under one name would
    /// share an inbox and split its requests between them without a word.
    /// This is what lets a join see that and refuse. Several processes of one
    /// role under a name are how a name scales; two roles are two
    /// services that were given one name.
    ///
    /// Written in bytes that were padding, like `pid`: a lane written before
    /// it existed reads as length zero — a role that did not say — and the
    /// layout version stays where it is.
    pub(crate) role: [u8; LANE_ROLE_MAX],
    pub(crate) role_len: AtomicU8,
    _identity_padding: [u8; 3],
}

// Two cache lines exactly: the identity grew into padding, not past it.
const _: () = assert!(size_of::<LaneHeader>() == 128);

/// One directory watcher's slot: a wake word and a reactor flag, nothing else.
///
/// A watcher is not a lane. It serves no name, takes no frames and never
/// appears in the directory; it is only told when the directory moves, the
/// way a cell tells whoever waits on it. Every slot is woken on every
/// directory change and only one that is armed is rung, so the writer never
/// learns who is listening and nobody is elected to pass the news on. A
/// watcher that was not armed at that moment sees the directory generation
/// moved on its next look; the generation is the truth, the wake a hint.
///
/// As many slots as lanes: every process that can join the fleet can watch it
/// instead.
#[repr(C, align(64))]
pub(crate) struct WatcherHeader {
    /// Bumped on every directory change.
    pub(crate) changes: AtomicU32,
    /// Set while the watcher's Tokio task waits on its named socket. Cleared
    /// by the waker before it rings, so changes in a burst ring once.
    pub(crate) reactor: AtomicU32,
    /// The process that holds the slot, for the operator. Zero when free.
    pub(crate) pid: AtomicU32,
    /// What the watching process is, in the same words a lane uses (`edge`,
    /// `php`), so a reader can tell which side of a link a watcher is on.
    pub(crate) role: [u8; LANE_ROLE_MAX],
    pub(crate) role_len: AtomicU8,
    _padding: [u8; 43],
}

const _: () = assert!(size_of::<WatcherHeader>() == 64);

/// Words in one interest set.
pub(crate) const INTEREST_WORDS: usize = 7;
/// Bits in one interest set.
#[cfg_attr(not(feature = "events"), allow(dead_code))]
pub(crate) const INTEREST_BITS: usize = INTEREST_WORDS * 64;

/// What one lane or watcher wants to receive: a fixed-size set of routing-key
/// hashes, owned and written only by the slot's holder.
///
/// A set rather than a list, so there is no count to run out of: a false
/// positive forwards something nobody consumes, and the receiver's own
/// subscriptions drop it. `seq` is odd while the holder rewrites the set; a
/// reader that sees it odd, or changed across its read, reads again.
#[repr(C, align(64))]
pub(crate) struct InterestEntry {
    pub(crate) seq: AtomicU32,
    _padding: [u8; 4],
    pub(crate) bits: [AtomicU64; INTEREST_WORDS],
}

const _: () = assert!(size_of::<InterestEntry>() == 64);

/// One frame's slot. `seq` is its full turn; `claim` has two state bits and
/// a producer-record index. Only an acquired COMMITTED claim publishes bytes.
#[repr(C, align(64))]
pub(crate) struct SlotHeader {
    pub(crate) seq: AtomicU64,
    pub(crate) claim: AtomicU64,
    pub(crate) work_epoch: AtomicU64,
    pub(crate) work_claim: AtomicU64,
    pub(crate) len: AtomicU32,
    pub(crate) work_slot: AtomicU32,
    _padding: [u8; 24],
}

const _: () = assert!(size_of::<SlotHeader>() == 64);

/// What a writer must know to refuse correctly.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Admission {
    /// There is room and someone is reading.
    Accepted,
    /// The lane holds `capacity` frames the owner has not taken yet.
    Full,
    /// No live consumer. Writing would leave a request nobody answers.
    NoConsumer,
}

/// A lane's geometry, shared by both ends because Orbit refuses to open a
/// segment shaped differently from the code's.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct InboxGeometry {
    pub capacity: usize,
    pub payload_capacity: usize,
}

impl InboxGeometry {
    pub const fn new(
        capacity: usize,
        payload_capacity: usize,
    ) -> Self {
        Self { capacity, payload_capacity }
    }

    /// Bytes one lane occupies: its header, then a slot header and payload for
    /// every position.
    pub const fn lane_bytes(&self) -> usize {
        size_of::<LaneHeader>() + self.capacity * self.slot_bytes()
    }

    const fn slot_bytes(&self) -> usize {
        // Every SlotHeader (and the following lane/registry) requires 64-byte
        // alignment, even for a caller-selected odd payload capacity.
        (size_of::<SlotHeader>() + self.payload_capacity + 63) & !63
    }

    /// What a fleet's whole table occupies: the header, every lane, one
    /// watcher slot per lane, then one interest entry per lane and per
    /// watcher slot. Everything new sits after the lanes, so a lane's offset
    /// and alignment are what they were before.
    pub const fn segment_bytes(
        &self,
        fleet_capacity: usize,
    ) -> usize {
        size_of::<TableHeader>()
            + fleet_capacity
                * (self.lane_bytes()
                    + size_of::<WatcherHeader>()
                    + 2 * size_of::<InterestEntry>())
            + claims::registry_bytes(fleet_capacity, self.capacity)
            + crate::admission::bytes(fleet_capacity, self.capacity)
    }

    pub(crate) fn validate(&self) -> Result<()> {
        if self.capacity == 0 || !self.capacity.is_power_of_two() {
            return Err(Error::Malformed(
                "inbox capacity must be a power of two",
            ));
        }
        if self.payload_capacity == 0 {
            return Err(Error::Malformed(
                "inbox payload capacity must not be zero",
            ));
        }
        if self.capacity > u32::MAX as usize
            || self.payload_capacity > u32::MAX as usize
        {
            return Err(Error::Malformed(
                "inbox geometry exceeds its wire fields",
            ));
        }
        Ok(())
    }
}

// The header keeps its size across versions: new words take its padding.
const _: () = assert!(size_of::<TableHeader>() == 128);

/// The segment's own header, checked before a single lane is touched.
#[repr(C, align(64))]
pub(crate) struct TableHeader {
    pub(crate) magic: AtomicU32,
    pub(crate) version: AtomicU32,
    pub(crate) fleet_capacity: AtomicU32,
    pub(crate) capacity: AtomicU32,
    pub(crate) payload_capacity: AtomicU32,
    /// Bumped whenever a lane's identity changes: a claim publishing a name,
    /// or a release taking one away.
    ///
    /// Which lanes serve a name is settled by those two events and by nothing
    /// else, so a caller that has read it once may keep the answer until this
    /// number moves. Depth is not in it — depth changes with every frame and
    /// is read per request, because it is the load signal rather than the
    /// address.
    pub(crate) directory: AtomicU64,
    /// Nonzero while the fleet's owner wants senders to report unmet demand:
    /// its declared growth policy, written by the owner alone, after the
    /// bounds below.
    pub(crate) policy: AtomicU32,
    /// Nonzero while a report of unmet demand is pending: set by the first
    /// sender that finds every receiver full, cleared by the owner once it
    /// has acted. One episode, one wake.
    pub(crate) pressure: AtomicU32,
    /// The owner's declared bounds, so a supervisor of any kind reads them
    /// from the fleet rather than from a configuration of its own.
    pub(crate) growth_min: AtomicU32,
    pub(crate) growth_max: AtomicU32,
    pub(crate) growth_step: AtomicU32,
    _padding: [u8; 16],
}

/// A mapped inbox table.
///
/// Holds a raw pointer into shared memory rather than a slice, because the
/// bytes are written by other processes: a `&[u8]` would promise Rust that
/// nothing else mutates them, and something else always does.
pub struct Inbox {
    pub(crate) base: *mut u8,
    /// How many lanes the table holds.
    ///
    /// It is the fleet capacity today because a lane belongs to a node: a
    /// process claims the index it was given. If lanes were ever leased from a
    /// pool instead — so one process could hold several, one per service
    /// it serves — this is the number that would stop being the fleet's. The
    /// rest of the interface already speaks in lanes rather than nodes, so
    /// that change would not reach the edge.
    pub(crate) lanes: usize,
    pub(crate) geometry: InboxGeometry,
    /// Installed once, before this mapping is exposed to SHM publishers.
    producer: Option<claims::Producer>,
    /// Named descriptor wake used by a Tokio receiver. Memory-backed tables
    /// keep using their process-local path.
    #[cfg(unix)]
    bell: Option<crate::bell::Bell>,
}

// The pointer addresses shared memory whose only mutable state is atomics.
unsafe impl Send for Inbox {}
unsafe impl Sync for Inbox {}

impl Inbox {
    /// Take ownership of a mapped region as a fresh table.
    ///
    /// Only the table header is written. All-zero is already a table of free
    /// lanes, and a lane is set up by whoever takes it (`claim_lane`, `join`),
    /// so nothing here touches a lane's pages: the kernel commits a page when
    /// it is first written, and a lane nobody claims costs no memory. Zeroing
    /// the whole segment here once made every byte of it resident — 69 MiB
    /// for 32 lanes of 128 frames of 17 KiB, whether or not a lane was used.
    ///
    /// # Safety
    ///
    /// `base` must point at `geometry.segment_bytes(fleet_capacity)` writable
    /// bytes, all zero, that stay mapped for as long as this `Inbox` lives. A
    /// newly created shared-memory object is: `ftruncate` extends it with
    /// zeros.
    /// Raw constructors do not install a producer death hold. Use
    /// `LinkSegment` for interprocess publishing; a raw mapping alone is not
    /// a registered SHM producer. Direct use is for process-local storage.
    pub unsafe fn initialize(
        base: *mut u8,
        fleet_capacity: usize,
        geometry: InboxGeometry,
    ) -> Result<Self> {
        geometry.validate()?;
        if fleet_capacity == 0 || fleet_capacity > u16::MAX as usize {
            return Err(Error::Malformed(
                "inbox fleet capacity must fit a nonzero u16",
            ));
        }
        let inbox = Self {
            base,
            lanes: fleet_capacity,
            geometry,
            producer: None,
            #[cfg(unix)]
            bell: None,
        };

        let header = inbox.table_header();
        header.fleet_capacity.store(fleet_capacity as u32, Ordering::Relaxed);
        header.capacity.store(geometry.capacity as u32, Ordering::Relaxed);
        header
            .payload_capacity
            .store(geometry.payload_capacity as u32, Ordering::Relaxed);
        header.version.store(INBOX_VERSION, Ordering::Relaxed);
        // Magic last: a reader that sees it sees a finished header.
        header.magic.store(INBOX_MAGIC, Ordering::Release);
        Ok(inbox)
    }

    /// The fleet capacity and inbox geometry an existing table's creator
    /// recorded in its header, so a caller can adopt the owner's shape
    /// instead of supplying one.
    ///
    /// # Safety
    ///
    /// `base` maps at least a [`TableHeader`] of a region whose creator has
    /// released its initialization lock.
    pub(crate) unsafe fn persisted_shape(
        base: *const u8
    ) -> Result<(usize, InboxGeometry)> {
        let header = unsafe { &*base.cast::<TableHeader>() };
        if header.magic.load(Ordering::Acquire) != INBOX_MAGIC {
            return Err(Error::Malformed(
                "inbox segment is not an inbox table",
            ));
        }
        if header.version.load(Ordering::Relaxed) != INBOX_VERSION {
            return Err(Error::Malformed(
                "inbox segment was written by another layout version",
            ));
        }
        let geometry = InboxGeometry::new(
            header.capacity.load(Ordering::Relaxed) as usize,
            header.payload_capacity.load(Ordering::Relaxed) as usize,
        );
        geometry.validate()?;
        Ok((header.fleet_capacity.load(Ordering::Relaxed) as usize, geometry))
    }

    /// Attach to a table another process created, refusing anything whose
    /// header does not match this build.
    ///
    /// # Safety
    ///
    /// As [`Inbox::initialize`].
    pub unsafe fn attach(
        base: *mut u8,
        fleet_capacity: usize,
        geometry: InboxGeometry,
    ) -> Result<Self> {
        geometry.validate()?;
        if fleet_capacity == 0 || fleet_capacity > u16::MAX as usize {
            return Err(Error::Malformed(
                "inbox fleet capacity must fit a nonzero u16",
            ));
        }
        let inbox = Self {
            base,
            lanes: fleet_capacity,
            geometry,
            producer: None,
            #[cfg(unix)]
            bell: None,
        };
        let header = inbox.table_header();
        if header.magic.load(Ordering::Acquire) != INBOX_MAGIC {
            return Err(Error::Malformed(
                "inbox segment is not an inbox table",
            ));
        }
        if header.version.load(Ordering::Relaxed) != INBOX_VERSION {
            return Err(Error::Malformed(
                "inbox segment was written by another layout version",
            ));
        }
        if header.fleet_capacity.load(Ordering::Relaxed) as usize
            != fleet_capacity
            || header.capacity.load(Ordering::Relaxed) as usize
                != geometry.capacity
            || header.payload_capacity.load(Ordering::Relaxed) as usize
                != geometry.payload_capacity
        {
            return Err(Error::Malformed(
                "inbox segment geometry differs from this build",
            ));
        }
        Ok(inbox)
    }

    pub fn geometry(&self) -> InboxGeometry {
        self.geometry
    }

    pub fn lanes(&self) -> usize {
        self.lanes
    }

    /// The lane lifetime to fence writes and capacity waits against.
    pub fn lane_epoch(
        &self,
        lane: usize,
    ) -> Result<u64> {
        self.check_lane(lane)?;
        Ok(self.lane_header(lane).epoch.load(Ordering::Acquire))
    }

    /// Advertise paired body support after the receiver's tables are ready.
    /// The caller must own the lane. Older receivers never write this field,
    /// and the lane's epoch changes even when one of them takes over.
    pub fn advertise_paired_bodies(
        &self,
        lane: usize,
    ) -> Result<()> {
        let epoch = u32::try_from(self.lane_epoch(lane)?).map_err(|_| {
            Error::Malformed("paired body advertisement epoch exhausted")
        })?;
        let previous = self
            .lane_header(lane)
            .paired_bodies_epoch
            .swap(epoch, Ordering::AcqRel);
        if previous != epoch {
            self.table_header().directory.fetch_add(1, Ordering::AcqRel);
            self.announce_directory();
        }
        Ok(())
    }

    /// The current epoch in which the receiver advertised paired bodies.
    pub fn paired_bodies_epoch(
        &self,
        lane: usize,
    ) -> Option<u64> {
        let epoch = self.lane_epoch(lane).ok()?;
        let stamp =
            self.lane_header(lane).paired_bodies_epoch.load(Ordering::Acquire);
        (stamp != 0 && u64::from(stamp) == epoch).then_some(epoch)
    }

    /// Claim a lane after fencing out its previous reader. Discard completed
    /// old work without resetting full queue positions. In-flight live writers
    /// retain ownership; their eventual frames are skipped by destination epoch.
    /// Named SHM users should use `LinkSegment::join`, which takes the hold.
    pub fn claim_lane(
        &self,
        lane_index: usize,
        service: &str,
        role: &str,
        incarnation: u64,
    ) -> Result<()> {
        self.claim_lane_with_capacity(
            lane_index,
            service,
            role,
            incarnation,
            None,
        )
    }

    /// Publish the work bound before making this lane discoverable.
    pub fn claim_lane_with_capacity(
        &self,
        lane_index: usize,
        service: &str,
        role: &str,
        incarnation: u64,
        capacity: Option<usize>,
    ) -> Result<()> {
        self.check_lane(lane_index)?;
        check_identity(service, role)?;
        self.validate_work_capacity(capacity)?;
        let pid = ProcessOwner::current()?.pid();
        self.reset_lane(lane_index)?;
        self.configure_capacity(lane_index, capacity)?;
        let lane = self.lane_header(lane_index);
        lane.consumers.store(1, Ordering::Release);
        self.publish_identity(lane, service, role, incarnation, pid);
        self.wake(lane_index, lane);
        Ok(())
    }

    /// Take a free lane and say which service this process serves.
    ///
    /// There is no pool and no allocator. A service process starts on its
    /// own — its own binary, its own virtual environment, its own moment — and
    /// introduces itself here. Several processes serving the same name know
    /// nothing about each other and do not need to: the lane is won with a
    /// compare-and-swap on the consumer count, so exactly one of them takes
    /// it.
    ///
    /// The name is published after the lane is won and cleared. In between,
    /// the lane is claimed but anonymous — and [`Inbox::targets`] matches on
    /// the name, so nothing is addressed to a lane that is still being made
    /// ready.
    ///
    /// The index that comes back is this process's address in the fleet, for
    /// the inbox and for its body streams alike.
    ///
    /// `hold` takes a free lane's hold before the lane is claimed: whatever it
    /// returns lives as long as the claim, and a lane it cannot hold is some
    /// live process's. Over shared memory that is the lane's lock
    /// ([`LinkSegment::join`](super::LinkSegment::join)); a
    /// table in private memory has nobody else to hold it.
    ///
    /// A name already served by another role is refused, naming the lane
    /// and process that hold it: two roles under one name would share this
    /// inbox and split its requests between them. The check runs before the
    /// lane is taken and again once this lane is published, because two
    /// processes of different roles joining at the same moment each pass
    /// the first; the second sees the other, and both refuse — a name given to
    /// two services is a configuration error either way, and it is caught
    /// at the door rather than half served.
    pub fn join<H>(
        &self,
        service: &str,
        role: &str,
        incarnation: u64,
        hold: impl FnMut(usize) -> Result<Option<H>>,
    ) -> Result<(usize, H)> {
        self.join_with_capacity(service, role, incarnation, None, hold)
    }

    pub fn join_with_capacity<H>(
        &self,
        service: &str,
        role: &str,
        incarnation: u64,
        capacity: Option<usize>,
        mut hold: impl FnMut(usize) -> Result<Option<H>>,
    ) -> Result<(usize, H)> {
        check_identity(service, role)?;
        self.validate_work_capacity(capacity)?;
        self.refuse_other_role(service, role, None)?;
        let pid = ProcessOwner::current()?.pid();
        for lane_index in 0..self.lanes {
            let lane = self.lane_header(lane_index);
            if lane.consumers.load(Ordering::Acquire) != 0 {
                continue;
            }
            let Some(held) = hold(lane_index)? else {
                continue;
            };
            if lane
                .consumers
                .compare_exchange(0, 1, Ordering::AcqRel, Ordering::Acquire)
                .is_err()
            {
                continue;
            }
            self.reset_lane(lane_index)?;
            self.configure_capacity(lane_index, capacity)?;
            self.publish_identity(lane, service, role, incarnation, pid);
            if let Err(conflict) =
                self.refuse_other_role(service, role, Some(lane_index))
            {
                let _ = self.release_lane(lane_index);
                return Err(conflict);
            }
            self.wake(lane_index, lane);
            return Ok((lane_index, held));
        }
        Err(Error::NoLane)
    }

    /// Take back a claimed lane whose owner is known to be gone, and say who it
    /// was: the incarnation is what its body streams are stamped with.
    ///
    /// The caller vouches for the death — over shared memory, by holding the
    /// lane's lock. `None` when the lane was not claimed.
    pub fn reclaim(
        &self,
        lane_index: usize,
    ) -> Result<Option<Reclaimed>> {
        self.check_lane(lane_index)?;
        let lane = self.lane_header(lane_index);
        if lane.consumers.load(Ordering::Acquire) == 0 {
            return Ok(None);
        }
        let reclaimed = Reclaimed {
            lane: lane_index,
            incarnation: lane.incarnation.load(Ordering::Acquire),
            pid: lane.pid.load(Ordering::Acquire),
        };
        self.release_lane(lane_index)?;
        Ok(Some(reclaimed))
    }

    /// A lane that serves `service` for another role, as an error.
    ///
    /// Only claimed lanes count: a lane its owner released holds nothing, and a
    /// lane a dead process left is taken back before a join gets here.
    fn refuse_other_role(
        &self,
        service: &str,
        role: &str,
        own: Option<usize>,
    ) -> Result<()> {
        for lane_index in self.serving(service) {
            if Some(lane_index) == own {
                continue;
            }
            let lane = self.lane_header(lane_index);
            if lane.consumers.load(Ordering::Acquire) == 0 {
                continue;
            }
            let held_by = self.role(lane_index)?.unwrap_or_default();
            if held_by != role {
                return Err(Error::RoleConflict {
                    name: service.to_owned(),
                    role: role.to_owned(),
                    held_by: if held_by.is_empty() {
                        "an unnamed role".into()
                    } else {
                        held_by
                    },
                    lane: lane_index,
                    pid: lane.pid.load(Ordering::Acquire),
                });
            }
        }
        Ok(())
    }

    /// Park until something changes in this lane.
    ///
    /// `expected` is the value [`Inbox::wait_word`] gave before the caller
    /// last drained, and the kernel compares it again under its own lock: a
    /// writer that committed in between means the wait returns instead of
    /// starting. There is no interval and no deadline here — the wait ends
    /// because someone wrote, or because [`Inbox::nudge`] woke it on purpose.
    pub fn park(
        &self,
        lane_index: usize,
        expected: u32,
    ) -> Result<()> {
        self.check_lane(lane_index)?;
        let lane = self.lane_header(lane_index);
        // Announce before waiting: a writer bumps the word and then reads this
        // count, so the two orders cross. If it reads zero anyway, it bumped
        // the word first and the kernel's own comparison ends the wait below.
        lane.waiters.fetch_add(1, Ordering::AcqRel);
        let waited = orbit_core::sync::wait_word(&lane.changes, expected);
        lane.waiters.fetch_sub(1, Ordering::AcqRel);
        waited.map_err(Error::Io)
    }

    /// Wake this lane's reader without writing anything.
    ///
    /// For the one case that is not a frame: the owner is shutting down and
    /// the thread parked on the lane has to notice. A flag the reader checks
    /// plus this, rather than a timeout it would otherwise have to wait out.
    pub fn nudge(
        &self,
        lane_index: usize,
    ) -> Result<()> {
        self.check_lane(lane_index)?;
        self.wake(lane_index, self.lane_header(lane_index));
        Ok(())
    }

    /// The service this lane serves, if it is claimed.
    pub fn service(
        &self,
        lane_index: usize,
    ) -> Result<Option<String>> {
        self.check_lane(lane_index)?;
        let lane = self.lane_header(lane_index);
        let len = lane.service_len.load(Ordering::Acquire) as usize;
        if len == 0 || len > LANE_NAME_MAX {
            return Ok(None);
        }
        let bytes =
            unsafe { std::slice::from_raw_parts(lane.service.as_ptr(), len) };
        Ok(String::from_utf8(bytes.to_vec()).ok())
    }

    /// The process that claimed this lane, if it said.
    pub fn owner(
        &self,
        lane_index: usize,
    ) -> Result<Option<u32>> {
        self.check_lane(lane_index)?;
        if self.consumers(lane_index)? == 0 {
            return Ok(None);
        }
        Ok(match self.lane_header(lane_index).pid.load(Ordering::Acquire) {
            0 => None,
            pid => Some(pid),
        })
    }

    /// The last process incarnation on a lane, including one withdrawn while
    /// its accepted exchanges drain. Not a routing or liveness observation.
    pub fn last_owner(
        &self,
        lane_index: usize,
    ) -> Result<Option<(u32, u64)>> {
        self.check_lane(lane_index)?;
        let lane = self.lane_header(lane_index);
        let pid = lane.pid.load(Ordering::Acquire);
        Ok((pid != 0).then(|| (pid, lane.incarnation.load(Ordering::Acquire))))
    }

    /// What serves this lane's name, if its owner said.
    /// Whether this lane's role is one `accept` takes. The role is copied
    /// into a fixed buffer, as [`Inbox::role`] copies it, but never into a
    /// `String`: callers ask this of every lane for every event they route.
    pub fn role_accepted(
        &self,
        lane_index: usize,
        accept: impl FnOnce(&str) -> bool,
    ) -> bool {
        if self.check_lane(lane_index).is_err() {
            return false;
        }
        let lane = self.lane_header(lane_index);
        accept_role(&lane.role, &lane.role_len, accept)
    }

    /// Whether this watcher slot is held and its role is one `accept` takes.
    /// Allocation-free, as [`Inbox::role_accepted`].
    pub fn watcher_role_accepted(
        &self,
        slot: usize,
        accept: impl FnOnce(&str) -> bool,
    ) -> bool {
        if self.check_lane(slot).is_err() {
            return false;
        }
        let watcher = self.watcher_header(slot);
        watcher.pid.load(Ordering::Acquire) != 0
            && accept_role(&watcher.role, &watcher.role_len, accept)
    }

    pub fn role(
        &self,
        lane_index: usize,
    ) -> Result<Option<String>> {
        self.check_lane(lane_index)?;
        let lane = self.lane_header(lane_index);
        let len = lane.role_len.load(Ordering::Acquire) as usize;
        if len == 0 || len > LANE_ROLE_MAX {
            return Ok(None);
        }
        let bytes =
            unsafe { std::slice::from_raw_parts(lane.role.as_ptr(), len) };
        Ok(String::from_utf8(bytes.to_vec()).ok())
    }

    /// Whether this lane advertises exactly this service.
    ///
    /// Compared as bytes. [`Inbox::service`] allocates a `String`, and
    /// this is on the dispatch path: every lane in the table is asked, for
    /// every exchange. An allocation per lane per request made the table cost
    /// grow with the fleet, which is the one thing a target scan must not do.
    fn serves(
        &self,
        lane_index: usize,
        service: &[u8],
    ) -> bool {
        let lane = self.lane_header(lane_index);
        let len = lane.service_len.load(Ordering::Acquire) as usize;
        if len != service.len() || len > LANE_NAME_MAX {
            return false;
        }
        let name =
            unsafe { std::slice::from_raw_parts(lane.service.as_ptr(), len) };
        name == service
    }

    /// Lanes serving `service` that are ready to take a frame, idlest
    /// first.
    ///
    /// This is the whole target-selection story: not a registry, not a health
    /// report, not a load metric anyone publishes — the queue an edge is about
    /// to write into, read directly. A worker that joined a moment ago is
    /// already here; one that left is already gone.
    pub fn targets(
        &self,
        service: &str,
    ) -> Vec<(usize, u64)> {
        self.ready(&self.serving(service))
    }

    /// The generation of the lane directory: which lanes serve which name.
    ///
    /// A caller that resolved a name while this number held may use that
    /// answer until it moves. It changes when a process claims a lane or
    /// gives one up, and at no other time — a frame written, read or refused
    /// leaves it alone.
    pub fn directory(&self) -> u64 {
        self.table_header().directory.load(Ordering::Acquire)
    }

    /// The fleet's owner declares its growth policy: `Some` asks senders to
    /// report unmet demand and publishes the bounds, `None` (static) asks for
    /// nothing, and `report_pressure` then writes nothing.
    pub fn set_growth_policy(
        &self,
        policy: Option<GrowthPolicy>,
    ) {
        let header = self.table_header();
        match policy {
            Some(policy) => {
                header.growth_min.store(policy.min.into(), Ordering::Relaxed);
                header.growth_max.store(policy.max.into(), Ordering::Relaxed);
                header.growth_step.store(policy.step.into(), Ordering::Relaxed);
                header.policy.store(1, Ordering::Release);
            }
            None => header.policy.store(0, Ordering::Release),
        }
    }

    /// The growth policy the owner declared, if any.
    pub fn growth_policy(&self) -> Option<GrowthPolicy> {
        let header = self.table_header();
        if header.policy.load(Ordering::Acquire) == 0 {
            return None;
        }
        let bound = |word: &AtomicU32| {
            u16::try_from(word.load(Ordering::Relaxed)).unwrap_or(u16::MAX)
        };
        Some(GrowthPolicy {
            min: bound(&header.growth_min),
            max: bound(&header.growth_max),
            step: bound(&header.growth_step),
        })
    }

    /// A sender that found every receiver full reports unmet demand. Only
    /// the first report of an episode writes and rings the directory
    /// watchers; every later one costs a load and returns `false`, so any
    /// number of senders produce one wake. Nothing is written unless the
    /// owner asked for reports.
    pub fn report_pressure(&self) -> bool {
        let header = self.table_header();
        if header.policy.load(Ordering::Acquire) == 0
            || header.pressure.load(Ordering::Acquire) != 0
            || header
                .pressure
                .compare_exchange(0, 1, Ordering::AcqRel, Ordering::Acquire)
                .is_err()
        {
            return false;
        }
        for slot in 0..self.lanes {
            self.wake_watcher(slot);
        }
        true
    }

    pub fn pressure_pending(&self) -> bool {
        self.table_header().pressure.load(Ordering::Acquire) != 0
    }

    /// The owner ends the episode once it has acted; the next report starts
    /// another. Returns whether one was pending.
    pub fn take_pressure(&self) -> bool {
        self.table_header().pressure.swap(0, Ordering::AcqRel) != 0
    }

    /// Which lanes advertise this name, live or not.
    ///
    /// The walk over every lane lives here, so a caller that keeps the result
    /// pays it once per directory generation rather than once per exchange.
    /// Presence and capacity are deliberately not checked: those change with
    /// traffic, and a list that changed with traffic could not be kept.
    pub fn serving(
        &self,
        service: &str,
    ) -> Vec<usize> {
        let wanted = service.as_bytes();
        (0..self.lanes).filter(|lane| self.serves(*lane, wanted)).collect()
    }

    /// Of these lanes, the ones that will take a frame now, idlest first.
    ///
    /// This is the per-exchange half: admission and depth are read every time
    /// because both answer "now", and depth is what the choice is made on.
    pub fn ready(
        &self,
        lanes: &[usize],
    ) -> Vec<(usize, u64)> {
        let mut found: Vec<(usize, u64)> = lanes
            .iter()
            .copied()
            .filter(|lane| {
                matches!(self.admits(*lane), Ok(Admission::Accepted))
            })
            .filter_map(|lane| self.depth(lane).ok().map(|depth| (lane, depth)))
            .collect();
        found.sort_by_key(|(_, depth)| *depth);
        found
    }

    /// The idlest of these lanes that will take a frame now: the first
    /// [`Inbox::ready`] would list, read without building the list.
    pub fn idlest(
        &self,
        lanes: &[usize],
    ) -> Option<(usize, u64)> {
        lanes
            .iter()
            .copied()
            .filter(|lane| {
                matches!(self.admits(*lane), Ok(Admission::Accepted))
            })
            .filter_map(|lane| self.depth(lane).ok().map(|depth| (lane, depth)))
            .min_by_key(|(_, depth)| *depth)
    }

    /// Give up a lane: its owner is leaving and writers should stop choosing
    /// it. In-flight frames are left where they are; the next incarnation
    /// clears them.
    pub fn release_lane(
        &self,
        lane_index: usize,
    ) -> Result<()> {
        self.check_lane(lane_index)?;
        let lane = self.lane_header(lane_index);
        lane.consumers.store(0, Ordering::Release);
        lane.service_len.store(0, Ordering::Release);
        lane.role_len.store(0, Ordering::Release);
        // Keep the ownership stamp until the next claim. Withdrawing from
        // routing is not death: accepted streams may still be draining. A
        // later confirmed process exit must still be able to end those sides.
        self.clear_interest(lane_index);
        std::sync::atomic::fence(Ordering::SeqCst);
        self.capacity_changed(lane_index);
        self.table_header().directory.fetch_add(1, Ordering::AcqRel);
        self.wake(lane_index, lane);
        self.announce_directory();
        Ok(())
    }

    /// Whether a writer may choose this lane, and why not when it may not.
    ///
    /// Capacity and presence, never a duration: a writer refused here has been
    /// refused now, not after waiting.
    pub fn admits(
        &self,
        lane_index: usize,
    ) -> Result<Admission> {
        self.check_lane(lane_index)?;
        let lane = self.lane_header(lane_index);
        if lane.consumers.load(Ordering::Acquire) == 0 {
            return Ok(Admission::NoConsumer);
        }
        let read = lane.read.load(Ordering::Acquire);
        // Read the consumer first. A producer may advance `reserve` between
        // these loads, but that only makes the snapshot conservatively
        // deeper. The opposite order can pair an old reserve with a newer
        // read and wrap the subtraction, falsely reporting a nearly empty
        // lane as full.
        let reserve = lane.reserve.load(Ordering::Acquire);
        if reserve.wrapping_sub(read) >= self.geometry.capacity as u64 {
            return Ok(Admission::Full);
        }
        Ok(Admission::Accepted)
    }

    /// Frames written to this lane that its owner has not taken yet.
    ///
    /// This is what lets an edge choose a target by reading rather than
    /// guessing: with a socket you would need the other side to report its
    /// load; here the queue is the shared memory you are about to write into.
    pub fn depth(
        &self,
        lane_index: usize,
    ) -> Result<u64> {
        self.check_lane(lane_index)?;
        let lane = self.lane_header(lane_index);
        let read = lane.read.load(Ordering::Acquire);
        let reserve = lane.reserve.load(Ordering::Acquire);
        Ok(reserve.wrapping_sub(read))
    }

    pub fn consumers(
        &self,
        lane_index: usize,
    ) -> Result<u32> {
        self.check_lane(lane_index)?;
        Ok(self.lane_header(lane_index).consumers.load(Ordering::Acquire))
    }

    pub fn incarnation(
        &self,
        lane_index: usize,
    ) -> Result<u64> {
        self.check_lane(lane_index)?;
        Ok(self.lane_header(lane_index).incarnation.load(Ordering::Acquire))
    }

    /// Put one frame in a node's lane.
    ///
    /// Bounded admission: claim races help the winner and try a later turn,
    /// with at most `capacity` attempts. Full capacity or an exhausted
    /// contention budget returns `InboxFull`. A producer whose every record
    /// names a frame not read yet, on any lane, gets `ProducerBusy`: it can
    /// wait for a reader with `LinkSegment::record_released`. Helpers never
    /// commit another producer's bytes.
    pub fn write(
        &self,
        lane_index: usize,
        payload: &[u8],
    ) -> Result<u64> {
        self.write_vectored(lane_index, &[payload])
    }

    /// [`Inbox::write`] for a frame held in pieces — a head encoded here and a
    /// body that already has an owner — copied into the slot one after the
    /// other, so they need not be joined into one buffer first.
    pub fn write_vectored(
        &self,
        lane_index: usize,
        parts: &[&[u8]],
    ) -> Result<u64> {
        self.write_frame(lane_index, parts, None, None, false)
    }

    /// Send only to the specified receiver epoch, including after reserving
    /// the producer frame. A replacement never receives this publication.
    pub fn write_vectored_at_epoch(
        &self,
        lane: usize,
        epoch: u64,
        parts: &[&[u8]],
    ) -> Result<u64> {
        self.write_frame(lane, parts, None, Some(epoch), false)
    }

    /// A reply write that distinguishes a full inbox from claim contention.
    pub fn write_reply_at_epoch(
        &self,
        lane: usize,
        epoch: u64,
        parts: &[&[u8]],
    ) -> Result<u64> {
        self.write_frame(lane, parts, None, Some(epoch), true)
    }

    pub(crate) fn write_work(
        &self,
        ticket: crate::WorkTicket,
        parts: &[&[u8]],
    ) -> Result<u64> {
        self.check_work(ticket)?;
        self.write_frame(
            usize::from(ticket.lane),
            parts,
            Some(ticket),
            Some(ticket.epoch),
            false,
        )
    }

    fn write_frame(
        &self,
        lane_index: usize,
        parts: &[&[u8]],
        work: Option<crate::WorkTicket>,
        epoch: Option<u64>,
        reply: bool,
    ) -> Result<u64> {
        self.check_lane(lane_index)?;
        if reply
            && (self.lane_epoch(lane_index)? != epoch.unwrap_or_default()
                || self.consumers(lane_index)? == 0)
        {
            return Err(Error::NoConsumer);
        }
        let len = parts
            .iter()
            .try_fold(0usize, |len, part| len.checked_add(part.len()))
            .ok_or(Error::FrameTooLarge)?;
        if len > self.geometry.payload_capacity {
            return Err(Error::FrameTooLarge);
        }
        let mut reservation = match self.reserve_frame(lane_index) {
            Err(Error::InboxContended) if !reply => {
                return Err(Error::InboxFull);
            }
            result => result?,
        };
        if epoch.is_some_and(|epoch| epoch != reservation.epoch)
            || (reply && self.consumers(lane_index)? == 0)
        {
            return Err(Error::NoConsumer);
        }
        let position = reservation.position;
        let slot = self.slot_header(lane_index, position);
        let mut at = self.payload_ptr(lane_index, position);
        for part in parts {
            // SAFETY: the reservation owns this slot's payload until it
            // commits, and the parts together fit its capacity.
            unsafe {
                std::ptr::copy_nonoverlapping(part.as_ptr(), at, part.len());
                at = at.add(part.len());
            }
        }
        #[cfg(test)]
        claims::checkpoint("payload");
        if let Some(ticket) = work {
            slot.work_epoch.store(ticket.epoch, Ordering::Relaxed);
            slot.work_slot.store(ticket.slot, Ordering::Relaxed);
            slot.work_claim.store(ticket.claim, Ordering::Relaxed);
        } else {
            slot.work_claim.store(0, Ordering::Relaxed);
        }
        slot.len.store(len as u32, Ordering::Relaxed);
        // Admission is not publication: only COMMITTED releases these bytes.
        slot.claim.store(reservation.claim(COMMITTED), Ordering::Release);
        #[cfg(test)]
        claims::checkpoint("committed");
        reservation.committed = true;
        self.wake(lane_index, self.lane_header(lane_index));
        Ok(position)
    }

    /// Capture the exclusive upper position of currently reserved turns.
    /// After recovering a dead producer, its committed frames precede this
    /// position even when a still-live producer owns an earlier turn.
    pub fn reserved_through(
        &self,
        lane: usize,
    ) -> Result<u64> {
        self.check_lane(lane)?;
        Ok(self.lane_header(lane).reserve.load(Ordering::Acquire))
    }

    /// The next turn the single reader will consume.
    pub fn read_position(
        &self,
        lane: usize,
    ) -> Result<u64> {
        self.check_lane(lane)?;
        Ok(self.lane_header(lane).read.load(Ordering::Acquire))
    }

    /// Take the next frame from this node's own lane, if one is there.
    ///
    /// Only the lane's owner may call this. It copies out rather than lending
    /// a slice, because the slot is released the moment it returns and another
    /// process may fill it immediately.
    pub fn read(
        &self,
        lane_index: usize,
        out: &mut Vec<u8>,
    ) -> Result<bool> {
        match self.read_frame(lane_index, out)? {
            None => Ok(false),
            Some(None) => Ok(true),
            Some(Some(ticket)) => {
                self.cancel_work(ticket);
                Err(Error::Malformed(
                    "work frames require an admission-aware receiver",
                ))
            }
        }
    }

    /// Copy a frame and its optional admission identity. Only the owning
    /// receiver may read, then accept work before dispatching its payload.
    pub fn read_frame(
        &self,
        lane_index: usize,
        out: &mut Vec<u8>,
    ) -> Result<Option<Option<crate::WorkTicket>>> {
        self.read_frame_before(lane_index, out, None)
    }

    pub(crate) fn read_frame_before(
        &self,
        lane_index: usize,
        out: &mut Vec<u8>,
        boundary: Option<u64>,
    ) -> Result<Option<Option<crate::WorkTicket>>> {
        self.check_lane(lane_index)?;
        let lane = self.lane_header(lane_index);
        for _ in 0..self.geometry.capacity {
            let position = lane.read.load(Ordering::Relaxed);
            if boundary.is_some_and(|boundary| position >= boundary)
                || position >= lane.reserve.load(Ordering::Acquire)
            {
                return Ok(None);
            }
            let slot = self.slot_header(lane_index, position);
            let claim = slot.claim.load(Ordering::Acquire);
            if slot.seq.load(Ordering::Acquire) != position
                || !matches!(claim & 3, COMMITTED | CANCELLED)
            {
                return Ok(None);
            }
            let intent = self.intent_for_claim(claim)?;
            if intent.position != position || intent.lane != lane_index {
                return Err(Error::Malformed(
                    "committed inbox intent has the wrong turn",
                ));
            }
            let deliver = claim & 3 == COMMITTED
                && intent.incarnation == lane.epoch.load(Ordering::Acquire);
            let work_claim = slot.work_claim.load(Ordering::Relaxed);
            let work = (work_claim != 0).then(|| crate::WorkTicket {
                lane: lane_index as u16,
                epoch: slot.work_epoch.load(Ordering::Relaxed),
                slot: slot.work_slot.load(Ordering::Relaxed),
                claim: work_claim,
            });
            if deliver {
                let len = slot.len.load(Ordering::Relaxed) as usize;
                if len > self.geometry.payload_capacity {
                    return Err(Error::Malformed(
                        "committed inbox length is invalid",
                    ));
                }
                out.clear();
                out.reserve(len);
                unsafe {
                    std::ptr::copy_nonoverlapping(
                        self.payload_ptr(lane_index, position),
                        out.spare_capacity_mut().as_mut_ptr().cast::<u8>(),
                        len,
                    );
                    out.set_len(len);
                }
            }
            self.consume_frame(lane_index, position, claim)?;
            if deliver {
                return Ok(Some(work));
            }
        }
        Ok(None)
    }

    /// The word a parked reader waits on, and its current value.
    pub fn wait_word(
        &self,
        lane_index: usize,
    ) -> Result<(&AtomicU32, u32)> {
        self.check_lane(lane_index)?;
        let lane = self.lane_header(lane_index);
        Ok((&lane.changes, lane.changes.load(Ordering::Acquire)))
    }

    /// Retire queued work only after the caller has acquired the consumer's
    /// kernel hold and withdrawn the lane. No live reader may still use it.
    pub(crate) fn retire_lane(
        &self,
        lane_index: usize,
    ) -> Result<()> {
        self.check_lane(lane_index)?;
        if self.consumers(lane_index)? != 0 {
            return Err(Error::Malformed("retiring an advertised inbox lane"));
        }
        self.reset_lane(lane_index)
    }

    fn reset_lane(
        &self,
        lane_index: usize,
    ) -> Result<()> {
        let lane = self.lane_header(lane_index);
        // The initial all-zero lane has no published incarnation. Thereafter
        // full positions never reset, including after a consumer replacement.
        let next_epoch = lane
            .epoch
            .load(Ordering::Acquire)
            .checked_add(1)
            .ok_or(Error::Malformed("inbox lane generation exhausted"))?;
        if lane.initialized.load(Ordering::Acquire) == 0 {
            for position in 0..self.geometry.capacity {
                let slot = self.slot_header(lane_index, position as u64);
                slot.seq.store(position as u64, Ordering::Release);
            }
            lane.initialized.store(1, Ordering::Release);
        } else {
            for _ in 0..self.geometry.capacity {
                let position = lane.read.load(Ordering::Relaxed);
                if position >= lane.reserve.load(Ordering::Acquire) {
                    break;
                }
                if self
                    .slot_header(lane_index, position)
                    .seq
                    .load(Ordering::Acquire)
                    > position
                {
                    // The previous reader released this turn but died before
                    // publishing head. Never reset the monotonic cursor.
                    let claim = self
                        .slot_header(lane_index, position)
                        .claim
                        .load(Ordering::Acquire);
                    if matches!(claim & 3, COMMITTED | CANCELLED)
                        && self.intent_for_claim(claim)?.position == position
                    {
                        self.consume_frame(lane_index, position, claim)?;
                    } else {
                        lane.read.store(position + 1, Ordering::Release);
                    }
                    continue;
                }
                let claim = self
                    .slot_header(lane_index, position)
                    .claim
                    .load(Ordering::Acquire);
                if !matches!(claim & 3, COMMITTED | CANCELLED) {
                    break;
                }
                self.consume_frame(lane_index, position, claim)?;
            }
        }
        // Not `consumers`: presence is how a lane is won, and clearing it here
        // would hand a just-claimed lane back to the next process looking for
        // a free one. `claim_lane` sets it after this; `join` set it before.
        lane.service_len.store(0, Ordering::Relaxed);
        lane.epoch.store(next_epoch, Ordering::Release);
        self.advertise_inbox_space(lane_index, next_epoch);
        std::sync::atomic::fence(Ordering::SeqCst);
        self.inbox_space_changed(lane_index);
        lane.role_len.store(0, Ordering::Relaxed);
        lane.waiters.store(0, Ordering::Relaxed);
        lane.reactor.store(0, Ordering::Relaxed);
        self.clear_interest(lane_index);
        self.recover_work(lane_index);
        self.configure_capacity(lane_index, None)?;
        Ok(())
    }

    /// Write a lane's identity: the bytes first, the length last, so a reader
    /// that sees a length sees the name it belongs to.
    fn publish_identity(
        &self,
        lane: &LaneHeader,
        service: &str,
        role: &str,
        incarnation: u64,
        pid: u32,
    ) {
        unsafe {
            std::ptr::copy_nonoverlapping(
                service.as_ptr(),
                lane.service.as_ptr().cast_mut(),
                service.len(),
            );
            std::ptr::copy_nonoverlapping(
                role.as_ptr(),
                lane.role.as_ptr().cast_mut(),
                role.len(),
            );
        }
        // The role before the name: a reader that sees the name sees who
        // serves it.
        lane.role_len.store(role.len() as u8, Ordering::Release);
        lane.service_len.store(service.len() as u8, Ordering::Release);
        lane.incarnation.store(incarnation, Ordering::Release);
        lane.pid.store(pid, Ordering::Release);
        // Last, and after the name: a caller that sees the new number sees
        // every byte that made it new.
        self.table_header().directory.fetch_add(1, Ordering::AcqRel);
        self.announce_directory();
    }

    /// Wake every claimed lane and every watcher once: the directory moved.
    /// A reader woken with no frame compares [`Inbox::directory`] with the
    /// value it last saw, so a process learns who joined or left from the
    /// lane it already reads, or from its watcher slot when it holds no lane,
    /// with no thread, registry or interval of its own. Claims and releases
    /// are rare; traffic never comes through here.
    fn announce_directory(&self) {
        for lane_index in 0..self.lanes {
            let lane = self.lane_header(lane_index);
            if lane.consumers.load(Ordering::Acquire) != 0 {
                self.wake(lane_index, lane);
            }
        }
        for slot in 0..self.lanes {
            self.wake_watcher(slot);
        }
    }

    /// Bump a watcher's word and ring it if it is waiting. A free slot or one
    /// whose holder is not waiting costs one atomic add.
    fn wake_watcher(
        &self,
        slot: usize,
    ) {
        let watcher = self.watcher_header(slot);
        watcher.changes.fetch_add(1, Ordering::SeqCst);
        #[cfg(unix)]
        if let Some(bell) = &self.bell
            && let Err(error) = ring_armed(&watcher.reactor, || {
                bell.ring(crate::bell::Doorbell::Watcher(slot))
            })
        {
            tracing::warn!(slot, %error, "Link watcher wake failed");
        }
    }

    /// Bump the word a reader watches, and wake it if one is parked.
    ///
    /// The bump comes first and the waiter count is read after, so a reader
    /// that registered itself in between is still seen; one that registers
    /// after finds the word already moved and does not start the wait.
    pub(crate) fn wake(
        &self,
        lane_index: usize,
        lane: &LaneHeader,
    ) {
        lane.changes.fetch_add(1, Ordering::SeqCst);
        if lane.waiters.load(Ordering::SeqCst) > 0 {
            let _ = orbit_core::sync::wake_word(&lane.changes);
        }
        #[cfg(unix)]
        if let Some(bell) = &self.bell
            && let Err(error) = ring_armed(&lane.reactor, || {
                bell.ring_lane(lane_index, lane.epoch.load(Ordering::Acquire))
            })
        {
            tracing::warn!(lane = lane_index, %error, "Link lane wake failed");
        }
    }

    /// Tell the process waiting to adopt this Link to look again. Only a
    /// hint: nobody may be waiting, and the waiter rechecks what exists.
    #[cfg(unix)]
    pub(crate) fn ring_adopter(&self) {
        if let Some(bell) = &self.bell {
            let _ = bell.ring(crate::bell::Doorbell::Adopter);
        }
    }

    #[cfg(unix)]
    pub(crate) fn install_bell_with_group(
        &mut self,
        segment: &str,
        group: Option<orbit_core::shm::GroupAccess>,
    ) -> Result<()> {
        self.bell = Some(
            crate::bell::Bell::with_group(segment, group, self.lanes)
                .map_err(Error::Io)?,
        );
        Ok(())
    }

    /// Bind this mapping's producer bell, rung when a reader frees one of
    /// its records while it waits.
    #[cfg(all(unix, feature = "tokio"))]
    pub(crate) fn bind_producer(&self) -> Result<tokio::net::UnixDatagram> {
        let index = self
            .producer_index()
            .ok_or(Error::Malformed("this inbox mapping has no producer"))?;
        let bell = self
            .bell
            .as_ref()
            .ok_or(Error::Malformed("the inbox has no reactor bell"))?;
        let socket = bell
            .bind(crate::bell::Doorbell::Producer(index))
            .map_err(Error::Io)?;
        tokio::net::UnixDatagram::from_std(socket).map_err(Error::Io)
    }

    #[cfg(all(unix, feature = "tokio"))]
    pub(crate) fn unbind_producer(&self) {
        if let (Some(index), Some(bell)) = (self.producer_index(), &self.bell) {
            bell.unbind(crate::bell::Doorbell::Producer(index));
        }
    }

    #[cfg(all(unix, feature = "tokio"))]
    pub(crate) fn bind_receiver(
        &self,
        lane_index: usize,
    ) -> Result<tokio::net::UnixDatagram> {
        self.check_lane(lane_index)?;
        let bell = self
            .bell
            .as_ref()
            .ok_or(Error::Malformed("the inbox has no reactor bell"))?;
        let socket = bell
            .bind(crate::bell::Doorbell::Lane(lane_index))
            .map_err(Error::Io)?;
        tokio::net::UnixDatagram::from_std(socket).map_err(Error::Io)
    }

    #[cfg(all(unix, feature = "tokio"))]
    pub(crate) fn unbind_receiver(
        &self,
        lane_index: usize,
    ) {
        self.disarm_receiver(lane_index);
        if let Some(bell) = &self.bell {
            bell.unbind(crate::bell::Doorbell::Lane(lane_index));
        }
    }

    #[cfg(all(unix, feature = "tokio"))]
    pub(crate) fn receiver_generation(
        &self,
        lane_index: usize,
    ) -> Result<u32> {
        self.check_lane(lane_index)?;
        Ok(self.lane_header(lane_index).changes.load(Ordering::SeqCst))
    }

    #[cfg(all(unix, feature = "tokio"))]
    pub(crate) fn arm_receiver(
        &self,
        lane_index: usize,
    ) -> Result<()> {
        self.check_lane(lane_index)?;
        self.lane_header(lane_index).reactor.store(1, Ordering::SeqCst);
        Ok(())
    }

    /// Lower the lane's arm and say whether it was still raised. One that
    /// was not has been taken by a writer, which sends exactly one bell for it.
    #[cfg(all(unix, feature = "tokio"))]
    pub(crate) fn take_receiver_arm(
        &self,
        lane_index: usize,
    ) -> bool {
        lane_index < self.lanes
            && self.lane_header(lane_index).reactor.swap(0, Ordering::SeqCst)
                != 0
    }

    #[cfg(all(unix, feature = "tokio"))]
    pub(crate) fn disarm_receiver(
        &self,
        lane_index: usize,
    ) {
        if lane_index < self.lanes {
            self.lane_header(lane_index).reactor.store(0, Ordering::SeqCst);
        }
    }

    /// Take a watcher slot whose hold the caller has just won: clear what a
    /// previous holder left and bind its socket.
    #[cfg(all(unix, feature = "tokio"))]
    pub(crate) fn bind_watcher(
        &self,
        slot: usize,
        role: &str,
    ) -> Result<tokio::net::UnixDatagram> {
        self.check_lane(slot)?;
        if role.is_empty() || role.len() > LANE_ROLE_MAX || !role.is_ascii() {
            return Err(Error::Malformed("role tag does not fit a watcher"));
        }
        let bell = self
            .bell
            .as_ref()
            .ok_or(Error::Malformed("the inbox has no reactor bell"))?;
        let watcher = self.watcher_header(slot);
        let pid = ProcessOwner::current()?.pid();
        watcher.reactor.store(0, Ordering::SeqCst);
        self.clear_interest(self.lanes + slot);
        let socket = bell
            .bind(crate::bell::Doorbell::Watcher(slot))
            .map_err(Error::Io)?;
        unsafe {
            std::ptr::copy_nonoverlapping(
                role.as_ptr(),
                watcher.role.as_ptr().cast_mut(),
                role.len(),
            );
        }
        watcher.role_len.store(role.len() as u8, Ordering::Release);
        watcher.pid.store(pid, Ordering::Release);
        tokio::net::UnixDatagram::from_std(socket).map_err(Error::Io)
    }

    #[cfg(all(unix, feature = "tokio"))]
    pub(crate) fn unbind_watcher(
        &self,
        slot: usize,
    ) {
        if slot >= self.lanes {
            return;
        }
        let watcher = self.watcher_header(slot);
        watcher.reactor.store(0, Ordering::SeqCst);
        watcher.pid.store(0, Ordering::Release);
        watcher.role_len.store(0, Ordering::Release);
        self.clear_interest(self.lanes + slot);
        if let Some(bell) = &self.bell {
            bell.unbind(crate::bell::Doorbell::Watcher(slot));
        }
    }

    #[cfg(all(unix, feature = "tokio"))]
    pub(crate) fn watcher_generation(
        &self,
        slot: usize,
    ) -> Result<u32> {
        self.check_lane(slot)?;
        Ok(self.watcher_header(slot).changes.load(Ordering::SeqCst))
    }

    #[cfg(all(unix, feature = "tokio"))]
    pub(crate) fn arm_watcher(
        &self,
        slot: usize,
    ) -> Result<()> {
        self.check_lane(slot)?;
        self.watcher_header(slot).reactor.store(1, Ordering::SeqCst);
        Ok(())
    }

    #[cfg(all(unix, feature = "tokio"))]
    pub(crate) fn disarm_watcher(
        &self,
        slot: usize,
    ) {
        if slot < self.lanes {
            self.watcher_header(slot).reactor.store(0, Ordering::SeqCst);
        }
    }

    /// The process holding this watcher slot, if one said.
    pub fn watcher(
        &self,
        slot: usize,
    ) -> Result<Option<u32>> {
        self.check_lane(slot)?;
        Ok(match self.watcher_header(slot).pid.load(Ordering::Acquire) {
            0 => None,
            pid => Some(pid),
        })
    }

    /// What the process holding this watcher slot said it is, if it holds it.
    pub fn watcher_role(
        &self,
        slot: usize,
    ) -> Result<Option<String>> {
        self.check_lane(slot)?;
        let watcher = self.watcher_header(slot);
        if watcher.pid.load(Ordering::Acquire) == 0 {
            return Ok(None);
        }
        let len = watcher.role_len.load(Ordering::Acquire) as usize;
        if len == 0 || len > LANE_ROLE_MAX {
            return Ok(None);
        }
        let bytes =
            unsafe { std::slice::from_raw_parts(watcher.role.as_ptr(), len) };
        Ok(String::from_utf8(bytes.to_vec()).ok())
    }

    /// Replace one interest entry. Only the holder of the lane or watcher
    /// slot it belongs to writes it.
    pub(crate) fn write_interest(
        &self,
        entry: usize,
        bits: &[u64; INTEREST_WORDS],
    ) {
        let interest = self.interest_entry(entry);
        // One writer per entry, so the parity is set rather than counted: a
        // holder that died between the two stores left it odd, and the next
        // holder's first write repairs it.
        let writing = interest.seq.load(Ordering::Relaxed) | 1;
        interest.seq.store(writing, Ordering::Release);
        for (word, value) in interest.bits.iter().zip(bits) {
            word.store(*value, Ordering::Release);
        }
        interest.seq.store(writing.wrapping_add(1), Ordering::Release);
    }

    /// Read one interest entry as it stood between two of its writes.
    ///
    /// A read that overlaps a write, or meets an entry its writer left half
    /// written, does not wait: it answers "wants everything". That is a false
    /// positive, which the set already allows — at worst something is
    /// forwarded that nobody consumes — and it never parks the reader on a
    /// writer that may be gone.
    #[cfg_attr(not(feature = "events"), allow(dead_code))]
    pub(crate) fn read_interest(
        &self,
        entry: usize,
    ) -> [u64; INTEREST_WORDS] {
        let interest = self.interest_entry(entry);
        let before = interest.seq.load(Ordering::Acquire);
        if before.is_multiple_of(2) {
            let mut bits = [0u64; INTEREST_WORDS];
            for (value, word) in bits.iter_mut().zip(&interest.bits) {
                *value = word.load(Ordering::Acquire);
            }
            if interest.seq.load(Ordering::Acquire) == before {
                return bits;
            }
        }
        [u64::MAX; INTEREST_WORDS]
    }

    fn clear_interest(
        &self,
        entry: usize,
    ) {
        self.write_interest(entry, &[0; INTEREST_WORDS]);
    }

    fn interest_entry(
        &self,
        entry: usize,
    ) -> &InterestEntry {
        unsafe {
            &*self
                .base
                .add(
                    size_of::<TableHeader>()
                        + self.lanes
                            * (self.geometry.lane_bytes()
                                + size_of::<WatcherHeader>())
                        + entry * size_of::<InterestEntry>(),
                )
                .cast::<InterestEntry>()
        }
    }

    fn watcher_header(
        &self,
        slot: usize,
    ) -> &WatcherHeader {
        unsafe {
            &*self
                .base
                .add(
                    size_of::<TableHeader>()
                        + self.lanes * self.geometry.lane_bytes()
                        + slot * size_of::<WatcherHeader>(),
                )
                .cast::<WatcherHeader>()
        }
    }

    pub(crate) fn check_lane(
        &self,
        lane_index: usize,
    ) -> Result<()> {
        if lane_index >= self.lanes {
            return Err(Error::Malformed("lane is outside the table"));
        }
        Ok(())
    }

    fn table_header(&self) -> &TableHeader {
        unsafe { &*self.base.cast::<TableHeader>() }
    }

    fn lane_base(
        &self,
        lane_index: usize,
    ) -> *mut u8 {
        unsafe {
            self.base.add(
                size_of::<TableHeader>()
                    + lane_index * self.geometry.lane_bytes(),
            )
        }
    }

    pub(crate) fn lane_header(
        &self,
        lane_index: usize,
    ) -> &LaneHeader {
        unsafe { &*self.lane_base(lane_index).cast::<LaneHeader>() }
    }

    fn slot_base(
        &self,
        lane_index: usize,
        position: u64,
    ) -> *mut u8 {
        let index = (position as usize) & (self.geometry.capacity - 1);
        let stride = self.geometry.slot_bytes();
        unsafe {
            self.lane_base(lane_index)
                .add(size_of::<LaneHeader>() + index * stride)
        }
    }

    fn slot_header(
        &self,
        lane_index: usize,
        position: u64,
    ) -> &SlotHeader {
        unsafe { &*self.slot_base(lane_index, position).cast::<SlotHeader>() }
    }

    fn payload_ptr(
        &self,
        lane_index: usize,
        position: u64,
    ) -> *mut u8 {
        unsafe {
            self.slot_base(lane_index, position).add(size_of::<SlotHeader>())
        }
    }
}

/// A lane's identity must fit it: a name and a role tag, neither empty,
/// neither truncated.
fn check_identity(
    service: &str,
    role: &str,
) -> Result<()> {
    if service.is_empty() || service.len() > LANE_NAME_MAX {
        return Err(Error::Malformed("service name does not fit a lane"));
    }
    if role.is_empty() || role.len() > LANE_ROLE_MAX || !role.is_ascii() {
        return Err(Error::Malformed("role tag does not fit a lane"));
    }
    Ok(())
}

/// Keep the interest visible after a failed send so another writer can retry.
/// A parked reader may still require an external wake when delivery fails.
#[cfg(unix)]
fn ring_armed(
    reactor: &AtomicU32,
    ring: impl FnOnce() -> io::Result<()>,
) -> io::Result<()> {
    if reactor.swap(0, Ordering::SeqCst) == 0 {
        return Ok(());
    }
    if let Err(error) = ring() {
        reactor.fetch_or(1, Ordering::SeqCst);
        return Err(error);
    }
    Ok(())
}

#[cfg(all(test, unix, feature = "tokio"))]
#[path = "../tests/unit/bell.rs"]
mod bell_tests;