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
use crate::Context;
use core::{convert::Infallible, num::NonZeroUsize, time::Duration};

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

use super::{
  super::{
    Ack, AckReceiver, Answer, Delivery, Downstream, Effect, Inbox, Item, ItemId, Lifecycle,
    LifecycleTap, NodeName, Observation, Outbox, Payload, RecordingTap, Settled, Sink, Station,
    Taps, Thread, Wake, Wanted, ack_channel, channel,
    feed::{FeedContext, FeedPolicy, Fixed, MemoryAware, Pressure, Steady},
    lane::{block_on, block_until},
  },
  StreamLane, StreamOptions, Streamed,
};
use crate::{Async, AsyncStreamOperator, Feed, Fin, StreamOperator};

// ---------------------------------------------------------------------------------------------
// fixtures
// ---------------------------------------------------------------------------------------------

fn width(n: usize) -> NonZeroUsize {
  NonZeroUsize::new(n).expect("the test's own width")
}

fn seats(in_flight: usize, feed: usize) -> StreamOptions {
  StreamOptions::new()
    .with_in_flight(width(in_flight))
    .with_feed_policy(Box::new(Fixed::of(width(feed))))
}

/// One delivery of `values`, with a custody token the caller can wait on.
fn delivery(values: &[u64]) -> (Delivery<u64>, AckReceiver<ItemId>) {
  let (ack, answers) = ack_channel();
  let items = values
    .iter()
    .enumerate()
    .map(|(seq, &value)| Item::new(ItemId::new(seq as u64), value))
    .collect();
  (Delivery::new(Payload::Batch(items), ack), answers)
}

/// Poll until the answer arrives, or give up — [`resident::tests`](super::super::resident)' own.
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 everything the lane publishes, releasing each delivery, until the edge hangs up.
fn drainer(inbox: Inbox<ItemId, u64>) -> (thread::JoinHandle<()>, Arc<Mutex<Vec<u64>>>) {
  let taken = Arc::new(Mutex::new(Vec::new()));
  let into = Arc::clone(&taken);
  let handle = thread::spawn(move || {
    while let Some(wake) = inbox.park(Duration::from_millis(20)) {
      let Wake::Delivered(delivery) = wake else {
        continue;
      };
      let (payload, ack) = delivery.into_parts();
      let released: HashSet<ItemId> = payload.keys().copied().collect();
      let values: Vec<u64> = payload.into_iter().map(|item| *item.value()).collect();
      into.lock().expect("the collector").extend(values);
      if let Some(ack) = ack {
        ack.send(Ack::new(released, "consumer", Lifecycle::Persisted(())));
      }
    }
  });
  (handle, taken)
}

/// [`drainer`], at an edge carrying a payload that does not copy — what the demux fixtures publish
/// into.
fn held_drainer(inbox: Inbox<ItemId, Held>) -> (thread::JoinHandle<()>, Arc<Mutex<Vec<u64>>>) {
  let taken = Arc::new(Mutex::new(Vec::new()));
  let into = Arc::clone(&taken);
  let handle = thread::spawn(move || {
    while let Some(wake) = inbox.park(Duration::from_millis(20)) {
      let Wake::Delivered(delivery) = wake else {
        continue;
      };
      let (payload, ack) = delivery.into_parts();
      let released: HashSet<ItemId> = payload.keys().copied().collect();
      let values: Vec<u64> = payload
        .into_iter()
        .map(|item| item.into_value().0)
        .collect();
      into.lock().expect("the collector").extend(values);
      if let Some(ack) = ack {
        ack.send(Ack::new(released, "consumer", Lifecycle::Persisted(())));
      }
    }
  });
  (handle, taken)
}

/// A body that gives each delivered value back, then ends — the plainest stream there is.
struct Passing;

impl StreamOperator for Passing {
  type Error = Infallible;
  type In = u64;
  type Out = u64;

  fn run(
    &mut self,
    _ctx: &Context,
    delivery: Delivery<Self::In>,
    feed: Feed<Self::Out>,
  ) -> Result<Fin, Self::Error> {
    for item in delivery.into_items() {
      if feed.give(item.into_value()).is_err() {
        return Ok(Fin::Stopped);
      }
    }
    Ok(Fin::Spent)
  }
}

/// A body that fans ONE delivered value into that many items — the shape the face exists for.
struct Fanning;

impl StreamOperator for Fanning {
  type Error = Infallible;
  type In = u64;
  type Out = u64;

  fn run(
    &mut self,
    _ctx: &Context,
    delivery: Delivery<Self::In>,
    feed: Feed<Self::Out>,
  ) -> Result<Fin, Self::Error> {
    for item in delivery.into_items() {
      for step in 0..item.into_value() {
        if feed.give(step).is_err() {
          return Ok(Fin::Stopped);
        }
      }
    }
    Ok(Fin::Spent)
  }
}

/// A body that says how many of itself are running, and holds the answer still long enough to see.
struct Crowding {
  live: Arc<AtomicUsize>,
  peak: Arc<AtomicUsize>,
}

impl StreamOperator for Crowding {
  type Error = Infallible;
  type In = u64;
  type Out = u64;

  fn run(
    &mut self,
    _ctx: &Context,
    delivery: Delivery<Self::In>,
    feed: Feed<Self::Out>,
  ) -> Result<Fin, Self::Error> {
    let now = self.live.fetch_add(1, Ordering::AcqRel) + 1;
    self.peak.fetch_max(now, Ordering::AcqRel);
    for item in delivery.into_items() {
      let _ = feed.give(item.into_value());
    }
    thread::sleep(Duration::from_millis(60));
    self.live.fetch_sub(1, Ordering::AcqRel);
    Ok(Fin::Spent)
  }
}

