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
use crate::Context;
use core::time::Duration;

use std::{
  collections::{HashSet, VecDeque},
  sync::{
    Arc, Mutex,
    atomic::{AtomicUsize, Ordering},
  },
  thread,
  time::Instant,
};

use super::super::{
  Ack, AckMode, AckReceiver, Answer, AsyncLands, Commit, Delivery, Drives, Effect, Inbox, Item,
  ItemId, Lifecycle, Outbox, Payload, RecordingTap, Resident, Settled, Station, Tally, Taps,
  Unpolled, Wake, ack_channel, channel,
};
use crate::{Emitter, Operator, Rings, Sink, SkipReason};

/// Emits `2 * item`. One in, one out.
struct Doubling;

impl Operator for Doubling {
  type Error = core::convert::Infallible;
  type In = u64;
  type Out = u64;

  fn accept(
    &mut self,
    _ctx: &Context,
    delivery: Delivery<Self::In>,
    emitter: &mut Emitter<u64>,
  ) -> Result<(), Self::Error> {
    for item in delivery.into_items() {
      let item = item.into_value();
      emitter.emit(item * 2);
    }
    Ok(())
  }
}

/// Emits twice per item — the 1→N shape a chained join has to count.
struct Splitting;

impl Operator for Splitting {
  type Error = core::convert::Infallible;
  type In = u64;
  type Out = u64;

  fn accept(
    &mut self,
    _ctx: &Context,
    delivery: Delivery<Self::In>,
    emitter: &mut Emitter<u64>,
  ) -> Result<(), Self::Error> {
    for item in delivery.into_items() {
      let item = item.into_value();
      emitter.emit(item);
      emitter.emit(item + 1_000);
    }
    Ok(())
  }
}

/// Refuses odd items and emits even ones.
struct Sieving;

impl Operator for Sieving {
  type Error = core::convert::Infallible;
  type In = u64;
  type Out = u64;

  fn accept(
    &mut self,
    _ctx: &Context,
    delivery: Delivery<Self::In>,
    emitter: &mut Emitter<u64>,
  ) -> Result<(), Self::Error> {
    for item in delivery.into_items() {
      let item = item.into_value();
      if item.is_multiple_of(2) {
        emitter.emit(item);
      } else {
        emitter.skip(SkipReason::Filtered);
      }
    }
    Ok(())
  }
}

#[derive(Debug, derive_more::Display)]
#[display("item {_0} is not decodable")]
struct Undecodable(u64);

impl core::error::Error for Undecodable {}

/// Emits, then fails, on the one item it is told to fail on — so the test can see that
/// emissions buffered before an error still travel.
struct Brittle(u64);

impl Operator for Brittle {
  type Error = Undecodable;
  type In = u64;
  type Out = u64;

  fn accept(
    &mut self,
    _ctx: &Context,
    delivery: Delivery<Self::In>,
    emitter: &mut Emitter<u64>,
  ) -> Result<(), Self::Error> {
    for item in delivery.into_items() {
      let item = item.into_value();
      emitter.emit(item * 2);
      if item == self.0 {
        return Err(Undecodable(item));
      }
    }
    Ok(())
  }
}

#[derive(Debug, derive_more::Display)]
#[display("{_0} rows did not go in")]
struct RowsRefused(usize);

impl core::error::Error for RowsRefused {}

/// What a lane wrote, shared with the walk that is watching it.
type Written = Arc<Mutex<Vec<u64>>>;

/// A write lane a walk can steer.
///
/// Three knobs, each for one question the socket has to answer: WHAT reached the store (the
/// ledger), what did NOT (a per-call set of refused positions), and WHEN — the gate, which holds
/// the node inside its own write so a walk can look at the oneshot while the write is still
/// running. That last one is the only way to state the ordering as a "not yet" rather than as a
/// "yes eventually".
struct Table {
  written: Written,
  /// Positions to refuse, ONE set per call and then none, so a re-delivery of a held item lands.
  refusals: VecDeque<HashSet<usize>>,
  arrived: Option<flume::Sender<()>>,
  gate: Option<flume::Receiver<()>>,
}

impl Table {
  fn new(written: Written) -> Self {
    Self {
      written,
      refusals: VecDeque::new(),
      arrived: None,
      gate: None,
    }
  }

  /// Refuse `positions` of the NEXT call, and take everything after that.
  fn refusing(mut self, positions: impl IntoIterator<Item = usize>) -> Self {
    self.refusals.push_back(positions.into_iter().collect());
    self
  }

  /// Report arrival and then wait to be let through, ONCE.
  fn gated(mut self, arrived: flume::Sender<()>, gate: flume::Receiver<()>) -> Self {
    self.arrived = Some(arrived);
    self.gate = Some(gate);
    self
  }
}

impl AsyncLands<u64> for Table {
  type Error = RowsRefused;

  async fn land(&mut self, items: &[u64]) -> Commit<Self::Error> {
    if let Some(gate) = self.gate.take() {
      if let Some(arrived) = self.arrived.take() {
        arrived.send(()).expect("the walk is waiting");
      }
      gate
        .recv_timeout(Duration::from_secs(20))
        .expect("the gate opened");
    }
    let refuse = self.refusals.pop_front().unwrap_or_default();
    let mut committed = Vec::new();
    let mut store = self.written.lock().expect("the lane's own store");
    for (position, item) in items.iter().enumerate() {
      if refuse.contains(&position) {
        continue;
      }
      store.push(*item);
      committed.push(position);
    }
    if refuse.is_empty() {
      Commit::all()
    } else {
      Commit::only(committed, RowsRefused(refuse.len()))
    }
  }
}

/// Emits three per item and RECORDS that its call returned — the staging physics' witness.
struct Fanning {
  returned: Arc<AtomicUsize>,
}

impl Operator for Fanning {
  type Error = core::convert::Infallible;
  type In = u64;
  type Out = u64;

  fn accept(
    &mut self,
    _ctx: &Context,
    delivery: Delivery<Self::In>,
    emitter: &mut Emitter<u64>,
  ) -> Result<(), Self::Error> {
    for item in delivery.into_items() {
      let item = item.into_value();
      emitter.emit(item);
      emitter.emit(item + 1);
      emitter.emit(item + 2);
    }
    self.returned.fetch_add(1, Ordering::SeqCst);
    Ok(())
  }
}

/// Computes only where somebody is listening — the `wanted` read, as an operator spends it.
struct Frugal;

impl Operator for Frugal {
  type Error = core::convert::Infallible;
  type In = u64;
  type Out = u64;

  fn accept(
    &mut self,
    _ctx: &Context,
    delivery: Delivery<Self::In>,
    emitter: &mut Emitter<u64>,
  ) -> Result<(), Self::Error> {
    for item in delivery.into_items() {
      if emitter.wanted() {
        emitter.emit(item.into_value() * 2);
      } else {
        emitter.skip(SkipReason::custom("unwanted"));
      }
    }
    Ok(())
  }
}

/// Send `keys` as one batch and keep the oneshot.
fn send(out: &Outbox<ItemId, u64>, keys: &[u64]) -> AckReceiver<ItemId> {
  let (ack, answers) = ack_channel();
  let items = keys
    .iter()
    .map(|&key| Item::new(ItemId::new(key), key))
    .collect();
  out
    .deliver(Delivery::new(Payload::Batch(items), ack))
    .expect("the resident is listening");
  answers
}

/// Poll until the answer arrives, or give up.
fn settled(answers: &AckReceiver<ItemId>, within: Duration) -> Option<Settled<ItemId>> {
  let deadline = Instant::now() + within;
  loop {
    match answers.take() {
      Answer::Settled(settled) => return Some(settled),
      Answer::HungUp => return None,
      Answer::Waiting if Instant::now() >= deadline => return None,
      Answer::Waiting => thread::sleep(Duration::from_millis(2)),
    }
  }
}

