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
//! THE STREAM LANE: what DRIVES a [`StreamOperator`](crate::StreamOperator).
//!
//! [`resident`](super::resident) is the buffered driver — one `accept` per item, every emission held
//! in an [`Emitter`](crate::Emitter) until the call returns. This is the other one: a run spawned per
//! DELIVERY, streaming through a bounded [`Feed`](crate::Feed) for that delivery's whole life, with
//! the fed items projected into the downstream set as they arrive. The two are peers rather than a
//! ladder, exactly as the two faces they spend are.
//!
//! # The lane, step by step
//!
//! 1. **Admission.** [`StreamLane::admit`] takes one warm instance out of the node's set, and there
//!    are only as many of those as the node's [`in_flight`](StreamOptions::in_flight) seat allows. A
//!    delivery that finds none WAITS, and the wait is what bounds this node's demand on whatever
//!    executor its runs are placed on. The permit and the instance are ONE thing here rather than two
//!    counted separately — see [`StreamLane::width`].
//! 2. **The warm instance.** A body keeps whatever state it likes across deliveries — a decoder, an
//!    open handle, a scratch buffer — because the same value is handed back to the next delivery that
//!    gets it. How many there are and which one a delivery got is the LANE's property and is invisible
//!    to the face, which is what [`StreamOperator`](crate::StreamOperator)'s own residency note
//!    promises.
//! 3. **The run.** The blocking face is placed on the [`Spawn`] seam — the drive layer's own executor
//!    door, the one the `spawn` and `rayon` poll words already select through — because a blocking
//!    `run` is a call that has to be somewhere other than the loop draining it. The awaited face is
//!    NOT placed anywhere: its run is a future this lane polls, which is
//!    [`Drives`](super::Drives)' own law about the awaited body said at a second seam, and is what
//!    keeps a `!Send` body an ordinary citizen here.
//! 4. **The projection drain.** Fed items are taken and routed into the downstream set through the
//!    same [`Sink`] every node's outputs cross, pruned by the same [`Wanted`](super::Wanted) the buffered face reads.
//!    The line closes when the run returns, because the [`Feed`](crate::Feed) was taken by value.
//! 5. **The endings.** `Ok(`[`Fin::Spent`]`)` and `Ok(`[`Fin::Stopped`]`)` settle the delivery at the
//!    node's [`Effect`]; `Err` settles it [`Failed`](Lifecycle::Failed) with the error aboard, and
//!    nothing else about the node changes — see [`StreamLane::admit`].
//!
//! # It is not the write `lane`
//!
//! [`lane`](super::lane) is the WRITE arm's seam and this is a driver, and the two words collide only
//! in the ordinary sense that a pipeline has lanes. The names are kept because both are the words
//! their own designs were ruled in; nothing here implements [`AsyncLands`](super::AsyncLands) and
//! nothing there drives anything.
//!
//! # What MOUNTS one, and what is still not here
//!
//! `#[ingraph::operator(stream, …)]` is the word, [`Declared::Pair`](crate::Declared::Pair) is the
//! seat it states the fact at, and [`Wiring::lane`](super::Wiring::lane) is the walk that builds one
//! of these from it — the node's own name, the [`Effect`] its declaration states, the downstream set
//! its declared out-edges make, and the deployment's taps. A deployment no longer reaches this type
//! by building it.
//!
//! What is NOT here is the ENGINE. No ignition door runs the [`admit`](StreamLane::admit) /
//! [`tend`](StreamLane::tend) loop, so the party that holds a mounted lane is the party that drives
//! it — the same posture the launch floor keeps for every value whose type it cannot name.

use core::{future::Future, marker::PhantomData, num::NonZeroUsize, pin::Pin, task::Poll};

use std::sync::Arc;

use smol_bytes::Utf8Bytes;

use super::{
  Context, Effect, ItemId, NodeName, Spawn, Thread,
  downstream::Sink,
  feed::{FeedContext, FeedPolicy, Fixed, MemoryProbe, Unpressured},
  lifecycle::{Failure, Lifecycle, LifecycleTap, Taps},
  message::{Delivery, Item, ack_channel},
  window::{Outbound, Owed},
};
use crate::{
  Async, AsyncStreamOperator, Block, Fin, Skip, SkipReason, Stopper, StreamOperator, Yielded,
};

#[cfg(test)]
mod tests;

/// HOW MANY DELIVERIES ONE STREAM-FACED NODE HOLDS AT ONCE, by default: one.
///
/// The buffered face's own posture: a resident takes one delivery, finishes it, and takes the next.
/// A node that says nothing behaves that way here too, so widening the lane is a thing a deployment
/// ASKS for rather than a thing it inherits — and the cost of the ask is visible, because every extra
/// in-flight delivery is another warm instance and another feed's worth of memory.
pub const DEFAULT_IN_FLIGHT: NonZeroUsize = NonZeroUsize::new(1).expect("1 is not zero");

/// THE LABEL A REFUSED FAN-OUT WEARS — what a tap matches when a downstream set promised one output
/// two seats and its payload makes one copy of itself: none.
///
/// Published as a constant rather than spelled at the tap, for [`SkipLabel`](crate::SkipLabel)'s own
/// reason: a refusal an app cannot act on is a refusal it cannot fix, and matching a string literal
/// written twice is how the two spellings drift. It rides as a
/// [`Custom`](crate::SkipReason::Custom) reason because core's built-in vocabulary is the OPERATOR's
/// contract and this refusal is the LANE's — see [`StreamLane::undividable`].
pub const UNDIVIDABLE: &str = "undividable_output";

