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
//! THE NODE'S OWN CREW: resident workers behind a key router, built inside a body's `run` and owned
//! by it.
//!
//! # A LIBRARY DEVICE, and the framework never sees one
//!
//! The framework knows WHAT nodes exist and HOW they connect, and nothing else. Fan-out, sharding
//! and threads INSIDE a node are the node's own, and that division is the first thing to say about
//! this module: a [`Crew`] is a value an author instantiates inside their own
//! [`run`](crate::AutonomousOperator::run), out of parts they already hold. It names no
//! [`Declared`](crate::Declared), knows no mount and no lane, and never touches an edge. What the
//! graph sees is still one node with its declared edges; what stands behind that node's door is the
//! node's business, and this is a TOOL for arranging it rather than a driver that would arrange it
//! on the node's behalf.
//!
//! That is why nothing here is a framework seam. Nobody registers a [`Bench`], no declaration word
//! selects a [`Router`], and a node that wants a different crew writes one — this module is what a
//! body reaches for when it would otherwise write the same three hundred lines again.
//!
//! # TWO FORMS, and the author's loop cannot tell them apart
//!
//! | [`workers`](CrewOptions::workers) | what a [`Crew`] is | where the work runs |
//! |---|---|---|
//! | one | the INLINE form | on the calling thread, inside [`route`](Crew::route) — no thread is spawned at all |
//! | two or more | the POOL form | on N resident threads, one bounded in-queue apiece, one shared return line |
//!
//! Both answer the same three calls in the same order, so the body below is what an author writes
//! once and a deployment tunes with a number:
//!
//! ```rust,ignore
//! let crew = Crew::spawn(options, HashRouter::new(), |_| Frames::new())?;   // the prologue
//! crew.route(&key, task)?;                                                  // the work in
//! for done in crew.harvest() { … }                                          // the work out
//! for done in crew.close() { … }                                            // the epilogue
//! ```
//!
//! **[`harvest`](Crew::harvest) is the ONE door results come out of**, in both forms, which is what
//! makes the two forms substitutable. The inline form never puts anything on the return line — a
//! single thread that pushed into a bounded channel it is also the only reader of would park forever
//! the moment a task yielded more than the free room — so what it computes is staged and comes out
//! of the same call. See [`Crew::route`] for the whole of that reasoning.
//!
//! # THE RETURN LINE IS A SELECT ARM, and the arm WATCHES rather than reads
//!
//! A body that owns its loop parks on its upstream edges; a crew that finishes work while the
//! upstreams are quiet has to be able to wake it. [`Returns::arm`] is that arm, spelled exactly as
//! [`conduit::arm`](crate::conduit::arm), [`arm`](crate::arm) and [`ShutdownSignal::arm`](crate::ShutdownSignal::arm)
//! are, so the four sit in one slice and one [`select`](crate::select) waits on all of them.
//!
//! What the arm answers is that SOMETHING LANDED, and it takes NOTHING: what landed is still on the
//! line, and [`harvest`](Crew::harvest) is what hands it out. That is what keeps one order, and the
//! reason is worth writing down because it is the whole design. A wait that TOOK would make the body
//! a second reader of one queue — a bounded channel may hand an item straight to a reader that is
//! waiting inside it rather than put the item in the queue, so what the wait took could be NEWER
//! than what the queue was still holding, and the two doors would hand one bench's stream back out
//! of order. A probe registers nothing that can be handed anything. One reader, one order.
//!
//! In the inline form the arm never fires, because nothing ever travels that line. It does not
//! answer *closed* either — a closed arm re-offered every turn is a busy loop rather than a wait —
//! so a body may hold it open for the crew's whole life and pay nothing for it.
//!
//! # THE LIFECYCLE, and [`Drop`] is the backstop rather than the plan
//!
//! [`Crew::close`] is the epilogue: the in-queues are closed, the workers drain the session tails
//! they were holding, the return line is drained to its end, the threads are joined, and what came
//! out last is handed back. [`Drop`] does the same thing and is idempotent, which is what makes a
//! PANIC-unwind terminate: closing the in-queues is what wakes a worker parked on a receive, so
//! **close before you join** — in the epilogue and in the drop alike — and the join has something to
//! join rather than a queue nobody will ever fill.
//!
//! # Examples
//!
//! The whole shape at once: an [`AutonomousOperator`](crate::AutonomousOperator) whose prologue
//! builds a crew out of its own parts, whose loop selects over an upstream edge, the crew's return
//! line and the stop, and whose epilogue drains the crew. It is driven TWICE — once with one worker
//! and once with four — and the assertion is that the per-key sequences agree.
//!
//! ```
//! use core::{num::NonZeroUsize, pin::pin, time::Duration};
//! use std::collections::BTreeMap;
//!
//! use ingraph::{Context,
//!   Arm, AutonomousOperator, Delivery, Downstream, Fin, Item, ItemId, Payload, ShutdownSignal, Upstreams,
//!   Wake, ack_channel, arm, channel, park_on, select,
//!   shard::{Bench, Crew, CrewOptions, HashRouter},
//!   shutdown_signal,
//! };
//!
//! /// THE NODE'S OWN COMPUTE, one instance per worker. What it remembers between tasks is its
//! /// session table, and no other worker can see it — which is the whole reason work is routed by
//! /// key rather than handed to whoever is free.
//! struct Frames {
//!   seen: u64,
//! }
//!
//! impl Bench for Frames {
//!   type Task = (u64, u64);
//!   type Yield = (u64, u64);
//!
//!   fn work(&mut self, (track, frame): (u64, u64)) -> impl IntoIterator<Item = (u64, u64)> {
//!     self.seen += 1;
//!     [(track, frame)]
//!   }
//! }
//!
//! /// THE NODE. Its own options embed the crew's, which is where a deployment says how wide it is.
//! struct Decode {
//!   crew: CrewOptions,
//! }
//!
//! impl AutonomousOperator for Decode {
//!   type In = (u64, u64);
//!   type Out = (u64, u64);
//!   type Error = std::io::Error;
//!
//!   fn run(
//!     self,
//!     ctx: Context,
//!     upstreams: Upstreams<Self::In>,
//!     downstream: Downstream<Self::Out>,
//!   ) -> Result<Fin, Self::Error> {
//!     // THE PROLOGUE: `self`'s parts become the crew. One worker or four — this line is the same.
//!     let crew = Crew::spawn(self.crew, HashRouter::new(), |_| Frames { seen: 0 })?;
//!     let Some(edge) = upstreams.edge(0) else {
//!       return Ok(Fin::Spent);
//!     };
//!
//!     // What the loop waits FOR, so that three channels of three types answer exactly one.
//!     enum Turn {
//!       Fed(Wake<ItemId, (u64, u64)>),
//!       Worked,
//!       Halt,
//!     }
//!
//!     let mut seq = 0;
//!     let mut turn = 0;
//!     let mut feeding = true;
//!     let fin = loop {
//!       {
//!         // THE ARMS: a framework edge, the crew's return line and the stop, in ONE select.
//!         let mut fed = pin!(arm(feeding, edge, Turn::Fed));
//!         let mut worked = pin!(crew.returns().arm(true, || Turn::Worked));
//!         let mut halting = pin!(ctx.shutdown().arm(true, || Turn::Halt));
//!         let mut arms: [Arm<'_, Option<Turn>>; 3] =
//!           [fed.as_mut(), worked.as_mut(), halting.as_mut()];
//!
//!         match park_on(select(turn, &mut arms), Duration::from_millis(20)) {
//!           // The sweep, or every arm closed: look at the crew anyway.
//!           None | Some(None) => {}
//!           Some(Some((index, heard))) => {
//!             // Past the winner, so a busy arm cannot starve a quiet one.
//!             turn = index + 1;
//!             match heard {
//!               // This edge has ended. The crew may still be holding work, so the loop does not
//!               // end here — the epilogue is what drains it.
//!               None => feeding = false,
//!               Some(Turn::Fed(Wake::Delivered(delivery))) => {
//!                 let (payload, custody) = delivery.into_parts();
//!                 let released = payload.keys().copied().collect();
//!                 for item in payload {
//!                   let (track, frame) = item.into_value();
//!                   // ROUTE BY KEY: one track always reaches the same bench.
//!                   crew
//!                     .route(&track, (track, frame))
//!                     .map_err(std::io::Error::other)?;
//!                 }
//!                 // The books, kept by the node: released when THIS body says so.
//!                 if let Some(custody) = custody {
//!                   custody.send(ingraph::Ack::new(
//!                     released,
//!                     "decode",
//!                     ingraph::Lifecycle::Processed(()),
//!                   ));
//!                 }
//!               }
//!               Some(Turn::Fed(Wake::Sweep | Wake::Tick(_))) => {}
//!               // The crew spoke. What it said is already in the harvest queue.
//!               Some(Turn::Worked) => {}
//!               Some(Turn::Halt) => break Fin::Stopped,
//!             }
//!           }
//!         }
//!       }
//!
//!       // THE WORK OUT, every pass and from ONE door.
//!       for done in crew.harvest() {
//!         let (ack, _answers) = ack_channel();
//!         if let Some(out) = downstream.edges().first() {
//!           let _ = out.deliver(Delivery::new(
//!             Payload::One(Item::new(ItemId::new(seq), done)),
//!             ack,
//!           ));
//!         }
//!         seq += 1;
//!       }
//!
//!       if !feeding {
//!         break Fin::Spent;
//!       }
//!     };
//!
//!     // THE EPILOGUE: close the in-queues, let the crew drain its tails, join, then answer.
//!     for done in crew.close() {
//!       let (ack, _answers) = ack_channel();
//!       if let Some(out) = downstream.edges().first() {
//!         let _ = out.deliver(Delivery::new(
//!           Payload::One(Item::new(ItemId::new(seq), done)),
//!           ack,
//!         ));
//!       }
//!       seq += 1;
//!     }
//!     Ok(fin)
//!   }
//! }
//!
//! /// Drive the SAME body at a given width, and read back what came out per track.
//! fn drive(workers: usize) -> BTreeMap<u64, Vec<u64>> {
//!   let (feed, from_feed) = channel::<ItemId, (u64, u64)>(32);
//!   let (out, from_out) = channel::<ItemId, (u64, u64)>(256);
//!   let (stopper, halt) = shutdown_signal();
//!
//!   for (index, task) in [(7, 0), (9, 0), (7, 1), (9, 1), (7, 2), (9, 2)].into_iter().enumerate() {
//!     let (ack, _answers) = ack_channel();
//!     let given = feed.deliver(Delivery::new(
//!       Payload::One(Item::new(ItemId::new(index as u64), task)),
//!       ack,
//!     ));
//!     assert!(given.is_ok(), "the edge holds thirty-two and nothing has read it yet");
//!   }
//!   // The upstream is spent once the queue drains, which is what ends the loop.
//!   drop(feed);
//!
//!   let mut downstream = Downstream::new();
//!   downstream.attach(out);
//!   let node = Decode {
//!     crew: CrewOptions::new().with_workers(NonZeroUsize::new(workers).expect("not zero")),
//!   };
//!   let fin = node
//!     .run(
//!       Context::new("decode").halting(halt),
//!       Upstreams::from_iter([from_feed]),
//!       downstream,
//!     )
//!     .expect("the body does not die");
//!   assert_eq!(fin, Fin::Spent);
//!   // Held until here: letting go of a `Stopper` SAYS the stop.
//!   drop(stopper);
//!
//!   let mut per_track: BTreeMap<u64, Vec<u64>> = BTreeMap::new();
//!   for wake in from_out.drain() {
//!     if let Wake::Delivered(delivery) = wake {
//!       for item in delivery.into_parts().0 {
//!         let (track, frame) = item.into_value();
//!         per_track.entry(track).or_default().push(frame);
//!       }
//!     }
//!   }
//!   per_track
//! }
//!
//! // ONE worker is the inline form and four is the pool; the per-key sequences are the same.
//! assert_eq!(drive(1), BTreeMap::from([(7, vec![0, 1, 2]), (9, vec![0, 1, 2])]));
//! assert_eq!(drive(1), drive(4));
//! ```