/// A body that KEEPS what it saw — the whole of what a warm instance is for.
struct Remembering {
  seen: u64,
}

impl StreamOperator for Remembering {
  type Error = Infallible;
  type In = u64;
  type Out = u64;

  fn run(
    &mut self,
    _ctx: &Context,
    delivery: Delivery<Self::In>,
    feed: Feed<Self::Out>,
  ) -> Result<Fin, Self::Error> {
    for item in delivery.into_items() {
      self.seen += item.into_value();
      if feed.give(self.seen).is_err() {
        return Ok(Fin::Stopped);
      }
    }
    Ok(Fin::Spent)
  }
}

#[derive(Debug, derive_more::Display)]
#[display("this delivery's read went bad half way through")]
struct WentBad;

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

/// A body that gives three items and then DIES — once, and afterwards behaves.
struct DyingOnce {
  died: bool,
}

impl StreamOperator for DyingOnce {
  type Error = WentBad;
  type In = u64;
  type Out = u64;

  fn run(
    &mut self,
    _ctx: &Context,
    delivery: Delivery<Self::In>,
    feed: Feed<Self::Out>,
  ) -> Result<Fin, Self::Error> {
    for item in delivery.into_items() {
      let _ = feed.give(item.into_value());
    }
    if self.died {
      return Ok(Fin::Spent);
    }
    self.died = true;
    Err(WentBad)
  }
}

/// A body with no end of its own: it streams until somebody says stop.
struct Endless;

impl StreamOperator for Endless {
  type Error = Infallible;
  type In = u64;
  type Out = u64;

  fn run(
    &mut self,
    ctx: &Context,
    _delivery: Delivery<Self::In>,
    feed: Feed<Self::Out>,
  ) -> Result<Fin, Self::Error> {
    // A prefix given before the stop is ever looked at, so that what a wound-down run KEPT is a fact
    // rather than a race against how fast the test says stop.
    for step in 0..PREFIX {
      if feed.give(step).is_err() {
        return Ok(Fin::Stopped);
      }
    }
    let mut next = PREFIX;
    loop {
      if ctx.shutdown().is_shutdown() {
        return Ok(Fin::Stopped);
      }
      if feed.give(next).is_err() {
        return Ok(Fin::Stopped);
      }
      next += 1;
    }
  }
}

/// How many items [`Endless`] gives before it starts looking at its stop.
const PREFIX: u64 = 3;

/// [`Fanning`] on the AWAITED face, parking on [`give_async`](Feed::give_async).
struct AwaitedFanning;

impl AsyncStreamOperator for AwaitedFanning {
  type Error = Infallible;
  type In = u64;
  type Out = u64;

  async fn run(
    &mut self,
    _ctx: &Context,
    delivery: Delivery<Self::In>,
    feed: Feed<Self::Out>,
  ) -> Result<Fin, Self::Error> {
    for item in delivery.into_items() {
      for step in 0..item.into_value() {
        if feed.give_async(step).await.is_err() {
          return Ok(Fin::Stopped);
        }
      }
    }
    Ok(Fin::Spent)
  }
}

/// A [`FeedPolicy`] that remembers what it was shown.
#[derive(Debug, Default)]
struct Watching {
  seen: Mutex<Vec<(usize, usize)>>,
}

impl FeedPolicy for Watching {
  fn capacity(&self, ctx: &FeedContext<'_>) -> NonZeroUsize {
    self
      .seen
      .lock()
      .expect("the recorder")
      .push((ctx.in_flight(), ctx.width().get()));
    width(4)
  }
}

/// A payload that DOES NOT COPY — a decoded buffer, an open device handle, an FFI session.
///
/// Deliberately not [`Clone`]: it is the whole of what the demux fixtures below pin.
#[derive(Debug, PartialEq, Eq)]
struct Held(u64);

/// A node's product sum where NEITHER product copies.
#[derive(Debug)]
enum Demuxed {
  Left(Held),
  Right(Held),
}

/// A body that DEMULTIPLEXES: every fed value goes to exactly one of two products.
struct Demuxing;

impl StreamOperator for Demuxing {
  type Error = Infallible;
  type In = u64;
  type Out = Demuxed;

  fn run(
    &mut self,
    _ctx: &Context,
    delivery: Delivery<Self::In>,
    feed: Feed<Self::Out>,
  ) -> Result<Fin, Self::Error> {
    for item in delivery.into_items() {
      let value = item.into_value();
      let product = if value.is_multiple_of(2) {
        Demuxed::Left(Held(value))
      } else {
        Demuxed::Right(Held(value))
      };
      if feed.give(product).is_err() {
        return Ok(Fin::Stopped);
      }
    }
    Ok(Fin::Spent)
  }
}

/// The demux node's OWN downstream set — ONE SLOT PER PRODUCT, which is the shape a node's emitted
/// `<Node>Downstream` has.
///
/// [`carries`](Sink::carries) is true for exactly one edge per output, so the fan-out's copy is
/// never reached: this is the set that proves the lane asks a payload for [`Clone`] only where a
/// second edge would spend one.
struct DemuxedDownstream {
  left: Option<Outbox<ItemId, Held>>,
  right: Option<Outbox<ItemId, Held>>,
}

impl Sink<Demuxed> for DemuxedDownstream {
  fn arity(&self) -> usize {
    2
  }

  fn connected(&self) -> Wanted {
    let mut mask = Wanted::none();
    if self.left.is_some() {
      mask = mask.with(0);
    }
    if self.right.is_some() {
      mask = mask.with(1);
    }
    mask
  }