/// THE STREAMING ROW of the two-face table: what one delivery's life IS, at each of the two faces.
///
/// [`Driven`](crate::Driven)'s shape one seam over, and it exists for the same reason: the two faces
/// carry the same three associated types under different trait names, and a driver written twice over
/// those names is a driver written twice. [`Block`] selects [`StreamOperator`](crate::StreamOperator)
/// and [`Async`] selects [`AsyncStreamOperator`](crate::AsyncStreamOperator), so a
/// `StreamLane<…, Block>` and a `StreamLane<…, Async>` are two types and one trait with two impls is
/// ordinary — which is `E0592`'s answer, argued in full at [`Drives`](super::Drives).
///
/// # [`Run`](Self::Run) is where the two faces genuinely differ
///
/// A blocking run was handed to an executor and what the lane holds is the line it will answer on. An
/// awaited run was handed to nobody and what the lane holds is the run ITSELF, polled here. That is
/// one associated type rather than two drivers, and it is the only asymmetry between the two impls
/// below.
#[diagnostic::on_unimplemented(
  message = "`{Self}` is not a STREAMING unit in the `{M}` mode",
  label = "no `run` of this mode's shape",
  note = "a streaming unit implements exactly ONE of `StreamOperator` (the blocking face, mode \
          `Block`) and `AsyncStreamOperator` (the awaited face, mode `Async`), and implementing \
          either IS implementing this trait's row for it",
  note = "where a declaration is mounted, the mode is the one its own word selected and its \
          `Declared::Mode` states: `stream` alone asks for `Block` and `stream, async` asks for \
          `Async`, so a body whose face differs from its word is refused here",
  note = "if `{Self}` wears the BUFFERED pair instead, it is mounted through `Blueprint::node` and \
          `Wiring::resident` — this door is the streaming one, and the `stream` word is what sends \
          a declaration to it"
)]
pub trait Streams<M> {
  /// Whether THIS mode's `run` answers without a future.
  ///
  /// [`Driven::SYNC`](crate::Driven::SYNC) verbatim, one pair over, and it exists for that const's
  /// own reason: a graph root folds an `ALL_SYNC` over every mount it carries, and a streaming mount
  /// has no [`Driven`](crate::Driven) row to read one off. Set by the two blanket rows below and by
  /// nothing an author can write, so it PROVES rather than claims — a declaration cannot state a
  /// syncness its face does not have.
  const SYNC: bool;

  /// The message this unit consumes — [`StreamOperator::In`](crate::StreamOperator::In).
  type In;
  /// The message it streams out — [`StreamOperator::Out`](crate::StreamOperator::Out).
  type Out: 'static;
  /// Its per-delivery failure — [`StreamOperator::Error`](crate::StreamOperator::Error).
  type Error;
  /// One delivery's run, AS THE LANE HOLDS IT — see the trait note.
  type Run;
}

/// The BLOCKING row: a run placed on the [`Spawn`] seam, answering on a line of capacity one.
impl<O> Streams<Block> for O
where
  O: StreamOperator,
{
  const SYNC: bool = true;

  type In = <O as StreamOperator>::In;
  type Out = <O as StreamOperator>::Out;
  type Error = <O as StreamOperator>::Error;
  type Run = flume::Receiver<Ended<Self, Block>>;
}

/// The AWAITED row: the run itself, boxed so that lines of one node sit in one vector, and pinned
/// because a half-driven future cannot move.
///
/// No `Send` anywhere, which is the whole of what this face buys: the future is polled by whoever
/// drives the lane, on that party's own thread, so a `!Send` body — a decoder holding a device
/// context, an FFI session — is an ordinary citizen here.
impl<O> Streams<Async> for O
where
  O: AsyncStreamOperator,
{
  const SYNC: bool = false;

  type In = <O as AsyncStreamOperator>::In;
  type Out = <O as AsyncStreamOperator>::Out;
  type Error = <O as AsyncStreamOperator>::Error;
  type Run = Pin<Box<dyn Future<Output = (Self, Result<Fin, <O as AsyncStreamOperator>::Error>)>>>;
}

/// WHAT A RUN ANSWERED WITH: the instance back, and how its delivery ended.
///
/// The instance travels with the answer because the run OWNED it — a blocking run took it across a
/// spawn, an awaited one into a future — so returning it to the warm set and reading the ending are
/// one act rather than two.
pub type Ended<O, M> = (O, Result<Fin, <O as Streams<M>>::Error>);

/// ONE LINE'S PARK, as the lane holds it while it waits: a take that answers `None` where the feed
/// has hung up.
///
/// Boxed and pinned so that the parks of a node's lines sit in one vector, and owning its own end of
/// the line rather than borrowing the lane — see [`StreamLane`]'s own park.
type Park<O, M> = Pin<Box<dyn Future<Output = Option<<O as Streams<M>>::Out>>>>;

/// WHAT ONE STREAMED DELIVERY DID — the info its ack carries and a tap reads back.
///
/// [`Tally`](super::Tally)'s sibling and deliberately a different type: a buffered delivery is
/// counted in items its operator ACCEPTED, and a streamed one has exactly one input and a count of
/// what came out of it. Adding them into one column would be counting two different things.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Streamed {
  given: usize,
  projected: usize,
  skipped: usize,
  fin: Option<Fin>,
}

impl Streamed {
  /// Items the body fed, whatever became of them.
  #[inline]
  #[must_use]
  pub const fn given(&self) -> usize {
    self.given
  }

  /// Items that reached at least one edge, counted per ITEM and not per edge — a fan-out of one item
  /// to three consumers is one here and three on the wire, which is
  /// [`Tally::emitted`](super::Tally::emitted)'s own rule.
  #[inline]
  #[must_use]
  pub const fn projected(&self) -> usize {
    self.projected
  }

  /// Items no edge carried — the streaming face's
  /// [`NoConsumers`](crate::SkipReason::NoConsumers) gap, counted rather than announced per item.
  #[inline]
  #[must_use]
  pub const fn skipped(&self) -> usize {
    self.skipped
  }

  /// How the run ENDED, or `None` where it failed rather than ending.
  #[inline]
  #[must_use]
  pub const fn fin(&self) -> Option<Fin> {
    self.fin
  }
}