use core::{
  cell::{RefCell, RefMut},
  hash::BuildHasher,
  num::NonZeroUsize,
  time::Duration,
};

use std::{collections::VecDeque, hash::RandomState, thread::JoinHandle};

use crate::conduit::{self, Taken, Unsent, park_on};

#[cfg(test)]
mod tests;

/// HOW MANY WORKERS A CREW HAS by default: ONE, which is the inline form and no thread at all.
///
/// A number and not a probe. [`available_parallelism`](std::thread::available_parallelism) is the
/// right answer for a decoder and the wrong one for a device whose default has to be the same on
/// every machine: a [`Default`] that read the host would make one options value mean two things in
/// two deployments, and a serialised one a record of a machine rather than of a decision. A body
/// that wants one worker per core reads the machine itself and says the number.
pub const DEFAULT_WORKERS: NonZeroUsize = NonZeroUsize::new(1).expect("1 is not zero");

/// HOW DEEP ONE WORKER'S IN-QUEUE IS by default.
///
/// Enough that a worker is never idle between two routes, small enough that what a full crew holds
/// is [`workers`](CrewOptions::workers) times this and no more — which is the number a deployment
/// budgets memory against.
pub const DEFAULT_QUEUE_DEPTH: NonZeroUsize = NonZeroUsize::new(16).expect("16 is not zero");