  fn carries(&self, edge: usize, output: &Demuxed) -> bool {
    match (edge, output) {
      (0, Demuxed::Left(_)) => self.left.is_some(),
      (1, Demuxed::Right(_)) => self.right.is_some(),
      _ => false,
    }
  }

  fn nudges(&self) -> Vec<Box<dyn crate::Rings>> {
    let mut ringers: Vec<Box<dyn crate::Rings>> = Vec::new();
    for edge in self.left.iter().chain(self.right.iter()) {
      ringers.push(Box::new(edge.nudge()) as Box<dyn crate::Rings>);
    }
    ringers
  }

  async fn deliver(
    &mut self,
    edge: usize,
    batch: Vec<Item<Demuxed>>,
    ack: crate::AckSender<ItemId>,
  ) -> bool {
    let (slot, want_left) = match edge {
      0 => (self.left.as_ref(), true),
      1 => (self.right.as_ref(), false),
      _ => return false,
    };
    let Some(edge) = slot else {
      return false;
    };
    let mut taken: Vec<Item<Held>> = Vec::with_capacity(batch.len());
    for message in batch {
      let (id, value) = message.into_parts();
      match (value, want_left) {
        (Demuxed::Left(held), true) | (Demuxed::Right(held), false) => {
          taken.push(Item::new(id, held));
        }
        // Not this edge's product. Answered `false` rather than dropped, exactly as the emission's
        // own arm is.
        _ => return false,
      }
    }
    edge
      .deliver_async(Delivery::new(Payload::Batch(taken), ack))
      .await
      .is_ok()
  }
}

/// A body whose ONE product does not copy.
struct Holding;

impl StreamOperator for Holding {
  type Error = Infallible;
  type In = u64;
  type Out = Held;

  fn run(
    &mut self,
    _ctx: &Context,
    delivery: Delivery<Self::In>,
    feed: Feed<Self::Out>,
  ) -> Result<Fin, Self::Error> {
    for item in delivery.into_items() {
      if feed.give(Held(item.into_value())).is_err() {
        return Ok(Fin::Stopped);
      }
    }
    Ok(Fin::Spent)
  }
}

/// A downstream set that PROMISES TWO SEATS for one output and can fill neither.
///
/// [`carries`](Sink::carries) is the inherited every-edge answer and
/// [`duplicate`](Sink::duplicate) the inherited `None` — a set contradicting itself, which the
/// framework's own two cannot be. It exists to pin what the lane does about it: the last edge takes
/// the value by move, the first is refused BY NAME, and nothing is dropped in silence.
struct Overpromising {
  edges: Vec<Outbox<ItemId, Held>>,
}

impl Sink<Held> for Overpromising {
  fn arity(&self) -> usize {
    self.edges.len()
  }

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

  async fn deliver(
    &mut self,
    edge: usize,
    batch: Vec<Item<Held>>,
    ack: crate::AckSender<ItemId>,
  ) -> bool {
    self.edges[edge]
      .deliver_async(Delivery::new(Payload::Batch(batch), ack))
      .await
      .is_ok()
  }
}

/// A tap that keeps the REASON of every refusal — what [`RecordingTap`] cannot say, because a
/// station is not a sentence.
#[derive(Debug, Default)]
struct Refusals {
  seen: Mutex<Vec<String>>,
}

impl LifecycleTap for Refusals {
  fn observe(&self, _node: &NodeName, observation: &Observation) {
    if let Some(skip) = observation.skip() {
      self
        .seen
        .lock()
        .expect("the refusals log")
        .push(skip.reason().as_str().to_owned());
    }
  }
}

// ---------------------------------------------------------------------------------------------
// the lane
// ---------------------------------------------------------------------------------------------

#[test]
fn one_delivery_is_streamed_through_the_lane_and_settles_at_its_ending() {
  let (out, inbox) = channel::<ItemId, u64>(64);
  let (collector, taken) = drainer(inbox);
  let tap = Arc::new(RecordingTap::new());
  let mut lane = StreamLane::new(
    Context::new("fan"),
    seats(1, 4),
    [Fanning],
    Downstream::from_iter([out]),
    Thread::new(),
  )
  .with_effect(Effect::Pure)
  .with_taps(Taps::new().with(Arc::clone(&tap) as Arc<dyn LifecycleTap>));

  assert_eq!(lane.width(), 1);
  let (delivery, answers) = delivery(&[5]);
  block_on(lane.admit(delivery)).expect("the lane has a body");
  assert_eq!(lane.in_flight(), 1);
  block_on(lane.drain());
  assert_eq!(lane.in_flight(), 0);
  assert_eq!(lane.idle(), 1);

  drop(lane);
  collector.join().expect("the collector thread");
  assert_eq!(*taken.lock().expect("the collector"), [0, 1, 2, 3, 4]);

  let answer = settled(&answers, Duration::from_secs(2)).expect("the delivery was answered");
  assert_eq!(answer.observation().station(), Some(Station::Processed));
  let info = answer
    .observation()
    .info::<Streamed>()
    .expect("the lane's own info type");
  assert_eq!(info.given(), 5);
  assert_eq!(info.projected(), 5);
  assert_eq!(info.skipped(), 0);
  assert_eq!(info.fin(), Some(Fin::Spent));
  // What the lane itself said about the delivery, told apart from what the CONSUMER said about the
  // items — an answer is observed under the worker's name, which is the harvest's own law.
  let spoken: Vec<_> = tap
    .seen()
    .into_iter()
    .filter(|(node, _)| node == "fan")
    .collect();
  assert_eq!(spoken, [("fan".to_owned(), Station::Processed)]);
}

