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 ;
use ;
use crate;
/// 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 = new.expect;
/// 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 = new.expect;
/// 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 = new.expect;
/// 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 = from_millis;
/// 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.
/// 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.
/// 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.
/// 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.
/// 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.
/// 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.
/// 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.
/// 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.
/// 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.