/// THE RUN ENDED WITHOUT ANSWERING — its body panicked, or its thread was killed under it.
///
/// The one failure this lane can state about a body rather than for it. The instance is gone with the
/// run, so the lane narrows by one and says so here; the delivery is settled
/// [`Failed`](Lifecycle::Failed) exactly as a returned `Err` would be, because from the sender's side
/// the two are the same fact.
#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Display)]
#[display(
  "this delivery's run ended without answering — its body panicked, or its thread was killed"
)]
pub struct Vanished;

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

/// THE TWO PER-NODE SEATS a stream-faced node carries, and the machine reading one of them decides on.
///
/// # What is here, and why it is one type
///
/// [`in_flight`](Self::in_flight) is the admission width and [`feed_policy`](Self::feed_policy) is
/// how deep one delivery's line is cut. They are folded into one options value rather than passed as
/// two arguments for [`MongoOptions`](crate::MongoOptions)' reason one layer over: the set will grow —
/// a per-node executor, a wind-down budget — and a signature that took each seat as an argument would
/// break at every one.
///
/// [`memory_probe`](Self::memory_probe) is the third seat and it is not a third CONCERN: a
/// [`FeedContext`] carries a probe by construction, so a lane that holds a feed policy has to hold the
/// probe it will be shown. A deployment that ships [`Fixed`] never reads it.
///
/// # Not `Copy`, not `PartialEq`, and the accessors are not `const`
///
/// [`Policies`](super::Policies)' trade verbatim: a seat holding a trait object cannot derive the
/// value-like traits its neighbours do, and demanding `Debug` of a policy would bound every
/// deployment's policy for the benefit of one line. What survives is [`Clone`] — an `Arc` apiece — and
/// a hand-written [`Debug`](core::fmt::Debug) that prints the number and not the advisors.
#[derive(Clone)]
pub struct StreamOptions {
  in_flight: NonZeroUsize,
  feed: Arc<dyn FeedPolicy>,
  probe: Arc<dyn MemoryProbe>,
}

impl StreamOptions {
  /// THE SHIPPED SEATS: [`DEFAULT_IN_FLIGHT`], [`Fixed`] at
  /// [`DEFAULT_FEED_DEPTH`](super::DEFAULT_FEED_DEPTH), and [`Unpressured`].
  ///
  /// Written out rather than left implicit, for [`Policies::new`](super::Policies::new)'s reason: an
  /// unconfigured node runs these three, and these three are what the lane would have done with no
  /// seats at all.
  #[inline]
  #[must_use]
  pub fn new() -> Self {
    Self {
      in_flight: DEFAULT_IN_FLIGHT,
      feed: Arc::new(Fixed::default()),
      probe: Arc::new(Unpressured),
    }
  }

  /// How many deliveries this node may hold at once.
  #[inline]
  #[must_use]
  pub const fn in_flight(&self) -> NonZeroUsize {
    self.in_flight
  }

  /// Hold up to `in_flight` deliveries at once.
  #[inline]
  #[must_use]
  pub fn with_in_flight(mut self, in_flight: NonZeroUsize) -> Self {
    self.set_in_flight(in_flight);
    self
  }

  /// [`with_in_flight`](Self::with_in_flight), in place.
  #[inline]
  pub fn set_in_flight(&mut self, in_flight: NonZeroUsize) -> &mut Self {
    self.in_flight = in_flight;
    self
  }

  /// The feed policy in force.
  #[inline]
  #[must_use]
  pub fn feed_policy(&self) -> &dyn FeedPolicy {
    &*self.feed
  }

  /// Cut every delivery's feed with `policy`.
  #[inline]
  #[must_use]
  pub fn with_feed_policy(mut self, policy: Box<dyn FeedPolicy>) -> Self {
    self.set_feed_policy(policy);
    self
  }

  /// [`with_feed_policy`](Self::with_feed_policy), in place.
  #[inline]
  pub fn set_feed_policy(&mut self, policy: Box<dyn FeedPolicy>) -> &mut Self {
    self.feed = Arc::from(policy);
    self
  }

  /// The memory probe a feed policy is shown.
  #[inline]
  #[must_use]
  pub fn memory_probe(&self) -> &dyn MemoryProbe {
    &*self.probe
  }

  /// Read the machine through `probe`.
  #[inline]
  #[must_use]
  pub fn with_memory_probe(mut self, probe: Box<dyn MemoryProbe>) -> Self {
    self.set_memory_probe(probe);
    self
  }

  /// [`with_memory_probe`](Self::with_memory_probe), in place.
  #[inline]
  pub fn set_memory_probe(&mut self, probe: Box<dyn MemoryProbe>) -> &mut Self {
    self.probe = Arc::from(probe);
    self
  }
}

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

impl core::fmt::Debug for StreamOptions {
  /// The width, and nothing about the two advisors — [`Policies`](super::Policies)' trade, for its
  /// reason.
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("StreamOptions")
      .field("in_flight", &self.in_flight)
      .finish_non_exhaustive()
  }
}

/// ONE DELIVERY IN FLIGHT, as the lane holds it.
struct Line<O, M>
where
  O: Streams<M>,
{
  // `Arc` so that a wait can be built as a future owning its own end of the line rather than
  // borrowing this vector — which is what lets one park cover every live line while the lane stays
  // free to project into the downstream set the moment one of them answers.
  yielded: Arc<Yielded<<O as Streams<M>>::Out>>,
  run: <O as Streams<M>>::Run,
  // Filled at the awaited face when the run future completes, and never at the blocking one, where
  // the answer is taken off `run` at closing time. `Option` is the *has the future finished* flag as
  // well as the answer: a completed future must not be polled again.
  ended: Option<Ended<O, M>>,
  // Announcing on it is what [`StreamLane::stop`] does, and DROPPING it is what makes a dropped lane
  // a wind-down: `Stopper`'s own `Drop` announces.
  stopper: Stopper,
  owed: Owed<ItemId>,
  info: Streamed,
}