/// Take one delivery off `inbox`, or give up.
fn taken(inbox: &Inbox<ItemId, u64>, within: Duration) -> Option<Delivery<u64>> {
  let deadline = Instant::now() + within;
  loop {
    match inbox.park(Duration::from_millis(5)) {
      Some(Wake::Delivered(delivery)) => return Some(delivery),
      None => return None,
      Some(Wake::Sweep | Wake::Tick(_)) if Instant::now() >= deadline => return None,
      Some(Wake::Sweep | Wake::Tick(_)) => {}
    }
  }
}

/// Answer a delivery in full, as the node named `worker`.
///
/// The name is the CONSUMER's, and every walk that reads a tap depends on it: an observation names
/// the node whose work it describes, so the answer a downstream consumer sends is what carries that
/// node's name back to the sender harvesting it.
fn release_all_as(worker: &str, delivery: Delivery<u64>) -> Vec<u64> {
  let (payload, ack) = delivery.into_parts();
  let ack = ack.expect("a delivery off the wire carries its custody token");
  let released: HashSet<ItemId> = payload.keys().copied().collect();
  let values = payload.into_iter().map(|item| *item.value()).collect();
  ack.send(Ack::new(released, worker, Lifecycle::Persisted(())));
  values
}

/// [`release_all_as`] under the ordinary downstream name these walks use.
fn release_all(delivery: Delivery<u64>) -> Vec<u64> {
  release_all_as("consumer", delivery)
}

#[test]
fn the_thread_engine_runs_a_unit_from_launch_to_shutdown() {
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let (out, downstream) = channel::<ItemId, u64>(8);
  let resident = Resident::new("double", Doubling, inbox)
    .publish(out)
    .with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });

  let first = send(&feed, &[1, 2, 3]);
  let delivery = taken(&downstream, Duration::from_secs(2)).expect("the outputs arrived");
  assert_eq!(release_all(delivery), [2, 4, 6]);

  let answer = settled(&first, Duration::from_secs(2)).expect("the input was answered");
  assert_eq!(answer.released().len(), 3);
  assert_eq!(answer.observation().station(), Some(Station::Processed));
  let tally = answer
    .observation()
    .info::<Tally>()
    .expect("the shipped loop's own info type");
  assert_eq!(tally.processed(), 3);
  assert_eq!(tally.emitted(), 3);

  // Dropping every sender is the shutdown, and the loop returns its report.
  drop(feed);
  let report = engine.join().expect("the engine thread");
  assert_eq!(report.deliveries(), 1);
  assert_eq!(report.items(), 3);
  assert_eq!(report.tally().processed(), 3);
}

#[test]
fn a_shutdown_drains_what_is_already_queued() {
  // Three deliveries queued and the sender dropped before the resident ever wakes: shutdown is a
  // drain, so all three are processed rather than discarded.
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let (out, downstream) = channel::<ItemId, u64>(64);
  let mut answers = Vec::new();
  for keys in [&[1u64][..], &[2][..], &[3][..]] {
    answers.push(send(&feed, keys));
  }
  drop(feed);

  let mut resident = Resident::new("double", Doubling, inbox)
    .publish(out)
    .with_sweep(Duration::from_millis(5));
  let report = resident.run();
  assert_eq!(report.deliveries(), 3);
  assert_eq!(report.items(), 3);

  let mut values = Vec::new();
  for wake in downstream.drain() {
    if let Wake::Delivered(delivery) = wake {
      values.extend(release_all(delivery));
    }
  }
  assert_eq!(values, [2, 4, 6]);
}

#[tokio::test]
async fn the_async_engine_is_the_same_loop_over_the_other_park() {
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let (out, downstream) = channel::<ItemId, u64>(8);
  let mut resident = Resident::new("double", Doubling, inbox).publish(out);
  let engine = tokio::spawn(async move { resident.run_async().await });

  let answers = send(&feed, &[5]);
  let delivery = tokio::task::spawn_blocking(move || {
    taken(&downstream, Duration::from_secs(2)).map(release_all)
  })
  .await
  .expect("the blocking take");
  assert_eq!(delivery, Some(vec![10]));

  let answers =
    tokio::task::spawn_blocking(move || settled(&answers, Duration::from_secs(2)).is_some())
      .await
      .expect("the blocking wait");
  assert!(answers);

  drop(feed);
  let report = engine.await.expect("the engine task");
  assert_eq!(report.items(), 1);
}

#[test]
fn local_release_does_not_wait_for_the_downstream_answer() {
  // The DEFAULT mode's whole trade: the input is released on this node's own completion, so the
  // upstream runs at full speed and the gap is healed by re-delivery rather than by waiting.
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let (out, downstream) = channel::<ItemId, u64>(8);
  let resident = Resident::new("double", Doubling, inbox)
    .publish(out)
    .with_ack(AckMode::Local)
    .with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });

  let answers = send(&feed, &[1, 2]);
  let answer = settled(&answers, Duration::from_secs(2)).expect("released without waiting");
  assert_eq!(answer.released().len(), 2);

  // The outputs are still sitting unanswered downstream, which is exactly the window `local` trades
  // away.
  let delivery = taken(&downstream, Duration::from_secs(2)).expect("the outputs are there");
  assert_eq!(release_all(delivery), [2, 4]);
  drop(feed);
  engine.join().expect("the engine thread");
}

#[test]
fn chained_withholds_the_input_until_its_output_comes_back() {
  // The mutation this pins: releasing the input at `Processed` under `Chained`. If the ack fires
  // before the downstream answers, the first assertion below sees a settled answer.
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let (out, downstream) = channel::<ItemId, u64>(8);
  let resident = Resident::new("double", Doubling, inbox)
    .publish(out)
    .with_ack(AckMode::Chained)
    .with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });

  let answers = send(&feed, &[1, 2]);
  // The output arriving proves the operator ran, so the input is processed and still unreleased.
  let delivery = taken(&downstream, Duration::from_secs(2)).expect("the outputs arrived");
  assert!(
    settled(&answers, Duration::from_millis(60)).is_none(),
    "the input is owed until its output is released"
  );

  assert_eq!(release_all(delivery), [2, 4]);
  let answer = settled(&answers, Duration::from_secs(2)).expect("the join completed");
  assert_eq!(answer.released().len(), 2);

  drop(feed);
  let report = engine.join().expect("the engine thread");
  assert_eq!(report.items(), 2);
}

#[test]
fn a_chained_fan_out_joins_on_every_arm() {
  // Two edges, so one emission becomes two items with two ids. Answering one arm must not release
  // the input — the join is an AND across the whole fan-out.
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let (left_out, left) = channel::<ItemId, u64>(8);
  let (right_out, right) = channel::<ItemId, u64>(8);
  let resident = Resident::new("double", Doubling, inbox)
    .publish(left_out)
    .publish(right_out)
    .with_ack(AckMode::Chained)
    .with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });

  let answers = send(&feed, &[3]);
  let left_delivery = taken(&left, Duration::from_secs(2)).expect("the left arm");
  let right_delivery = taken(&right, Duration::from_secs(2)).expect("the right arm");
  assert_eq!(release_all(left_delivery), [6]);
  assert!(
    settled(&answers, Duration::from_millis(60)).is_none(),
    "one arm answered is not the join"
  );

  assert_eq!(release_all(right_delivery), [6]);
  assert!(
    settled(&answers, Duration::from_secs(2)).is_some(),
    "both arms answered completes it"
  );

  drop(feed);
  engine.join().expect("the engine thread");
}

#[test]
fn a_chained_unit_that_produced_nothing_releases_at_once() {
  // A refcount answers this silently; a "wait for a child" rule would deadlock on it.
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let (out, downstream) = channel::<ItemId, u64>(8);
  let resident = Resident::new("sieve", Sieving, inbox)
    .publish(out)
    .with_ack(AckMode::Chained)
    .with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });

  // Every item odd, so every one is refused and nothing is emitted.
  let answers = send(&feed, &[1, 3, 5]);
  let answer = settled(&answers, Duration::from_secs(2)).expect("nothing to wait for");
  assert_eq!(answer.released().len(), 3);
  assert_eq!(answer.observation().station(), Some(Station::Skipped));
  assert!(
    answer
      .observation()
      .skip()
      .expect("skipped")
      .reason()
      .is_filtered()
  );

  drop(feed);
  engine.join().expect("the engine thread");
  assert!(downstream.is_empty());
}