#[test]
fn in_flight_bounds_how_many_runs_are_live_at_once() {
  // Four deliveries, two permits: two runs overlap and a third never joins them.
  let (out, inbox) = channel::<ItemId, u64>(256);
  let (collector, _taken) = drainer(inbox);
  let live = Arc::new(AtomicUsize::new(0));
  let peak = Arc::new(AtomicUsize::new(0));
  let bodies: Vec<Crowding> = (0..2)
    .map(|_| Crowding {
      live: Arc::clone(&live),
      peak: Arc::clone(&peak),
    })
    .collect();
  let mut lane = StreamLane::new(
    Context::new("crowd"),
    seats(2, 8),
    bodies,
    Downstream::from_iter([out]),
    Thread::new(),
  );
  assert_eq!(lane.width(), 2);

  block_on(async {
    for value in 1..=4u64 {
      let (delivery, _answers) = delivery(&[value]);
      lane.admit(delivery).await.expect("the lane has bodies");
      assert!(
        lane.in_flight() <= 2,
        "the admission bound is what the lane counts"
      );
    }
    lane.drain().await;
  });

  drop(lane);
  collector.join().expect("the collector thread");
  assert_eq!(
    peak.load(Ordering::Acquire),
    2,
    "two permits means exactly two runs live at the busiest moment"
  );
  assert_eq!(live.load(Ordering::Acquire), 0);
}

#[test]
fn a_warm_instance_keeps_what_it_learned_for_the_next_delivery() {
  let (out, inbox) = channel::<ItemId, u64>(64);
  let (collector, taken) = drainer(inbox);
  let mut lane = StreamLane::new(
    Context::new("remember"),
    seats(1, 4),
    [Remembering { seen: 0 }],
    Downstream::from_iter([out]),
    Thread::new(),
  );

  block_on(async {
    for value in [10u64, 5, 1] {
      let (delivery, _answers) = delivery(&[value]);
      lane.admit(delivery).await.expect("the lane has a body");
      lane.drain().await;
    }
  });

  drop(lane);
  collector.join().expect("the collector thread");
  // 10, then 10 + 5, then 10 + 5 + 1: the running total is state ONE instance carried across three
  // deliveries, which is what a warm set is for.
  assert_eq!(*taken.lock().expect("the collector"), [10, 15, 16]);
}

/// **ingraph #472 — A LANE WHOSE EVERY LINE HAS DRAINED MUST NOT PARK.**
///
/// The defect was a lost wakeup and it wedged the lane for good. `tend` reaches `woken` only where
/// `pass` moved nothing, so every live line was UNdrained when `pass` last looked; a run thread that
/// returns in the window between that look and `arms` drops its feed, the last real arm becomes a
/// `pending()` placeholder, and the blocking face — which polls the arms and nothing else — parks on
/// an arm set carrying no waker at all. Nothing ever unparks it. Measured as a live hang under
/// parallel load with three threads standing: the driver in `std::thread::park`, the test's own
/// collector healthy in its 20ms sweep, and the run thread already gone.
///
/// THE RACE IS NOT WHAT IS ASSERTED HERE — the window is a few instructions wide and a test that
/// waited for it would be the flake it is replacing. What is asserted is the STATE the race arrives
/// at, reached deliberately: the line is drained by hand, which is exactly what `pass`'s first loop
/// does, and `woken` is then asked the question the run thread's exit would have left it holding.
///
/// Under a deadline, because the regression's signature is *does not return*: a bare call would hang
/// the suite instead of failing it, which is how this reached `main` in the first place.
#[test]
fn a_lane_whose_every_line_has_drained_answers_instead_of_parking() {
  let (out, inbox) = channel::<ItemId, u64>(64);
  let (collector, _taken) = drainer(inbox);
  let mut lane = StreamLane::new(
    Context::new("drained"),
    seats(1, 4),
    [Passing],
    Downstream::from_iter([out]),
    Thread::new(),
  );

  let (delivery, answers) = delivery(&[7]);
  block_on(lane.admit(delivery)).expect("the lane has a body");

  // The run gives its one item and ends, which is what closes the feed. Spun rather than slept: what
  // this waits for is the body's own exit, and a sleep would assert a duration instead of a state.
  let deadline = Instant::now() + Duration::from_secs(5);
  while !lane.live[0].yielded.is_disconnected() {
    assert!(Instant::now() < deadline, "the body ends on its own");
    thread::yield_now();
  }
  // `pass`'s FIRST loop, by hand — and stopping there is the point: its second loop would remove the
  // line, and the run thread's exit lands between the two.
  let taken: Vec<u64> = lane.live[0].yielded.drain().collect();
  assert_eq!(taken, [7], "the body fed its one item before it ended");
  assert!(
    lane.live[0].drained(),
    "the feed has hung up and what it held is taken — the state the window leaves behind"
  );

  let answered = block_until(lane.woken(), Some(Instant::now() + Duration::from_secs(5)));
  let answered = answered.expect(
    "a park over an arm set that is placeholders throughout has no waker in it and never returns",
  );
  assert_eq!(
    answered, None,
    "nothing more can arrive on any line, and the hang-up is what that state IS"
  );

  // And the answer is USEFUL rather than merely prompt: the pass after it closes the line the answer
  // was about, so the wind-down finishes instead of spinning.
  block_on(lane.drain());
  assert_eq!(lane.in_flight(), 0);
  assert_eq!(lane.idle(), 1, "the instance went back to the warm set");

  drop(lane);
  collector.join().expect("the collector thread");
  let answer = settled(&answers, Duration::from_secs(2)).expect("the delivery was answered");
  assert_eq!(
    answer.observation().info::<Streamed>().map(Streamed::fin),
    Some(Some(Fin::Spent)),
    "the run's own ending reached the settlement"
  );
}