impl<O, M> Line<O, M>
where
  O: Streams<M>,
{
  /// Whether NOTHING MORE can arrive on this line: the feed has hung up and what it held is taken.
  ///
  /// The [`Feed`](crate::Feed) was taken by value, so it drops when the run returns — but a body may
  /// also drop it EARLY and go on doing something else, which is why this says only what it says. It
  /// is the blocking face's closing trigger, because there the run's answer arrives on a line of its
  /// own; the awaited face reads [`answered`](Self::answered) instead.
  fn drained(&self) -> bool {
    self.yielded.is_disconnected() && self.yielded.is_empty()
  }

  /// Whether the AWAITED run has answered and everything it fed has been taken.
  ///
  /// It asks about the run rather than about the feed, and that is what makes an early-dropped feed
  /// harmless here: a line whose feed went before its run did is not finished, it is quiet.
  fn answered(&self) -> bool {
    self.ended.is_some() && self.yielded.is_empty()
  }
}

/// THE STREAM LANE: N warm instances of one stream-faced unit, the deliveries in flight over them,
/// and the downstream set their outputs cross.
///
/// # What builds it, and what drives it
///
/// [`Wiring::lane`](super::Wiring::lane) BUILDS one, from the declaration that wrote `stream`, and a
/// `#[ingraph::graph]` root builds one too — [`App::lane`](super::App::lane) is where a deployment
/// takes it. What DRIVES it is still the party that holds it: a lane is handed deliveries through
/// [`admit`](Self::admit) and [`tend`](Self::tend)ed — and both of those are `async fn`s, so the
/// thread engine drives them with this layer's own `block_on` and the async engine awaits them,
/// which is the trade every other two-engine seam here already makes.
///
/// # The mode parameter, and the spawner seat only one face reads
///
/// `M` selects the face, exactly as [`Resident`](super::Resident)'s does and for `E0592`'s reason.
/// `X` is the executor a BLOCKING run is placed on; the awaited face polls its runs here and reads
/// this seat not at all. It is a field rather than an argument because an executor is chosen for a
/// node once, and threading it through every admission would be a knob at a call site that has no
/// opinion about it.
pub struct StreamLane<O, S, X = Thread, M = Block>
where
  O: Streams<M>,
{
  /// The node's own WINDOW — the deployment's resources, the LANE's wind-down line and its name.
  /// Each admission [`reopens`](Context) it onto that run's own line, the streaming seat being
  /// taken by value: one delivery is one whole life, so one delivery is one line.
  window: Context,
  options: StreamOptions,
  spawner: X,
  downstream: S,
  windows: Vec<Outbound<ItemId>>,
  effect: Effect,
  taps: Taps,
  warm: Vec<O>,
  live: Vec<Line<O, M>>,
  // How many instances this lane HAS, idle or out. It is what `width` is computed from, so that a
  // depth asked for one admission is the same number whether it was asked before or after the
  // instance was taken out of the warm set. Only a lost body — one that panicked — moves it.
  minted: usize,
  next_item: u64,
  turn: usize,
  mode: PhantomData<fn() -> M>,
}

impl<O, S, X, M> StreamLane<O, S, X, M>
where
  O: Streams<M>,
{
  /// A lane over `instances` of the node called `name`, publishing to `downstream` and placing
  /// blocking runs on `spawner`.
  ///
  /// # The warm set is what the caller hands over
  ///
  /// The lane mints no instances: building one is the construction layer's question — options,
  /// resources, a constructor that can fail — and a lane that could build one would be answering it
  /// twice. So the honest size for `instances` is the node's
  /// [`in_flight`](StreamOptions::in_flight), and [`width`](Self::width) is what the lane actually
  /// runs at.
  #[must_use]
  pub fn new(
    ctx: Context,
    options: StreamOptions,
    instances: impl IntoIterator<Item = O>,
    downstream: S,
    spawner: X,
  ) -> Self {
    Self {
      window: ctx,
      options,
      spawner,
      downstream,
      windows: Vec::new(),
      effect: Effect::Pure,
      taps: Taps::new(),
      warm: Vec::new(),
      live: Vec::new(),
      minted: 0,
      next_item: 0,
      turn: 0,
      mode: PhantomData,
    }
    .warmed(instances)
  }

  /// Seat the warm set — [`new`](Self::new)'s own last step, where the count `width` reads is taken.
  fn warmed(mut self, instances: impl IntoIterator<Item = O>) -> Self {
    self.warm.extend(instances);
    self.minted = self.warm.len();
    self
  }

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

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

  /// HOW MANY DELIVERIES THIS LANE CAN ACTUALLY HOLD: the smaller of the
  /// [`in_flight`](StreamOptions::in_flight) seat and the warm set it was handed.
  ///
  /// The permit and the instance are one thing here, which is what makes the admission bound
  /// deadlock-free by construction: a delivery is admitted exactly when there is a body free to run
  /// it, so there is no second counter that can disagree with the first.
  ///
  /// A lane that was handed nothing runs at zero and admits nothing — see [`admit`](Self::admit). A
  /// body that PANICKED narrows this by one permanently: its instance went with it, and reusing a
  /// value whose invariants an unwind left half-written is not something this lane will do.
  #[inline]
  #[must_use]
  pub fn width(&self) -> usize {
    self.minted.min(self.options.in_flight.get())
  }

  /// How many deliveries are in flight right now.
  #[inline]
  #[must_use]
  pub fn in_flight(&self) -> usize {
    self.live.len()
  }

  /// How many instances are idle.
  #[inline]
  #[must_use]
  pub fn idle(&self) -> usize {
    self.warm.len()
  }

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

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

  /// Say what it does with what it produces.
  #[inline]
  #[must_use]
  pub fn with_effect(mut self, effect: Effect) -> Self {
    self.set_effect(effect);
    self
  }

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

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

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

  /// SAY STOP to every run in flight.
  ///
  /// Each delivery gets a [`ShutdownSignal`](crate::ShutdownSignal) of its own — the seat is taken by value, so it cannot
  /// be one line shared — and this announces on all of them at once. A body that reads its stop winds
  /// down and answers [`Fin::Stopped`]; one that never looks runs to its end, which is the same
  /// contract an origin's stop has.
  ///
  /// Dropping the lane does this too, because [`Stopper`]'s own `Drop` announces.
  pub fn stop(&self) {
    for line in &self.live {
      line.stopper.announce();
    }
  }
}