#[test]
fn a_failed_item_holds_the_window_and_its_neighbours_do_not() {
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let (out, downstream) = channel::<ItemId, u64>(8);
  let resident = Resident::new("brittle", Brittle(2), inbox)
    .publish(out)
    .with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });

  let answers = send(&feed, &[1, 2, 3]);
  let answer = settled(&answers, Duration::from_secs(2)).expect("answered");
  assert_eq!(answer.released().len(), 2, "the failed item is held");
  assert!(!answer.released().contains(&ItemId::new(2)));
  assert_eq!(answer.observation().station(), Some(Station::Failed));
  let failure = answer.observation().failure().expect("a failure");
  assert_eq!(failure.to_string(), "item 2 is not decodable");

  // Everything the failing item emitted BEFORE it failed still travelled — the driver drains the
  // buffer on both paths, which is the contract `Operator` states.
  let delivery = taken(&downstream, Duration::from_secs(2)).expect("the outputs arrived");
  assert_eq!(release_all(delivery), [2, 4, 6]);

  drop(feed);
  let report = engine.join().expect("the engine thread");
  assert_eq!(report.tally().failed(), 1);
  assert_eq!(report.tally().processed(), 2);
}

#[test]
fn an_emission_with_no_consumer_is_recorded_rather_than_dropped_in_silence() {
  // A PURE node, which is what the refusal is about: an emission's only destination at one is an
  // edge, so an emission with no edge is a gap. The storing case is its opposite and has a walk of
  // its own — there the destination was the store.
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let resident = Resident::new("double", Doubling, inbox)
    .with_effect(Effect::Pure)
    .with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });

  let answers = send(&feed, &[1]);
  let answer = settled(&answers, Duration::from_secs(2)).expect("answered");
  assert_eq!(answer.observation().station(), Some(Station::Skipped));
  assert!(
    answer
      .observation()
      .skip()
      .expect("skipped")
      .reason()
      .is_no_consumers()
  );

  drop(feed);
  engine.join().expect("the engine thread");
}

#[test]
fn a_storing_unit_says_persisted_and_a_pure_one_says_processed() {
  for (effect, station) in [
    (Effect::Lands, Station::Persisted),
    (Effect::Pure, Station::Processed),
  ] {
    let (feed, inbox) = channel::<ItemId, u64>(4);
    let (out, downstream) = channel::<ItemId, u64>(4);
    let resident = Resident::new("node", Doubling, inbox)
      .publish(out)
      .with_effect(effect)
      .with_sweep(Duration::from_millis(5));
    let engine = thread::spawn(move || {
      let mut resident = resident;
      resident.run()
    });

    let answers = send(&feed, &[1]);
    let answer = settled(&answers, Duration::from_secs(2)).expect("answered");
    assert_eq!(answer.observation().station(), Some(station));
    drop(feed);
    engine.join().expect("the engine thread");
    drop(downstream);
  }
}

/// A downstream set NOT written by the framework — the seam's proof.
///
/// It is what a node's own emitted `<Node>Downstream` will be: a struct with a field per product, an
/// `Option` for the connection state, and one [`Sink`] impl per product. Hand-written here because
/// the emission is S2b's; what this pins is that the driver routes through the trait and never
/// through the framework's own holder.
struct TitleDownstream {
  titles: Option<Outbox<ItemId, u64>>,
  routed: Arc<Mutex<Vec<ItemId>>>,
}

impl Sink<u64> for TitleDownstream {
  fn arity(&self) -> usize {
    usize::from(self.titles.is_some())
  }

  fn nudges(&self) -> Vec<Box<dyn crate::Rings>> {
    self
      .titles
      .iter()
      .map(|edge| Box::new(edge.nudge()) as Box<dyn crate::Rings>)
      .collect()
  }

  async fn deliver(
    &mut self,
    _edge: usize,
    batch: Vec<Item<u64>>,
    ack: crate::AckSender<ItemId>,
  ) -> bool {
    let Some(titles) = self.titles.as_ref() else {
      return false;
    };
    self
      .routed
      .lock()
      .expect("the routed log")
      .extend(batch.iter().map(|item| *item.key()));
    titles
      .deliver_async(Delivery::new(Payload::Batch(batch), ack))
      .await
      .is_ok()
  }
}

#[test]
fn a_node_can_bring_its_own_downstream_set() {
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let (out, downstream) = channel::<ItemId, u64>(8);
  let routed: Arc<Mutex<Vec<ItemId>>> = Arc::default();
  let resident = Resident::new("double", Doubling, inbox)
    .wire(TitleDownstream {
      titles: Some(out),
      routed: routed.clone(),
    })
    .with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });

  let answers = send(&feed, &[1, 2]);
  let delivery = taken(&downstream, Duration::from_secs(2)).expect("the outputs arrived");
  assert_eq!(release_all(delivery), [2, 4]);
  let answer = settled(&answers, Duration::from_secs(2)).expect("the input was answered");
  assert_eq!(answer.released().len(), 2);
  assert_eq!(
    routed.lock().expect("the routed log").len(),
    2,
    "the driver routed through the hand-written sink and not around it"
  );

  drop(feed);
  engine.join().expect("the engine thread");
}

#[test]
fn emitting_stages_and_the_drain_is_where_the_wait_lands() {
  // THE STAGING PHYSICS. The only edge out is a RENDEZVOUS — nothing can be handed over until a
  // consumer takes it — and the operator's call still returns at once, because `emit` is a push
  // into a buffer. The wait is the DRIVER's, and it happens after the call, which is what makes an
  // operator unable to deadlock on its own full output.
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let (out, downstream) = channel::<ItemId, u64>(0);
  let returned: Arc<AtomicUsize> = Arc::default();
  let resident = Resident::new(
    "fan",
    Fanning {
      returned: returned.clone(),
    },
    inbox,
  )
  .publish(out)
  .with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });

  let answers = send(&feed, &[1]);
  let deadline = Instant::now() + Duration::from_secs(5);
  while returned.load(Ordering::SeqCst) == 0 {
    assert!(Instant::now() < deadline, "the call never returned");
    thread::sleep(Duration::from_millis(2));
  }
  assert!(
    settled(&answers, Duration::from_millis(50)).is_none(),
    "the driver is still handing the batch over, so nothing is answered yet"
  );

  // Taking the batch is what lets the pass finish: the backpressure was the drain's.
  let delivery = taken(&downstream, Duration::from_secs(5)).expect("the outputs arrived");
  assert_eq!(release_all(delivery), [1, 2, 3]);
  let answer = settled(&answers, Duration::from_secs(5)).expect("answered once the edge took it");
  assert_eq!(answer.released().len(), 1);

  drop(feed);
  engine.join().expect("the engine thread");
}

#[test]
fn an_operator_can_read_whether_anything_downstream_wants_its_product() {
  // Wired: `wanted` is true, and the work is done.
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let (out, downstream) = channel::<ItemId, u64>(8);
  let resident = Resident::new("frugal", Frugal, inbox)
    .publish(out)
    .with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });
  let answers = send(&feed, &[2]);
  let delivery = taken(&downstream, Duration::from_secs(2)).expect("the outputs arrived");
  assert_eq!(release_all(delivery), [4]);
  assert_eq!(
    settled(&answers, Duration::from_secs(2))
      .expect("answered")
      .observation()
      .station(),
    Some(Station::Processed)
  );
  drop(feed);
  engine.join().expect("the engine thread");

  // Unwired: nobody subscribes, so the same operator refuses in its OWN words rather than
  // computing into a downstream set with nowhere to put the answer.
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let resident = Resident::new("frugal", Frugal, inbox).with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });
  let answers = send(&feed, &[2]);
  let answer = settled(&answers, Duration::from_secs(2)).expect("answered");
  assert_eq!(answer.observation().station(), Some(Station::Skipped));
  assert_eq!(
    answer
      .observation()
      .skip()
      .expect("skipped")
      .reason()
      .as_str(),
    "unwanted"
  );
  drop(feed);
  engine.join().expect("the engine thread");
}

