ingraph 0.1.0

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

use core::{any::Any, future::Future, hash::Hash, marker::PhantomData, time::Duration};

use std::{
  collections::{HashMap, HashSet},
  sync::Arc,
  time::{Instant, SystemTime},
};

use smol_bytes::Utf8Bytes;

use crate::{
  Async, AsyncOperator, Block, Context, Driven, Emission, Emitter, Operator, Resources, Skip,
  SkipReason,
};

use super::{
  AckMode, Effect, ItemId, NodeName, Rings,
  channel::{Inbox, Outbox, Wake},
  downstream::{Downstream, Sink},
  intake::Intake,
  journal::{Attributes, JournalRow, Ledger},
  lane::{AsyncLands, Commit, Unwritten, block_on},
  lifecycle::{Failure, Lifecycle, LifecycleTap, Observation, Station, Taps},
  message::{Delivery, Item, Payload, ack_channel},
  observe::{self, TracingLevel},
  policy::Policies,
  poll::{Clock, PollUpstream, Schedule, Seats, Swept, Unpolled},
  registry::{Counting, Registries, RootKey},
  window::{Lineage, Outbound, Owed},
};

/// The per-edge batches one delivery produced, before they are handed to the edges.
///
/// One inner `Vec` per output edge, in the order the edges were declared — a named type because the
/// nesting is the fact worth reading: an emission becomes one item per edge, which is what makes a
/// fan-out join on all of its arms.
///
/// Parameterised by the MESSAGE and not by the operator, which is what keeps the half of the loop
/// that routes it free of the face: an edge carries a product, and nothing about handing one over
/// depends on whether the body that made it awaited.
type Emitted<T> = Vec<Vec<Item<T>>>;

/// What a delivery's items did — the per-item detail a batch ack carries in its info slot.
///
/// One ack covers many items and states ONE station, so the counts are where "250 of 256" is
/// actually said. A tap asks for this type back through
/// [`Observation::info`](super::Observation::info).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Tally {
  processed: usize,
  emitted: usize,
  skipped: usize,
  failed: usize,
  refused: usize,
}

impl Tally {
  /// Items whose `accept` returned `Ok`.
  #[inline]
  #[must_use]
  pub const fn processed(&self) -> usize {
    self.processed
  }

  /// Outputs emitted downstream, counted per EMISSION and not per edge — a fan-out of one
  /// emission to three consumers is one emission here and three items on the wire.
  #[inline]
  #[must_use]
  pub const fn emitted(&self) -> usize {
    self.emitted
  }

  /// Emissions that were intentional refusals.
  #[inline]
  #[must_use]
  pub const fn skipped(&self) -> usize {
    self.skipped
  }

  /// Items whose `accept` returned `Err`. Every one of them is held.
  #[inline]
  #[must_use]
  pub const fn failed(&self) -> usize {
    self.failed
  }

  /// Records the write lane did NOT commit — counted per staged record, as
  /// [`emitted`](Self::emitted) is counted per emission.
  ///
  /// It is where "250 of 256" is said from the socket's side, and it is a different fact from
  /// [`failed`](Self::failed): an item can survive its operator and still be held because the store
  /// would not take what it produced.
  #[inline]
  #[must_use]
  pub const fn refused(&self) -> usize {
    self.refused
  }
}

/// What one run of a resident did, from launch to shutdown.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Drained {
  deliveries: usize,
  items: usize,
  sweeps: usize,
  ticks: usize,
  tally: Tally,
}

impl Drained {
  /// Deliveries taken off the intake.
  #[inline]
  #[must_use]
  pub const fn deliveries(&self) -> usize {
    self.deliveries
  }

  /// Items inside them.
  #[inline]
  #[must_use]
  pub const fn items(&self) -> usize {
    self.items
  }

  /// Passes driven by a sweep rather than by data — counted AFTER a burst of rings is collapsed, so
  /// this is looks and not rings.
  #[inline]
  #[must_use]
  pub const fn sweeps(&self) -> usize {
    self.sweeps
  }

  /// Sweep entries invoked because a POLL UPSTREAM came due — counted after a burst of one upstream's
  /// ticks is collapsed, so this is looks and not ticks, exactly as [`sweeps`](Self::sweeps) is.
  ///
  /// One per upstream per pass: two upstreams coming due together are two here, which is the difference
  /// from a sweep and the whole reason a tick carries an identity.
  #[inline]
  #[must_use]
  pub const fn ticks(&self) -> usize {
    self.ticks
  }

  /// The totals across every delivery.
  #[inline]
  #[must_use]
  pub const fn tally(&self) -> Tally {
    self.tally
  }
}

/// What a delivery amounted to, accumulated while it is processed and turned into ONE station when
/// the ack is finally sent.
#[derive(Debug, Default)]
struct Verdict {
  tally: Tally,
  failure: Option<Failure>,
  skip: Option<Skip>,
}

impl Verdict {
  /// The station this delivery reached, WITHOUT consuming the verdict.
  ///
  /// The strong half of the journal needs it before the ack is built, because the row is what the
  /// ack certifies and the ack's own [`Lifecycle`] moves the payloads out.
  ///
  /// The arms are in order of severity, and each is a claim about the window:
  ///
  /// - a failure anywhere means the delivery is not settled, and [`Failed`](Lifecycle::Failed) is
  ///   what says so;
  /// - a delivery that emitted NOTHING and refused something IS a refusal, and calling it
  ///   processed would erase the only record of the gap;
  /// - otherwise the station is what the node's [`Effect`] makes it — a landing node reached
  ///   durability before it answered, and a pure one did not and must not claim to have.
  ///
  /// It states the same table [`into_lifecycle`](Self::into_lifecycle) does, and the two are pinned
  /// against each other by `the_station_a_verdict_reports_is_the_one_its_lifecycle_reaches`.
  fn station(&self, effect: Effect) -> Station {
    if self.failure.is_some() {
      return Station::Failed;
    }
    if self.tally.emitted == 0 && self.skip.is_some() {
      return Station::Skipped;
    }
    effect.station()
  }

  /// The same table as [`station`](Self::station), carrying the payload each arm names.
  fn into_lifecycle(self, effect: Effect) -> Lifecycle<Tally> {
    if let Some(failure) = self.failure {
      return Lifecycle::Failed(failure);
    }
    if self.tally.emitted == 0
      && let Some(skip) = self.skip
    {
      return Lifecycle::Skipped(skip);
    }
    effect.reached(self.tally)
  }
}

/// A delivery whose ack is still owed — [`Chained`](AckMode::Chained)'s bookkeeping.
#[derive(Debug)]
struct Held {
  id: u64,
  owed: Owed<ItemId>,
  verdict: Verdict,
}

/// ONE input item of a held delivery — what [`Chained`](AckMode::Chained)'s join maps an output
/// back to.
///
/// Two facts and not one, because neither identifies an input on its own. The key belongs to the
/// SENDER, and a held item comes back on the next pass under the key it always had, so two
/// obligations can be waiting on the same key at once; the delivery id says which obligation
/// without saying which of its items. Only the pair says both, which is why it is what
/// [`Lineage`]'s input type is here.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct HeldItem {
  delivery: u64,
  key: ItemId,
}

impl HeldItem {
  /// The `key` of the delivery held under `delivery`.
  #[inline]
  const fn new(delivery: u64, key: ItemId) -> Self {
    Self { delivery, key }
  }

  /// Which held obligation this input belongs to.
  #[inline]
  const fn delivery(&self) -> u64 {
    self.delivery
  }

  /// The sender's own key, to release it with.
  #[inline]
  const fn into_key(self) -> ItemId {
    self.key
  }
}

/// ONE input item as its delivery tracks it: what it produced, and the two facts that decide
/// whether its key may be released.
#[derive(Debug)]
struct Descent {
  key: ItemId,
  produced: Vec<ItemId>,
  survived: bool,
  refused: bool,
}

impl Descent {
  /// An item that has run and staged nothing yet. `survived` is what its `accept` answered.
  #[inline]
  const fn new(key: ItemId, survived: bool) -> Self {
    Self {
      key,
      produced: Vec::new(),
      survived,
      refused: false,
    }
  }

  /// Whether this input is finished with — its operator returned `Ok` AND everything it staged
  /// reached the store.
  ///
  /// BOTH, because a release is a promise about the effect and not about the attempt. An item whose
  /// write the store refused is held exactly as a failed one is, and comes back on the sender's next
  /// pass.
  #[inline]
  const fn is_done(&self) -> bool {
    self.survived && !self.refused
  }
}

/// One delivery between its operator and its write: the records it wants stored, which input each
/// descends from, and the obligation waiting on the answer.
///
/// It exists because the write is the ONE step the two engines take differently — the thread engine
/// blocks on it, the async engine awaits it — so a pass is split around exactly that call and
/// everything on either side of it is written once.
#[derive(Debug)]
struct Staged<T> {
  id: u64,
  owed: Owed<ItemId>,
  verdict: Verdict,
  /// The records to write, in emission order. A [`Commit`] answers by POSITION in this.
  outputs: Vec<T>,
  /// Per staged record, the index into `descent` of the input that produced it.
  owner: Vec<usize>,
  descent: Vec<Descent>,
}

/// ONE delivery's per-item bookkeeping, gathered as the walk goes.
///
/// It exists because the walk over a delivery is the ONE place the two faces differ, and everything
/// AROUND the call is the same on both: which entry an emission belongs to, whether the input
/// survived, what the delivery amounts to. Holding those here is what keeps a face's own middle
/// third down to the call itself — see [`Drives`], where the two are written.
#[derive(Debug)]
struct Pass<T> {
  verdict: Verdict,
  /// The records to write, in emission order.
  outputs: Vec<T>,
  /// Per staged record, the index into `descent` of the input that produced it.
  owner: Vec<usize>,
  descent: Vec<Descent>,
  /// The answers this delivery's items stated, keyed by the item that stated one — see
  /// [`Emitter::receipt`](crate::Emitter::receipt).
  ///
  /// A `Vec` of pairs and not a map: a delivery states nothing here in the ordinary case, so the
  /// idle cost is what `Vec::new` does — nothing — and an item states at most one, so there is no
  /// lookup to perform on the way in. The map is built once, at the obligation, and only where a
  /// receipt was actually stated.
  receipts: Vec<(ItemId, Box<dyn core::any::Any + Send + Sync>)>,
}

impl<T> Pass<T> {
  /// An empty pass over a delivery of `items`.
  fn opening(items: usize) -> Self {
    Self {
      verdict: Verdict::default(),
      outputs: Vec::new(),
      owner: Vec::new(),
      descent: Vec::with_capacity(items),
      receipts: Vec::new(),
    }
  }