/// HOW DEEP THE SHARED RETURN LINE IS by default.
///
/// Wider than an in-queue on purpose: one task can yield many results — a demux frame becomes a
/// packet run — and a worker that had to park in the middle of one would hold its bench across the
/// pause. A body that harvests every pass never fills this.
pub const DEFAULT_RETURN_DEPTH: NonZeroUsize = NonZeroUsize::new(64).expect("64 is not zero");

/// WHAT A CREW'S THREADS ARE CALLED by default — each worker is `shard-<index>`.
pub const DEFAULT_LABEL: &str = "shard";

/// How long [`Crew::route`] watches the return line before looking at a full in-queue again — see
/// that method's note on why the watch is on the RETURN line and why it expires.
const BACKPRESSURE_SWEEP: Duration = Duration::from_millis(1);

/// THE CREW'S SEATS: how wide it is, and how much each of its two queues holds.
///
/// One value rather than three arguments, for [`StreamOptions`](crate::StreamOptions)' reason one
/// layer over: the set will grow, and a constructor that took each seat as an argument would break
/// at every one. A node's OWN options embed one of these — a deployment tunes the node, and the
/// crew's seats are part of what a node is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CrewOptions {
  workers: NonZeroUsize,
  queue_depth: NonZeroUsize,
  return_depth: NonZeroUsize,
  label: &'static str,
}

impl CrewOptions {
  /// THE SHIPPED SEATS: [`DEFAULT_WORKERS`], [`DEFAULT_QUEUE_DEPTH`], [`DEFAULT_RETURN_DEPTH`] and
  /// [`DEFAULT_LABEL`].
  ///
  /// `const`, and every seat is a constant rather than a reading of the host — see
  /// [`DEFAULT_WORKERS`] for why a device's default may not be machine-dependent.
  #[inline]
  #[must_use]
  pub const fn new() -> Self {
    Self {
      workers: DEFAULT_WORKERS,
      queue_depth: DEFAULT_QUEUE_DEPTH,
      return_depth: DEFAULT_RETURN_DEPTH,
      label: DEFAULT_LABEL,
    }
  }

  /// How many workers the crew has. ONE is the inline form.
  #[inline]
  #[must_use]
  pub const fn workers(&self) -> NonZeroUsize {
    self.workers
  }

  /// Run `workers` benches.
  #[inline]
  #[must_use]
  pub const fn with_workers(mut self, workers: NonZeroUsize) -> Self {
    self.workers = workers;
    self
  }

  /// [`with_workers`](Self::with_workers), in place.
  #[inline]
  pub const fn set_workers(&mut self, workers: NonZeroUsize) -> &mut Self {
    self.workers = workers;
    self
  }

  /// How many tasks ONE worker's in-queue holds before [`Crew::route`] waits.
  #[inline]
  #[must_use]
  pub const fn queue_depth(&self) -> NonZeroUsize {
    self.queue_depth
  }

  /// Hold `depth` tasks per worker.
  #[inline]
  #[must_use]
  pub const fn with_queue_depth(mut self, depth: NonZeroUsize) -> Self {
    self.queue_depth = depth;
    self
  }

  /// [`with_queue_depth`](Self::with_queue_depth), in place.
  #[inline]
  pub const fn set_queue_depth(&mut self, depth: NonZeroUsize) -> &mut Self {
    self.queue_depth = depth;
    self
  }