#[test]
fn a_burst_of_sweeps_is_one_look() {
  // The collapse: rings are redundant by construction, so a hundred of them cost one pass. Data is
  // never collapsed, which the delivery count beside it shows.
  let (feed, inbox) = channel::<ItemId, u64>(256);
  let (out, downstream) = channel::<ItemId, u64>(256);
  let nudge = feed.nudge();
  for _ in 0..100 {
    nudge.ring();
  }
  let answers = send(&feed, &[1]);
  drop(feed);
  drop(nudge);

  let mut resident = Resident::new("double", Doubling, inbox)
    .publish(out)
    .with_sweep(Duration::from_millis(5));
  let report = resident.run();
  assert_eq!(report.deliveries(), 1);
  assert!(
    report.sweeps() <= 2,
    "a burst collapsed, saw {}",
    report.sweeps()
  );
  assert!(settled(&answers, Duration::from_millis(50)).is_some());
  drop(downstream);
}

#[test]
fn every_arm_of_a_fan_out_gets_its_own_item_id() {
  // The ids are what a chained join counts, so two edges sharing one id would make an AND-join a
  // first-one-wins. Each edge's delivery carries a distinct key for the same value.
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let (left_out, left) = channel::<ItemId, u64>(8);
  let (right_out, right) = channel::<ItemId, u64>(8);
  let resident = Resident::new("split", Splitting, inbox)
    .publish(left_out)
    .publish(right_out)
    .with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });

  let _answers = send(&feed, &[1]);
  let left_delivery = taken(&left, Duration::from_secs(2)).expect("left");
  let right_delivery = taken(&right, Duration::from_secs(2)).expect("right");
  let left_keys: Vec<ItemId> = left_delivery.payload().keys().copied().collect();
  let right_keys: Vec<ItemId> = right_delivery.payload().keys().copied().collect();
  assert_eq!(left_keys.len(), 2, "one item per emission, two emissions");
  assert_eq!(right_keys.len(), 2);
  for key in &left_keys {
    assert!(!right_keys.contains(key), "{key} is on both edges");
  }
  assert_eq!(release_all(left_delivery), [1, 1_001]);
  assert_eq!(release_all(right_delivery), [1, 1_001]);

  drop(feed);
  engine.join().expect("the engine thread");
}

#[test]
fn a_consumer_that_hangs_up_is_observed_and_never_stalls_the_unit() {
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let (out, downstream) = channel::<ItemId, u64>(1);
  drop(downstream);
  let tap = Arc::new(RecordingTap::new());
  let resident = Resident::new("double", Doubling, inbox)
    .publish(out)
    .with_ack(AckMode::Chained)
    .with_taps(Taps::new().with(tap.clone()))
    .with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });

  let answers = send(&feed, &[1]);
  // The join has an arm that will never come back, so the input stays owed — and the node keeps
  // running, which is what the report on shutdown shows.
  assert!(settled(&answers, Duration::from_millis(80)).is_none());
  drop(feed);
  let report = engine.join().expect("the engine thread");
  assert_eq!(report.items(), 1);
  assert!(
    tap
      .seen()
      .iter()
      .any(|(_, station)| *station == Station::Skipped),
    "the refusal reached a tap: {:?}",
    tap.seen()
  );
}

#[test]
fn a_storing_unit_answers_only_after_its_own_write_commits() {
  // THE ordering the socket exists for, stated as a "not yet". The gate holds the node inside its
  // own write, so the walk looks at the oneshot at a moment when nothing has reached the store —
  // and there is no answer there. Move the ack ahead of the write and this walk sees one.
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let written: Written = Arc::new(Mutex::new(Vec::new()));
  let (report_arrival, arrived) = flume::bounded::<()>(1);
  let (open_gate, gate) = flume::bounded::<()>(1);
  let resident = Resident::new("titles", Doubling, inbox)
    .land(Table::new(written.clone()).gated(report_arrival, gate))
    .with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });

  let answers = send(&feed, &[1, 2]);
  arrived
    .recv_timeout(Duration::from_secs(20))
    .expect("the lane was called");
  assert!(
    written.lock().expect("the store").is_empty(),
    "the write has not happened yet"
  );
  assert!(
    settled(&answers, Duration::from_millis(60)).is_none(),
    "answered before its own write"
  );

  open_gate.send(()).expect("the lane is waiting");
  let answer = settled(&answers, Duration::from_secs(2)).expect("answered after the write");
  assert_eq!(answer.released().len(), 2);
  assert_eq!(answer.observation().station(), Some(Station::Persisted));
  assert_eq!(*written.lock().expect("the store"), [2, 4]);

  drop(feed);
  engine.join().expect("the engine thread");
}

#[test]
fn a_storing_unit_at_the_end_of_a_lane_is_persisted_and_not_a_refusal() {
  // The ordinary storing terminal: it writes and publishes to nobody. Its emission had a
  // destination — the store — so a missing downstream edge is not a `NoConsumers` gap here, and the
  // station is the durability it actually reached.
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let written: Written = Arc::new(Mutex::new(Vec::new()));
  let resident = Resident::new("titles", Doubling, inbox)
    .land(Table::new(written.clone()))
    .with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });

  let answers = send(&feed, &[1, 2]);
  let answer = settled(&answers, Duration::from_secs(2)).expect("answered");
  assert_eq!(answer.observation().station(), Some(Station::Persisted));
  assert!(answer.observation().skip().is_none());
  assert_eq!(answer.released().len(), 2);
  assert_eq!(*written.lock().expect("the store"), [2, 4]);

  drop(feed);
  let report = engine.join().expect("the engine thread");
  assert_eq!(report.tally().emitted(), 0, "nothing went on a wire");
  assert_eq!(report.tally().refused(), 0);
}

/// The positions the store refuses in the 256-row page below, and the ids they hold.
///
/// Scattered rather than a tail: the release is a positive SET, so a walk whose refusals were the
/// last six rows could not tell it apart from a watermark that simply stopped early.
const REFUSED: [usize; 6] = [3, 17, 100, 200, 249, 255];

#[test]
fn a_batch_that_lands_in_part_releases_exactly_what_the_store_took() {
  // 250 of 256 — the record's own example. The window walks a page item by item, so the six held
  // rows are named in no released set and come back, while the two hundred and fifty that reached
  // the store are forgotten.
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let written: Written = Arc::new(Mutex::new(Vec::new()));
  let resident = Resident::new("titles", Doubling, inbox)
    .land(Table::new(written.clone()).refusing(REFUSED))
    .with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });

  let keys: Vec<u64> = (1..=256).collect();
  let answers = send(&feed, &keys);
  let answer = settled(&answers, Duration::from_secs(2)).expect("answered");

  assert_eq!(answer.released().len(), 250);
  for position in REFUSED {
    let held = ItemId::new(keys[position]);
    assert!(
      !answer.released().contains(&held),
      "{held} was released with nothing written for it"
    );
  }
  assert_eq!(written.lock().expect("the store").len(), 250);
  // The six are reported through the lifecycle, and the COUNT is the socket's own — the lane knows
  // why, and only the delivery knows how many of how many.
  assert_eq!(answer.observation().station(), Some(Station::Failed));
  assert_eq!(
    answer
      .observation()
      .failure()
      .expect("a failure")
      .to_string(),
    "the write lane committed 250 of 256: 6 rows did not go in"
  );

  drop(feed);
  let report = engine.join().expect("the engine thread");
  assert_eq!(report.tally().refused(), 6);
  assert_eq!(report.tally().failed(), 0, "every operator call succeeded");
}