  /// Fold ONE input's outcome in: what it emitted, then whether it survived.
  ///
  /// Emissions buffered before an error are staged exactly as on the `Ok` path — the driver drains
  /// the buffer first either way, which is the contract [`Operator`] states and
  /// [`AsyncOperator`] repeats.
  fn absorb<E>(&mut self, key: ItemId, mut emitter: Emitter<T>, outcome: Result<(), E>)
  where
    E: core::error::Error + Send + Sync + 'static,
  {
    // The item's ANSWER, keyed by the item, taken before the buffer is drained. The body never
    // touched a transport key to state it — `Emitter::receipt` names no key — because the driver is
    // walking the delivery and already knows which item this call was for. That is the same division
    // every other per-item fact here keeps: an operator states what it did, and the driver says
    // which item it did it to.
    if let Some(receipt) = emitter.take_receipt() {
      self.receipts.push((key, receipt));
    }
    // The entry this item's emissions belong to, taken BEFORE the entry is pushed. Attributing an
    // emission to the input that produced it is what turns a per-record write answer back into a
    // per-input release, and the attribution lives HERE — nothing about it goes on the wire.
    let mine = self.descent.len();
    for emission in emitter.drain() {
      match emission {
        Emission::Emit(output) => {
          self.outputs.push(output);
          self.owner.push(mine);
        }
        Emission::Skip(skip) => {
          self.verdict.tally.skipped += 1;
          if self.verdict.skip.is_none() {
            self.verdict.skip = Some(skip);
          }
        }
      }
    }
    match outcome {
      Ok(()) => {
        self.verdict.tally.processed += 1;
        self.descent.push(Descent::new(key, true));
      }
      Err(error) => {
        self.verdict.tally.failed += 1;
        if self.verdict.failure.is_none() {
          self.verdict.failure = Some(Failure::new(error));
        }
        // A failed item is released by nothing: it is named in no set, so its sender re-delivers
        // it. Whatever it emitted before failing is still written and still travels, and keyed
        // replace is what makes the second arrival harmless.
        self.descent.push(Descent::new(key, false));
      }
    }
  }

  /// Close the pass into the delivery's [`Staged`], under the obligation `owed` and the id `id`.
  ///
  /// The answers move ONTO the obligation here, which is where they have to live: the ack is sent
  /// once for the whole delivery, and under [`Chained`](AckMode::Chained) not until a later pass —
  /// so the obligation is the only thing that is still around when the answer finally goes out.
  fn staged(self, id: u64, mut owed: Owed<ItemId>) -> Staged<T> {
    for (key, receipt) in self.receipts {
      owed.receipting(key, receipt);
    }
    Staged {
      id,
      owed,
      verdict: self.verdict,
      outputs: self.outputs,
      owner: self.owner,
      descent: self.descent,
    }
  }
}

/// One node, resident for the process's life.
///
/// # The two engines
///
/// [`run`](Drives::run) is the thread engine and [`run_async`](Drives::run_async) the async one.
/// They differ in exactly three calls — how the loop PARKS, how it waits for its own WRITE, and how
/// a dispatch waits for room — and share every other line, because the wake they park for is one
/// vocabulary: a thread self-times, an async task is rung by the launch's own clock putting a
/// [`Wake::Sweep`] on its intake. Neither spawns anything, neither returns until its senders are
/// gone, and the operator is constructed by the caller ON the engine that will run it, once.
///
/// The park is the [`Intake`]'s, which is what keeps the two engines one loop where a node draws
/// from several upstreams: one select, expressed as a future, awaited by the async engine and driven
/// to a deadline by the thread engine.
///
/// # And the two FACES, which is the other axis
///
/// `M` is the MODE this resident was built in — [`Block`] for a body that answers, [`Async`] for
/// one that answers a future — and it is the parameter nobody writes: it defaults to [`Block`],
/// which is the mode a bare declaration has. [`Drives`] is where the two meet the two engines, four
/// cells in all, and the table is written there.
///
/// The mode rides here rather than on a bound because a bound cannot make two bodies exist
/// conditionally: two `impl` blocks whose only difference is a where-clause are `E0592`, and two
/// impls of one trait for one Self type are `E0119`. A parameter makes the Self types differ, which
/// is the one mechanism stable Rust offers — and it costs the ordinary node nothing, because the
/// default is the ordinary face.
///
/// # One pass
///
/// Drain the intake — a burst of wakes is one pass, a burst of sweeps is one look and a burst of ONE
/// upstream's ticks is one look at that upstream — then, per delivery: run the operator, WRITE what it
/// produced through the node's own lane, dispatch what the store took, and settle. Then sweep every
/// poll upstream that came due, once each. Afterwards harvest the answers this node's own outputs have
/// earned, which is where [`Chained`](AckMode::Chained) releases the inputs whose outputs have now
/// come back.
///
/// # The orderings that are not negotiable
///
/// An input's ack is sent AFTER its emissions have been handed to the edges that carry them.
/// Reversing those two is what would make a lost message a lost item rather than a re-delivery.
///
/// And, where the node has a write lane, AFTER that write has committed — see [`AsyncLands`] and
/// [`land`](Self::land). Answering first would release an input whose effect is not durable, which
/// is the exact gap a crash turns into skipped work.
///
/// # THE THREE ACK DISCIPLINES, and what they are now load-bearing for
///
/// Those orderings were always the message layer's. They are now also the ROOT REGISTRY's, because
/// a key returns to [`Idle`](crate::RootState::Idle) the moment its inflight count reaches zero —
/// so an ack sent one step too early no longer merely risks a lost item, it declares a chain
/// finished in the middle of itself. Three rules make that reading correct, and each is a property
/// of code in this crate rather than a hope about it:
///
/// **R1 — dispatch before ack.** A node's `+n` for an input's outputs precedes the release of that
/// input's ack. Here the margin is two steps, not one: [`reconcile`](Self::reconcile) counts each
/// item out as it puts it on an edge, and what follows is the physical
/// [`dispatch`](Self::dispatch) and only THEN [`settle`](Self::settle), which is where an ack
/// reaches the wire. The [`Owed::release`](super::Owed) calls in between move a key from *pending*
/// to *released* inside the obligation and send nothing.
///
/// **R2 — a stream is bracketed.** A streaming producer's input stays unacked for the whole
/// stream: [`StreamLane`](super::StreamLane) opens the delivery's obligation at admission and
/// holds it on the line until the line closes, and its pass projects everything the run yielded
/// before it settles anything. There is no separate end-of-stream item on the wire to ack early —
/// the end is [`Fin`](crate::Fin), carried on the settlement itself, which is the same bracket
/// said as one delivery.
///
/// **R3 — never ack what you hold.** A buffered, batched or windowed item keeps its custody until
/// it is dispatched. This loop cannot break it: the only place an obligation is answered is
/// `settle`, and under [`Chained`](AckMode::Chained) an input is not released at all until the
/// outputs it produced have come back.
///
/// The counting itself is the framework's, and the node never sees it — see
/// [`Registries`](crate::Registries).
///
/// # Two vocabularies, and the line between them
///
/// `with_*` is a VALUE on this type — the ack mode, the effect, the sweep interval, the taps — and
/// every one of them has a `set_*` partner that does the same thing in place. The consuming half
/// delegates to it, so a knob's assignment is written down once.
///
/// A VERB is WIRING and has no in-place half, because it does not leave the type where it found it:
/// [`land`](Self::land), [`attributing`](Self::attributing), [`polling`](Self::polling) and
/// [`recording_to`](Self::recording_to) each answer a differently parameterised `Resident`, which
/// `&mut self` cannot express, and [`publish`](Self::publish) appends an edge rather than replacing
/// one.
///
/// # So is the INTAKE
///
/// `I` is where this node's input comes from, and the parameter is the whole of what a node with
/// SEVERAL upstreams costs the loop. A node drawing from one upstream carries the framework's own
/// [`Inbox`] — the default, so nothing is named and nothing is paid — while a node whose
/// declaration writes a `subscribe(…)` container carries its own: one edge per upstream, a select
/// across them, and the by-key join that assembles the keyed group before the body ever sees it.
/// Both are [`Intake`], both answer the same [`Wake`], and the loop below is written once.
///
/// [`new`](Self::new) takes whichever it is handed, so the multi-upstream shape needs no second
/// constructor and no verb — the intake is what a resident is BUILT with, unlike the wire set,
/// which is attached afterwards.
///
/// # The lane is a TYPE
///
/// `W` is the node's write lane, and a node with none carries `()` — the absence spelled as a type,
/// which is [`AsyncBlobEngine for ()`](crate::AsyncBlobEngine)'s answer to the same question. [`new`](Self::new)
/// therefore builds a `Resident<O, ()>` and [`land`](Self::land) is what changes the type, so a
/// caller never names the parameter and inference never has to guess it.
///
/// # So is the poll context
///
/// `C` is the node's LENDING — the value a [`Seats`] impl seats the operator through, and a node
/// with no poll upstream carries [`Unpolled`] — the same trade one parameter over, and
/// [`polling`](Self::polling) is what changes it. The resident HOLDS the lending and never hands it
/// out: a sweep is handed its own clock's context for the call, so capabilities live here and the
/// node value holds only its own state.
#[derive(Debug)]
pub struct Resident<
  O,
  W,
  A = (),
  L = (),
  C = Unpolled,
  S = Downstream<<O as Operator>::Out>,
  I = Inbox<ItemId, <O as Operator>::In>,
  M = Block,
> where
  O: Driven<M>,
  A: Attributes<<O as Driven<M>>::Out>,
{
  name: Utf8Bytes,
  operator: O,
  intake: I,
  downstream: S,
  windows: Vec<Outbound<ItemId>>,
  lane: W,
  ack: AckMode,
  effect: Effect,
  sweep: Duration,
  schedule: Schedule,
  context: C,
  // THIS NODE'S WINDOW, handed to every `accept` as its first argument: the deployment's resource
  // map, this node's own wind-down line, and its name. Held rather than rebuilt per call because
  // none of the three changes for the life of the node, and it is a VALUE rather than a borrow
  // because a resident is moved onto an engine — a lifetime here would be a lifetime on the engine.
  window: Context,
  taps: Taps,
  // The deployment's four policies, spent through gates this loop mints. Held by value rather than
  // behind the resource map, because a policy is chosen for the DEPLOYMENT and a resident is what
  // meets it: the gate a decision goes through has to be able to name this node.
  policies: Policies,
  // THE ROOT-KEY REGISTRIES, one object for the whole deployment and a handle per resident — the
  // taps' and the policies' own arrangement, and threaded the same way: built once by the wiring
  // walk, cloned to every body it wires, and reachable afterwards through `App::registries`.
  //
  // `None` where nothing wired one, which is every hand-built resident that never asked. It is an
  // absence rather than an empty default because an empty `Registries` is a real thing a caller can
  // build and share, and a resident holding one it was never given would be indistinguishable from
  // a resident sharing the deployment's.
  //
  // The NODE never touches it — it is not on the `Context` every `accept` is handed, and that is
  // deliberate: counting is the framework's act inside the loop, and the query and command faces
  // read it from outside.
  registries: Option<Arc<Registries>>,
  // The level this node's four framework spans open at — the `tracing(level = …)` word, carried from
  // the declaration by the wiring walk. Held in every build: a build with no observation compiled in
  // hands it to constructors that read nothing, which is what keeps the two engines' loops free of a
  // `#[cfg]` — see `drive::observe`.
  tracing: TracingLevel,
  attribution: A,
  ledger: L,
  // The root each item this node SENT descends from, kept until the answer for it comes back.
  //
  // It lives here for `Lineage`'s reason and pays the same way: the sender knows what it emitted, so
  // remembering the projection costs a map entry, while putting the root in the message would put it
  // in the app's declared struct — the envelope this layer's design removed. The map is bounded by
  // the windows' own outstanding set, and a delivery that hung up leaves an entry in both.
  roots: HashMap<ItemId, A::Root>,
  lineage: Lineage<HeldItem, ItemId>,
  held: HashMap<u64, Held>,
  next_held: u64,
  next_item: u64,
  // The MODE, as a marker: `fn() -> M` so the parameter carries no ownership and none of the mode
  // marker's own auto traits, exactly as `Ignition`'s runtime marker does. `S` and `I` default
  // through `Operator` rather than through `Driven<M>` because a default may not reference a
  // parameter declared after it (`E0128`) — and it says the right thing anyway: the defaults are
  // the DEFAULT mode's, which is what a node that names neither is.
  mode: PhantomData<fn() -> M>,
}