  /// How many results the SHARED return line holds before a worker waits.
  ///
  /// NON-ZERO where [`conduit::bounded`] would take a zero, and the refusal is in the type on
  /// purpose: a rendezvous return line completes a send only while a reader is parked inside a
  /// receive, and this line's reader takes from it WITHOUT parking. Zero would therefore be a
  /// deadlock wearing a bound's clothes rather than the strongest bound.
  #[inline]
  #[must_use]
  pub const fn return_depth(&self) -> NonZeroUsize {
    self.return_depth
  }

  /// Hold `depth` results on the return line.
  #[inline]
  #[must_use]
  pub const fn with_return_depth(mut self, depth: NonZeroUsize) -> Self {
    self.return_depth = depth;
    self
  }

  /// [`with_return_depth`](Self::with_return_depth), in place.
  #[inline]
  pub const fn set_return_depth(&mut self, depth: NonZeroUsize) -> &mut Self {
    self.return_depth = depth;
    self
  }

  /// What this crew's threads are called — each worker is `<label>-<index>`.
  #[inline]
  #[must_use]
  pub const fn label(&self) -> &'static str {
    self.label
  }

  /// Name this crew's threads `<label>-<index>`.
  ///
  /// Worth setting where a node holds MORE THAN ONE crew: a stack trace or a profile that names
  /// `resample-0` beside `decode-0` is the difference between reading one and guessing.
  #[inline]
  #[must_use]
  pub const fn with_label(mut self, label: &'static str) -> Self {
    self.label = label;
    self
  }

  /// [`with_label`](Self::with_label), in place.
  #[inline]
  pub const fn set_label(&mut self, label: &'static str) -> &mut Self {
    self.label = label;
    self
  }
}

impl Default for CrewOptions {
  #[inline]
  fn default() -> Self {
    Self::new()
  }
}

/// WHICH WORKER A KEY BELONGS TO — a PURE function from a key to a number.
///
/// # Purity is the contract, and it is what the device rests on
///
/// The same key must answer the same number every time, for this router's whole life. That is not a
/// quality bar: a crew's promise is that one key's tasks all reach one bench, and a bench's state is
/// only correct because nothing else ever touches it. A router that answered differently on the
/// second call would split a session across two benches, and the halves would both be wrong.
///
/// It answers a `u64` rather than a worker INDEX, so a router knows nothing about how wide the crew
/// it serves is: [`Crew::route`] folds the answer over its own width. A rule written for eight
/// workers therefore keeps working at four.
///
/// # It is a SEAM, and [`HashRouter`] is only what is shipped
///
/// A key that is already a number routes by arithmetic; a key with a natural affinity — a track that
/// should share a bench with its own audio — routes by a table. Both are ordinary impls of this
/// trait, and neither is a special case of the shipped one.
pub trait Router<K: ?Sized> {
  /// This key's number. The same key, the same answer — see the trait's own note.
  fn route(&self, key: &K) -> u64;
}

/// THE SHIPPED ROUTER: the key's hash, under a [`BuildHasher`] of the caller's choosing.
///
/// # Why the hasher is a parameter
///
/// [`RandomState`] seeds itself per instance, so this router's answers are stable for its own life
/// and for nothing longer. That is exactly right for a crew — one crew, one router, one life — and
/// exactly wrong for anything that has to agree with a decision made in another process. A caller
/// who needs that supplies a fixed-seed hasher through [`with_hasher`](Self::with_hasher), and the
/// seat is here so that they never have to write the rest of this type to get it.
///
/// The default is `std`'s own rather than a faster third-party one, which is this crate's census
/// answering: nothing in `ingraph` depends on a hasher today, and the one place a stable hash IS
/// required — [`OrderSignature`](crate::query) over a cursor that outlives its process — writes its
/// own FNV-1a for that reason. A router's answer outlives nothing, so it may take the standard
/// library's and add no dependency to anyone.
#[derive(Debug, Clone, Default)]
pub struct HashRouter<S = RandomState> {
  hasher: S,
}

impl HashRouter {
  /// A router over [`RandomState`] — the shipped default.
  #[inline]
  #[must_use]
  pub fn new() -> Self {
    Self {
      hasher: RandomState::new(),
    }
  }
}

impl<S> HashRouter<S> {
  /// A router over `hasher`, for a caller who needs the answers to be reproducible beyond this
  /// value's own life — see the type's note.
  #[inline]
  #[must_use]
  pub const fn with_hasher(hasher: S) -> Self {
    Self { hasher }
  }
}

impl<K, S> Router<K> for HashRouter<S>
where
  K: core::hash::Hash + ?Sized,
  S: BuildHasher,
{
  #[inline]
  fn route(&self, key: &K) -> u64 {
    self.hasher.hash_one(key)
  }
}

/// WHAT ONE WORKER DOES, and what the node writes.
///
/// A bench is the compute the crew exists to arrange: a decoder holding a track's state, a resampler
/// holding a filter's history, an embedder holding a warm model. ONE INSTANCE PER WORKER, built by
/// the factory [`Crew::spawn`] is handed, and no other worker can reach it — which is what makes
/// whatever it remembers between tasks a session table rather than a race.
///
/// # It is deliberately not a lifecycle
///
/// There is no *start*, no *flush* and no *end* here, because a task vocabulary already carries all
/// three: a body whose stream has an end sends the end AS A TASK, and the bench answers it with
/// whatever the end produces. Putting the phases in the device would be this module choosing a
/// session model for every node that ever uses it, and the one thing it is not allowed to know is
/// what the work means.
///
/// # `work` may yield NOTHING, ONE, or MANY
///
/// A decoder given a partial packet yields nothing; given a flush it may yield a hundred. The
/// results are put on the return line AS THEY COME rather than after the last one, so a long task's
/// first result reaches the loop while the rest are still being made — and a full return line parks
/// the worker mid-task, which is the backpressure a bounded line is for.
pub trait Bench {
  /// What the node routes IN — one unit of work, whatever the node's own vocabulary calls one.
  type Task;
  /// What comes back OUT. Nothing here is per-task: a body reads its results as a stream and the
  /// task they came from is whatever the yield itself says.
  type Yield;