#[test]
fn a_record_the_store_refused_is_not_emitted_and_its_input_comes_back() {
  // Emitting an artifact that is not durable would let a downstream node make a derivation of
  // something that is not there. So the refused record goes nowhere, its input is held, and the
  // re-delivery — which the lane takes this time — is what lands both.
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let (out, downstream) = channel::<ItemId, u64>(8);
  let written: Written = Arc::new(Mutex::new(Vec::new()));
  let resident = Resident::new("titles", Doubling, inbox)
    .publish(out)
    .land(Table::new(written.clone()).refusing([1]))
    .with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });

  let answers = send(&feed, &[1, 2]);
  let answer = settled(&answers, Duration::from_secs(2)).expect("answered");
  assert_eq!(answer.released().len(), 1);
  assert!(answer.released().contains(&ItemId::new(1)));
  let delivery = taken(&downstream, Duration::from_secs(2)).expect("the committed output");
  assert_eq!(release_all(delivery), [2], "only what the store took");

  let again = send(&feed, &[2]);
  let answer = settled(&again, Duration::from_secs(2)).expect("the re-delivery was answered");
  assert_eq!(answer.released().len(), 1);
  assert_eq!(answer.observation().station(), Some(Station::Persisted));
  let delivery = taken(&downstream, Duration::from_secs(2)).expect("the second output");
  assert_eq!(release_all(delivery), [4]);
  assert_eq!(*written.lock().expect("the store"), [2, 4]);

  drop(feed);
  engine.join().expect("the engine thread");
}

#[tokio::test]
async fn the_async_engine_awaits_the_write_the_other_one_blocks_on() {
  // The socket is one seam over two engines. The thread engine drives the lane's future to
  // completion on its own thread; this one awaits it, and everything either side of the call is the
  // same code.
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let written: Written = Arc::new(Mutex::new(Vec::new()));
  let mut resident = Resident::new("titles", Doubling, inbox).land(Table::new(written.clone()));
  let engine = tokio::spawn(async move { resident.run_async().await });

  let answers = send(&feed, &[5]);
  let answer = tokio::task::spawn_blocking(move || settled(&answers, Duration::from_secs(2)))
    .await
    .expect("the blocking wait")
    .expect("answered");
  assert_eq!(answer.observation().station(), Some(Station::Persisted));
  assert_eq!(*written.lock().expect("the store"), [10]);

  drop(feed);
  let report = engine.await.expect("the engine task");
  assert_eq!(report.items(), 1);
}

/// The observation names the WORKER — the node whose work it describes — and not the sender that
/// harvested it.
///
/// This walk used to assert `("double", Persisted)`, and that assertion was WRONG: `double` is the
/// pure node that SENT the item, `Persisted` is a durability the node downstream of it reached, and
/// keyed `(root, node)` a journal written from this vantage would have named `double` in every
/// row while describing somebody else's work.
#[test]
fn the_tap_names_the_unit_whose_work_the_answer_describes() {
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let (out, downstream) = channel::<ItemId, u64>(8);
  let tap = Arc::new(RecordingTap::new());
  let resident = Resident::new("double", Doubling, inbox)
    .publish(out)
    .with_taps(Taps::new().with(tap.clone()))
    .with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });

  let _answers = send(&feed, &[1, 2]);
  let delivery = taken(&downstream, Duration::from_secs(2)).expect("outputs");
  release_all_as("keeper", delivery);
  // The observation is collected on the node's next wake, which the sweep provides.
  let deadline = Instant::now() + Duration::from_secs(2);
  while tap.is_empty() && Instant::now() < deadline {
    thread::sleep(Duration::from_millis(5));
  }
  assert_eq!(tap.seen(), vec![("keeper".to_owned(), Station::Persisted)]);

  drop(feed);
  engine.join().expect("the engine thread");
}