impl<O, I, M> Resident<O, (), (), (), Unpolled, Downstream<<O as Driven<M>>::Out>, I, M>
where
  O: Driven<M>,
{
  /// A resident for `operator`, reading `intake`, storing NOTHING of its own.
  ///
  /// The operator is taken BY VALUE and never handed back, which is the residency ruling written
  /// into the type: whatever it loaded, it loaded on this engine, and it does not migrate.
  ///
  /// It answers `Resident<O, ()>` rather than a lane the caller must name, because a node with no
  /// write of its own is the ordinary one: a pure operator has none, and a landing node whose
  /// durability comes from a downstream co-subscriber has none either.
  ///
  /// # The FACE is not asked for, and could not usefully be
  ///
  /// `M` is inferred from the operator's own type: implementing [`Operator`] IS implementing
  /// `Driven<Block>` and implementing [`AsyncOperator`] IS implementing `Driven<Async>`, so a unit
  /// answers the question by existing. ONE constructor for both faces follows from that — a second
  /// door would ask a caller to state a fact the value already carries, and a `with_*` could not
  /// change it anyway, the face being a type rather than a knob.
  ///
  /// A type wearing BOTH faces is the one case where the answer is not unique, and it is `E0283` at
  /// this call naming both candidates. Spell the mode — `Resident::<_, _, _, _, _, _, _, Block>` —
  /// which is the same disambiguation `land` on a handle implementing both lane faces asks for. The
  /// intake door does not ask it: a declaration's own `Declared::Mode` answers there, where this
  /// hand-wired constructor has no declaration to read.
  #[must_use]
  pub fn new(name: impl Into<Utf8Bytes>, operator: O, intake: I) -> Self {
    let name = name.into();
    Self {
      window: Context::new(name.clone()),
      name,
      operator,
      intake,
      downstream: Downstream::new(),
      windows: Vec::new(),
      lane: (),
      ack: AckMode::Local,
      effect: Effect::Pure,
      sweep: Self::SWEEP,
      schedule: Schedule::new(),
      context: Unpolled,
      taps: Taps::new(),
      policies: Policies::new(),
      registries: None,
      tracing: TracingLevel::Info,
      attribution: (),
      ledger: (),
      roots: HashMap::new(),
      lineage: Lineage::new(),
      held: HashMap::new(),
      next_held: 0,
      next_item: 0,
      mode: PhantomData,
    }
  }
}

/// The verbs that only the FRAMEWORK's downstream set answers.
///
/// [`publish`](Resident::publish) appends ONE edge, which is a sentence about a set of edges of one
/// product — so it belongs to [`Downstream`] and not to the [`Sink`] seam, where a node's own
/// downstream set is a struct with a field per product and nothing to append to.
impl<O, W, A, L, C, I, M> Resident<O, W, A, L, C, Downstream<<O as Driven<M>>::Out>, I, M>
where
  O: Driven<M>,
  A: Attributes<<O as Driven<M>>::Out>,
{
  /// Publish to `outbox` as well.
  ///
  /// Every output edge gets its OWN window and its own item ids, which is what makes a fan-out join
  /// on all of its arms: one emission becomes one item per edge, each released by its own consumer,
  /// and [`Chained`](AckMode::Chained) counts them separately.
  #[must_use]
  pub fn publish(mut self, outbox: Outbox<ItemId, <O as Driven<M>>::Out>) -> Self {
    self.downstream.attach(outbox);
    self.windows.push(Outbound::new());
    self
  }
}