impl<O, S, X, M> StreamLane<O, S, X, M>
where
  O: Streams<M>,
  S: Sink<<O as Streams<M>>::Out>,
{
  /// Route `items` fed by the line at `index` into the downstream set, and hand each edge its batch.
  ///
  /// [`Resident::fan_out`](super::Resident)'s walk, at this face's own grain: the value moves into the
  /// LAST edge that carries it and is COPIED for the others, so a one-consumer node pays for no copy
  /// at all. What differs is the accounting — a streamed item has no per-item obligation of its own,
  /// because the obligation is the DELIVERY's and is settled once when the run ends.
  ///
  /// # The copy is the DOWNSTREAM SET's, which is why nothing here bounds the payload
  ///
  /// The copy is taken through [`Sink::duplicate`] rather than through a `Clone` on
  /// [`Out`](Streams::Out), because whether one output has a second seat is a fact about the SET and
  /// not about the payload. A node's own emitted `<Node>Downstream` answers it PER PRODUCT — a
  /// product with one subscriber reaches the copy never and is asked for none, while its neighbour
  /// with three is asked twice — so one non-copying product costs its copyable siblings nothing.
  /// [`Downstream`](super::Downstream), whose N edges of one product ARE the fan-out, pays the
  /// `Clone` on its own impl.
  async fn project(&mut self, index: usize, items: Vec<<O as Streams<M>>::Out>) {
    self.live[index].info.given += items.len();
    let arity = self.downstream.arity();
    while self.windows.len() < arity {
      self.windows.push(Outbound::new());
    }
    // The whole-node read, once per batch rather than once per item — `Wanted`'s own shape, and the
    // gate the buffered face takes before it computes anything.
    if !self.downstream.connected().any() {
      self.live[index].info.skipped += items.len();
      return;
    }
    let mut batches: Vec<Vec<Item<<O as Streams<M>>::Out>>> =
      core::iter::repeat_with(Vec::new).take(arity).collect();
    let mut undividable = false;
    for output in items {
      let Some(last) = (0..arity)
        .rev()
        .find(|edge| self.downstream.carries(*edge, &output))
      else {
        // An item with nowhere on the wire to go. Counted rather than announced per item: a stream
        // that fans a million of these would otherwise fan a million observations, and the one fact a
        // reader wants — how many of this delivery's items reached nobody — is the count.
        self.live[index].info.skipped += 1;
        continue;
      };
      let mut value = Some(output);
      // The walk STOPS at the last carrying edge, which is what keeps the value readable throughout:
      // past it there is nothing left to route and nothing left to ask `carries` about.
      for (edge, batch) in batches.iter_mut().enumerate().take(last + 1) {
        let held = value
          .as_ref()
          .expect("the value is taken only at the last edge");
        if edge != last && !self.downstream.carries(edge, held) {
          continue;
        }
        let copy = if edge == last {
          value.take().expect("taken exactly once")
        } else if let Some(copy) = self.downstream.duplicate(held) {
          copy
        } else {
          // The set promised this edge a seat and cannot fill it. The value goes on to the LAST edge
          // — that one takes it by move — and this edge is refused by name once the batch is walked,
          // rather than left looking like an item nobody wanted.
          undividable = true;
          continue;
        };
        let id = ItemId::new(self.next_item);
        self.next_item += 1;
        batch.push(Item::new(id, copy));
      }
      self.live[index].info.projected += 1;
    }
    if undividable {
      self.undividable();
    }
    for (edge, batch) in batches.into_iter().enumerate() {
      if batch.is_empty() {
        continue;
      }
      let ids: Vec<ItemId> = batch.iter().map(|item| *item.key()).collect();
      let (ack, answers) = ack_channel();
      if self.downstream.deliver(edge, batch, ack).await {
        self.windows[edge].record(ids, answers);
      } else {
        self.hung_up();
      }
    }
  }

  /// A consumer that has hung up will never release what was just sent it.
  ///
  /// [`Resident::hung_up`](super::Resident)'s observation, without its two other halves: there is no
  /// root map to clear and no lineage to retract, because a streamed item's obligation is its
  /// delivery's and not its own.
  fn hung_up(&self) {
    let observation =
      Lifecycle::<Streamed>::Skipped(Skip::new(SkipReason::ServiceInactive)).erase();
    self.taps.observe(self.window.node(), &observation);
  }

  /// A SECOND EDGE CARRIES ONE OUTPUT AND THE PAYLOAD DOES NOT COPY — this node's downstream set
  /// promised a seat it cannot fill.
  ///
  /// It is [`hung_up`](Self::hung_up)'s shape and it is announced for that reason: nothing
  /// downstream of the refused edge will ever see the item, and the honest answer to that is a named
  /// refusal rather than a silent drop. Announced ONCE per projected batch, which is the
  /// [`skipped`](Streamed::skipped) count's own law — a stream that fanned a million undividable
  /// items would otherwise fan a million observations of one topology fact.
  ///
  /// The framework's own sets cannot reach it: [`Downstream`](super::Downstream) duplicates and a
  /// one-seat-per-product set never asks. What reaches it is a hand-written [`Sink`] whose
  /// [`carries`](Sink::carries) is true for a second edge while its
  /// [`duplicate`](Sink::duplicate) is the inherited `None`, and the label says which law it broke.
  fn undividable(&self) {
    let reason = SkipReason::custom(Utf8Bytes::from_static(UNDIVIDABLE));
    let observation = Lifecycle::<Streamed>::Skipped(Skip::new(reason)).erase();
    self.taps.observe(self.window.node(), &observation);
  }

  /// Collect whatever the edges have answered, so the windows do not grow without bound.
  ///
  /// An answer is observed under the WORKER's name and never under this node's —
  /// [`Resident::harvest`](super::Resident)'s law verbatim: the observation was produced by the
  /// consumer downstream and its station is a fact about that node's work, so a record written from
  /// this node's name would name the wrong node in every row.
  fn harvest(&mut self) {
    let taps = &self.taps;
    for window in &mut self.windows {
      for answer in window.harvest().into_answers() {
        taps.observe(answer.worker(), answer.observation());
      }
    }
  }

  /// Settle `line`'s delivery with what its run answered, and put the instance back.
  ///
  /// # The four parts of what `Err` costs, performed
  ///
  /// The instance goes back into the warm set and the lane keeps its width, so the next delivery
  /// proceeds; everything already projected stands, because it crossed the feed before the failure
  /// and nothing here recalls it; the error rides into the settlement as a
  /// [`Failure`], which is what reaches the sender's oneshot and the taps; and nothing re-runs
  /// anything, because what a retry would even mean is a question only the app that minted the
  /// identity can answer.
  fn settle(&mut self, mut line: Line<O, M>, ended: Result<Fin, Failure>) {
    let lifecycle = match ended {
      Ok(fin) => {
        line.info.fin = Some(fin);
        self.effect.reached(line.info)
      }
      Err(failure) => Lifecycle::Failed(failure),
    };
    self
      .taps
      .observe(self.window.node(), &lifecycle.clone().erase());
    line.owed.settle(self.window.named().clone(), lifecycle);
  }
}