#[test]
fn the_station_a_verdict_reports_is_the_one_its_lifecycle_reaches() {
  // `Verdict::station` and `Verdict::into_lifecycle` state the same table twice — one without
  // consuming the verdict, because the journal's row is written before the ack that carries the
  // other. Two spellings of one table can drift, so this pins them against each other over every
  // shape a verdict takes.
  use super::{super::Effect, Verdict};

  /// A verdict's three deciding fields, as a shape to build one from.
  type Shape = (&'static str, bool, bool, usize);

  fn build((_, failed, skipped, emitted): Shape) -> Verdict {
    Verdict {
      tally: Tally {
        emitted,
        ..Tally::default()
      },
      failure: failed.then(|| super::super::Failure::new(std::io::Error::other("no"))),
      skip: skipped.then(|| crate::Skip::new(SkipReason::Filtered)),
    }
  }

  let shapes: [Shape; 5] = [
    ("plain", false, false, 0),
    ("failed", true, false, 0),
    ("skipped", false, true, 0),
    ("skipped but emitted", false, true, 1),
    ("failed and skipped", true, true, 0),
  ];

  for shape in shapes {
    for effect in [Effect::Lands, Effect::Pure] {
      let reported = build(shape).station(effect);
      let reached = build(shape).into_lifecycle(effect).station();
      assert_eq!(reported, reached, "{} at {effect}", shape.0);
    }
  }
}

/// The POLL arm at the resident: a node whose work is driven by its own clock rather than by data.
///
/// It sits here rather than beside the clock's own arithmetic because what these walks are about is
/// the LOOP — that a tick reaches the node's sweep entry naming the upstream that came due, that the
/// context is lent for the call and never held by the node, and that what a sweep did reaches the
/// same taps every other node's work does. `poll` proves the clock; this proves what the clock
/// drives.
mod sweeping {
  use crate::{Context, drive::Drives};
  use core::time::Duration;

  use std::{
    sync::{Arc, Mutex},
    thread,
    time::Instant,
  };

  use super::super::super::{
    Drained, Effect, ItemId, LifecycleTap, NodeName, Observation, PollUpstream, RecordingTap,
    Resident, Rings, Schedule, Seats, Station, Sweeper, Swept, Taps, channel,
  };
  use crate::{Delivery, Emitter, Operator};

  /// A tap that keeps the sweep's own INFO as well as its station.
  ///
  /// [`RecordingTap`] is the shipped recorder and keeps what a journal is keyed by; this one
  /// keeps the third thing a poll walk is actually about — *how many rows did that look remove* —
  /// which is the payload the erasure exists to carry home.
  #[derive(Debug, Default)]
  struct Counting {
    seen: Mutex<Vec<(Station, Option<usize>)>>,
  }

  impl Counting {
    fn seen(&self) -> Vec<(Station, Option<usize>)> {
      self.seen.lock().expect("the counting tap").clone()
    }
  }

  impl LifecycleTap for Counting {
    fn observe(&self, _unit: &NodeName, observation: &Observation) {
      let Some(arrival) = observation.arrival() else {
        return;
      };
      self
        .seen
        .lock()
        .expect("the counting tap")
        .push((arrival.station(), arrival.info::<usize>().copied()));
    }
  }

  /// The per-node context a poll node is LENT: the store handles its declared grants gave it.
  ///
  /// A plain struct the wiring builds, which is what an emitted one is — the emission adds one
  /// `AsyncLands<Granted>` impl per `write` grant, stated once for the whole node. Nothing here ever
  /// lives in the node: the resident holds this and lends `&mut` for the call.
  ///
  /// Its one slot is shared with the walk, which is the only way a test can tell that a sweep wrote
  /// through the CONTEXT rather than through something the node was carrying.
  struct Granted {
    rows: Arc<Mutex<Vec<u64>>>,
  }

  /// What a sweep left behind, from outside the resident.
  #[derive(Clone)]
  struct Watched {
    looked: Arc<Mutex<Vec<PollUpstream>>>,
    rows: Arc<Mutex<Vec<u64>>>,
  }

  impl Watched {
    fn new(rows: &[u64]) -> Self {
      Self {
        looked: Arc::new(Mutex::new(Vec::new())),
        rows: Arc::new(Mutex::new(rows.to_vec())),
      }
    }

    /// How many times `upstream` was swept.
    fn looks(&self, upstream: PollUpstream) -> usize {
      self
        .looked
        .lock()
        .expect("the walk's own record")
        .iter()
        .filter(|&&seen| seen == upstream)
        .count()
    }

    fn rows(&self) -> Vec<u64> {
      self.rows.lock().expect("the store").clone()
    }
  }

  /// A maintenance node: it holds only its OWN state and reaps through the context it is lent.
  ///
  /// `Operator` is implemented because a poll node is an ordinary declared node and may have
  /// channel upstreams too — the mixed walk below gives it one — and `accept` is what those feed.
  struct Reaping {
    looked: Arc<Mutex<Vec<PollUpstream>>>,
    /// The tick number to fail on, if any — so a walk can see a refused sweep observed and the
    /// loop carry on past it.
    brittle: Option<usize>,
    ticks: usize,
    /// What `on_item` saw, for the mixed walk.
    consumed: Arc<Mutex<Vec<u64>>>,
  }

  impl Reaping {
    fn new(watched: &Watched) -> Self {
      Self {
        looked: watched.looked.clone(),
        brittle: None,
        ticks: 0,
        consumed: Arc::new(Mutex::new(Vec::new())),
      }
    }

    /// Fail the sweep numbered `tick`, counting from zero.
    fn failing_on(mut self, tick: usize) -> Self {
      self.brittle = Some(tick);
      self
    }

    fn consumed(&self) -> Arc<Mutex<Vec<u64>>> {
      self.consumed.clone()
    }
  }

  #[derive(Debug, derive_more::Display)]
  #[display("the store would not answer")]
  struct Unreachable;

  impl core::error::Error for Unreachable {}

  impl Operator for Reaping {
    type Error = core::convert::Infallible;
    type In = u64;
    type Out = u64;

    fn accept(
      &mut self,
      _ctx: &Context,
      delivery: Delivery<Self::In>,
      emitter: &mut Emitter<u64>,
    ) -> Result<(), Self::Error> {
      for item in delivery.into_items() {
        let item = item.into_value();
        self.consumed.lock().expect("the walk's record").push(item);
        emitter.emit(item);
      }
      Ok(())
    }
  }

  /// A hand-written lending: this node grants nothing, so nothing is emitted for it and the
  /// deployment's own value implements the seam and reads the position itself.
  impl Seats<Reaping> for Granted {
    type Error = Unreachable;
    /// How many rows this look removed — the info the observation carries.
    type Info = usize;

    async fn seat(
      &mut self,
      operator: &mut Reaping,
      upstream: PollUpstream,
    ) -> Result<Swept<usize>, Self::Error> {
      let mine = operator.ticks;
      operator.ticks += 1;
      operator
        .looked
        .lock()
        .expect("the walk's record")
        .push(upstream);
      if operator.brittle == Some(mine) {
        return Err(Unreachable);
      }
      // Through the LENDING, and only the upstream that came due decides what to do — which is the
      // whole content of a tick carrying an identity. Upstream 0 reaps; upstream 1 only looks.
      let mut rows = self.rows.lock().expect("the granted store");
      if upstream == PollUpstream::new(0) {
        let before = rows.len();
        rows.retain(|row| row % 2 == 0);
        return Ok(Swept::Ran(before - rows.len()));
      }
      Ok(Swept::Ran(0))
    }
  }

  /// Poll `check` until it holds, or give up.
  fn until(within: Duration, what: &str, mut check: impl FnMut() -> bool) {
    let deadline = Instant::now() + within;
    while !check() {
      assert!(Instant::now() < deadline, "{what}");
      thread::sleep(Duration::from_millis(2));
    }
  }

  /// The fast/slow schedule every walk here uses: upstream 0 reaps often, upstream 1 looks rarely.
  fn schedule() -> Schedule {
    Schedule::new()
      .every(Duration::from_millis(5))
      .every(Duration::from_millis(60))
  }

  #[test]
  fn a_tick_invokes_the_sweep_entry_naming_the_source_that_came_due() {
    // THE MUTATION: hand the node a fixed upstream — or the wrong one — and upstream 1 is never looked
    // at, so the wait below runs out. A reaper told it was the compactor would reap the wrong
    // store, and nothing but the identity can tell the two apart.
    let watched = Watched::new(&[1, 2, 3, 4, 5, 6]);
    let (out, inbox) = channel::<ItemId, u64>(8);
    let rows = watched.rows.clone();
    let resident = Resident::new("reaper", Reaping::new(&watched), inbox)
      .polling(schedule(), Granted { rows })
      .with_sweep(Duration::from_secs(30));
    let engine = thread::spawn(move || {
      let mut resident = resident;
      resident.run()
    });

    until(
      Duration::from_secs(20),
      "the two clocks never both ran",
      || watched.looks(PollUpstream::new(0)) >= 8 && watched.looks(PollUpstream::new(1)) >= 1,
    );
    // A poll-only node's outbox is its shutdown handle: nothing else holds its inbox open.
    drop(out);
    let report: Drained = engine.join().expect("the engine thread");

    let fast = watched.looks(PollUpstream::new(0));
    let slow = watched.looks(PollUpstream::new(1));
    assert!(
      fast > slow,
      "each upstream keeps its own cadence: {fast}/{slow}"
    );
    assert_eq!(
      report.ticks(),
      fast + slow,
      "one look per upstream per pass"
    );
    assert_eq!(report.deliveries(), 0, "no data reached this node at all");
    // Upstream 0 is the one with the write grant, so the odd rows are gone and nothing else changed.
    assert_eq!(watched.rows(), [2, 4, 6]);
  }

  #[test]
  fn a_sweep_reports_through_the_same_taps_at_the_units_own_effect_and_says_what_it_removed() {
    let watched = Watched::new(&[1, 2, 3, 4]);
    let tap = Arc::new(RecordingTap::new());
    let counting = Arc::new(Counting::default());
    let (out, inbox) = channel::<ItemId, u64>(8);
    let rows = watched.rows.clone();
    let resident = Resident::new("reaper", Reaping::new(&watched), inbox)
      .polling(
        Schedule::new().every(Duration::from_millis(5)),
        Granted { rows },
      )
      .with_taps(Taps::new().with(tap.clone()).with(counting.clone()))
      .with_sweep(Duration::from_secs(30));
    let engine = thread::spawn(move || {
      let mut resident = resident;
      resident.run()
    });

    until(Duration::from_secs(20), "no sweep was observed", || {
      tap.len() >= 2
    });
    drop(out);
    engine.join().expect("the engine thread");

    // Under this node's OWN name — nobody answered for a tick, because a tick is not a delivery —
    // and at the station its `Effect` reaches, which for a node whose write goes through a lent
    // handle is `Processed` and not a durability it did not claim.
    assert!(
      tap
        .seen()
        .iter()
        .all(|(node, station)| node == "reaper" && *station == Station::Processed),
      "{:?}",
      tap.seen()
    );
    // Nothing new was invented for a sweep's own detail: it rides the SAME erased info slot a
    // delivery's `Tally` does, so a tap that knows this node's type asks for it back and one that
    // does not still has the station.
    let seen = counting.seen();
    assert_eq!(
      seen[0],
      (Station::Processed, Some(2)),
      "the first look removed both odd rows"
    );
    assert!(
      seen[1..]
        .iter()
        .all(|&(station, removed)| station == Station::Processed && removed == Some(0)),
      "and every look after it found nothing left: {seen:?}"
    );
  }

  #[test]
  fn a_storing_poll_unit_reaches_the_station_its_effect_names() {
    let watched = Watched::new(&[1, 2, 3]);
    let tap = Arc::new(RecordingTap::new());
    let (out, inbox) = channel::<ItemId, u64>(8);
    let rows = watched.rows.clone();
    let resident = Resident::new("compactor", Reaping::new(&watched), inbox)
      .polling(
        Schedule::new().every(Duration::from_millis(5)),
        Granted { rows },
      )
      .with_effect(Effect::Lands)
      .with_taps(Taps::new().with(tap.clone()))
      .with_sweep(Duration::from_secs(30));
    let engine = thread::spawn(move || {
      let mut resident = resident;
      resident.run()
    });
    until(Duration::from_secs(20), "no sweep was observed", || {
      !tap.is_empty()
    });
    drop(out);
    engine.join().expect("the engine thread");

    assert!(
      tap
        .seen()
        .iter()
        .all(|(_, station)| *station == Station::Persisted),
      "{:?}",
      tap.seen()
    );
  }

  #[test]
  fn a_refused_sweep_is_observed_and_the_next_tick_still_comes() {
    // A sweep that could not reach its store is a FAILURE and nothing more: there is no window for
    // it to hold and no input for it to re-deliver, so the only thing owed is that somebody is told
    // and that the clock keeps running.
    let watched = Watched::new(&[1, 2, 3, 4]);
    let tap = Arc::new(RecordingTap::new());
    let (out, inbox) = channel::<ItemId, u64>(8);
    let rows = watched.rows.clone();
    let resident = Resident::new("reaper", Reaping::new(&watched).failing_on(0), inbox)
      .polling(
        Schedule::new().every(Duration::from_millis(5)),
        Granted { rows },
      )
      .with_taps(Taps::new().with(tap.clone()))
      .with_sweep(Duration::from_secs(30));
    let engine = thread::spawn(move || {
      let mut resident = resident;
      resident.run()
    });
    until(
      Duration::from_secs(20),
      "the clock stopped at the failure",
      || tap.len() >= 3,
    );
    drop(out);
    engine.join().expect("the engine thread");

    let stations: Vec<Station> = tap.seen().iter().map(|(_, station)| *station).collect();
    assert_eq!(stations[0], Station::Failed, "the first look refused");
    assert!(
      stations[1..].iter().all(|s| *s == Station::Processed),
      "the clock carried on: {stations:?}"
    );
    // And the work the later looks did still landed, through the same lent handle.
    assert_eq!(watched.rows(), [2, 4]);
  }

  #[test]
  fn a_unit_reading_a_channel_and_a_clock_at_once_serves_both() {
    // The mixability ruling, extended: a poll upstream is one more producer on the one inbox, so a
    // node with data and a schedule is a node with two, and the loop never learns which mode a
    // pass came from.
    let watched = Watched::new(&[1, 2, 3, 4]);
    let (feed, inbox) = channel::<ItemId, u64>(8);
    let (out, downstream) = channel::<ItemId, u64>(8);
    let node = Reaping::new(&watched);
    let consumed = node.consumed();
    let rows = watched.rows.clone();
    let resident = Resident::new("reaper", node, inbox)
      .publish(out)
      .polling(
        Schedule::new().every(Duration::from_millis(5)),
        Granted { rows },
      )
      .with_sweep(Duration::from_secs(30));
    let engine = thread::spawn(move || {
      let mut resident = resident;
      resident.run()
    });

    let answers = super::send(&feed, &[7, 8]);
    let delivery = super::taken(&downstream, Duration::from_secs(20)).expect("the data arm ran");
    assert_eq!(super::release_all(delivery), [7, 8]);
    assert!(
      super::settled(&answers, Duration::from_secs(20)).is_some(),
      "the channel upstream was answered"
    );
    until(Duration::from_secs(20), "the clock arm never ran", || {
      watched.looks(PollUpstream::new(0)) >= 2
    });

    drop(feed);
    let report = engine.join().expect("the engine thread");
    assert_eq!(
      consumed.lock().expect("the walk's record").as_slice(),
      [7, 8]
    );
    assert_eq!(report.items(), 2);
    assert!(report.ticks() >= 2, "both arms ran: {}", report.ticks());
  }

  #[tokio::test]
  async fn the_async_engine_is_rung_for_its_ticks_as_it_is_for_its_sweep() {
    // The engines differ in how a tick ARRIVES and in nothing else: a task cannot time itself, so
    // its schedule becomes a `Sweeper` over the same intervals and the ticks reach it as messages.
    let watched = Watched::new(&[1, 2, 3, 4, 5, 6]);
    let (out, inbox) = channel::<ItemId, u64>(8);
    let rows = watched.rows.clone();
    let schedule = schedule();
    let sweeper = Sweeper::ticking(schedule.cadences(&out));
    let mut resident =
      Resident::new("reaper", Reaping::new(&watched), inbox).polling(schedule, Granted { rows });

    let seen = watched.clone();
    let engine = tokio::spawn(async move { resident.run_async().await });
    // The tickers the sweeper holds keep the inbox alive, so this outbox is not what is standing
    // between the node and shutdown — dropping the SWEEPER is.
    drop(out);
    tokio::task::spawn_blocking(move || {
      until(
        Duration::from_secs(20),
        "the rung clocks never both ran",
        || seen.looks(PollUpstream::new(0)) >= 8 && seen.looks(PollUpstream::new(1)) >= 1,
      );
    })
    .await
    .expect("the waiter");
    drop(sweeper);

    let report = engine.await.expect("the engine task");
    let fast = watched.looks(PollUpstream::new(0));
    let slow = watched.looks(PollUpstream::new(1));
    assert!(
      fast > slow,
      "each upstream keeps its own cadence: {fast}/{slow}"
    );
    assert_eq!(report.ticks(), fast + slow);
    assert_eq!(watched.rows(), [2, 4, 6]);
  }

  #[test]
  fn two_ticks_for_one_source_in_one_pass_are_one_look() {
    // In the shipped wiring this is what a ringer racing the drain produces: a upstream's cell is
    // freed the moment its tick leaves the inbox, so the next one can be queued while the same
    // drain is still walking. Two independent tickers for one upstream is the same shape, arranged
    // rather than raced.
    let watched = Watched::new(&[1, 2, 3, 4]);
    let (out, inbox) = channel::<ItemId, u64>(8);
    let first = out.ticker(PollUpstream::new(0));
    let second = out.ticker(PollUpstream::new(0));
    assert!(first.ring());
    assert!(second.ring());
    assert_eq!(inbox.len(), 2, "two ticks are queued for one upstream");

    let rows = watched.rows.clone();
    let mut resident = Resident::new("reaper", Reaping::new(&watched), inbox)
      // No schedule: every tick here was rung, so nothing but the two queued ones can arrive.
      .polling(Schedule::new(), Granted { rows })
      .with_sweep(Duration::from_millis(5));
    drop((out, first, second));
    let report = resident.run();

    assert_eq!(report.ticks(), 1, "one look at one store");
    assert_eq!(watched.looks(PollUpstream::new(0)), 1);
  }
}

#[test]
fn the_two_halves_of_a_knob_agree_and_every_wired_part_reads_back() {
  // The FLUENT half, as a wiring call site spells it.
  let (_feed, inbox) = channel::<ItemId, u64>(8);
  let fluent = Resident::new("double", Doubling, inbox)
    .with_ack(AckMode::Chained)
    .with_effect(Effect::Lands)
    .with_sweep(Duration::from_millis(7));
  assert_eq!(fluent.name().as_str(), "double");
  assert_eq!(fluent.ack(), AckMode::Chained);
  assert_eq!(fluent.effect(), Effect::Lands);
  assert_eq!(fluent.sweep(), Duration::from_millis(7));

  // The IN-PLACE half, chained on `&mut Self`. The consuming form delegates to exactly this, so
  // the two cannot drift: a knob's assignment is written down once.
  let (_second, inbox) = channel::<ItemId, u64>(8);
  let mut in_place = Resident::new("double", Doubling, inbox);
  in_place
    .set_ack(AckMode::Chained)
    .set_effect(Effect::Lands)
    .set_sweep(Duration::from_millis(7));
  assert_eq!(in_place.ack(), fluent.ack());
  assert_eq!(in_place.effect(), fluent.effect());
  assert_eq!(in_place.sweep(), fluent.sweep());

  // What a resident starts at, read through the same accessors.
  let (_third, inbox) = channel::<ItemId, u64>(8);
  let plain = Resident::new("plain", Doubling, inbox);
  assert_eq!(plain.ack(), AckMode::Local);
  assert_eq!(plain.effect(), Effect::Pure);
  assert_eq!(plain.sweep(), Resident::<Doubling, ItemId, ()>::SWEEP);
  // A schedule with no entry, asserted by its emptiness rather than by equality: a parsed
  // calendar has no meaningful `==`, so `Schedule` carries none.
  assert!(plain.schedule().is_empty());
  assert!(plain.taps().is_empty());
  assert_eq!(plain.context(), &Unpolled);
  assert_eq!(plain.lane(), &());
  assert_eq!(plain.attribution(), &());
  assert_eq!(plain.ledger(), &());
  assert_eq!(plain.outstanding(), 0);
  assert_eq!(plain.holding(), 0);

  // And what a caller WIRED, including the parts that change the type. A lane is read back through
  // the same borrow the loop uses, which is what makes `land` inspectable at all.
  let (_fourth, inbox) = channel::<ItemId, u64>(8);
  let written: Written = Arc::default();
  let storing = Resident::new("store", Doubling, inbox).land(Table::new(written.clone()));
  assert_eq!(
    storing.effect(),
    Effect::Lands,
    "a lane declares its effect"
  );
  assert!(
    storing
      .lane()
      .written
      .lock()
      .expect("the lane's store")
      .is_empty(),
    "the lane wired is the lane read back"
  );

  // A tap wired is a tap counted, and the taps accessor is the only vantage on that.
  let (_fifth, inbox) = channel::<ItemId, u64>(8);
  let tapped = Resident::new("tapped", Doubling, inbox)
    .with_taps(Taps::new().with(Arc::new(RecordingTap::default())));
  assert_eq!(tapped.taps().len(), 1);
}

// THE CONSUMER'S HALF OF THE ACKED GIVE: a seat that answers its producer with a VALUE, and the
// ordering that makes the value worth anything.

/// A durable id, standing where a seat's own key type would. Nothing upstream could have computed
/// it, which is the whole reason it has to travel back rather than be derived.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct SceneId(u64);

/// A SEAT: it lands what it was given and states the durable id the row got.
///
/// The shape a scene seat has — the row is upserted, the matched natural key keeps the id it already
/// had, and only this node knows what that id is.
struct Seating;

impl Operator for Seating {
  type Error = core::convert::Infallible;
  type In = u64;
  type Out = u64;

  fn accept(
    &mut self,
    _ctx: &Context,
    delivery: Delivery<Self::In>,
    emitter: &mut Emitter<u64>,
  ) -> Result<(), Self::Error> {
    for item in delivery.into_items() {
      let value = item.into_value();
      emitter.emit(value);
      // The id this row is known by, from here on. `receipt` names no key: the driver is walking the
      // delivery and already knows which item this call was for.
      emitter.receipt(SceneId(value * 10 + 7));
    }
    Ok(())
  }
}

#[test]
fn a_staged_receipt_travels_back_on_the_ack_keyed_by_its_own_item() {
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let (out, downstream) = channel::<ItemId, u64>(8);
  let resident = Resident::new("seat", Seating, inbox)
    .publish(out)
    .with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });

  let answers = send(&feed, &[1, 2]);
  release_all(taken(&downstream, Duration::from_secs(2)).expect("the outputs arrived"));
  let answer = settled(&answers, Duration::from_secs(2)).expect("answered");

  // PER ITEM, and each item's own answer: a batch is one ack and two receipts, which is why the slot
  // is keyed rather than one per delivery.
  assert_eq!(answer.receipt::<SceneId>(&ItemId::new(1)), Ok(&SceneId(17)));
  assert_eq!(answer.receipt::<SceneId>(&ItemId::new(2)), Ok(&SceneId(27)));
  assert_eq!(answer.released().len(), 2);

  drop(feed);
  engine.join().expect("the engine thread");
}