impl<O, W, A, L, C, S, I, M> Resident<O, W, A, L, C, S, I, M>
where
  O: Driven<M>,
  A: Attributes<<O as Driven<M>>::Out>,
{
  /// The sweep interval a resident takes unless told otherwise.
  ///
  /// A LIVENESS floor and not a latency budget: everything it does, a hint or a delivery does
  /// sooner. A second is long enough to cost nothing and short enough that a stuck watermark is
  /// noticed while a human is still looking at it.
  pub const SWEEP: Duration = Duration::from_secs(1);

  /// Land what this node emits in `lane`, and answer each delivery only after that write has
  /// committed — the storage socket, and [`AsyncLands`] is what a lane implements.
  ///
  /// The verb is deliberately the capability's own: this INSTALLS the lane, and [`AsyncLands::land`] is
  /// what the runtime then calls on it per batch — one word, two receivers, and the pair is the one
  /// double-role this vocabulary keeps.
  ///
  /// It also declares [`Effect::Lands`]. A node holding a write lane lands by construction, and
  /// saying so in two places would be a fact two places could disagree about.
  #[must_use]
  pub fn land<X>(self, lane: X) -> Resident<O, X, A, L, C, S, I, M> {
    Resident {
      name: self.name,
      operator: self.operator,
      intake: self.intake,
      downstream: self.downstream,
      windows: self.windows,
      lane,
      ack: self.ack,
      effect: Effect::Lands,
      sweep: self.sweep,
      schedule: self.schedule,
      context: self.context,
      window: self.window,
      taps: self.taps,
      policies: self.policies,
      registries: self.registries,
      tracing: self.tracing,
      attribution: self.attribution,
      ledger: self.ledger,
      roots: self.roots,
      lineage: self.lineage,
      held: self.held,
      next_held: self.next_held,
      next_item: self.next_item,
      mode: self.mode,
    }
  }

  /// Write this node's own `(root, node)` completion rows to `ledger` — the journal's STRONG
  /// half for a node with no durable position.
  ///
  /// A changes-fed node does not need this: its rows ride the transaction that advances its cursor,
  /// which is [`Positions::advance`](super::Positions::advance). A CHANNEL-fed one has no cursor,
  /// so there is nothing for its row to be atomic with and a lone upsert is the whole write.
  ///
  /// The row is written BEFORE the ack it certifies goes out, and a refusal makes the delivery a
  /// failure — see [`Ledger`]. That is what separates it from the queued diagnostic half.
  #[must_use]
  pub fn recording_to<X>(self, ledger: X) -> Resident<O, W, A, X, C, S, I, M> {
    Resident {
      name: self.name,
      operator: self.operator,
      intake: self.intake,
      downstream: self.downstream,
      windows: self.windows,
      lane: self.lane,
      ack: self.ack,
      effect: self.effect,
      sweep: self.sweep,
      schedule: self.schedule,
      context: self.context,
      window: self.window,
      taps: self.taps,
      policies: self.policies,
      registries: self.registries,
      tracing: self.tracing,
      attribution: self.attribution,
      ledger,
      roots: self.roots,
      lineage: self.lineage,
      held: self.held,
      next_held: self.next_held,
      next_item: self.next_item,
      mode: self.mode,
    }
  }

  /// Attribute what this node emits to the chain ROOT it descends from, through `attribution`.
  ///
  /// The type changes, exactly as [`land`](Self::land)'s does and for the same reason: the absence
  /// of an attribution is `()`, so a node that wires none never names the parameter and inference
  /// never has to guess it.
  ///
  /// Wiring one is what turns this node's observations from counter-grade into rows a journal can
  /// be keyed by — see [`Attributes`]. It changes nothing else: the projection is read where an
  /// output is fanned out, and the observation is offered where the answer for it comes back.
  #[must_use]
  pub fn attributing<B>(self, attribution: B) -> Resident<O, W, B, L, C, S, I, M>
  where
    B: Attributes<<O as Driven<M>>::Out>,
  {
    Resident {
      name: self.name,
      operator: self.operator,
      intake: self.intake,
      downstream: self.downstream,
      windows: self.windows,
      lane: self.lane,
      ack: self.ack,
      effect: self.effect,
      sweep: self.sweep,
      schedule: self.schedule,
      context: self.context,
      window: self.window,
      taps: self.taps,
      policies: self.policies,
      registries: self.registries,
      tracing: self.tracing,
      attribution,
      ledger: self.ledger,
      // The old map's roots are the OLD projection's answers, and a wiring call happens before the
      // node runs, so there is nothing here to carry over and nothing that could be carried.
      roots: HashMap::new(),
      lineage: self.lineage,
      held: self.held,
      next_held: self.next_held,
      next_item: self.next_item,
      mode: self.mode,
    }
  }

  /// Tick this node's poll upstreams on `schedule`, seating the operator at each clock that comes due
  /// through the capabilities `context` lends it.
  ///
  /// The type changes, as [`land`](Self::land)'s does and for the same reason: the absence of a
  /// poll arm is [`Unpolled`], so a node that wires none never names the parameter.
  ///
  /// # Which engine reads the schedule
  ///
  /// The THREAD engine's: [`run`](Self::run) folds these intervals into the timeout it was already
  /// computing for the sweep, so a resident thread produces its own ticks and needs no second
  /// thread. [`run_async`](Self::run_async) is RUNG instead — hand
  /// [`Schedule::cadences`](Schedule::cadences) over the same schedule to the launch's own clock —
  /// which is exactly the asymmetry [`sweeping_every`](Self::sweeping_every) already has.
  ///
  /// # A poll-only node's shutdown handle is its [`Outbox`]
  ///
  /// A loop ends when every sender to its inbox is gone, and a node whose only upstreams are poll
  /// upstreams has no data producer to be one. What holds its channel open is therefore whatever the
  /// arrangement kept — the outbox it minted its [`Ticker`](super::Ticker)s from, or the tickers
  /// themselves — and dropping those is how such a node is stopped. That is the shipped shutdown
  /// rather than a special case: the party that can still reach a node is the party that decides it
  /// is finished.
  #[must_use]
  pub fn polling<X>(self, schedule: Schedule, context: X) -> Resident<O, W, A, L, X, S, I, M>
  where
    X: Seats<O>,
  {
    Resident {
      name: self.name,
      operator: self.operator,
      intake: self.intake,
      downstream: self.downstream,
      windows: self.windows,
      lane: self.lane,
      ack: self.ack,
      effect: self.effect,
      sweep: self.sweep,
      schedule,
      context,
      window: self.window,
      taps: self.taps,
      policies: self.policies,
      registries: self.registries,
      tracing: self.tracing,
      attribution: self.attribution,
      ledger: self.ledger,
      roots: self.roots,
      lineage: self.lineage,
      held: self.held,
      next_held: self.next_held,
      next_item: self.next_item,
      mode: self.mode,
    }
  }

  /// Route what this node emits through `downstream` — the [`Sink`] seam, and what a node with
  /// SEVERAL products is wired by.
  ///
  /// The type changes, as [`land`](Self::land)'s does and for the same reason: the downstream set
  /// is the framework's [`Downstream`] until a node hands its own, and a caller that hands none
  /// never names the parameter. Installing one REPLACES whatever was attached, windows included —
  /// the windows are per edge, and the edges are what just changed.
  #[must_use]
  pub fn wire<X>(self, downstream: X) -> Resident<O, W, A, L, C, X, I, M>
  where
    X: Sink<<O as Driven<M>>::Out>,
  {
    Resident {
      windows: core::iter::repeat_with(Outbound::new)
        .take(downstream.arity())
        .collect(),
      downstream,
      name: self.name,
      operator: self.operator,
      intake: self.intake,
      lane: self.lane,
      ack: self.ack,
      effect: self.effect,
      sweep: self.sweep,
      schedule: self.schedule,
      context: self.context,
      window: self.window,
      taps: self.taps,
      policies: self.policies,
      registries: self.registries,
      tracing: self.tracing,
      attribution: self.attribution,
      ledger: self.ledger,
      roots: self.roots,
      lineage: self.lineage,
      held: self.held,
      next_held: self.next_held,
      next_item: self.next_item,
      mode: self.mode,
    }
  }

  /// Release inputs in `ack` mode.
  #[inline]
  #[must_use]
  pub const fn with_ack(mut self, ack: AckMode) -> Self {
    self.set_ack(ack);
    self
  }

  /// [`with_ack`](Self::with_ack), in place.
  #[inline]
  pub const fn set_ack(&mut self, ack: AckMode) -> &mut Self {
    self.ack = ack;
    self
  }

  /// Declare what this node does with what it produces — see [`Effect`].
  #[inline]
  #[must_use]
  pub const fn with_effect(mut self, effect: Effect) -> Self {
    self.set_effect(effect);
    self
  }

  /// [`with_effect`](Self::with_effect), in place.
  #[inline]
  pub const fn set_effect(&mut self, effect: Effect) -> &mut Self {
    self.effect = effect;
    self
  }

  /// Look at least this often when nothing arrives.
  #[inline]
  #[must_use]
  pub const fn with_sweep(mut self, sweep: Duration) -> Self {
    self.set_sweep(sweep);
    self
  }

  /// [`with_sweep`](Self::with_sweep), in place.
  #[inline]
  pub const fn set_sweep(&mut self, sweep: Duration) -> &mut Self {
    self.sweep = sweep;
    self
  }

  /// Reach the deployment's shared resources from inside `accept` — the RUNTIME DOOR's other end.
  ///
  /// The launch walk hands every node the ONE map it built, so an operator can ask for a resource
  /// it did not take at construction. A resident wired without it answers every such ask with the
  /// map's own refusal naming the type, which is the truth from the operator's side: no such
  /// resource is reachable from here.
  #[inline]
  #[must_use]
  pub fn with_resources(mut self, resources: Arc<Resources>) -> Self {
    self.set_resources(resources);
    self
  }

  /// [`with_resources`](Self::with_resources), in place.
  #[inline]
  pub fn set_resources(&mut self, resources: Arc<Resources>) -> &mut Self {
    self.window.set_resources(resources);
    self
  }

  /// Hear the WIND-DOWN on `shutdown` — the line an `accept` reads through
  /// [`Context::shutdown`], and the launch's own half of it is what
  /// [`App::shutdown`](super::App::shutdown) announces on.
  ///
  /// A resident wired without one holds the private line [`Context::new`] minted, which nobody can
  /// say the stop on — the honest shape for a hand-driven node that no launch is winding down.
  #[inline]
  #[must_use]
  pub fn with_shutdown(mut self, shutdown: crate::ShutdownSignal) -> Self {
    self.set_shutdown(shutdown);
    self
  }

  /// [`with_shutdown`](Self::with_shutdown), in place.
  #[inline]
  pub fn set_shutdown(&mut self, shutdown: crate::ShutdownSignal) -> &mut Self {
    self.window.set_shutdown(shutdown);
    self
  }

  /// Observe through `taps`.
  #[inline]
  #[must_use]
  pub fn with_taps(mut self, taps: Taps) -> Self {
    self.set_taps(taps);
    self
  }

  /// [`with_taps`](Self::with_taps), in place.
  #[inline]
  pub fn set_taps(&mut self, taps: Taps) -> &mut Self {
    self.taps = taps;
    self
  }

  /// Decide the runtime forks with `policies`.
  ///
  /// The wiring walk calls it with the set the deployment stated, so every resident in an
  /// arrangement answers with one voice. A hand-wired resident that never calls it runs
  /// [`Policies::new`] — today's behaviour, spelled out.
  #[inline]
  #[must_use]
  pub fn with_policies(mut self, policies: Policies) -> Self {
    self.set_policies(policies);
    self
  }

  /// [`with_policies`](Self::with_policies), in place.
  #[inline]
  pub fn set_policies(&mut self, policies: Policies) -> &mut Self {
    self.policies = policies;
    self
  }

  /// The policies it runs under.
  #[inline]
  #[must_use]
  pub const fn policies(&self) -> &Policies {
    &self.policies
  }

  /// **SHARE THE ROOT-KEY REGISTRIES**: coordinate root keys through `registries`.
  ///
  /// The wiring walk calls it with the one object it built for the deployment, so every body in an
  /// arrangement coordinates through the same tables and
  /// [`App::registries`](super::App::registries) reaches those same ones. A hand-wired resident that
  /// never calls it carries none, which is the shape a resident had before there was a registry at
  /// all.
  ///
  /// It is a `with_*` and not a VERB, and the line between the two is the same one everywhere here:
  /// the registries do not change this type, because they are the DEPLOYMENT's rather than the
  /// node's — [`with_policies`](Self::with_policies)'s own reason. What IS per node is the root
  /// projection, and that arrives through [`attributing`](Self::attributing), which is a verb
  /// precisely because it changes the type.
  #[inline]
  #[must_use]
  pub fn with_registries(mut self, registries: Arc<Registries>) -> Self {
    self.set_registries(registries);
    self
  }

  /// [`with_registries`](Self::with_registries), in place.
  #[inline]
  pub fn set_registries(&mut self, registries: Arc<Registries>) -> &mut Self {
    self.registries = Some(registries);
    self
  }

  /// The root-key registries it coordinates through, or `None` where none was wired.
  #[inline]
  #[must_use]
  pub fn registries(&self) -> Option<&Registries> {
    self.registries.as_deref()
  }

  /// Open its four framework spans at `level` — the node's own `tracing(level = …)` word.
  ///
  /// The wiring walk calls it with what the declaration said, so a node's spans and its emitted
  /// query entries answer to ONE knob. A hand-wired resident that never calls it runs at
  /// [`TracingLevel::Info`], which is the same default a declaration with no word gets.
  ///
  /// It is not behind the observation feature and could not usefully be: the level is a fact about
  /// the DECLARATION, and a builder that existed in one build and not another would make a
  /// hand-wired arrangement's source depend on which features its framework was compiled with.
  #[inline]
  #[must_use]
  pub const fn with_tracing_level(mut self, level: TracingLevel) -> Self {
    self.tracing = level;
    self
  }

  /// The level its framework spans open at.
  #[inline]
  #[must_use]
  pub const fn tracing_level(&self) -> TracingLevel {
    self.tracing
  }

  /// This node's name.
  #[inline]
  #[must_use]
  pub fn name(&self) -> &NodeName {
    NodeName::new(&self.name)
  }

  /// Take the operator back, and let everything else this node held go.
  ///
  /// The ONE exception to *never handed back*, and it is the residency ruling rather than a breach
  /// of it: this is what an engine calls after its own loop has returned, ON the thread or task that
  /// owned the value, so that the goodbye a declaration enrolled has something to be said over. The
  /// value does not migrate — the engine simply stops holding the rest of the resident around it.
  ///
  /// What goes here is everything the drive layer put around the operator: the intake, the
  /// downstream and its windows, the write lane, the ledger, the resource map's handle. Every one of
  /// them has finished by the time an engine reaches this, which is why the order is safe — the loop
  /// ends when its senders are gone, and a goodbye said afterwards is said to a node nothing can
  /// still reach.
  #[inline]
  #[must_use]
  pub fn into_operator(self) -> O {
    self.operator
  }

  /// The operator this node runs.
  ///
  /// Borrowed and never handed back, which is the residency ruling as an accessor: whatever it
  /// loaded, it loaded on the engine that will run it, and a `&` is a look rather than a move.
  #[inline]
  #[must_use]
  pub const fn operator(&self) -> &O {
    &self.operator
  }

  /// When this node releases its inputs — see [`AckMode`].
  #[inline]
  #[must_use]
  pub const fn ack(&self) -> AckMode {
    self.ack
  }

  /// What this node does with what it produces — see [`Effect`].
  #[inline]
  #[must_use]
  pub const fn effect(&self) -> Effect {
    self.effect
  }

  /// How often it looks when nothing arrives.
  #[inline]
  #[must_use]
  pub const fn sweep(&self) -> Duration {
    self.sweep
  }

  /// The taps it observes through.
  #[inline]
  #[must_use]
  pub const fn taps(&self) -> &Taps {
    &self.taps
  }

  /// The intervals its poll upstreams come due on — empty where it declared none.
  #[inline]
  #[must_use]
  pub const fn schedule(&self) -> &Schedule {
    &self.schedule
  }

  /// The lending a sweep is seated through, or [`Unpolled`] where the node has no poll upstream.
  ///
  /// A LOOK and not a hand-out: the resident holds the lending so the node value does not have to,
  /// and a borrow is what a sweep's own clock context gets too.
  #[inline]
  #[must_use]
  pub const fn context(&self) -> &C {
    &self.context
  }

  /// The shared resource map, or `None` where none was wired.
  #[inline]
  #[must_use]
  pub fn resources(&self) -> Option<&Resources> {
    self.window.resources()
  }

  /// THIS NODE'S WINDOW — what every `accept` is handed first, borrowed.
  #[inline]
  #[must_use]
  pub const fn window(&self) -> &Context {
    &self.window
  }

  /// The write lane, or `()` where this node lands nothing of its own.
  #[inline]
  #[must_use]
  pub const fn lane(&self) -> &W {
    &self.lane
  }

  /// The projection its outputs' roots are read through, or `()` where none was wired.
  #[inline]
  #[must_use]
  pub const fn attribution(&self) -> &A {
    &self.attribution
  }

  /// Where its own completion rows go, or `()` where none was wired.
  #[inline]
  #[must_use]
  pub const fn ledger(&self) -> &L {
    &self.ledger
  }

  /// A sweep ringer per output edge, for a [`Sweeper`](super::Sweeper) that has to wake this node's
  /// CONSUMERS. A resident's own clock is its engine's business.
  #[must_use]
  pub fn nudges(&self) -> Vec<Box<dyn Rings>>
  where
    S: Sink<<O as Driven<M>>::Out>,
  {
    self.downstream.nudges()
  }

  /// The downstream set its emissions are routed through.
  #[inline]
  #[must_use]
  pub const fn downstream(&self) -> &S {
    &self.downstream
  }

  /// How many items are sent and not yet released, across every output edge.
  #[must_use]
  pub fn outstanding(&self) -> usize {
    self.windows.iter().map(Outbound::outstanding).sum()
  }

  /// How many inbound deliveries are waiting on their outputs — always zero under
  /// [`Local`](AckMode::Local).
  #[inline]
  #[must_use]
  pub fn holding(&self) -> usize {
    self.held.len()
  }
}