  /// Do one task, yielding whatever it produced.
  ///
  /// `&mut self` and never `&self`: the state a bench holds between tasks is the reason it exists,
  /// and exclusivity is what makes that state safe without a lock. Nothing else can call this while
  /// one call is running, because nothing else holds this bench at all.
  fn work(&mut self, task: Self::Task) -> impl IntoIterator<Item = Self::Yield>;
}

/// WHICH FORM A CREW TOOK — one bench here, or N benches on N threads.
///
/// Private, and it is the whole of the difference between the two: every public call folds over this
/// and the surface above it is one shape.
enum Form<B: Bench> {
  /// ONE bench, no thread. Behind a [`RefCell`] because [`Crew::route`] takes `&self` — the arms a
  /// body pins over its crew borrow it for the length of a select, and a `&mut` route would fight
  /// them for no gain.
  Inline(RefCell<B>),
  /// N workers: one in-queue apiece, and the handle that joins each.
  ///
  /// `lanes` is emptied FIRST at wind-down and `hands` joined after, which is the close-before-join
  /// order the whole module rests on.
  Pool {
    lanes: Vec<conduit::Sender<B::Task>>,
    hands: Vec<JoinHandle<()>>,
  },
}

/// THE DEVICE: N resident benches behind a key router, with one line back.
///
/// Built in a body's prologue, held for the body's life, and closed in its epilogue. See the
/// [module's own note](self) for the division it is written under and for the loop it is spent in.
pub struct Crew<B: Bench, R> {
  router: R,
  workers: NonZeroUsize,
  form: Form<B>,
  /// The device's OWN hold on the return line, in the inline form only.
  ///
  /// It exists so that [`Returns::arm`] parks instead of answering *closed* on a line no worker will
  /// ever speak on. In the pool form this is `None` and the only senders are the workers, so the
  /// line ends exactly when the last of them does — which is what
  /// [`wind_down`](Self::wind_down)'s drain reads as *everybody is finished*.
  keeper: Option<conduit::Sender<B::Yield>>,
  /// WHAT HAS BEEN TAKEN OFF THE LINE AND NOT YET HANDED OUT.
  ///
  /// A [`RefCell`] and not a lock, and the difference is the whole of this device's ordering
  /// claim. Everything here arrived through [`absorb`](Crew::absorb) — one whole drain of the line,
  /// in the line's own order, on the body's own thread — or, in the inline form, straight off a
  /// bench that ran on that same thread. Nothing else can reach it, because nothing else HOLDS it:
  /// a `&mut` out of the cell is the only way in, and [`Crew`] is not [`Sync`].
  ///
  /// So *everything staged is older than everything still on the line* is not an invariant somebody
  /// keeps. It is what the two writers do and the only thing they can do — see
  /// [`harvest`](Crew::harvest), which reads this first for exactly that reason.
  staged: RefCell<VecDeque<B::Yield>>,
  returns: Returns<B::Yield>,
}

impl<B: Bench, R> Crew<B, R> {
  /// BUILD THE CREW — the prologue, and the only constructor.
  ///
  /// `factory` is called once per worker with that worker's index, and what it answers is that
  /// worker's own bench. The index is there for the cases that need one — a per-worker seed, a
  /// device ordinal — and is ignored by everything else.
  ///
  /// [`workers`](CrewOptions::workers) picks the form: one takes the INLINE form and spawns no
  /// thread at all, two or more take the POOL form. Nothing else about the call differs.
  ///
  /// # Errors
  ///
  /// Whatever [`Builder::spawn`](std::thread::Builder::spawn) refuses with — the operating system
  /// declining a thread. A partly-built crew is wound down before the refusal is returned, so a
  /// failure at worker three leaves no workers one and two behind it.
  ///
  /// The inline form cannot fail, and answers a `Result` regardless: a constructor whose shape
  /// changed with a number is a constructor a body could not write once.
  pub fn spawn<F>(options: CrewOptions, router: R, mut factory: F) -> std::io::Result<Self>
  where
    B: Send + 'static,
    B::Task: Send + 'static,
    B::Yield: Send + 'static,
    F: FnMut(usize) -> B,
  {
    let (giving, line) = conduit::bounded::<B::Yield>(options.return_depth().get());
    let workers = options.workers();

    if workers.get() == 1 {
      return Ok(Self {
        router,
        workers,
        form: Form::Inline(RefCell::new(factory(0))),
        // HELD FOR LIFE: the inline form never speaks on this line, and a line with no sender at
        // all would make the arm answer *closed* on every turn instead of parking.
        keeper: Some(giving),
        staged: RefCell::new(VecDeque::new()),
        returns: Returns::over(line),
      });
    }

    let mut crew = Self {
      router,
      workers,
      form: Form::Pool {
        lanes: Vec::with_capacity(workers.get()),
        hands: Vec::with_capacity(workers.get()),
      },
      // Held only while the loop below runs, and held HERE rather than in a local of this function:
      // a refusal midway drops `crew` and nothing else, so the one sender that could keep the drain
      // in `wind_down` from ever ending has to be inside the thing that drops.
      keeper: Some(giving),
      staged: RefCell::new(VecDeque::new()),
      returns: Returns::over(line),
    };

    for index in 0..workers.get() {
      let (giving_tasks, taking_tasks) = conduit::bounded::<B::Task>(options.queue_depth().get());
      let mut bench = factory(index);
      let giving = crew
        .keeper
        .as_ref()
        .expect("the keeper is held until this loop ends")
        .clone();
      // `?` here drops `crew`, and its `Drop` closes the lanes already opened, lets go of the keeper
      // above and joins the workers already spawned — the same wind-down the epilogue runs.
      let hand = std::thread::Builder::new()
        .name(format!("{}-{index}", options.label()))
        .spawn(move || {
          while let Some(task) = taking_tasks.recv() {
            for made in bench.work(task) {
              // The results go out AS THEY COME, so a full line parks the worker mid-task. `Err`
              // is nobody left to take them, and there is nothing to do with the rest.
              if giving.send(made).is_err() {
                return;
              }
            }
          }
        })?;
      let Form::Pool { lanes, hands } = &mut crew.form else {
        unreachable!("the pool form is what this branch built");
      };
      lanes.push(giving_tasks);
      hands.push(hand);
    }

    // The workers are the only senders from here on, which is what lets the wind-down read the end
    // of the line as *every worker is finished*.
    crew.keeper = None;
    Ok(crew)
  }