#[test]
fn a_unit_that_states_no_receipt_answers_exactly_as_it_always_did() {
  // THE ZERO-CEREMONY HALF: every operator written before this slot existed states nothing in it,
  // and what its ack carries is what it always carried.
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let (out, downstream) = channel::<ItemId, u64>(8);
  let resident = Resident::new("double", Doubling, inbox)
    .publish(out)
    .with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });

  let answers = send(&feed, &[4]);
  release_all(taken(&downstream, Duration::from_secs(2)).expect("the outputs arrived"));
  let answer = settled(&answers, Duration::from_secs(2)).expect("answered");
  assert!(!answer.has_receipt(&ItemId::new(4)));
  assert_eq!(
    answer.receipt::<SceneId>(&ItemId::new(4)),
    Err(crate::Unreceipted::Silent)
  );
  // The rest of the answer is untouched — the released set, the worker, the station.
  assert_eq!(answer.released().len(), 1);
  assert_eq!(answer.observation().station(), Some(Station::Processed));

  drop(feed);
  engine.join().expect("the engine thread");
}

#[test]
fn a_receipt_does_not_reach_its_producer_until_the_row_has_landed() {
  // THE ORDERING THE RECEIPT EXISTS FOR, stated as a "not yet". The body has already RETURNED — its
  // outputs are in the lane — and the gate holds the node inside its own write, so a producer
  // looking at the oneshot now must see nothing. A receipt that arrived here would be a durable id
  // pointing at a row that is not there.
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let (out, downstream) = channel::<ItemId, u64>(8);
  let written: Written = Arc::new(Mutex::new(Vec::new()));
  let (report_arrival, arrived) = flume::bounded::<()>(1);
  let (open_gate, gate) = flume::bounded::<()>(1);
  let resident = Resident::new("seat", Seating, inbox)
    .publish(out)
    .land(Table::new(written.clone()).gated(report_arrival, gate))
    .with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });

  let answers = send(&feed, &[3]);
  arrived
    .recv_timeout(Duration::from_secs(20))
    .expect("the lane was called");
  assert!(
    written.lock().expect("the store").is_empty(),
    "the write has not happened yet"
  );
  assert!(
    settled(&answers, Duration::from_millis(60)).is_none(),
    "the receipt reached its producer before the row landed"
  );

  open_gate.send(()).expect("the lane is waiting");
  release_all(taken(&downstream, Duration::from_secs(2)).expect("the outputs arrived"));
  let answer = settled(&answers, Duration::from_secs(2)).expect("answered after the write");
  assert_eq!(*written.lock().expect("the store"), [3]);
  assert_eq!(answer.receipt::<SceneId>(&ItemId::new(3)), Ok(&SceneId(37)));
  assert_eq!(answer.observation().station(), Some(Station::Persisted));

  drop(feed);
  engine.join().expect("the engine thread");
}

#[test]
fn a_chained_unit_carries_its_receipt_across_the_pass_that_holds_it() {
  // Under `Chained` the ack is withheld until the outputs the item produced have themselves been
  // released — a whole pass later, from a different call. The receipt rides the OBLIGATION, which is
  // the one thing still around when the answer finally goes out.
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let (out, downstream) = channel::<ItemId, u64>(8);
  let resident = Resident::new("seat", Seating, inbox)
    .publish(out)
    .with_ack(AckMode::Chained)
    .with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });

  let answers = send(&feed, &[5]);
  let delivery = taken(&downstream, Duration::from_secs(2)).expect("the outputs arrived");
  assert!(
    settled(&answers, Duration::from_millis(60)).is_none(),
    "the input is owed until its output is released"
  );

  assert_eq!(release_all(delivery), [5]);
  let answer = settled(&answers, Duration::from_secs(2)).expect("the join completed");
  assert_eq!(answer.receipt::<SceneId>(&ItemId::new(5)), Ok(&SceneId(57)));

  drop(feed);
  engine.join().expect("the engine thread");
}