impl<O, W, A, L, C, S, I, M> Resident<O, W, A, L, C, S, I, M>
where
  O: Driven<M>,
  C: Seats<O>,
  <O as Driven<M>>::Out: Clone,
  S: Sink<<O as Driven<M>>::Out>,
  I: Intake<<O as Driven<M>>::In>,
  <O as Driven<M>>::Error: core::error::Error + Send + Sync + 'static,
  // The sweep's own two, bounded HERE rather than on [`Seats`] for the reason `Operator::Error` is
  // bounded here: the erasure a tap needs is the driver's demand, and a node whose sweeps nobody
  // observes should not pay for it in its own declaration.
  <C as Seats<O>>::Error: core::error::Error + Send + Sync + 'static,
  <C as Seats<O>>::Info: Any + Send + Sync,
  W: AsyncLands<<O as Driven<M>>::Out>,
  W::Error: core::error::Error + Send + Sync + 'static,
  A: Attributes<<O as Driven<M>>::Out>,
  // Hashed and compared for what a page costs, not for a lookup: 256 records from ONE root are ONE
  // `(root, node)` row, and without this the delivery would issue 256 identical upserts of it.
  //
  // `RootKey` is that pair plus what SHARING costs — `Send + Sync + 'static`, which is what living
  // inside the `Arc<Registry<Root>>` every resident holds a handle to asks for. It is a widening of
  // `Clone + Eq + Hash` and it is deliberate: this loop now counts into that table, and a root that
  // cannot cross a thread boundary cannot be coordinated by a component the whole deployment
  // shares. Every id in the vocabulary already satisfies it, and so does the `()` a node with no
  // projection carries.
  A::Root: RootKey,
  L: Ledger,
  L::Row: JournalRow<A::Root>,
  L::Error: core::error::Error + Send + Sync + 'static,
{
  /// **THIS PASS'S COUNTING SEAT** — the root family this node's work belongs to, or `None`.
  ///
  /// `None` for either of two honest reasons: nothing wired registries (a hand-built resident that
  /// never asked), or this node carries no projection at all — see [`Registries::counting`], where
  /// the second is argued.
  ///
  /// It is taken ONCE per pass and handed down, never reached for per item; see
  /// [`Counting`]'s own note for what that saves.
  fn counting(&self) -> Option<Counting<A::Root>> {
    Counting::open(self.registries.as_ref(), A::FAMILY)
  }

  /// The pass's LANDING half: write what the operator staged, reconcile the store's answer, record
  /// the journal row it earned, hand the survivors to the edges, and settle the obligation.
  ///
  /// Everything after the operator's own call, and the ORDER inside it is the contract — see the
  /// type's own note on the orderings that are not negotiable. It is written once per ENGINE and
  /// never per face, because none of it names the operator: a face decides how a body is spent, and
  /// this half spends nothing but the records the body already produced.
  ///
  /// This is the THREAD engine's, which blocks on its own write for the same reason it blocks in
  /// `park`. The JOURNAL row is the exception and it is the seam's own doing: [`Ledger`] has a
  /// blocking spelling, so this engine calls it and drives no future at all — the `block_on` that
  /// used to stand here was a driver spun up for a write the thread was standing right next to.
  fn landing(&mut self, staged: Staged<<O as Driven<M>>::Out>, report: &mut Drained) {
    let commit = {
      let _entered =
        observe::commit(self.tracing, self.name(), self.effect, staged.outputs.len()).entered();
      block_on(self.lane.land(&staged.outputs))
    };
    let (batches, mut held, journal) = self.reconcile(staged, commit, report);
    let recorded = self.ledger.record(&journal);
    Self::sealed(&mut held, recorded);
    block_on(self.dispatch(batches));
    self.settle(held);
  }

  /// [`landing`](Self::landing) on the ASYNC engine: the same steps in the same order, awaited
  /// rather than blocked on.
  async fn landing_async(&mut self, staged: Staged<<O as Driven<M>>::Out>, report: &mut Drained) {
    let commit = observe::commit(self.tracing, self.name(), self.effect, staged.outputs.len())
      .over(self.lane.land(&staged.outputs))
      .await;
    let (batches, mut held, journal) = self.reconcile(staged, commit, report);
    let recorded = self.ledger.record_async(&journal).await;
    Self::sealed(&mut held, recorded);
    self.dispatch(batches).await;
    self.settle(held);
  }

  /// Take the wake that woke us plus everything already queued, collapsing sweeps and collecting
  /// the poll upstreams that ticked.
  ///
  /// The queue is the INTAKE's, however many edges it holds: a multi-upstream intake walks each of
  /// its own and hands back what its join made of them, so this walk reads one list either way.
  ///
  /// The collapse is the whole point of draining first: a burst of rings is redundant by
  /// construction — each says "look again", and one look answers all of them — while every delivery
  /// is data and is kept. A tick is a ring that says WHICH store, so it collapses the same way and
  /// per upstream rather than across them.
  fn collect(
    &mut self,
    first: Wake<ItemId, <O as Driven<M>>::In>,
    report: &mut Drained,
    ticked: &mut Vec<PollUpstream>,
  ) -> Vec<Delivery<<O as Driven<M>>::In>> {
    let mut wakes = vec![first];
    self.intake.drain(&mut wakes);
    let mut deliveries = Vec::new();
    let mut swept = false;
    for wake in wakes {
      match wake {
        Wake::Delivered(delivery) => deliveries.push(delivery),
        Wake::Sweep => swept = true,
        // The tick's own cell is freed as it is DROPPED here, at the end of this arm, which is what
        // puts the coalescing window exactly where it belongs: this upstream may ring again from the
        // moment its tick is taken off the intake, and everything that rang before that is one look.
        Wake::Tick(tick) => ticked.push(tick.upstream()),
      }
    }
    if swept {
      report.sweeps += 1;
    }
    report.deliveries += deliveries.len();
    deliveries
  }

  /// The upstreams this pass will actually LOOK at: everything that ticked, once each and in
  /// declaration order.
  ///
  /// The de-duplication is the last of the per-upstream collapse. A upstream can appear twice in one
  /// pass — its cell is freed the moment its tick leaves the intake, so a ringer may queue the next
  /// one while the same drain is still walking — and two looks at one store in one pass is exactly
  /// the redundancy the cell exists to remove.
  fn looks(mut ticked: Vec<PollUpstream>) -> Vec<PollUpstream> {
    ticked.sort_unstable();
    ticked.dedup();
    ticked
  }

  /// Invoke the node's sweep entry for `upstream`, and OBSERVE what it answered.
  ///
  /// The context is LENT: `&mut C` for the call and nothing longer, which is what keeps a node
  /// struct free of handle fields. Whatever the sweep changed, it changed through the capabilities
  /// that borrow lends, so nothing is staged here — a sweep produces no records, stages nothing
  /// through the write lane and releases nobody's window.
  ///
  /// The borrow is SPLIT off `self` rather than taken through it, because the operator and the
  /// context are two fields and the call wants both mutably. [`process`](Self::process) does the
  /// same thing for the same reason, one arm over.
  ///
  /// The station is the node's own [`Effect`], the same table a delivery's verdict reads, and the
  /// info is whatever the sweep had to say about itself — which is where *deleted 412 rows* lands.
  /// It goes to the [`LifecycleTap`]s and NOWHERE ELSE: a journal row is keyed `(root, node)`,
  /// and a sweep has no record to project a root out of, so attributing one would mean inventing a
  /// root the node never named.
  async fn swept(&mut self, upstream: PollUpstream) {
    let Self {
      operator,
      context,
      effect,
      ..
    } = self;
    let observation = match context.seat(operator, upstream).await {
      Ok(Swept::Ran(info)) => effect.reached(info).erase(),
      // NOTHING IS SAID. The tick left for an executor and its answer will not come back here, so
      // an observation now would be an account of work that has not happened — and one at the end
      // is not this party's to make: the driver has moved on and the thread that will finish holds
      // no tap. See `Spawn`'s own note; a body whose outcome must be watched runs inline.
      Ok(Swept::Dispatched) => return,
      // THE SKIP SPEAKS, and it is the resident that says it: the emitted route decided the lap,
      // and this is the party holding the taps. It goes out as its own arm rather than through a
      // `Lifecycle`, because nothing arrived anywhere — a lap is not a station.
      Ok(Swept::Lapped) => Observation::Lapped { poll: upstream },
      Err(error) => Lifecycle::<<C as Seats<O>>::Info>::Failed(Failure::new(error)).erase(),
    };
    // Under THIS node's own name, which is the whole of the attribution a sweep has: nobody
    // answered for it, because a tick is not a delivery and there is no consumer downstream of it.
    self.taps.observe(NodeName::new(&self.name), &observation);
  }

  /// Take the write's answer: emit what the store took, hold what it refused, and decide what is
  /// owed for the delivery.
  ///
  /// A refused record is NOT dispatched. Its input is held, so it will be produced again when the
  /// sender re-delivers, and emitting an artifact that is not durable would let a downstream node
  /// make a derivation of something that is not there.
  ///
  /// The answer is read back BY POSITION in the slice the lane was given. Nothing here names what a
  /// record is — the keyed replace that makes the replay harmless belongs to the lane, where the
  /// record's own type is known.
  ///
  /// It also builds this node's own journal rows, from the roots of the records that COMMITTED
  /// and at the station this delivery will answer with — the strong half's payload, which the caller
  /// writes before the ack goes out.
  ///
  /// It is named for what it does rather than for the lane, because [`land`](Self::land) is the
  /// BUILDER's verb: this runs after [`AsyncLands::land`] has answered, and reconciles that answer with
  /// what the delivery staged.
  fn reconcile(
    &mut self,
    staged: Staged<<O as Driven<M>>::Out>,
    commit: Commit<W::Error>,
    report: &mut Drained,
  ) -> (Emitted<<O as Driven<M>>::Out>, Held, Vec<L::Row>) {
    let Staged {
      id,
      mut owed,
      mut verdict,
      outputs,
      owner,
      mut descent,
    } = staged;
    let mut batches: Emitted<<O as Driven<M>>::Out> = core::iter::repeat_with(Vec::new)
      .take(self.downstream.arity())
      .collect();

    let attempted = outputs.len();
    let mut committed = 0usize;
    // The roots whose records reached the store, de-duplicated: a page of 256 from one root is ONE
    // `(root, node)` row, and writing it 256 times would be 256 statements saying the same thing.
    let mut landed: Vec<A::Root> = Vec::new();
    let mut seen: HashSet<A::Root> = HashSet::new();
    // Opened BEFORE the walk, so the whole delivery counts through one table and one instant. The
    // de-duplication above is NOT shared with it: a journal row is one per `(root, node)` and an
    // inflight count is one per ITEM, so the count is taken inside `fan_out`, per item that
    // actually went onto an edge.
    //
    // Not opened at all for a delivery that staged nothing, which is what a filtering node's
    // ordinary pass looks like: a family-map lock and two clock readings for a walk with no items
    // in it would be paid by every node that refused everything it was handed.
    let counting = if attempted == 0 {
      None
    } else {
      self.counting()
    };
    for (position, output) in outputs.into_iter().enumerate() {
      let mine = owner[position];
      if commit.committed(position) {
        committed += 1;
        let root = self.attribution.root(&output);
        if seen.insert(root.clone()) {
          landed.push(root.clone());
        }
        self.fan_out(
          output,
          root,
          &mut batches,
          &mut descent[mine].produced,
          &mut verdict,
          counting.as_ref(),
        );
      } else {
        verdict.tally.refused += 1;
        descent[mine].refused = true;
      }
    }
    // The COUNT is the socket's fact and the reason is the lane's, so the two are reported as one
    // error with the lane's own kept as its source. First failure wins, as it does for `accept`:
    // one delivery states one station.
    if committed < attempted
      && verdict.failure.is_none()
      && let Some(refusal) = commit.into_refusal()
    {
      verdict.failure = Some(Failure::new(Unwritten::new(attempted, committed, refusal)));
    }

    match self.ack {
      AckMode::Local => {
        for item in descent {
          if item.is_done() {
            owed.release(item.key);
          }
        }
      }
      AckMode::Chained => {
        for item in descent {
          if !item.is_done() {
            continue;
          }
          // No outputs means nothing to wait for, which a refcount answers at once and a
          // "wait for a child" rule would deadlock on.
          if self
            .lineage
            .expect(HeldItem::new(id, item.key), item.produced)
          {
            owed.release(item.key);
          }
        }
      }
    }
    report.tally.processed += verdict.tally.processed;
    report.tally.emitted += verdict.tally.emitted;
    report.tally.skipped += verdict.tally.skipped;
    report.tally.failed += verdict.tally.failed;
    report.tally.refused += verdict.tally.refused;

    // The STRONG half's rows. Only at `Persisted`, because that is what a completion row says: this
    // node finished this root. A failure or a refusal is the other node's story to tell — it reaches
    // the record through whoever SENT this delivery, whose answer names this node as the worker.
    let journal = if verdict.station(self.effect).is_persisted() {
      let now = SystemTime::now();
      landed
        .iter()
        .map(|root| L::Row::of(root, NodeName::new(&self.name), &Self::completed(), now))
        .collect()
    } else {
      Vec::new()
    };
    (batches, Held { id, owed, verdict }, journal)
  }

  /// The observation a completion row is built from: this node's own `Persisted`, carrying no info.
  ///
  /// Built rather than taken from the ack, because the ack's own [`Lifecycle`] is consumed on its way
  /// to the sender and the row is written BEFORE it goes. The station is the fact the row is about;
  /// the per-item tally belongs to the answer.
  fn completed() -> super::Arrival {
    Lifecycle::<()>::Persisted(()).arrive()
  }

  /// Fold the control store's answer into the delivery's verdict.
  ///
  /// A refused completion row makes the delivery a FAILURE, exactly as a refused content write does,
  /// and for the same reason: the ack certifies the row, so an ack that went out over a row that did
  /// not would make the journal answer a question it cannot answer. First failure wins, as
  /// everywhere else here — one delivery states one station.
  fn sealed(held: &mut Held, recorded: Result<(), L::Error>) {
    if let Err(refusal) = recorded
      && held.verdict.failure.is_none()
    {
      held.verdict.failure = Some(Failure::new(refusal));
    }
  }

  /// One emission, one item per output edge THAT CARRIES ITS PRODUCT — each with its own id, so the
  /// join counts arms.
  ///
  /// Which edges those are is [`Sink::carries`]'s answer and never a count taken here. A
  /// one-product downstream set carries every output on every edge, which is the fan-out this crate has
  /// always had; a node that declared several products has one subscription per product, and
  /// putting a caption on the summary's edge would be a type the consumer never asked for.
  fn fan_out(
    &mut self,
    output: <O as Driven<M>>::Out,
    root: A::Root,
    batches: &mut [Vec<Item<<O as Driven<M>>::Out>>],
    produced: &mut Vec<ItemId>,
    verdict: &mut Verdict,
    counting: Option<&Counting<A::Root>>,
  ) {
    let last = (0..batches.len())
      .rev()
      .find(|edge| self.downstream.carries(*edge, &output));
    let Some(last) = last else {
      // An emission with nowhere on the WIRE to go, and what that means is what the node's
      // [`Effect`] says. At a PURE node an emission's only destination is an edge, so this is a
      // gap — recorded rather than dropped in silence, as the framework's own refusal honestly
      // carrying no content, because core cannot name the app's item. It is counted as a REFUSAL
      // and not as an emission, which is what makes the delivery's station `Skipped` rather than a
      // durability this node did not achieve. It is also the per-delivery half of the same fact
      // `PureLeafError` refuses a whole node for.
      //
      // At a LANDING node the destination was the store and the record reached it; a downstream
      // edge is where it goes NEXT, if anywhere, and having none is the ordinary end of a lane.
      //
      // A node with several products reaches here per PRODUCT: an unsubscribed product is this same
      // gap, stated about the one output rather than about the node.
      if self.effect.is_pure() {
        verdict.tally.skipped += 1;
        if verdict.skip.is_none() {
          verdict.skip = Some(Skip::new(SkipReason::NoConsumers));
        }
      }
      return;
    };
    verdict.tally.emitted += 1;
    // The projection was read ONCE, by the caller and before this record's fate was decided. Every
    // edge's item carries the same root because it carries the same record — a fan-out is one record
    // at several consumers, each of which will answer about it separately.
    //
    // The value moves into the LAST CARRYING edge and is cloned for the others, so the
    // one-consumer case — which is most of them — pays for no clone at all.
    //
    // The walk STOPS at that edge, and that is what keeps the value readable throughout: past the
    // last edge that carries this product there is nothing left to route and nothing left to ask
    // `carries` about.
    let mut value = Some(output);
    for (edge, batch) in batches.iter_mut().enumerate().take(last + 1) {
      let held = value
        .as_ref()
        .expect("the value is taken only at the last edge");
      if edge != last && !self.downstream.carries(edge, held) {
        continue;
      }
      let id = ItemId::new(self.next_item);
      self.next_item += 1;
      let copy = if edge == last {
        value.take().expect("taken exactly once")
      } else {
        held.clone()
      };
      batch.push(Item::new(id, copy));
      self.roots.insert(id, root.clone());
      // **THE `+1`, AND WHERE IT SITS IS THE WHOLE POINT.** It is beside the map entry because the
      // two say the same thing — this node has an item out under this root — and because this is
      // the last moment before the ack is even considered: `reconcile` fans out its whole delivery
      // here, and only then releases the input's obligation. See the type's own note on the
      // orderings that are not negotiable.
      //
      // Per EDGE and not per record. A record on two edges is two items, two consumers and two
      // separate answers, so a count taken once per record would go to zero while one of the two
      // was still out.
      if let Some(counting) = counting {
        counting.dispatched(&root);
      }
      produced.push(id);
    }
  }

  /// Hand each edge its batch through the downstream set, AWAITING room.
  ///
  /// One walk for both engines, because the wait is the [`Sink`]'s: the thread engine drives this
  /// future to completion on its own thread and the async engine awaits it, which is the same trade
  /// the write already makes. The backpressure is therefore the driver's and never the operator's —
  /// an emission was staged into the [`Emitter`](crate::Emitter) without waiting for anybody, and
  /// the wait happens here, after the operator has returned.
  async fn dispatch(&mut self, batches: Emitted<<O as Driven<M>>::Out>) {
    for (edge, batch) in batches.into_iter().enumerate() {
      if batch.is_empty() {
        continue;
      }
      let ids: Vec<ItemId> = batch.iter().map(|item| *item.key()).collect();
      let (ack, answers) = ack_channel();
      if self.downstream.deliver(edge, batch, ack).await {
        self.windows[edge].record(ids, answers);
      } else {
        self.hung_up(&ids);
      }
    }
  }

  /// A consumer that has hung up will never release these.
  ///
  /// Two consequences, and both are stated rather than inferred: the refusal is OBSERVED, since a
  /// tap is the only vantage an app has on it, and under [`Chained`](AckMode::Chained) the lineage
  /// forgets them — a join waiting on an arm that no longer exists would hold its input forever.
  fn hung_up(&mut self, ids: &[ItemId]) {
    // Under THIS node's own name, which is the one case where that is right: there is no worker to
    // name, because nobody took the delivery. It is the framework speaking for the sender about a
    // dispatch that reached nowhere.
    let observation = Lifecycle::<Tally>::Skipped(Skip::new(SkipReason::ServiceInactive)).erase();
    self.taps.observe(NodeName::new(&self.name), &observation);
    let counting = self.counting();
    for id in ids {
      // Their answers will never arrive, so their roots would sit in the map forever.
      //
      // **AND SO WOULD THEIR COUNT** — the third consequence, and it is the registry's. These items
      // were counted out at `fan_out` and nothing is ever coming back for them, so a key whose only
      // outstanding work went to a hung-up consumer would stay `Analyzing` for the life of the
      // deployment. Crediting them here is what makes *inflight is dispatched minus answered* true
      // over a graph where a consumer can leave.
      let credited = self.roots.remove(id);
      if let (Some(counting), Some(root)) = (counting.as_ref(), credited) {
        counting.observed(&root);
      }
      if self.ack.is_chained() {
        self.lineage.retract(id);
      }
    }
  }

  /// Collect the answers this node's outputs have earned, observe them, and release whatever they
  /// complete.
  ///
  /// An answer is observed under the WORKER's name and never under this node's. The observation was
  /// produced by the consumer downstream — its station is a fact about that node's work — so a run
  /// record keyed `(root, node)` written from this node's name would name the wrong node in every
  /// row it wrote.
  fn harvest(&mut self) {
    // Taken before the borrows below split `self`, and once for the whole pass: a harvest may walk
    // several windows' worth of answers, and every one of them counts into the same family at the
    // same instant.
    //
    // Not taken where this node has nothing out. `roots` is exactly the set of items whose answers
    // could decrement anything, so an empty one means no answer this pass can be about work of
    // ours — and this runs on EVERY loop pass, sweeps included, so an idle node would otherwise pay
    // the family map's lock and two clock readings every few milliseconds for the rest of its life.
    let counting = if self.roots.is_empty() {
      None
    } else {
      self.counting()
    };
    let taps = &self.taps;
    let attribution = &self.attribution;
    let roots = &mut self.roots;
    let mut released: Vec<ItemId> = Vec::new();
    for window in &mut self.windows {
      for answer in window.harvest().into_answers() {
        taps.observe(answer.worker(), answer.observation());
        released.extend(answer.released().iter().copied());
        // An ack always carries an ARRIVAL — a consumer answers about an ITEM, and the framework's
        // own observations are about no item any consumer holds — so the other arms are skipped
        // rather than unwrapped: a run record is keyed `(root, node, station)`, and an observation
        // with no station has no honest row to write.
        let Some(arrival) = answer.observation().arrival() else {
          continue;
        };
        // Every key the answer SPOKE FOR and not only the ones it released, because a failure
        // releases nothing and is the observation most worth attributing. The root is taken out of
        // the map: an item that was not released comes back under a fresh id, so keeping the old
        // one would leak an entry per retry.
        for id in answer.covered() {
          if let Some(root) = roots.remove(id) {
            attribution.observe(&root, answer.worker(), arrival);
            // **THE `-1`**, beside the map entry leaving for `fan_out`'s reason: the two say the
            // same thing, and this is the moment the item stops being out. Every key the answer
            // SPOKE FOR and not only the ones it released — a failure releases nothing and its item
            // comes back under a fresh id, which is a fresh `+1`, so counting only releases would
            // leak one per retry.
            if let Some(counting) = counting.as_ref() {
              counting.observed(&root);
            }
          }
        }
      }
    }
    if !self.ack.is_chained() {
      return;
    }
    for id in released {
      let Some(parent) = self.lineage.retire(&id) else {
        continue;
      };
      let delivery = parent.delivery();
      let Some(entry) = self.held.get_mut(&delivery) else {
        continue;
      };
      entry.owed.release(parent.into_key());
      if entry.owed.is_complete() {
        let mut entry = self.held.remove(&delivery).expect("just borrowed it");
        let lifecycle = core::mem::take(&mut entry.verdict).into_lifecycle(self.effect);
        entry.owed.settle(self.name.clone(), lifecycle);
      }
    }
  }

  /// Send the ack if it is due, or hold the obligation until its outputs come back.
  fn settle(&mut self, mut held: Held) {
    if self.ack.is_local() || held.owed.is_complete() {
      let lifecycle = core::mem::take(&mut held.verdict).into_lifecycle(self.effect);
      held.owed.settle(self.name.clone(), lifecycle);
      return;
    }
    self.held.insert(held.id, held);
  }

  /// The last pass before the loop returns: harvest whatever came back, then answer every still-held
  /// obligation with what it has, since nothing more is coming.
  fn finish(&mut self) {
    self.harvest();
    let effect = self.effect;
    let name = self.name.clone();
    for (_, mut held) in self.held.drain() {
      let lifecycle = core::mem::take(&mut held.verdict).into_lifecycle(effect);
      held.owed.settle(name.clone(), lifecycle);
    }
  }
}