/// THE BLOCKING FACE: a run placed on the [`Spawn`] seam, drained here.
///
/// # `Send` is asked at THIS door and nowhere else
///
/// [`StreamOperator`](crate::StreamOperator) asks for nothing — mobility belongs to the engines, which
/// is [`Operator`](crate::Operator)'s law verbatim. A blocking run has to be somewhere other than the
/// party draining its feed, so placing one costs the `'static` wall a spawn demands and the `Send` that
/// crosses it. A body that cannot pay wears the awaited face, where this lane asks for neither.
///
/// # What the OUTPUT is asked for, and what it is not
///
/// `Send`, and that is the whole of it. It is the spawn's: the [`Feed`](crate::Feed) crosses into the
/// placed run, so the closure carrying it has to be one an executor can take. The `'static` beside it
/// is NOT written here — [`Streams::Out`] already carries one, for the park's own reason, and a bound
/// another bound implies is a bound said twice.
///
/// `Clone` is not here either. The fan-out's copy is taken through [`Sink::duplicate`], at the
/// downstream set that has the second seat to fill, so a lane over a set whose products each have
/// one subscriber drives a payload that does not copy at all.
impl<O, S, X> StreamLane<O, S, X, Block>
where
  O: StreamOperator + Send + 'static,
  <O as StreamOperator>::In: Send + 'static,
  <O as StreamOperator>::Out: Send,
  <O as StreamOperator>::Error: core::error::Error + Send + Sync + 'static,
  S: Sink<<O as StreamOperator>::Out>,
  X: Spawn,
{
  /// TAKE ONE DELIVERY: wait for a warm instance, cut a feed for it, and place its run.
  ///
  /// The wait is the admission bound, and it TENDS while it waits — the lines already in flight are
  /// drained and closed by the same loop that is waiting for one of them to free an instance, which is
  /// what keeps a full lane from deadlocking against its own backpressure.
  ///
  /// The feed's depth is asked of the node's [`FeedPolicy`] HERE, once per delivery, with the
  /// in-flight count as it stands before this admission — see [`FeedContext`].
  ///
  /// # Errors
  ///
  /// The delivery back, where this lane has no body to run it: a lane built with no instance, or one
  /// every instance of which was lost to a panicking run. It is the one state that waiting cannot
  /// resolve, and it is [`Outbox::deliver`](super::Outbox::deliver)'s posture — a refusal hands back
  /// what it would not take.
  pub async fn admit(
    &mut self,
    delivery: Delivery<<O as StreamOperator>::In>,
  ) -> Result<(), Delivery<<O as StreamOperator>::In>> {
    while self.warm.is_empty() {
      if !self.tend().await {
        return Err(delivery);
      }
    }
    let unit = self.warm.pop().expect("the loop above left one");
    let (feed, yielded) = crate::feed(self.depth().get());
    let (stopper, stop) = crate::shutdown_signal();
    // THIS RUN's window: the node's map and name, on the line this delivery alone hears.
    let ctx = self.window.reopened(stop);
    let (tell, told) = flume::bounded(1);
    let (payload, ack) = delivery.into_parts();
    let owed = Owed::open(payload.keys().copied(), ack);
    let handed = Delivery::in_custody(payload);
    self.spawner.spawn(move || {
      let mut unit = unit;
      let ended = unit.run(&ctx, handed, feed);
      // The line has capacity one and the lane holds the other end until it closes, so this never
      // waits and never loses the answer.
      let _ = tell.send((unit, ended));
    });
    self.live.push(Line {
      yielded: Arc::new(yielded),
      run: told,
      ended: None,
      stopper,
      owed,
      info: Streamed::default(),
    });
    Ok(())
  }

  /// ONE STEP OF THE LANE: project everything ready, close everything finished, and — where neither
  /// was — park until one line says something.
  ///
  /// `false` once nothing is in flight, which is what a wind-down loop reads as done.
  pub async fn tend(&mut self) -> bool {
    if self.live.is_empty() {
      return false;
    }
    if !self.pass().await {
      if let Some((index, item)) = self.woken().await {
        self.project(index, vec![item]).await;
      }
      self.pass().await;
    }
    true
  }

  /// Tend until nothing is left in flight — the wind-down.
  ///
  /// It says no stop of its own: a caller that wants the runs to hear one calls [`stop`](Self::stop)
  /// first, and one that wants every delivery finished simply drains.
  pub async fn drain(&mut self) {
    while self.tend().await {}
  }

  /// One sweep: everything queued projected, everything finished closed, the windows harvested.
  /// `true` where anything at all happened.
  async fn pass(&mut self) -> bool {
    let mut moved = false;
    for index in 0..self.live.len() {
      let taken: Vec<_> = self.live[index].yielded.drain().collect();
      if !taken.is_empty() {
        moved = true;
        self.project(index, taken).await;
      }
    }
    let mut index = 0;
    while index < self.live.len() {
      if !self.live[index].drained() {
        index += 1;
        continue;
      }
      moved = true;
      let line = self.live.remove(index);
      // Ordinarily already on the line: the run sent it after dropping the feed, which is what
      // `drained` just observed. A body that dropped its feed EARLY and went on working is the one
      // case this genuinely waits for, and waiting is right — the delivery is not over.
      match line.run.recv_async().await {
        Ok((unit, ended)) => {
          self.warm.push(unit);
          self.settle(line, ended.map_err(Failure::new));
        }
        // The sender went without answering: the body panicked or its thread was killed. The
        // instance is gone with it and the lane narrows by one.
        Err(_) => {
          self.minted -= 1;
          self.settle(line, Err(Failure::new(Vanished)));
        }
      }
    }
    self.harvest();
    moved
  }

  /// Park until the first live line hands over an item or hangs up, and HAND BACK what it said.
  ///
  /// A take is destructive — the item leaves the line with it — so the winner's item travels out of
  /// here and is projected by the caller. `None` is the hang-up, which the pass after this one reads
  /// off the line itself.
  ///
  /// The arms are built ONCE and held across the whole park, which is what makes a wake reach the
  /// receive that registered for it — [`select`](super::select)'s own note, at a set that changes
  /// between parks rather than between polls.
  ///
  /// # EVERY ARM A PLACEHOLDER IS NOT A WAIT — ingraph #472, and it wedged a shipped lane
  ///
  /// This face polls the ARMS and nothing else: a blocking run's answer arrives on a channel that
  /// [`pass`](Self::pass) reads at closing time, so unlike the awaited face one seam below there is
  /// no run future here to be the waker of last resort. An arm set that is `pending()` throughout
  /// therefore registers no waker at all, and the driver's `park()` under it never returns.
  ///
  /// That set is reachable, and it is a RACE rather than an exotic state. [`tend`](Self::tend) calls
  /// this only where [`pass`](Self::pass) moved nothing, so every live line was UNdrained when
  /// `pass` last looked — and a run thread that returns in the window between that look and
  /// [`arms`](Self::arms) drops its feed, which is exactly what turns the last real arm into a
  /// placeholder. One delivery, one instance and a body that ends is the whole recipe; it hung
  /// `drive::stream::tests` under parallel load, and in a deployment it is a `stream` node on the
  /// thread engine that stops draining its inbox and never resumes.
  ///
  /// The answer is the hang-up, which is what the state IS: nothing more can arrive on any line, so
  /// the caller's follow-up `pass` closes every one of them — [`drained`](Line::drained) is that
  /// face's own closing trigger — and the wind-down finishes instead of parking. It cannot spin,
  /// because that pass removes the lines the answer was about.
  async fn woken(&mut self) -> Option<(usize, <O as StreamOperator>::Out)> {
    let (mut arms, waiting) = self.arms();
    if !waiting {
      return None;
    }
    let turn = self.turn;
    let (index, item) = core::future::poll_fn(|cx| {
      let count = arms.len();
      if count == 0 {
        return Poll::Ready((0, None));
      }
      for step in 0..count {
        let index = (turn + step) % count;
        if let Poll::Ready(item) = arms[index].as_mut().poll(cx) {
          return Poll::Ready((index, item));
        }
      }
      Poll::Pending
    })
    .await;
    // Past the winner, so a busy line cannot starve a quiet one — `select`'s own turn cursor.
    self.turn = index + 1;
    item.map(|item| (index, item))
  }
}