  /// GIVE THE CREW A TASK, for the worker `key` belongs to.
  ///
  /// The same key reaches the same bench for this crew's whole life, which is the promise the whole
  /// device is for. Which bench that is is [`Router`]'s answer folded over the crew's width, so a
  /// rule written once serves a crew of any size.
  ///
  /// # It WAITS, and what it waits on is not what a reader would guess
  ///
  /// A full in-queue makes this call wait, which is the backpressure a bounded queue is for: a body
  /// that could route faster than its benches can work would otherwise put the difference in memory.
  ///
  /// The wait is spent ON THE RETURN LINE rather than on the in-queue, and that is what keeps the
  /// two bounds from meeting in a deadlock. A worker parked on a FULL return line is not reading its
  /// in-queue; a caller parked on that full in-queue is not reading the return line; and each is
  /// waiting for the other. So this call takes what the line is holding before it looks at the queue
  /// again — a worker that gets to speak gets back to its queue — and the results it takes are
  /// staged, where [`harvest`](Self::harvest) will hand them out in order. The wait EXPIRES because
  /// there is a second case with no return traffic in it at all: a bench that yields nothing frees
  /// its in-queue by consuming it, and nothing would ever wake a reader waiting on a line that stays
  /// silent.
  ///
  /// What it WAITS with is a probe — [`readable_async`](conduit::Receiver::readable_async) — and
  /// never a receive, which is not a detail. This call runs while the body's own arms are still
  /// pinned over the same line, so a wait that made this a second reader of the queue would let a
  /// sender hand ITS item here while an older one was still queued behind the arm — and the two
  /// doors would deliver one bench's stream out of order. The probe takes nothing, so everything
  /// that reaches the staging reaches it through the drain below, in the line's own order.
  ///
  /// # In the INLINE form the work happens HERE, and that is not an optimisation
  ///
  /// With one bench there is no queue to put anything in, so the bench is run on this thread and
  /// what it makes is staged where [`harvest`](Self::harvest) hands it out. The alternative —
  /// pushing the results through the same bounded return line the pool form uses — cannot work at
  /// all in this form: the only reader of that line is the thread now inside this call, so a task
  /// that yielded more than the line's free room would park forever on its own results. The uniform
  /// surface is therefore [`harvest`](Self::harvest) rather than the line, and the line's uniformity
  /// is what had to give.
  ///
  /// The router is not consulted in this form: with one bench there is no choice to make, and a pure
  /// router's answer has nothing to show for having been asked.
  ///
  /// # Errors
  ///
  /// [`Unsent`], carrying the task back, where the worker that key belongs to is GONE — a bench that
  /// panicked, or a crew already wound down. It is [`conduit::Sender::send`]'s own refusal and reads
  /// the same way: waiting for room is what this call does, so the only way it refuses is that
  /// nobody is there at all. The task comes back because a refused task is not a loss until the body
  /// decides it is.
  pub fn route<K>(&self, key: &K, task: B::Task) -> Result<(), Unsent<B::Task>>
  where
    K: ?Sized,
    R: Router<K>,
  {
    let lanes = match &self.form {
      Form::Inline(bench) => {
        let mut bench = bench.borrow_mut();
        let made = bench.work(task);
        self.staged().extend(made);
        return Ok(());
      }
      Form::Pool { lanes, .. } => lanes,
    };

    let slot = (self.router.route(key) % self.workers.get() as u64) as usize;
    let Some(lane) = lanes.get(slot) else {
      // Unreachable: the fold above is over this crew's own width, and `lanes` is that wide.
      return Err(Unsent::of(task));
    };

    let mut task = match lane.try_send(task) {
      Ok(()) => return Ok(()),
      Err(refused) => refused.into_inner(),
    };
    loop {
      if lane.is_disconnected() {
        return Err(Unsent::of(task));
      }
      // See the note above: taking what the line holds is what frees a worker that cannot read its
      // own queue, and the expiry is for the bench that yields nothing at all.
      self.absorb();
      match lane.try_send(task) {
        Ok(()) => return Ok(()),
        Err(refused) => task = refused.into_inner(),
      }
      // WATCH, never take. What lands here is taken by the drain at the top of the next turn, in
      // the line's own order and by the only reader this line has.
      park_on(self.returns.line().readable_async(), BACKPRESSURE_SWEEP);
    }
  }

  /// TAKE EVERYTHING THE LINE IS HOLDING onto the staging, WITHOUT waiting — what frees a worker
  /// parked on a full line.
  ///
  /// A WHOLE drain and never a single take, which is what makes the staging's order the line's:
  /// this walks the line to its end in one pass, on the one thread that reads it, so what it appends
  /// is a run of the line's own front.
  fn absorb(&self) {
    let mut staged = self.staged();
    while let Taken::Item(made) = self.returns.line().try_recv() {
      staged.push_back(made);
    }
  }