/// THE DRIVING MATRIX: which of the two engines spends which of the two faces, and how.
///
/// Four cells, all legal, and each one a line in a [`Resident`]'s loop:
///
/// | | [`Operator`] (blocking) | [`AsyncOperator`] (awaited) |
/// |---|---|---|
/// | **thread engine** ([`run`](Self::run)) | a PURE DIRECT CALL — no future is minted | `block_on`, the same driver every other async seam is spent through here |
/// | **async engine** ([`run_async`](Self::run_async)) | the same direct call, INLINE in the resident's task | awaited |
///
/// # Why this is a trait and not four methods on the type
///
/// Because the two faces have to EXIST CONDITIONALLY, and stable Rust offers exactly one mechanism
/// for that: distinct Self types. Two inherent `impl` blocks differing only in a where-clause are
/// `E0592` — rustc does not read where-clauses when it looks for duplicate inherent methods — and
/// two impls of one trait for one Self type are `E0119` whatever their bounds say. The face
/// parameter makes `Resident<…, Block>` and `Resident<…, Async>` two types, and then one trait
/// with two impls is ordinary.
///
/// # Heavy blocking work on the async engine is the AUTHOR's word, never a stolen spawn
///
/// The async × blocking cell runs the body inline, in the resident's own task, and a long one there
/// holds the executor's worker. The answer is the node's engine word — the thread engine exists for
/// exactly this, and it is where a `!Send` unit already lives. It is not a `spawn_blocking` taken
/// behind the author's back, and it could not be: `accept` borrows the operator and the emitter, and
/// neither borrow crosses the `'static` wall a spawn demands.
///
/// # Nothing here is chosen at run time
///
/// [`SYNC`](Self::SYNC) states the face for a proof or a diagnostic and decides nothing: a const
/// cannot select an impl on stable, so every fork above is taken by a BOUND, at compile time, by
/// which of the two faces the operator's type wears.
///
/// # The STREAMING contract is a table of its own, and this pair is unchanged by it
///
/// This paragraph said *the SESSION execution contract … is a further middle third and this seam is
/// left open for it* until that contract was written. It is written now, and it did NOT arrive as a
/// third row here. [`StreamOperator`](crate::StreamOperator) /
/// [`AsyncStreamOperator`](crate::AsyncStreamOperator) is the un-buffered shape a demuxer needs, and
/// what drives it is [`StreamLane`](super::StreamLane) — its own two-by-one table, with the same
/// [`Block`] and [`Async`] parameter and the same `E0592` argument for it.
///
/// A separate driver rather than two more methods here, and the reason is what the two drivers
/// COUNT. This one's unit of work is an ITEM: a delivery is walked, `accept` is called per item, each
/// item's outcome is folded into a per-delivery verdict and a per-item obligation. The streaming
/// one's unit is the DELIVERY: one call spans the whole of it, there is no per-item outcome to fold,
/// and what a lane holds instead is N warm instances, an admission bound and a feed depth — none of
/// which is a field this loop has anywhere to put. Two loops that share a vocabulary and not a body
/// are two types, and both spend the same [`Sink`], the same [`Taps`], the same [`Owed`] and the same
/// [`Effect`].
///
/// So the table below is COMPLETE rather than open: the four cells are the whole of what a buffered
/// unit can be driven as.
#[diagnostic::on_unimplemented(
  message = "`{Self}` has no engine",
  label = "this resident cannot be run",
  note = "a resident is drivable when every seam around its operator is satisfied: the downstream \
          set is a `Sink` of the product, the intake an `Intake` of the message, the lane an \
          `AsyncLands`, the poll context a `Seats`, the ledger a `Ledger`, and the operator's own \
          error, the sweep's error and info, and the attribution's root carry the driver's \
          erasure bounds",
  note = "and the FACE has to match: `Resident<…, Block>` is driven for an `Operator` and \
          `Resident<…, Async>` for an `AsyncOperator`"
)]
pub trait Drives {
  /// Whether the operator this drives answers without a future — [`Driven::SYNC`] for the face the
  /// resident was built on.
  ///
  /// It PROVES and never selects. A deployment folds one of these per node into the emitted root's
  /// `ALL_SYNC`, which is what an assertion about a whole graph reads.
  const SYNC: bool;