#[test]
fn a_narrow_feed_carries_a_wide_stream() {
  // The S1 test's shape, through the lane: a feed one item deep and an edge four deliveries deep,
  // carrying two thousand items. Nothing is lost and nothing is buffered, because every `give` waits
  // for the drain that is running beside it.
  let (out, inbox) = channel::<ItemId, u64>(4);
  let (collector, taken) = drainer(inbox);
  let mut lane = StreamLane::new(
    Context::new("narrow"),
    seats(1, 1),
    [Fanning],
    Downstream::from_iter([out]),
    Thread::new(),
  );

  let (delivery, answers) = delivery(&[2_000]);
  block_on(async {
    lane.admit(delivery).await.expect("the lane has a body");
    lane.drain().await;
  });

  drop(lane);
  collector.join().expect("the collector thread");
  let taken = taken.lock().expect("the collector");
  assert_eq!(taken.len(), 2_000);
  assert!(
    taken.iter().copied().eq(0..2_000),
    "a bounded feed reorders nothing"
  );

  let answer = settled(&answers, Duration::from_secs(2)).expect("the delivery was answered");
  let info = answer
    .observation()
    .info::<Streamed>()
    .expect("the lane's own info type");
  assert_eq!(info.given(), 2_000);
  assert_eq!(info.projected(), 2_000);
}

#[test]
fn an_err_dead_letters_the_delivery_and_the_next_one_still_runs() {
  let (out, inbox) = channel::<ItemId, u64>(64);
  let (collector, taken) = drainer(inbox);
  let tap = Arc::new(RecordingTap::new());
  let mut lane = StreamLane::new(
    Context::new("dying"),
    seats(1, 8),
    [DyingOnce { died: false }],
    Downstream::from_iter([out]),
    Thread::new(),
  )
  .with_taps(Taps::new().with(Arc::clone(&tap) as Arc<dyn LifecycleTap>));

  let (first, failing) = delivery(&[1, 2, 3]);
  let (second, surviving) = delivery(&[4, 5]);
  block_on(async {
    lane.admit(first).await.expect("the lane has a body");
    lane.drain().await;
    lane.admit(second).await.expect("the pool is not poisoned");
    lane.drain().await;
  });

  drop(lane);
  collector.join().expect("the collector thread");
  // EVERYTHING ALREADY GIVEN STANDS: the three items crossed the feed before the failure.
  assert_eq!(*taken.lock().expect("the collector"), [1, 2, 3, 4, 5]);

  let answer = settled(&failing, Duration::from_secs(2)).expect("the failed delivery was answered");
  assert_eq!(answer.observation().station(), Some(Station::Failed));
  assert_eq!(
    answer
      .observation()
      .failure()
      .expect("the error rides the settlement")
      .to_string(),
    WentBad.to_string()
  );
  assert!(
    answer.released().is_empty(),
    "a failed delivery is released by nothing, so its sender can re-deliver it"
  );

  let answer = settled(&surviving, Duration::from_secs(2)).expect("the next delivery ran");
  assert_eq!(answer.observation().station(), Some(Station::Processed));
  let spoken: Vec<_> = tap
    .seen()
    .into_iter()
    .filter(|(node, _)| node == "dying")
    .map(|(_, station)| station)
    .collect();
  assert_eq!(spoken, [Station::Failed, Station::Processed]);
}

#[test]
fn a_stop_winds_a_run_down_and_the_ending_says_so() {
  let (out, inbox) = channel::<ItemId, u64>(8);
  let (collector, taken) = drainer(inbox);
  let mut lane = StreamLane::new(
    Context::new("endless"),
    seats(1, 4),
    [Endless],
    Downstream::from_iter([out]),
    Thread::new(),
  );

  let (delivery, answers) = delivery(&[1]);
  block_on(lane.admit(delivery)).expect("the lane has a body");
  lane.stop();
  block_on(lane.drain());

  drop(lane);
  collector.join().expect("the collector thread");
  assert!(
    taken.lock().expect("the collector").len() >= PREFIX as usize,
    "a wound-down run keeps what it had already given"
  );

  let answer = settled(&answers, Duration::from_secs(2)).expect("the delivery was answered");
  assert_eq!(answer.observation().station(), Some(Station::Processed));
  let info = answer
    .observation()
    .info::<Streamed>()
    .expect("the lane's own info type");
  assert_eq!(info.fin(), Some(Fin::Stopped));
}

#[test]
fn the_feed_policy_is_asked_at_every_spawn_and_shown_the_count() {
  let (out, inbox) = channel::<ItemId, u64>(256);
  let (collector, _taken) = drainer(inbox);
  let watching = Arc::new(Watching::default());
  let policy = Arc::clone(&watching);
  let live = Arc::new(AtomicUsize::new(0));
  let peak = Arc::new(AtomicUsize::new(0));
  let bodies: Vec<Crowding> = (0..2)
    .map(|_| Crowding {
      live: Arc::clone(&live),
      peak: Arc::clone(&peak),
    })
    .collect();
  let mut lane = StreamLane::new(
    Context::new("asked"),
    StreamOptions::new()
      .with_in_flight(width(2))
      .with_feed_policy(Box::new(Recorded(policy))),
    bodies,
    Downstream::from_iter([out]),
    Thread::new(),
  );

  block_on(async {
    for value in 1..=3u64 {
      let (delivery, _answers) = delivery(&[value]);
      lane.admit(delivery).await.expect("the lane has bodies");
    }
    lane.drain().await;
  });

  drop(lane);
  collector.join().expect("the collector thread");
  let seen = watching.seen.lock().expect("the recorder").clone();
  assert_eq!(seen.len(), 3, "once per delivery, at its spawn");
  // The count is read BEFORE the admission it is being asked about, so the first delivery of an idle
  // lane sees nothing in flight and the second — admitted while the first is still sleeping — sees one.
  assert_eq!(seen[0], (0, 2));
  assert_eq!(seen[1], (1, 2));
  assert!(seen[2].0 <= 2, "never past the width: {:?}", seen[2]);
  assert_eq!(seen[2].1, 2);
}