  /// The staging, exclusively.
  ///
  /// [`borrow_mut`](RefCell::borrow_mut) rather than a lock, and it cannot fail: every caller takes
  /// it, appends or pops, and lets go inside its own statement — [`Harvest`] takes it per step for
  /// that reason, so a body may route from inside its own harvest walk.
  #[inline]
  fn staged(&self) -> RefMut<'_, VecDeque<B::Yield>> {
    self.staged.borrow_mut()
  }

  /// EVERYTHING THE CREW HAS FINISHED, oldest first — the ONE door results come out of.
  ///
  /// It never waits: what is ready is ready, and a body calls this once per pass. Both forms answer
  /// it the same way, which is what makes the two substitutable — see [`route`](Self::route) for why
  /// the inline form's results arrive here rather than on the line.
  ///
  /// The order is the crew's own: one key's results are in the order its bench made them, always,
  /// because one key has one bench and a bench works one task at a time. Across keys there is no
  /// order to promise and none is made — two benches run at once, and which of them speaks first is
  /// what *at once* means.
  ///
  /// What makes the *always* true is that the line has exactly ONE reader. Everything staged got
  /// there by [`absorb`](Self::absorb) walking the line to its end on this thread, so the staging is
  /// a prefix of the line and reading it first is reading the line from the front. Nothing else ever
  /// takes from the line — the arm over it WATCHES — so no item can reach a body by a door the rest
  /// of the line did not pass through first.
  #[inline]
  pub fn harvest(&self) -> Harvest<'_, B::Yield> {
    Harvest {
      staged: &self.staged,
      line: self.returns.line(),
    }
  }

  /// THE RETURN LINE, for a body that wants to be WOKEN when the crew speaks.
  ///
  /// [`Returns::arm`] is the arm; the items still come out of [`harvest`](Self::harvest).
  #[inline]
  #[must_use]
  pub const fn returns(&self) -> &Returns<B::Yield> {
    &self.returns
  }

  /// HOW MANY RESULTS ARE WAITING to be harvested.
  ///
  /// A body that harvests every pass sees a small number or zero. A number that only grows is a
  /// body that is routing without harvesting, and this is what says so.
  #[inline]
  #[must_use]
  pub fn pending(&self) -> usize {
    self.staged.borrow().len() + self.returns.line().len()
  }

  /// How wide this crew is.
  #[inline]
  #[must_use]
  pub const fn workers(&self) -> NonZeroUsize {
    self.workers
  }

  /// Whether this crew is the INLINE form — one bench, no thread.
  #[inline]
  #[must_use]
  pub const fn is_inline(&self) -> bool {
    matches!(self.form, Form::Inline(_))
  }

  /// CLOSE THE CREW — the epilogue, and what it answers is the tail.
  ///
  /// Close the in-queues, let the workers finish the tasks they were already holding, drain the
  /// return line to its end, join the threads, and hand back everything that had not been harvested
  /// yet. It is the orderly wind-down; [`Drop`] is the same thing for the path that does not reach
  /// here.
  ///
  /// Nothing is lost: a task already in a queue is worked before the queue reports its end, and the
  /// results of it come back before the line reports its own. What bounds the call is therefore the
  /// benches' own bound: a [`work`](Bench::work) that returns is a crew that closes, and one that
  /// never returns is a body waiting on itself.
  ///
  /// `impl Iterator` rather than the queue behind it, for [`conduit::Receiver::drain`]'s reason: how
  /// a tail is held on the way out is an implementation choice, and a signature naming it would make
  /// the choice part of the surface.
  #[must_use = "the tail is the last of the crew's work — dropping it drops results"]
  pub fn close(mut self) -> impl Iterator<Item = B::Yield> {
    self.wind_down().into_iter()
  }

  /// CLOSE, DRAIN, JOIN — in that order, and idempotently.
  ///
  /// The order is the invariant the whole module rests on. Dropping the in-queue senders is what
  /// tells a worker parked on a receive that its stream is over; draining the return line is what
  /// frees a worker parked on a send; and only a worker that is free can be joined. A join placed
  /// before either would wait on a thread that is waiting on this one.
  ///
  /// Called by [`close`](Self::close) and by [`Drop`], and safe to call twice: the second call finds
  /// no lanes, no keeper and a line that has already ended.
  fn wind_down(&mut self) -> VecDeque<B::Yield> {
    // CLOSE. The lanes go first, and the keeper with them — a line whose last sender is this crew
    // would never report an end for the drain below to stop at.
    if let Form::Pool { lanes, .. } = &mut self.form {
      lanes.clear();
    }
    drop(self.keeper.take());

    // DRAIN, to the end of the line. In the pool form the workers are the only senders left, so the
    // end IS the last worker finishing — which is also what makes the join below immediate.
    //
    // WATCH-then-take, as every other reader of this line does: the probe answers `false` only once
    // every sender is gone and nothing is queued, which is the end this loop stops at.
    let mut tail = core::mem::take(self.staged.get_mut());
    loop {
      while let Taken::Item(made) = self.returns.line().try_recv() {
        tail.push_back(made);
      }
      if !self.returns.line().readable() {
        break;
      }
    }

    // JOIN. A worker that panicked is joined all the same and its panic is not re-raised here: this
    // runs on the unwind path too, and a panic inside a drop during an unwind aborts the process.
    if let Form::Pool { hands, .. } = &mut self.form {
      for hand in hands.drain(..) {
        drop(hand.join());
      }
    }
    tail
  }
}