  /// Run on THIS thread until every sender is gone — the thread engine.
  ///
  /// It parks in a blocking receive with the sweep as its timeout, so an idle node costs a reserved
  /// stack and no CPU, and a wake is a notify rather than a spawn. Where the node declared poll
  /// upstreams, that timeout is the nearest of them and the sweep — one park serving every clock this
  /// node has, which is why the poll mode needs no thread of its own.
  fn run(&mut self) -> Drained;

  /// Run as a task until every sender is gone — the async engine.
  ///
  /// The differences from [`run`](Self::run) are the park, the write and the dispatch. The sweep
  /// arrives as [`Wake::Sweep`] on the intake instead of as a timeout — and a poll tick as
  /// [`Wake::Tick`], rung by the launch's own clock over this node's own schedule — while the write
  /// and a full edge are awaited rather than blocked on: the same ordering and the same
  /// backpressure, expressed in the engine that is running.
  fn run_async(&mut self) -> impl Future<Output = Drained>;
}

impl<O, W, A, L, C, S, I> Resident<O, W, A, L, C, S, I, Block>
where
  O: Operator,
  A: Attributes<<O as Operator>::Out>,
  S: Sink<<O as Operator>::Out>,
  <O as Operator>::Error: core::error::Error + Send + Sync + 'static,
{
  /// Run the operator over one delivery and STAGE what it produced.
  ///
  /// THE BLOCKING FACE's, and the whole of what makes this cell the direct one: the call answers,
  /// so this is an ordinary `fn` whose return type is a `Staged` rather than a future over one.
  ///
  /// It emits nothing and releases nothing: the records go to the write lane first, and only
  /// what the store took is handed to the edges. [`reconcile`](Resident::reconcile) is the other
  /// half, and [`landing`](Resident::landing) is what calls it.
  ///
  /// # Why the WALK is the driver's, and not the operator's
  ///
  /// `accept` takes a [`Delivery`], and this hands it ONE ITEM per call: the
  /// obligation this batch owes is per item — a failed item holds its own key while its neighbours
  /// are released, and 250 of 256 is an ordinary answer — so the driver has to know which input each
  /// outcome belongs to, and one `Result` for a page could not say. The custody token stays here
  /// with the obligation ([`Delivery::in_custody`] is the shape that goes out), which is the ruled
  /// "ack protocol unchanged beneath".
  ///
  /// A body written as a walk over its delivery is what keeps compiling when the full-custody
  /// contract hands the whole page across, which is why the parameter is the delivery and not the
  /// bare message.
  ///
  fn process(
    &mut self,
    delivery: Delivery<<O as Operator>::In>,
    report: &mut Drained,
  ) -> Staged<<O as Operator>::Out> {
    let (payload, ack) = delivery.into_parts();
    report.items += payload.len();
    let owed = Owed::open(payload.keys().copied(), ack);
    let mut pass = Pass::opening(payload.len());

    // Split BEFORE the walk: the operator is borrowed mutably per item while the map and the
    // downstream set are read, and the three are disjoint fields of one value.
    let Self {
      operator,
      window,
      downstream,
      ..
    } = self;
    let wanted = downstream.connected();

    for item in payload {
      let key = *item.key();
      let mut emitter = Emitter::new().wanting(wanted);
      let outcome = operator.accept(
        window,
        Delivery::in_custody(Payload::One(item)),
        &mut emitter,
      );
      pass.absorb(key, emitter, outcome);
    }

    let id = self.next_held;
    self.next_held += 1;
    pass.staged(id, owed)
  }
}