/// A [`FeedPolicy`] that delegates to a shared recorder — what lets one test hold the recorder while
/// the lane holds the policy.
#[derive(Debug)]
struct Recorded(Arc<Watching>);

impl FeedPolicy for Recorded {
  fn capacity(&self, ctx: &FeedContext<'_>) -> NonZeroUsize {
    self.0.capacity(ctx)
  }
}

#[test]
fn a_memory_aware_policy_cuts_to_the_floor_under_pressure_through_the_lane() {
  // The seam end to end: a pinned probe, a scaling policy, and a real delivery streamed at whatever
  // depth the pair answered.
  for (pressure, expected) in [(Pressure::NONE, 32usize), (Pressure::CRITICAL, 2usize)] {
    let (out, inbox) = channel::<ItemId, u64>(64);
    let (collector, taken) = drainer(inbox);
    let options = StreamOptions::new()
      .with_feed_policy(Box::new(MemoryAware::between(width(2), width(32))))
      .with_memory_probe(Box::new(Steady::at(pressure)));
    let mut lane = StreamLane::new(
      Context::new("aware"),
      options,
      [Fanning],
      Downstream::from_iter([out]),
      Thread::new(),
    );
    assert_eq!(
      lane.options().feed_policy().capacity(&FeedContext::new(
        0,
        width(1),
        lane.options().memory_probe()
      )),
      width(expected)
    );

    let (delivery, _answers) = delivery(&[40]);
    block_on(async {
      lane.admit(delivery).await.expect("the lane has a body");
      lane.drain().await;
    });
    drop(lane);
    collector.join().expect("the collector thread");
    assert_eq!(taken.lock().expect("the collector").len(), 40);
  }
}

#[test]
fn the_awaited_face_is_driven_by_the_same_lane() {
  // No spawn anywhere: the run is a future this lane polls, which is what keeps a `!Send` body an
  // ordinary citizen here.
  let (out, inbox) = channel::<ItemId, u64>(4);
  let (collector, taken) = drainer(inbox);
  let mut lane: StreamLane<AwaitedFanning, _, Thread, Async> = StreamLane::new(
    Context::new("awaited"),
    seats(1, 2),
    [AwaitedFanning],
    Downstream::from_iter([out]),
    Thread::new(),
  );

  let (delivery, answers) = delivery(&[500]);
  block_on(async {
    lane.admit(delivery).await.expect("the lane has a body");
    lane.drain().await;
  });

  drop(lane);
  collector.join().expect("the collector thread");
  let taken = taken.lock().expect("the collector");
  assert_eq!(taken.len(), 500);
  assert!(taken.iter().copied().eq(0..500));

  let answer = settled(&answers, Duration::from_secs(2)).expect("the delivery was answered");
  let info = answer
    .observation()
    .info::<Streamed>()
    .expect("the lane's own info type");
  assert_eq!(info.given(), 500);
  assert_eq!(info.fin(), Some(Fin::Spent));
}

#[test]
fn a_lane_with_no_body_hands_the_delivery_back() {
  let (out, inbox) = channel::<ItemId, u64>(8);
  let (collector, _taken) = drainer(inbox);
  let mut lane: StreamLane<Passing, _> = StreamLane::new(
    Context::new("empty"),
    seats(1, 4),
    [],
    Downstream::from_iter([out]),
    Thread::new(),
  );
  assert_eq!(lane.width(), 0);
  let (delivery, _answers) = delivery(&[1]);
  assert!(
    block_on(lane.admit(delivery)).is_err(),
    "waiting cannot resolve a lane that has nothing to run with"
  );
  drop(lane);
  collector.join().expect("the collector thread");
}

#[test]
fn an_item_no_edge_carries_is_counted_rather_than_announced() {
  let mut lane = StreamLane::new(
    Context::new("unwired"),
    seats(1, 8),
    [Fanning],
    Downstream::<u64>::new(),
    Thread::new(),
  );
  let (delivery, answers) = delivery(&[6]);
  block_on(async {
    lane.admit(delivery).await.expect("the lane has a body");
    lane.drain().await;
  });

  let answer = settled(&answers, Duration::from_secs(2)).expect("the delivery was answered");
  let info = answer
    .observation()
    .info::<Streamed>()
    .expect("the lane's own info type");
  assert_eq!(info.given(), 6);
  assert_eq!(info.projected(), 0);
  assert_eq!(info.skipped(), 6);
}

#[test]
fn the_seats_carry_the_shipped_defaults_and_the_rendering_hides_the_advisors() {
  let options = StreamOptions::new();
  assert_eq!(options.in_flight(), super::DEFAULT_IN_FLIGHT);
  assert_eq!(
    options
      .feed_policy()
      .capacity(&FeedContext::new(0, width(1), options.memory_probe())),
    super::super::DEFAULT_FEED_DEPTH
  );
  let rendered = format!("{options:?}");
  assert!(rendered.contains("in_flight"), "{rendered}");
  assert!(!rendered.contains("Fixed"), "{rendered}");
}