/// THE BACKSTOP, and the reason a panic-unwind cannot deadlock.
///
/// [`wind_down`](Crew::wind_down) verbatim — close, drain, join — so a body that never reached its
/// epilogue winds its crew down anyway. What it drops that [`Crew::close`] hands back is the tail:
/// there is nobody left to give it to.
impl<B: Bench, R> Drop for Crew<B, R> {
  fn drop(&mut self) {
    drop(self.wind_down());
  }
}

impl<B: Bench, R> core::fmt::Debug for Crew<B, R> {
  /// The SHAPE and what is waiting — never the tasks or the results. `B`'s types are the author's
  /// own, and demanding a [`Debug`](core::fmt::Debug) of them would bound every bench for the
  /// benefit of this line, which is [`conduit::Sender`]'s own reason one layer down.
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("Crew")
      .field("workers", &self.workers)
      .field("inline", &self.is_inline())
      .field("pending", &self.pending())
      .finish_non_exhaustive()
  }
}

/// THE RETURN SIDE of a crew: the line the workers speak on, and nothing else.
///
/// ONE channel and no second half. What a body waits on and what a body reads are the same queue in
/// the same order, because the wait does not read: [`arm`](Self::arm) is a
/// [`readable`](conduit::Receiver::readable) probe that answers *the crew spoke* and takes nothing,
/// and [`Crew::harvest`] is the only door items come out of.
///
/// That division is the whole of this device's ordering claim. A wait that TOOK would make the body
/// a second reader of one queue, and a sender may hand its item straight to a waiting reader rather
/// than queue it — so an item taken by the wait could skip everything the queue was still holding.
/// One reader, one order, and the promise at [`Crew::harvest`] is true because there is no second
/// door for it to be false through.
pub struct Returns<Y> {
  line: conduit::Receiver<Y>,
}

impl<Y> Returns<Y> {
  /// The return side over `line`.
  #[inline]
  const fn over(line: conduit::Receiver<Y>) -> Self {
    Self { line }
  }

  /// ONE ARM of a [`select`](crate::select): wait for the crew to speak, and say so.
  ///
  /// [`conduit::arm`]'s shape exactly — `open`, a wrap, and `None` for the end — so this arm, an
  /// upstream edge's [`arm`](crate::arm) and [`ShutdownSignal::arm`](crate::ShutdownSignal::arm) sit in one slice and one
  /// select waits on all three.
  ///
  /// # It WATCHES, and that is what keeps one order
  ///
  /// It takes nothing at all. What landed is still on the line when this answers, and
  /// [`Crew::harvest`] is what hands it out; the caller gets its own word for *the crew spoke* and
  /// nothing more.
  ///
  /// A wait that took would be a SECOND READER of the line, and a body routes and harvests while
  /// this arm is still pinned over it. A bounded channel may hand an item straight to a waiting
  /// reader instead of queueing it, so the item this arm took could be newer than one the queue was
  /// still holding — and a per-key sequence delivered out of order is the one failure a keyed device
  /// may not have. A probe cannot be handed anything, so the line's order is the only order and no
  /// invariant has to be kept for it to hold.
  ///
  /// `None` is the line's END — every worker is gone and nothing is left on it. A caller marks the
  /// arm closed then, exactly as it would for any other channel that has finished.
  ///
  /// In the INLINE form this never fires and never ends: nothing travels that line, and a crew holds
  /// it open so that an arm offered every turn parks rather than spinning on a closed channel.
  ///
  /// An arm that is DROPPED mid-flight — the loser of a select — takes nothing and loses nothing,
  /// which is now true by shape rather than by the transport's promise: there was nothing in it.
  pub async fn arm<R>(&self, open: bool, wrap: impl FnOnce() -> R) -> Option<R> {
    if !open {
      // Never resolves — the caller has already decided this line is finished for its purposes.
      core::future::pending::<()>().await;
    }
    self.line.readable_async().await.then(wrap)
  }

  /// The line itself, for the crew's own drains.
  #[inline]
  const fn line(&self) -> &conduit::Receiver<Y> {
    &self.line
  }
}

impl<Y> core::fmt::Debug for Returns<Y> {
  /// WHAT IS ON THE LINE — never the results, for [`Crew`]'s own reason. It is the line's depth and
  /// not the crew's backlog: what a crew has staged is the crew's, and [`Crew::pending`] is what
  /// answers for both.
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("Returns")
      .field("queued", &self.line.len())
      .finish_non_exhaustive()
  }
}

/// WHAT THE CREW HAS FINISHED — [`Crew::harvest`]'s walk, oldest first.
///
/// It takes the STAGING first and the line after, which is the order the two hold: nothing reaches
/// the staging except by a whole drain of the line on this thread, so everything in it is a prefix
/// of the line and reading it first is reading the line from the front.
///
/// LAZY, and it never waits. Each step takes what is there; dropping the walk half-way leaves the
/// rest where it was, and the next call carries on from it.
#[must_use = "a harvest that is not walked hands nothing out"]
pub struct Harvest<'a, Y> {
  staged: &'a RefCell<VecDeque<Y>>,
  line: &'a conduit::Receiver<Y>,
}

impl<Y> Iterator for Harvest<'_, Y> {
  type Item = Y;

  fn next(&mut self) -> Option<Y> {
    // The borrow is taken and released per step rather than held across the walk, so a body may
    // route from inside its own harvest loop.
    if let Some(made) = self.staged.borrow_mut().pop_front() {
      return Some(made);
    }
    self.line.try_recv().into_item()
  }

  fn size_hint(&self) -> (usize, Option<usize>) {
    // A lower bound only: the workers may speak again while this walk is running.
    (self.staged.borrow().len() + self.line.len(), None)
  }
}

impl<Y> core::fmt::Debug for Harvest<'_, Y> {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("Harvest")
      .field("pending", &(self.staged.borrow().len() + self.line.len()))
      .finish_non_exhaustive()
  }
}