impl<O, W, A, L, C, S, I> Resident<O, W, A, L, C, S, I, Async>
where
  O: AsyncOperator,
  A: Attributes<<O as AsyncOperator>::Out>,
  S: Sink<<O as AsyncOperator>::Out>,
  <O as AsyncOperator>::Error: core::error::Error + Send + Sync + 'static,
{
  /// Run the operator over one delivery and STAGE what it produced.
  ///
  /// THE AWAITED FACE's: the same walk with the one call awaited. Everything either side of it is
  /// [`Pass`]'s, which is why the two middles differ by a line.
  ///
  /// It emits nothing and releases nothing: the records go to the write lane first, and only
  /// what the store took is handed to the edges. [`reconcile`](Resident::reconcile) is the other
  /// half, and [`landing`](Resident::landing) is what calls it.
  ///
  /// # Why the WALK is the driver's, and not the operator's
  ///
  /// `accept` takes a [`Delivery`], and this hands it ONE ITEM per call: the
  /// obligation this batch owes is per item — a failed item holds its own key while its neighbours
  /// are released, and 250 of 256 is an ordinary answer — so the driver has to know which input each
  /// outcome belongs to, and one `Result` for a page could not say. The custody token stays here
  /// with the obligation ([`Delivery::in_custody`] is the shape that goes out), which is the ruled
  /// "ack protocol unchanged beneath".
  ///
  /// A body written as a walk over its delivery is what keeps compiling when the full-custody
  /// contract hands the whole page across, which is why the parameter is the delivery and not the
  /// bare message.
  ///
  async fn process(
    &mut self,
    delivery: Delivery<<O as AsyncOperator>::In>,
    report: &mut Drained,
  ) -> Staged<<O as AsyncOperator>::Out> {
    let (payload, ack) = delivery.into_parts();
    report.items += payload.len();
    let owed = Owed::open(payload.keys().copied(), ack);
    let mut pass = Pass::opening(payload.len());

    // Split BEFORE the walk: the operator is borrowed mutably per item while the map and the
    // downstream set are read, and the three are disjoint fields of one value.
    let Self {
      operator,
      window,
      downstream,
      ..
    } = self;
    let wanted = downstream.connected();

    for item in payload {
      let key = *item.key();
      let mut emitter = Emitter::new().wanting(wanted);
      let outcome = operator
        .accept(
          window,
          Delivery::in_custody(Payload::One(item)),
          &mut emitter,
        )
        .await;
      pass.absorb(key, emitter, outcome);
    }

    let id = self.next_held;
    self.next_held += 1;
    pass.staged(id, owed)
  }
}

/// The BLOCKING face's two cells — a direct call on either engine.
impl<O, W, A, L, C, S, I> Drives for Resident<O, W, A, L, C, S, I, Block>
where
  O: Operator,
  C: Seats<O>,
  <O as Operator>::Out: Clone,
  S: Sink<<O as Operator>::Out>,
  I: Intake<<O as Operator>::In>,
  <O as Operator>::Error: core::error::Error + Send + Sync + 'static,
  <C as Seats<O>>::Error: core::error::Error + Send + Sync + 'static,
  <C as Seats<O>>::Info: Any + Send + Sync,
  W: AsyncLands<<O as Operator>::Out>,
  W::Error: core::error::Error + Send + Sync + 'static,
  A: Attributes<<O as Operator>::Out>,
  A::Root: RootKey,
  L: Ledger,
  L::Row: JournalRow<A::Root>,
  L::Error: core::error::Error + Send + Sync + 'static,
{
  const SYNC: bool = <O as Driven<Block>>::SYNC;

  fn run(&mut self) -> Drained {
    let mut report = Drained::default();
    let mut clock = Clock::start(&self.schedule, Instant::now());
    // Minted ONCE, outside the loop: a gate is a policy handle and a node name, and neither changes
    // for as long as this body runs.
    let ticks = self.policies.ticks(self.name.clone(), self.taps.clone());
    loop {
      let Some(wake) = self.intake.park(clock.park_for(self.sweep, Instant::now())) else {
        break;
      };
      let mut ticked = Vec::new();
      for delivery in self.collect(wake, &mut report, &mut ticked) {
        // THE BATCH SPAN, entered rather than wrapped: this engine blocks in place, so the guard is
        // held across a call that parks the thread and never across a yield.
        let batch = observe::batch(self.tracing, self.name(), delivery.payload().len());
        // THREAD × BLOCKING — a PURE DIRECT CALL. `accept` answers a `Result`, so the operator's
        // own step mints no future and `block_on` is not reached FOR IT; the calls below it still
        // spend one on the lane, the ledger and the dispatch, which are async seams whose blocking
        // twins are a different round's. And for a single-inbox node the park above is a blocking
        // receive rather than a select, so nothing of the OPERATOR's is driven anywhere in this
        // pass. (A node with SEVERAL upstreams keeps exactly one future, and it is the intake's
        // WAIT — never the body's.)
        let staged = {
          let _entered = batch.entered();
          self.process(delivery, &mut report)
        };
        self.landing(staged, &mut report);
      }
      // The intake's own rings collapse FIRST, and the clock's ticks are appended after — which is
      // what keeps a made-up interval from being collapsed away. A burst of rings from one upstream
      // says the same thing several times and is one look; a series of owed intervals is several
      // DIFFERENT instants, and a policy that asked for them asked for one look each.
      //
      // The thread engine's own ticks are synthesised here because this engine has no ringer to
      // deliver them. They are swept in the SAME place the async engine sweeps its own — after the
      // pass's deliveries — so a maintenance look always sees this pass's writes rather than the
      // state before them.
      let mut looks = Self::looks(ticked);
      clock.take_due(Instant::now(), &mut looks, &ticks);
      for upstream in looks {
        let _entered = observe::tick(self.tracing, self.name(), upstream).entered();
        block_on(self.swept(upstream));
        report.ticks += 1;
      }
      self.harvest();
    }
    self.finish();
    report
  }

  async fn run_async(&mut self) -> Drained {
    let mut report = Drained::default();
    while let Some(wake) = self.intake.park_async().await {
      let mut ticked = Vec::new();
      for delivery in self.collect(wake, &mut report, &mut ticked) {
        let batch = observe::batch(self.tracing, self.name(), delivery.payload().len());
        // ASYNC × BLOCKING — the same direct call, INLINE in the resident's own task. Heavy work
        // on this cell is the author's engine word to answer, never a spawn stolen here: `accept`
        // borrows the operator and the emitter, and neither borrow can cross the `'static` wall a
        // spawn puts in front of it.
        //
        // The span is ENTERED rather than wrapped, which is the one place this engine's rule flips:
        // a direct call has no await inside it, so no other task can be scheduled onto this thread
        // while the guard is held.
        let staged = {
          let _entered = batch.entered();
          self.process(delivery, &mut report)
        };
        self.landing_async(staged, &mut report).await;
      }
      for upstream in Self::looks(ticked) {
        observe::tick(self.tracing, self.name(), upstream)
          .over(self.swept(upstream))
          .await;
        report.ticks += 1;
      }
      self.harvest();
    }
    self.finish();
    report
  }
}

/// The AWAITED face's two cells — `block_on` on the thread engine, `await` on the async one.
impl<O, W, A, L, C, S, I> Drives for Resident<O, W, A, L, C, S, I, Async>
where
  O: AsyncOperator,
  C: Seats<O>,
  <O as AsyncOperator>::Out: Clone,
  S: Sink<<O as AsyncOperator>::Out>,
  I: Intake<<O as AsyncOperator>::In>,
  <O as AsyncOperator>::Error: core::error::Error + Send + Sync + 'static,
  <C as Seats<O>>::Error: core::error::Error + Send + Sync + 'static,
  <C as Seats<O>>::Info: Any + Send + Sync,
  W: AsyncLands<<O as AsyncOperator>::Out>,
  W::Error: core::error::Error + Send + Sync + 'static,
  A: Attributes<<O as AsyncOperator>::Out>,
  A::Root: RootKey,
  L: Ledger,
  L::Row: JournalRow<A::Root>,
  L::Error: core::error::Error + Send + Sync + 'static,
{
  const SYNC: bool = <O as Driven<Async>>::SYNC;

  fn run(&mut self) -> Drained {
    let mut report = Drained::default();
    let mut clock = Clock::start(&self.schedule, Instant::now());
    // Minted ONCE, outside the loop: a gate is a policy handle and a node name, and neither changes
    // for as long as this body runs.
    let ticks = self.policies.ticks(self.name.clone(), self.taps.clone());
    loop {
      let Some(wake) = self.intake.park(clock.park_for(self.sweep, Instant::now())) else {
        break;
      };
      let mut ticked = Vec::new();
      for delivery in self.collect(wake, &mut report, &mut ticked) {
        // THE BATCH SPAN, entered rather than wrapped: this engine blocks in place, so the guard is
        // held across a call that parks the thread and never across a yield.
        let batch = observe::batch(self.tracing, self.name(), delivery.payload().len());
        // THREAD × AWAITED — `block_on`, which is the machinery this layer already runs every other
        // async seam through on this engine: the lane's write, the ledger's row, the dispatch.
        let staged = {
          let _entered = batch.entered();
          block_on(self.process(delivery, &mut report))
        };
        self.landing(staged, &mut report);
      }
      // The intake's own rings collapse FIRST, and the clock's ticks are appended after — which is
      // what keeps a made-up interval from being collapsed away. A burst of rings from one upstream
      // says the same thing several times and is one look; a series of owed intervals is several
      // DIFFERENT instants, and a policy that asked for them asked for one look each.
      //
      // The thread engine's own ticks are synthesised here because this engine has no ringer to
      // deliver them. They are swept in the SAME place the async engine sweeps its own — after the
      // pass's deliveries — so a maintenance look always sees this pass's writes rather than the
      // state before them.
      let mut looks = Self::looks(ticked);
      clock.take_due(Instant::now(), &mut looks, &ticks);
      for upstream in looks {
        let _entered = observe::tick(self.tracing, self.name(), upstream).entered();
        block_on(self.swept(upstream));
        report.ticks += 1;
      }
      self.harvest();
    }
    self.finish();
    report
  }

  async fn run_async(&mut self) -> Drained {
    let mut report = Drained::default();
    while let Some(wake) = self.intake.park_async().await {
      let mut ticked = Vec::new();
      for delivery in self.collect(wake, &mut report, &mut ticked) {
        let batch = observe::batch(self.tracing, self.name(), delivery.payload().len());
        // ASYNC × AWAITED — the body is awaited, and THE SPAN IS WRAPPED rather than entered: an
        // executor is free to run another task on this thread at every await inside, and a guard
        // held here would attribute that task's work to this node.
        let staged = batch.over(self.process(delivery, &mut report)).await;
        self.landing_async(staged, &mut report).await;
      }
      for upstream in Self::looks(ticked) {
        observe::tick(self.tracing, self.name(), upstream)
          .over(self.swept(upstream))
          .await;
        report.ticks += 1;
      }
      self.harvest();
    }
    self.finish();
    report
  }
}

#[cfg(test)]
mod inflight_tests;

#[cfg(test)]
mod matrix_tests;

#[cfg(test)]
mod tests;