// ---------------------------------------------------------------------------------------------
// what the fan-out's copy is asked of, and what it is not
// ---------------------------------------------------------------------------------------------

/// **THE DEMUX SHAPE**: several products, ONE seat apiece, and a payload that does not copy.
///
/// The wall this pins is the lane's, not the face's: a node whose downstream set hands each output
/// to exactly one edge reaches the fan-out's copy never, so demanding [`Clone`] of its payload was
/// demanding a capability nothing spends.
#[test]
fn a_multi_product_lane_streams_a_payload_that_does_not_copy() {
  let (left, left_inbox) = channel::<ItemId, Held>(64);
  let (right, right_inbox) = channel::<ItemId, Held>(64);
  let (left_taker, lefts) = held_drainer(left_inbox);
  let (right_taker, rights) = held_drainer(right_inbox);

  let mut lane = StreamLane::new(
    Context::new("demux"),
    seats(1, 4),
    [Demuxing],
    DemuxedDownstream {
      left: Some(left),
      right: Some(right),
    },
    Thread::new(),
  )
  .with_effect(Effect::Pure);

  let (delivery, answers) = delivery(&[1, 2, 3, 4]);
  block_on(lane.admit(delivery)).expect("the lane has a body");
  block_on(lane.drain());

  drop(lane);
  left_taker.join().expect("the left collector");
  right_taker.join().expect("the right collector");
  assert_eq!(*lefts.lock().expect("the left collector"), [2, 4]);
  assert_eq!(*rights.lock().expect("the right collector"), [1, 3]);

  let answer = settled(&answers, Duration::from_secs(2)).expect("the delivery was answered");
  let info = answer
    .observation()
    .info::<Streamed>()
    .expect("the lane's own info type");
  assert_eq!(info.given(), 4);
  assert_eq!(info.projected(), 4);
  assert_eq!(info.skipped(), 0);
}

/// The OTHER half of the same law: where a second edge genuinely carries one output, the copy is
/// still taken — through [`Sink::duplicate`], at the set that has the seat to fill.
#[test]
fn one_output_that_two_edges_carry_is_moved_into_the_last_and_copied_for_the_first() {
  let (first, first_inbox) = channel::<ItemId, u64>(64);
  let (second, second_inbox) = channel::<ItemId, u64>(64);
  let (firsts, from_first) = drainer(first_inbox);
  let (seconds, from_second) = drainer(second_inbox);

  let mut lane = StreamLane::new(
    Context::new("both"),
    seats(1, 4),
    [Passing],
    Downstream::from_iter([first, second]),
    Thread::new(),
  )
  .with_effect(Effect::Pure);

  let (delivery, answers) = delivery(&[7, 8]);
  block_on(lane.admit(delivery)).expect("the lane has a body");
  block_on(lane.drain());

  drop(lane);
  firsts.join().expect("the first collector");
  seconds.join().expect("the second collector");
  assert_eq!(*from_first.lock().expect("the first collector"), [7, 8]);
  assert_eq!(*from_second.lock().expect("the second collector"), [7, 8]);

  let answer = settled(&answers, Duration::from_secs(2)).expect("the delivery was answered");
  let info = answer
    .observation()
    .info::<Streamed>()
    .expect("the lane's own info type");
  // Per ITEM and not per edge — two items over two edges is four on the wire and two here.
  assert_eq!(info.given(), 2);
  assert_eq!(info.projected(), 2);
  assert_eq!(info.skipped(), 0);
}

/// A downstream set that promised a seat it cannot fill is REFUSED BY NAME, and the value still
/// reaches the edge that takes it by move.
///
/// The framework's own sets cannot reach this: [`Downstream`] duplicates and pays a `Clone` for the
/// right to, and a one-seat-per-product set never asks. A hand-written [`Sink`] can, and what it
/// gets is a sentence rather than a silence.
#[test]
fn a_second_seat_a_payload_cannot_fill_is_refused_by_name() {
  let (first, first_inbox) = channel::<ItemId, Held>(64);
  let (second, second_inbox) = channel::<ItemId, Held>(64);
  let (firsts, from_first) = held_drainer(first_inbox);
  let (seconds, from_second) = held_drainer(second_inbox);
  let refusals = Arc::new(Refusals::default());

  let mut lane = StreamLane::new(
    Context::new("overpromised"),
    seats(1, 4),
    [Holding],
    Overpromising {
      edges: vec![first, second],
    },
    Thread::new(),
  )
  .with_effect(Effect::Pure)
  .with_taps(Taps::new().with(Arc::clone(&refusals) as Arc<dyn LifecycleTap>));

  let (delivery, answers) = delivery(&[11]);
  block_on(lane.admit(delivery)).expect("the lane has a body");
  block_on(lane.drain());

  drop(lane);
  firsts.join().expect("the first collector");
  seconds.join().expect("the second collector");
  // The LAST edge takes it by move; the one before it was refused rather than handed a copy nobody
  // could make.
  assert_eq!(
    *from_first.lock().expect("the first collector"),
    [] as [u64; 0]
  );
  assert_eq!(*from_second.lock().expect("the second collector"), [11]);

  assert_eq!(
    *refusals.seen.lock().expect("the refusals log"),
    [super::UNDIVIDABLE],
    "announced once for the batch, under the label a tap matches"
  );

  let answer = settled(&answers, Duration::from_secs(2)).expect("the delivery was answered");
  let info = answer
    .observation()
    .info::<Streamed>()
    .expect("the lane's own info type");
  assert_eq!(info.given(), 1);
  // It reached an edge, so it is projected rather than skipped — `skipped` is *no edge at all*.
  assert_eq!(info.projected(), 1);
  assert_eq!(info.skipped(), 0);
}