/// THE AWAITED FACE: runs polled where they were made, and no `Send` asked of anything.
///
/// The OUTPUT is asked for nothing at all here — the `'static` its park needs is [`Streams::Out`]'s
/// own, and the fan-out's copy is the downstream set's, exactly as it is one face over.
impl<O, S, X> StreamLane<O, S, X, Async>
where
  O: AsyncStreamOperator + 'static,
  <O as AsyncStreamOperator>::In: 'static,
  <O as AsyncStreamOperator>::Error: core::error::Error + Send + Sync + 'static,
  S: Sink<<O as AsyncStreamOperator>::Out>,
{
  /// [`StreamLane::<…, Block>::admit`](StreamLane::admit)'s contract verbatim, with the run kept here
  /// instead of placed on an executor.
  ///
  /// # Errors
  ///
  /// The blocking face's, unchanged: the delivery back where this lane has no body to run it.
  pub async fn admit(
    &mut self,
    delivery: Delivery<<O as AsyncStreamOperator>::In>,
  ) -> Result<(), Delivery<<O as AsyncStreamOperator>::In>> {
    while self.warm.is_empty() {
      if !self.tend().await {
        return Err(delivery);
      }
    }
    let unit = self.warm.pop().expect("the loop above left one");
    let (feed, yielded) = crate::feed(self.depth().get());
    let (stopper, stop) = crate::shutdown_signal();
    // THIS RUN's window — the blocking face's own sentence, one face over.
    let ctx = self.window.reopened(stop);
    let (payload, ack) = delivery.into_parts();
    let owed = Owed::open(payload.keys().copied(), ack);
    let handed = Delivery::in_custody(payload);
    let run: <O as Streams<Async>>::Run = Box::pin(async move {
      let mut unit = unit;
      let ended = unit.run(&ctx, handed, feed).await;
      (unit, ended)
    });
    self.live.push(Line {
      yielded: Arc::new(yielded),
      run,
      ended: None,
      stopper,
      owed,
      info: Streamed::default(),
    });
    Ok(())
  }

  /// [`StreamLane::<…, Block>::tend`](StreamLane::tend)'s contract verbatim.
  ///
  /// The one difference is what the park waits on: this face's runs are futures the lane owns, so the
  /// park polls THEM beside the drains. A run nobody polls is a run that never reaches its next
  /// `give`, which is why the two cannot be separated here as they can one face over.
  pub async fn tend(&mut self) -> bool {
    if self.live.is_empty() {
      return false;
    }
    if !self.pass().await {
      if let Some((index, item)) = self.woken().await {
        self.project(index, vec![item]).await;
      }
      self.pass().await;
    }
    true
  }

  /// Tend until nothing is left in flight — the wind-down.
  pub async fn drain(&mut self) {
    while self.tend().await {}
  }

  /// One sweep — the blocking face's, reading the run's answer off the line rather than off a channel.
  async fn pass(&mut self) -> bool {
    let mut moved = false;
    for index in 0..self.live.len() {
      let taken: Vec<_> = self.live[index].yielded.drain().collect();
      if !taken.is_empty() {
        moved = true;
        self.project(index, taken).await;
      }
    }
    let mut index = 0;
    while index < self.live.len() {
      if !self.live[index].answered() {
        index += 1;
        continue;
      }
      moved = true;
      let mut line = self.live.remove(index);
      let (unit, ended) = line
        .ended
        .take()
        .expect("`answered` is exactly the question of whether this is `Some`");
      self.warm.push(unit);
      self.settle(line, ended.map_err(Failure::new));
    }
    self.harvest();
    moved
  }

  /// Park until the first live line hands over an item, hangs up, or ENDS — the blocking face's
  /// contract, with the runs polled beside the drains.
  async fn woken(&mut self) -> Option<(usize, <O as AsyncStreamOperator>::Out)> {
    // The "can any arm answer" bit is DELIBERATELY dropped at this face, and the asymmetry is the
    // one sentence this method's own note already states: the runs are polled HERE, beside the
    // drains, so an unfinished run is the waker a placeholder arm does not carry. Reading the bit
    // and answering the hang-up on it would be wrong rather than redundant — a body that dropped its
    // feed EARLY and went on working is `drained()` and not `answered()`, so this face's `pass` will
    // not close it, and a `None` here would spin the wind-down instead of parking it.
    let (mut arms, _waiting) = self.arms();
    let lines = &mut self.live;
    let turn = self.turn;
    let (index, item) = core::future::poll_fn(|cx| {
      let count = arms.len();
      if count == 0 {
        return Poll::Ready((0, None));
      }
      for step in 0..count {
        let index = (turn + step) % count;
        // The run FIRST: a run that can make progress is what puts the next item on the line, and a
        // drain polled ahead of it would answer about a line nobody has fed yet.
        if lines[index].ended.is_none()
          && let Poll::Ready(answered) = lines[index].run.as_mut().poll(cx)
        {
          lines[index].ended = Some(answered);
          return Poll::Ready((index, None));
        }
        if let Poll::Ready(item) = arms[index].as_mut().poll(cx) {
          return Poll::Ready((index, item));
        }
      }
      Poll::Pending
    })
    .await;
    self.turn = index + 1;
    item.map(|item| (index, item))
  }
}

impl<O, S, X, M> StreamLane<O, S, X, M>
where
  O: Streams<M>,
{
  /// One take-future per live line, owning its own end of the line rather than borrowing this
  /// vector — which is what lets the park cover every line while the lane stays free to project the
  /// moment one of them answers.
  ///
  /// A line with nothing more to say gets an arm that NEVER answers, and the alignment with the
  /// live set is kept rather than compacted — [`arm`](super::arm)'s own law one seam
  /// over: a take on a hung-up line returns at once, so re-offering one would spin the park rather
  /// than wait in it.
  ///
  /// # The `bool` IS WHETHER ANY ARM CAN ANSWER, and it is read from the SAME observation
  ///
  /// A `pending()` placeholder registers NO waker — that is the whole of what "never answers" means
  /// — so an arm set that is placeholders throughout is a park with no waker anywhere in it. The
  /// count of real arms is therefore not a convenience: it is the only thing that tells a caller
  /// whether the park it is about to enter has a way out.
  ///
  /// It is returned FROM HERE rather than re-asked by the caller, and that is the race ingraph #472
  /// was: `drained()` is a fact about a line the RUN THREAD is still changing, so two reads of it
  /// are two different answers. A caller that asked "is anything live" and then called this would be
  /// asking twice — and a run that ended between the two questions gives the first answer *yes* and
  /// the second answer *placeholder*. One reading per line, used for both decisions, is what closes
  /// that window; see [`StreamLane::<…, Block>::woken`](StreamLane::woken).
  fn arms(&self) -> (Vec<Park<O, M>>, bool) {
    let mut waiting = false;
    let arms = self
      .live
      .iter()
      .map(|line| {
        if line.drained() {
          return Box::pin(core::future::pending()) as Park<O, M>;
        }
        waiting = true;
        let yielded = Arc::clone(&line.yielded);
        Box::pin(async move { yielded.take_async().await }) as Park<O, M>
      })
      .collect();
    (arms, waiting)
  }

  /// Ask this node's policy how deep to cut the next delivery's feed.
  ///
  /// The in-flight count is read BEFORE the admission it is being asked about, which is
  /// [`FeedContext::in_flight`]'s own promise, and the width is what the lane actually runs at rather
  /// than what the seat asked for.
  fn depth(&self) -> NonZeroUsize {
    let width = NonZeroUsize::new(self.width()).unwrap_or(NonZeroUsize::MIN);
    let ctx = FeedContext::new(self.live.len(), width, self.options.memory_probe());
    self.options.feed_policy().capacity(&ctx)
  }
}

impl<O, S, X, M> core::fmt::Debug for StreamLane<O, S, X, M>
where
  O: Streams<M>,
{
  /// The node, the width and what it is holding — never the bodies and never the items. `O` is the
  /// author's own type and demanding a [`Debug`](core::fmt::Debug) of it would bound every stream-faced
  /// unit for the benefit of this line, which is [`Feed`](crate::Feed)'s own reason one layer down.
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("StreamLane")
      .field("node", &self.window.node().as_str())
      .field("width", &self.width())
      .field("in_flight", &self.live.len())
      .field("idle", &self.warm.len())
      .finish_non_exhaustive()
  }
}