// ---------------------------------------------------------------------------------------------
// the measurements
//
// `#[ignore]`d on purpose: a number that depends on the machine cannot be a gate. They are the
// harnesses the two ruled measurements were taken on, kept so the evidence beside
// `DEFAULT_FEED_DEPTH` and `MemoryAware`'s live-adjustment note can be reproduced rather than
// believed. Run them with `--release`, which is the build the numbers were taken in:
//
//   cargo test -p ingraph --lib --all-features --release -- --ignored --nocapture stream::tests
// ---------------------------------------------------------------------------------------------

/// One delivery fanned to `FAN` items, through a lane cut at each of several depths.
#[test]
#[ignore = "a measurement, not an assertion — see the module note"]
fn the_measured_knee_is_where_the_default_sits() {
  const FAN: u64 = 200_000;

  const ROUNDS: usize = 7;
  const DEPTHS: [usize; 8] = [8, 32, 64, 128, 256, 512, 1_024, 2_048];

  // INTERLEAVED and BEST-OF, which is what makes the table readable on a machine that is doing other
  // things: every depth meets the same weather in each round, and the best round for each is the one
  // where the depth — rather than the machine's other work — was the limit.
  let mut best = [0.0f64; DEPTHS.len()];
  for _ in 0..ROUNDS {
    for (slot, depth) in DEPTHS.iter().enumerate() {
      let (out, inbox) = channel::<ItemId, u64>(64);
      let (collector, taken) = drainer(inbox);
      let mut lane = StreamLane::new(
        Context::new("knee"),
        seats(1, *depth),
        [Fanning],
        Downstream::from_iter([out]),
        Thread::new(),
      );
      let (delivery, _answers) = delivery(&[FAN]);
      let started = Instant::now();
      block_on(async {
        lane.admit(delivery).await.expect("the lane has a body");
        lane.drain().await;
      });
      let elapsed = started.elapsed();
      drop(lane);
      collector.join().expect("the collector thread");
      assert_eq!(taken.lock().expect("the collector").len(), FAN as usize);
      let rate = f64::from(u32::try_from(FAN).expect("the fan fits")) / elapsed.as_secs_f64();
      best[slot] = best[slot].max(rate);
    }
  }
  let table: Vec<(usize, f64)> = DEPTHS.iter().copied().zip(best).collect();

  let floor = table[0].1;
  println!("\nfeed depth | items/second | relative | step");
  let mut previous = floor;
  for (depth, rate) in &table {
    println!(
      "{depth:>10} | {rate:>12.0} | {:>7.2}x | {:+.1}%",
      rate / floor,
      (rate / previous - 1.0) * 100.0
    );
    previous = *rate;
  }
}

/// What a MOVABLE bound would cost on the path every give takes.
///
/// The live-adjustment design is a semaphore in front of the transport: a permit per give, released
/// when the item is taken, so `add_permits` widens the line and an acquire-and-forget narrows it. The
/// mechanism is exactly one extra acquire and one extra release per item, so this measures that pair
/// against the plain bounded channel the feed is today — the same transport, the same producer and
/// consumer, with and without the permit.
#[test]
#[ignore = "a measurement, not an assertion — see the module note"]
fn what_a_movable_feed_bound_would_cost_per_give() {
  const ITEMS: usize = 500_000;
  const DEPTH: usize = 64;
  const ROUNDS: usize = 7;

  /// The plain bounded channel the feed is today: one send, one receive, and the capacity is the bound.
  fn plain() -> Duration {
    let (tx, rx) = flume::bounded::<u64>(DEPTH);
    let started = Instant::now();
    let taker = thread::spawn(move || while rx.recv().is_ok() {});
    for item in 0..ITEMS as u64 {
      tx.send(item).expect("the taker is there");
    }
    drop(tx);
    taker.join().expect("the taker thread");
    started.elapsed()
  }

  /// The same traffic with the bound held as PERMITS rather than as the channel's own capacity —
  /// which is what makes a bound movable, and what puts one acquire and one release on every give.
  fn permitted() -> Duration {
    let (tx, rx) = flume::unbounded::<u64>();
    let (give_back, permits) = flume::bounded::<()>(DEPTH);
    for _ in 0..DEPTH {
      give_back.send(()).expect("the permit line has room");
    }
    let started = Instant::now();
    let taker = thread::spawn(move || {
      while rx.recv().is_ok() {
        // The take is what returns the permit — the item has left the line.
        let _ = give_back.send(());
      }
    });
    for item in 0..ITEMS as u64 {
      permits.recv().expect("a permit comes back");
      tx.send(item).expect("the taker is there");
    }
    drop(tx);
    taker.join().expect("the taker thread");
    started.elapsed()
  }

  // Interleaved and best-of, for the knee harness's reason.
  let mut fastest_plain = Duration::MAX;
  let mut fastest_permitted = Duration::MAX;
  for _ in 0..ROUNDS {
    fastest_plain = fastest_plain.min(plain());
    fastest_permitted = fastest_permitted.min(permitted());
  }

  let cost = fastest_permitted.as_secs_f64() / fastest_plain.as_secs_f64() - 1.0;
  println!("\nplain bounded channel : {fastest_plain:?}");
  println!("semaphore-backed bound: {fastest_permitted:?}");
  println!(
    "cost of a movable bound on the plain path: {:+.1}%",
    cost * 100.0
  );
}