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
//! THE RUNNING WORLD, and how it stops.
//!
//! What [`Ignition::into_app`](super::Ignition::into_app) hands back is the whole deployment as one
//! value: the resources it holds open, the engines under its bodies, the sources feeding it, and
//! the registry that knows exactly who has to answer before it may be called stopped. Three things
//! can be done with it, and the third is the daemon's last line.
//!
//! # THE EXIT SOURCES ARE THE APP'S OWN SEAT, and the handlers are still the application's
//!
//! [`halt_on`](App::halt_on) registers any fire-once source — a `Ctrl-C` handler's line, a unix
//! signal's, a supervisor's socket, a test's own channel — and a registered source firing WAKES
//! [`until_stopped`](App::until_stopped)'s park. The App natively accepts registrations; the
//! handlers are still the app's to supply, and installing one is an act with process-wide
//! consequences that no library should take on an application's behalf.
//!
//! What a woken caller does next is its own: the park returns, and the ordinary next line is
//! [`shutdown`](App::shutdown) — whose first step announces on every node's wind-down line, so the
//! registration reaches a body inside `accept` through the one door
//! [`Context::shutdown`](crate::Context::shutdown) opens. Nothing here consumes the [`App`] or runs
//! the seven steps for the caller: a source firing is INFORMATION, and what to do about it is a
//! decision.
//!
//! # It is the FRAMEWORK's type, and `I` is the seat the generated faces will sit in
//!
//! Every indexer's running world is the same world — the lifecycle face below is identical whatever
//! a deployment declared — so it lives here once rather than being emitted per root. What differs
//! between two deployments is what can be ASKED of them, and that is what the `I` parameter is for:
//! it names the generated root, so the emitted query faces and typed feeders of a later round hang
//! off `App<Media>` rather than off a second emitted type beside it.
//!
//! Today it carries NO machinery. The parameter is held by a `PhantomData<fn() -> I>` and every
//! method below is written without it, which is deliberate: the seat is reserved at the shape a
//! deployment already spells (`Media::launch` gives back an `App<Media>`), and nothing is invented
//! to fill it before there is something to put there. `fn() -> I` rather than `I` so the marker
//! carries no ownership, no drop obligation and no auto-trait of the root's — a `!Send` root does
//! not make a running world `!Send`.
//!
//! # The shutdown ANNOUNCES and COUNTS — it does not orchestrate
//!
//! There is no wave to conduct, because the arrangement already carries one. The framework says
//! *wind down* to every registered party — and to every mounted ORIGIN on its own stop line, that
//! being the one road a body which is inside `run` for its whole life ever listens to — stops the
//! sources, releases its own halves of the edges,
//! and then WAITS. What happens in between is data-flow causality: a source that has stopped closes
//! its senders, a resident whose senders are all gone drains what is queued and returns, its own
//! outboxes go with it, and the node below sees a closed and drained inbox and does the same. The
//! order emerges from the topology rather than from a list somebody has to keep in step with it.
//!
//! Nothing here calls a `drain` on anybody, and no such method exists to call: settling custody is
//! the node's own business, the ack window already counts what is outstanding, and a closed inbox is
//! the actor-classic nudge that the stream has ended. A hook to flush a partial batch early would be
//! a real thing to add the day something measures the need for one; until then it would be a word
//! with no reader.
//!
//! # The GOODBYES come back through the settlements, and the resources go last
//!
//! A node's value is on an engine, so the chain cannot reach it — what reaches the chain is what the
//! body handed back as it settled: the goodbye itself, boxed, or a turn signal onto the thread still
//! holding it. See [`Settlement`](super::shutdown::Settlement) for the two roads. So the stop
//! COLLECTS after its wait, walks the collection backwards, and releases the resources after all of
//! it — which is what makes [`Arc::into_inner`](std::sync::Arc::into_inner) an honest question by
//! the time it is asked: every node that held a handle has already finished with it.
//!
//! # What a deadline is for, and what it is not
//!
//! A deadline bounds the WAIT, never the wave. Where it runs out, the report names who had not
//! answered and the world is abandoned where it stands — the ruled abort — which is also why the
//! goodbyes are not said on that path: a teardown that flushes a store while the node writing to it
//! is still running is a worse ending than an un-torn value.
//!
//! # The stop BLOCKS, so it does not belong on the executor
//!
//! [`shutdown`](App::shutdown) parks the calling thread until every party has settled, then joins
//! the engines. Where a deployment's bodies are ASYNC, both halves of that are waiting on tasks the
//! app's own runtime has to poll — so calling it from ON that runtime, with nothing else to drive
//! them, is a wait for work the waiter is preventing.
//!
//! It is a fact about the call and not a defect in it: a stop is a blocking shutdown, and a runtime
//! that has one thread has to be left one. Under tokio the idiom is
//! `spawn_blocking(move || app.shutdown(None))`, which is what the async engine's own end-to-end
//! test spells, and a daemon whose main thread is not the executor's calls it directly.
//!
//! # Dropping an `App` is the abort without the report
//!
//! No [`Drop`] impl is written and none is wanted. Letting one fall out of scope drops the sources,
//! then the framework's edge halves, then the engines' handles — threads detached, tasks detached —
//! and finally the resources: the same releases [`abort`](App::abort) performs, with nobody waiting
//! to hear how it went. The field order in this module's struct is that sequence, and it is
//! load-bearing.

use core::{marker::PhantomData, time::Duration};

use std::{
  any::{Any, TypeId},
  collections::HashMap,
  sync::{
    Arc,
    atomic::{AtomicBool, Ordering},
  },
  thread::JoinHandle,
  time::Instant,
};

use smol_bytes::Utf8Bytes;

use crate::drive::{
  ItemId, NodeName, Outbox, Party, Registries, Resources, Shutdown, Streams, Taps, Thread,
  engine::Join, lane::block_on,
};

use super::{
  Cell, Declared, Enrolled, Farewell, Mount, Untorn,
  ignition::joined,
  resources::released,
  teardown::{Collected, collected, farewell},
  wiring::{LaneMount, MountedLane},
};

#[cfg(test)]
mod tests;

/// A started deployment of the indexer `I`.
///
/// The framework's own type, generic over the GENERATED ROOT: the lifecycle below is every
/// indexer's and lives here once, and `I` is the seat the emitted faces of a later round hang off.
/// It carries no machinery today — see the module note for the whole of what the parameter is and
/// is not.
///
/// A deployment wired BY HAND has no generated root to name, and writes `App<()>`.
///
/// # Examples
///
/// See [`Ignition`](super::Ignition), which is the only thing that builds one.
pub struct App<I> {
  // DECLARATION ORDER IS DROP ORDER, and this one is the shutdown's own sequence: the intake this
  // world offers is let go of first, the sources stop admitting, the mounted origins are told to
  // wind down, the framework lets go of the edges it was holding open, the engines are released,
  // the goodbyes the ignition still held are abandoned unsaid, and the resources go LAST — a
  // resource dropped while a body still held it would be the one ordering this layer cannot recover
  // from.
  /// The FEEDERS: one sending half per head node, keyed by the node's own type.
  ///
  /// The `I` seat's first flesh, and the shape it takes is the one the seat was reserved for — the
  /// door is `app.feeder::<Head>()`, typed by the head's own `In`, and the map underneath is
  /// erased because a heterogeneous set of them has no other form. What keys it is the TYPE and not
  /// the mount, for the join's own reason: a caller holds the node's type and never the deployment's
  /// word for it.
  feeders: HashMap<TypeId, Box<dyn Any + Send>>,
  /// The MOUNTED LANES, one per streaming node this deployment launched, keyed by the node's own
  /// type — the feeders' twin one pair over, and erased for their reason.
  ///
  /// What is held is the ACT of building each lane rather than the lane, so that this value stays
  /// one a spawn can take — see [`Wiring::lane_mount`](super::Wiring::lane_mount), which carries the
  /// argument, and [`lane`](Self::lane), which spends them.
  ///
  /// They sit here — after the feeders, before the sources — for the declaration-order reason the
  /// whole list is arranged by: a lane nobody took holds a downstream set of live sending halves, so
  /// letting go of one is letting go of edges the framework opened, and that belongs beside the other
  /// halves rather than after the engines.
  lanes: HashMap<TypeId, (Box<dyn Any + Send>, Enrolled)>,
  /// The BRIDGED ORIGINS this world mounted, one per origin field the launch started, keyed by the
  /// origin's own type — the feeders' twin one tier over, and erased for their reason.
  ///
  /// They sit HERE, before the sources, because dropping one is TELLING AN ORIGIN TO STOP: a
  /// [`Bridged`](super::Bridged) owns a [`Stopper`](crate::Stopper) and a stopper says the stop as
  /// it goes, so declaration order puts the origins at the head of the wind-down — an origin hears
  /// the instruction before a source stops admitting and long before the framework lets go of the
  /// edges. [`stop`](App::stop) says the same thing explicitly at its own step 1b rather than
  /// leaving it to this order, and the two agree.
  ///
  /// Holding them is also what keeps an origin RUNNING at all: the handle is the world's, and a
  /// launch that let it go would have wound down every origin it started — see
  /// [`Ignition::origin_kept`](super::Ignition::origin_kept), which is why that door exists.
  origins: HashMap<TypeId, Box<dyn Any + Send>>,
  sources: Vec<Box<dyn Any + Send>>,
  /// The launch's own half of every MOUNTED ORIGIN's stop line — see
  /// [`Ignition::origin_declared`](super::Ignition::origin_declared), where the join is made.
  ///
  /// BESIDE the sources and not among them, because the two are stopped by different acts: a light
  /// source is stopped by DROPPING what starting it gave back, and an origin is stopped by being
  /// TOLD. They drop here all the same — a [`Stopper`](crate::Stopper) says the stop as it goes — so
  /// the abort-without-report an [`App`] falling out of scope amounts to reaches an origin exactly
  /// as it reaches everything else.
  halts: Vec<crate::Stopper>,
  senders: Vec<Box<dyn Any + Send>>,
  bodies: Vec<JoinHandle<()>>,
  /// The bodies the framework spawned onto the app's own runtime, each already erased to the join it
  /// is awaited by — see [`Join`]. They sit beside the threads because they are the same thing said
  /// in the other engine, and they drop where the threads drop: releasing one detaches its task
  /// exactly as releasing a thread's handle detaches a thread.
  tasks: Vec<Join>,
  teardowns: Vec<Farewell>,
  shutdown: Shutdown,
  /// Whether a REGISTERED EXIT SOURCE has fired — see [`halt_on`](App::halt_on).
  ///
  /// Shared with every watcher this world spawned, and read by
  /// [`until_stopped`](App::until_stopped) around its park. It is a LATCH and never cleared: a
  /// source that fired has fired, and a park that woke to find it set must not park again on the
  /// strength of a flag somebody reset.
  halted: Arc<AtomicBool>,
  taps: Taps,
  ctx: Arc<Resources>,
  /// THE ROOT-KEY REGISTRIES this world coordinates through — the same object every body in it is
  /// holding, and what [`registries`](App::registries) hands a reader.
  ///
  /// It sits beside the resource map and drops with it, at the very end, for the resource map's own
  /// reason: a body still running may be counting into it, so letting go of the tables while a
  /// resident could still reach them would be the one ordering this layer cannot recover from.
  registries: Arc<Registries>,
  /// The generated root this world belongs to — a NAME and nothing else. See the module note.
  indexer: PhantomData<fn() -> I>,
}

/// Written rather than derived, for the reason the emitted options spine's own is: a derived one
/// carries `I: Debug`, and `I` is a NAME here rather than a value — a root that cannot print itself
/// would make its whole running world unprintable for the sake of a marker nothing reads. What a
/// reader of a start-up log wants is the arity anyway: how much is still holding the world open.
impl<I> core::fmt::Debug for App<I> {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("App")
      .field("feeders", &self.feeders.len())
      .field("lanes", &self.lanes.len())
      .field("origins", &self.origins.len())
      .field("sources", &self.sources.len())
      .field("halts", &self.halts.len())
      .field("senders", &self.senders.len())
      .field("bodies", &self.bodies.len())
      .field("tasks", &self.tasks.len())
      .field("teardowns", &self.teardowns.len())
      .field("shutdown", &self.shutdown)
      .field("halted", &self.halted.load(Ordering::Acquire))
      .field("taps", &self.taps)
      .field("ctx", &self.ctx)
      .field("registries", &self.registries)
      .finish()
  }
}

/// How long a stop waits for settlement.
enum Settling {
  /// Until every party has finished, however long that takes.
  Forever,
  /// For at most this long.
  Within(Duration),
  /// Not at all — the abort, which is the one posture that says no goodbyes.
  Never,
}

impl<I> App<I> {
  /// The started world the ignition assembled.
  #[expect(
    clippy::too_many_arguments,
    reason = "the running world's parts, handed over by the one stage that assembles them; a \
              parameter object here would be an `Ignition` with a second name"
  )]
  pub(super) fn new(
    ctx: Arc<Resources>,
    shutdown: Shutdown,
    taps: Taps,
    registries: Arc<Registries>,
    senders: Vec<Box<dyn Any + Send>>,
    sources: Vec<Box<dyn Any + Send>>,
    halts: Vec<crate::Stopper>,
    bodies: Vec<JoinHandle<()>>,
    tasks: Vec<Join>,
    teardowns: Vec<Farewell>,
    feeders: HashMap<TypeId, Box<dyn Any + Send>>,
    lanes: HashMap<TypeId, (Box<dyn Any + Send>, Enrolled)>,
    origins: HashMap<TypeId, Box<dyn Any + Send>>,
  ) -> Self {
    Self {
      feeders,
      lanes,
      origins,
      sources,
      halts,
      senders,
      bodies,
      tasks,
      teardowns,
      shutdown,
      halted: Arc::new(AtomicBool::new(false)),
      taps,
      ctx,
      registries,
      indexer: PhantomData,
    }
  }

  /// **REGISTER AN EXIT SOURCE**: when `source` speaks — or hangs up — wake
  /// [`until_stopped`](Self::until_stopped).
  ///
  /// This is the seat a daemon's `Ctrl-C` handler, a unix signal handler, a supervisor's socket or
  /// a test's own channel lands in, and it may be called MORE THAN ONCE: every registration watches
  /// its own line, and whichever speaks first wakes the park. Nothing is un-registered — a
  /// deployment's exit sources are decided when it starts.
  ///
  /// # It does not stop anything
  ///
  /// A registered source firing sets the halt latch and rings the registry, which is exactly enough
  /// to end the park. The caller then proceeds to [`shutdown`](Self::shutdown) — or does not, the
  /// [`App`] being still whole and still running. That division is deliberate: the seven-step
  /// wind-down takes a deadline nobody but the application can choose, and a library that ran it on
  /// a signal would be choosing.
  ///
  /// # A HANG-UP is the same news as a message
  ///
  /// The source is a [`conduit::Receiver<()>`](crate::conduit::Receiver), so it fires on a `()`
  /// sent through it AND on every sender being dropped — which is [`ShutdownSignal`](crate::ShutdownSignal)'s own reading
  /// of a line whose other half let go, applied one layer out: a handler that vanished is not a
  /// handler that will speak later, and a park waiting on it would be waiting on nobody.
  ///
  /// # What it costs
  ///
  /// ONE THREAD per registration, parked on the source's own blocking door for the deployment's
  /// life. It is the honest price of the park's own shape: [`until_stopped`](Self::until_stopped)
  /// is a blocking receive on the registry's bell and not a select over it, so a second line has to
  /// be watched somewhere. The watcher rings the same bell a finishing party does, so nothing about
  /// the wait had to change to accept one.
  ///
  /// # Examples
  ///
  /// ```
  /// use ingraph::conduit;
  ///
  /// # fn wire(app: &mut ingraph::App<()>) {
  /// // The handler is the application's — this is only where its line is registered.
  /// let (fired, source) = conduit::bounded::<()>(1);
  /// app.halt_on(source);
  ///
  /// std::thread::spawn(move || {
  ///   // …whatever the application decided *time to go* is: a signal handler, a socket, a timer.
  ///   let _ = fired.send(());
  /// });
  ///
  /// app.until_stopped();
  /// # }
  /// ```
  pub fn halt_on(&mut self, source: crate::conduit::Receiver<()>) {
    let ringer = self.shutdown.ringer();
    let halted = Arc::clone(&self.halted);
    // DETACHED on purpose: the watcher's whole life is one blocking receive, and a handle held
    // here would be a join the shutdown had to wait on for a thread whose line may never speak.
    // It ends when the source does — a message, or the last sender letting go — and a deployment
    // that stops first leaves it parked on a line nobody will use again.
    let _ = std::thread::Builder::new()
      .name("ingraph-halt".to_owned())
      .spawn(move || {
        // Both answers are the same news; see the door's own note.
        let _ = source.recv();
        // The LATCH FIRST and the ring second, which is the whole of the race protocol: a waiter
        // this ring wakes re-reads the latch, so setting it after would let one park return, see
        // nothing, and park again on a bell that had already rung.
        halted.store(true, Ordering::Release);
        ringer.ring();
      });
  }

  /// Whether a registered exit source has fired — see [`halt_on`](Self::halt_on).
  #[inline]
  #[must_use]
  pub fn halted(&self) -> bool {
    self.halted.load(Ordering::Acquire)
  }

  /// Everyone who has to answer before this world may be called stopped.
  #[inline]
  #[must_use]
  pub fn parties(&self) -> &[Party] {
    self.shutdown.parties()
  }

  /// The shared resources, which this value keeps alive for as long as the deployment runs.
  #[inline]
  #[must_use]
  pub fn context(&self) -> &Resources {
    &self.ctx
  }

  /// **THE ROOT-KEY REGISTRIES** this world coordinates through — where a query face reads a root's
  /// state and a command face retires or restores one.
  ///
  /// The SAME object every body in this world is holding, which is the whole point of it: a
  /// retirement asked for here is seen by the residents, and a count a resident makes is seen here.
  /// [`Registries::of`](crate::Registries::of) is the typed door onto one family's table, and it
  /// answers `None` for a family nothing in this deployment has opened.
  ///
  /// A BORROW rather than a handout, on [`context`](Self::context)'s own reasoning: the world keeps
  /// the tables alive for as long as it runs, and a caller that needs one past the world's own life
  /// takes the family's [`Arc`] out of `of` instead.
  #[inline]
  #[must_use]
  pub fn registries(&self) -> &Registries {
    &self.registries
  }

  /// **INSTALL the root-key registries on a schema being built** — the GraphQL registry face's own
  /// door, [`SqlDoor::install`](crate::graphql::SqlDoor::install)'s exact convention one seat over:
  ///
  /// ```ignore
  /// let schema = app
  ///   .install_registries(Schema::build(
  ///     MediaQuery::default(),
  ///     RegistryMutationRoot::default(),
  ///     EmptySubscription,
  ///   ))
  ///   .finish();
  /// ```
  ///
  /// A named act rather than a bare `.data(Arc::clone(…))`, because [`registries`](Self::registries)
  /// deliberately hands out a BORROW and nothing else — see that method's own note — while a schema's
  /// context data has to hold an owned, cloneable handle. This is the one door that clones the
  /// [`Arc`] on the world's behalf, and it hands the clone straight into the builder's own opaque
  /// storage rather than back to the caller, which is what keeps the "borrow, not a handout" rule
  /// true of every OTHER door this type has.
  #[cfg(feature = "async-graphql")]
  #[must_use]
  pub fn install_registries<Q, M, S>(
    &self,
    builder: async_graphql::SchemaBuilder<Q, M, S>,
  ) -> async_graphql::SchemaBuilder<Q, M, S>
  where
    Q: async_graphql::ObjectType + 'static,
    M: async_graphql::ObjectType + 'static,
    S: async_graphql::SubscriptionType + 'static,
  {
    builder.data(Arc::clone(&self.registries))
  }

  /// How many sources are admitting work.
  #[inline]
  #[must_use]
  pub fn sources(&self) -> usize {
    self.sources.len()
  }

  /// **THE INTAKE DOOR onto the head node `N`** — a sending half of its inbox, or `None` where this
  /// deployment does not launch it.
  ///
  /// A dataflow head is fed from OUTSIDE the graph, and this is where the outside reaches it. The
  /// deployment's own arrangement opens the edge; what a caller needs is a handle onto it, typed by
  /// `N`'s own input so nothing has to be said about the message twice.
  ///
  /// It CLONES rather than takes, so an application may hold several — a signal handler and a
  /// request loop feeding one head is ordinary. What that costs is stated in
  /// [`shutdown`](Self::shutdown) and is the same for every sender: a live handle is a live producer,
  /// and a head with one has not been told its stream is over. The app releases its OWN copies where
  /// it releases the rest of the framework's halves, so a caller who dropped theirs is not waiting on
  /// this value's.
  ///
  /// `None` for a node this deployment does not run, and `None` too for one that is not a head: a
  /// node the graph itself feeds has no door for anybody else to open.
  ///
  /// # ONE DOOR FOR ALL THREE KINDS, and `app.feeder::<Head>()` is the whole of what a caller spells
  ///
  /// `N`'s input is `<Cell<N> as Mount<N>>::In` — the CELL its own declaration named, so the pair
  /// word picks which face's row the message is read off and the mode word picks which half of that
  /// pair. Both are read off the node rather than taken as parameters, which is three fixes in one
  /// and each was a defect while a face parameter existed: the turbofish is one word again (a
  /// turbofish takes all of a function's generics or none, so `feeder::<Head, _>()` was the toll a
  /// parameter nobody chose charged every call); a type wearing BOTH faces is no longer `E0283`,
  /// because the declaration decides and inference has nothing left to guess; and a caller who named
  /// the WRONG face used to get a silently `None`-answering downcast — a live door reported absent —
  /// where the mismatch is now unspellable.
  ///
  /// It was TWO doors, and the second was the streaming pair's row spelled apart because no bound
  /// could name both: `Mount` was indexed by a CONST then, and a const argument may not depend on a
  /// generic parameter on stable, so the cell was writable in an emission and in no signature at
  /// all. [`Declared::Pair`](super::Declared::Pair) is a seat now, the cell is two ordinary
  /// projections, and a streaming head is fed through this door exactly as a buffered one is.
  ///
  /// # What the merge COST, and why it costs no caller
  ///
  /// The obligation moved off a face row and onto the mount predicate, which is wider by
  /// `N: Send + 'static`, a `Clone` output and an erasable error. Nothing loses a door to it: the
  /// map's entries are put there by [`Mount::feeder`](super::Mount::feeder), so an entry exists only
  /// for a node that went through a cell — and a hand-wired arrangement pays the same three at the
  /// ignition, which spawns an engine by value over a [`Downstream`](crate::Downstream) that fans
  /// one output to N edges.
  #[inline]
  #[must_use]
  pub fn feeder<N>(&self) -> Option<Outbox<ItemId, <Cell<N> as Mount<N>>::In>>
  where
    N: Declared,
    Cell<N>: Mount<N>,
  {
    self
      .feeders
      .get(&TypeId::of::<N>())
      .and_then(|feeder| feeder.downcast_ref::<Outbox<ItemId, <Cell<N> as Mount<N>>::In>>())
      .cloned()
  }

  /// How many heads this world offers a door onto.
  #[inline]
  #[must_use]
  pub fn feeders(&self) -> usize {
    self.feeders.len()
  }

  /// **THE MOUNTED ORIGIN `S`** — the command line it is told things down and the handle that stops
  /// it early, or `None` where this deployment does not mount it.
  ///
  /// [`feeder`](Self::feeder)'s twin one tier over, and the mirror image of it: a feeder is the door
  /// INTO a head this world runs, and this is the two ends of a head that runs ITSELF. What is
  /// missing from it is a [`Yielded`](crate::Yielded), and its absence is the bridge — an origin
  /// mounted by a graph root feeds its consumer's inbox directly, so there is no line for a
  /// deployment to drain.
  ///
  /// It BORROWS rather than taking or cloning, and that is the [`Stopper`](crate::Stopper)'s rule
  /// rather than a choice: letting go of one says the stop, so a handle a caller could take out of
  /// this world would be a handle that stopped the origin when the caller was done with it. What a
  /// caller usually wants is a copy of the [`Commands`](crate::Commands) line, which is `Clone` and
  /// is reached through the borrow.
  ///
  /// # It is keyed BY TYPE, exactly as an intake door is
  ///
  /// A caller holds the origin's own type and never the deployment's word for it — see
  /// [`Ignition::origin_kept`](super::Ignition::origin_kept), which is the end that fills the map.
  #[inline]
  #[must_use]
  pub fn origin<S>(&self) -> Option<&super::Bridged<super::Ordered<S>>>
  where
    S: crate::DeclaredOrigin + super::Lived<<S as crate::DeclaredOrigin>::Mode>,
  {
    self
      .origins
      .get(&TypeId::of::<S>())
      .and_then(|origin| origin.downcast_ref::<super::Bridged<super::Ordered<S>>>())
  }

  /// How many origins this world mounted.
  #[inline]
  #[must_use]
  pub fn origins(&self) -> usize {
    self.origins.len()
  }

  /// **THE MOUNTED LANE for the streaming node `N`** — the lane, the inbox its upstreams fill and the
  /// shutdown enrolment, or `None` where this deployment does not launch it.
  ///
  /// It TAKES rather than clones, which is the one place it differs from
  /// [`feeder`](Self::feeder) and the difference is the thing itself: an intake door is a sending
  /// half and an application may hold several, and a lane is a set of warm bodies that exactly one
  /// party may drive. A second call answers `None`.
  ///
  /// # What the caller owes it, and it is the whole of the streaming contract's open end
  ///
  /// THE LOOP. No ignition door runs a lane's `admit` / `tend` cycle — the boundary the streaming
  /// contract was ruled to end at — so what comes back is a mounted lane that is not yet running, and
  /// the party that took it is the party that drives it: deliveries taken off the inbox and handed to
  /// [`admit`](crate::StreamLane::admit), the lane [`tend`](crate::StreamLane::tend)ed, and the
  /// enrolment settled when it is finished. Every edge is already open and every seat already
  /// filled; what is not here is the cycle.
  ///
  /// # Why the app held the ACT of building one rather than the lane
  ///
  /// A `StreamLane<…, Async>` is `!Send` by [`AsyncStreamOperator`](crate::AsyncStreamOperator)'s own
  /// design, so an [`App`] carrying one would be an [`App`] no spawn could take — see
  /// [`Wiring::lane_mount`](super::Wiring::lane_mount), which holds the parts instead. The lane is
  /// minted HERE, in the hands that will drive it, which is also the only place it ever needed to
  /// exist.
  ///
  /// # The MODE is the DECLARATION's, exactly as it is at [`feeder`](Self::feeder)
  ///
  /// `app.lane::<Windows>()` is the whole of what a caller spells: the face is read off `N`'s own
  /// `Declared::Mode`, so a body wearing both streaming faces comes back at the one its word chose
  /// rather than being `E0283` at a call that had already said.
  #[must_use]
  pub fn lane<N>(&mut self) -> Option<MountedLane<N, Thread, <N as Declared>::Mode>>
  where
    N: Declared + Streams<<N as Declared>::Mode> + Send + 'static,
    <N as Streams<<N as Declared>::Mode>>::In: Send + 'static,
    <N as Streams<<N as Declared>::Mode>>::Out: Send + 'static,
  {
    let (held, enrolled) = self.lanes.remove(&TypeId::of::<N>())?;
    let mount = held
      .downcast::<LaneMount<N, Thread, <N as Declared>::Mode>>()
      .ok()?;
    Some(mount.build(enrolled))
  }

  /// How many mounted lanes are still waiting for a party to drive them.
  #[inline]
  #[must_use]
  pub fn lanes(&self) -> usize {
    self.lanes.len()
  }

  /// Park until the world ends OF ITSELF — the daemon's last line.
  ///
  /// It announces nothing and stops nothing: what it waits for is every party finishing on its own,
  /// which happens when the arrangement runs out of work that can reach it — every source exhausted,
  /// every edge closed behind it. A deployment fed by a live change feed never gets there, and that
  /// is the point: the app parks here until a registered exit source speaks
  /// ([`halt_on`](Self::halt_on)) and the caller then calls [`shutdown`](Self::shutdown). The App
  /// natively accepts the registrations; the handlers are still the app's to supply.
  ///
  /// It takes `&self`, so parking is not the end of the value: the report is still to be had by
  /// asking for one afterwards.
  ///
  /// # It also ends where a REGISTERED EXIT SOURCE speaks
  ///
  /// [`halt_on`](Self::halt_on) is the seat, and this is the wait it ends. Nothing is announced and
  /// nothing is stopped by the source firing — the park returns and the caller decides, which is
  /// usually [`shutdown`](Self::shutdown). [`halted`](Self::halted) is what says WHICH of the two
  /// endings this was, for a caller that wants to tell a wound-down world from a finished one.
  ///
  /// # It is also the DRAIN-FIRST door, and a finite origin is what wants one
  ///
  /// [`shutdown`](Self::shutdown) tells every mounted origin to wind down, so an origin with items
  /// left ends [`Fin::Stopped`](crate::Fin::Stopped) where it would have ended
  /// [`Spent`](crate::Fin::Spent) — an ordinary ending, and the earliest honest one. A caller that
  /// wants the whole of what a finite origin produces parks HERE first and stops afterwards, which
  /// costs nothing and has no race in it: the wait ends exactly when the last party finished.
  pub fn until_stopped(&self) {
    // The latch is read BEFORE the park and again after every wake, which is the other half of
    // `halt_on`'s race protocol: a source that fired before this call was even made must not be
    // waited past, and one that fires while the park holds rings the bell this wakes on.
    while !self.shutdown.is_finished() && !self.halted() {
      // A registry with nobody in it cannot be waited on, and spinning on it would be the one way
      // to turn an empty deployment into a busy one.
      if !self.shutdown.park(None) {
        break;
      }
    }
  }

  /// Wind the world down, waiting at most `deadline` for it to settle.
  ///
  /// `None` waits for as long as it takes, which is the honest default for a deployment whose nodes
  /// are trusted to finish: what holds the wait open is work still in flight, and abandoning it is
  /// what a deadline is for. Note that a handle the APP still holds — a feeder into a head node, a
  /// door onto a query arm — holds the wave open too, because a node with a live sender has not been
  /// told the stream is over. A negative deadline is an expired one and waits for nothing.
  ///
  /// # The sequence
  ///
  /// 1. every registered party hears *wind down*, and every mounted ORIGIN hears it on BOTH halves
  ///    of its own stop line — the launch's, and the handle this world kept — so an origin is told
  ///    before anything else in this list happens. See
  ///    [`Ignition::origin_declared`](super::Ignition::origin_declared) for why an origin is told
  ///    rather than announced to, and [`until_stopped`](Self::until_stopped) for what a caller takes
  ///    when it wants a FINITE origin's last item instead of its earliest honest ending;
  /// 2. the sources stop admitting, LAST STARTED FIRST — and the ROOT-KEY REGISTRY's DRIVER is one
  ///    of them, which is where its own place in this sequence comes from: it is released after the
  ///    origins that push keys into it and before the edges it writes through are let go of, so a
  ///    pending batch is dropped rather than shovelled into a graph that is winding down. See
  ///    [`RegistryDriver`](crate::RegistryDriver), whose note argues that choice;
  /// 3. the framework releases its own halves of the edges — the wave's first domino;
  /// 4. the wait, bounded by `deadline`;
  /// 5. the settle seat is read ONCE, which is what decides both of the report's classes at
  ///    the same instant — see [`Stopped`], whose disjointness this step is;
  /// 6. where everyone settled: the goodbyes each body handed back at its settlement are said, LAST
  ///    ENROLLED FIRST, never interrupted by one another's refusals;
  /// 7. the resources are released after all of them, the engines are joined, and the report says
  ///    what happened.
  ///
  /// The engines are joined AFTER the chain and not before, and that is the parked road's own
  /// requirement: a thread holding a `!Send` goodbye does not return until the chain has told it to
  /// go, so joining first would be waiting for a value nothing had yet released. What is joined
  /// before the chain is the ASYNC bodies, whose goodbyes travelled — a teardown may flush the very
  /// store a task is still writing to.
  ///
  /// Where the deadline ran out, steps 6 and 7 are the abort: nothing is joined, no goodbye is said,
  /// and the report names every party that had not answered and every goodbye that had been handed
  /// back and was never told to be said.
  #[must_use]
  pub fn shutdown(self, deadline: Option<jiff::SignedDuration>) -> Stopped {
    let settling = match deadline {
      // A negative span is a deadline that passed before it was given, which is a wait of nothing
      // rather than a wait of its magnitude.
      Some(deadline) => Settling::Within(Duration::try_from(deadline).unwrap_or(Duration::ZERO)),
      None => Settling::Forever,
    };
    self.stop(settling)
  }

  /// Stop now, and do not wait to hear how it went.
  ///
  /// The same announcement and the same releases as [`shutdown`](Self::shutdown), and none of the
  /// waiting: what comes back names whoever had already settled by the time it was asked, and every
  /// enrolled goodbye as one that was never said. Nothing is torn down explicitly here on purpose —
  /// a goodbye is an ASYNC act against a world that may still be moving, and a stop that would not
  /// wait for its own nodes must not wait for their stores either.
  #[must_use]
  pub fn abort(self) -> Stopped {
    self.stop(Settling::Never)
  }

  /// The announcement, the releases, the wait, and the report — see [`shutdown`](Self::shutdown).
  fn stop(self, settling: Settling) -> Stopped {
    let Self {
      mut feeders,
      mut lanes,
      origins,
      mut sources,
      halts,
      mut senders,
      bodies,
      tasks,
      teardowns,
      shutdown,
      halted: _,
      taps,
      ctx,
      // NAMED AND DROPPED HERE, at the head of the sequence rather than at the end of it, and the
      // difference from the resource map is what the naming is for: a resource is a HANDLE a node
      // may still be using, so it goes last; the registries are a COORDINATION CACHE that nothing
      // durable depends on, and every body holding one keeps its own `Arc` alive for exactly as
      // long as that body runs. So this world letting go of its handle is the world letting go, and
      // the tables outlive it precisely as long as somebody is still counting into them.
      registries: _,
      indexer: _,
    } = self;

    // 1. THE BROADCAST. A party that reads its own announcement stops taking new work now; a
    // resident reads nothing and is told by its edges instead, which is the same instruction
    // arriving by the road the topology already provides.
    for party in shutdown.parties() {
      party.announce();
    }
    // 1b. AND EVERY MOUNTED ORIGIN hears the same instruction on the one road it listens to. An
    // origin's body is inside `run` for its whole life, so it never reads the announcement above —
    // its `ShutdownSignal` is where the wind-down reaches it, and this is the launch's own half of that line.
    // Without it an infinite origin whose handle a deployment kept would never be told anything, and
    // the wait below would be a wait for a party that had no way of finishing.
    //
    // SAID rather than left to the drop at the end of this function, so the instruction goes out
    // beside every other party's rather than after the wait it is supposed to end.
    for halt in &halts {
      halt.announce();
    }
    // 1c. AND THE ORIGINS' OWN HALVES GO, which is the same instruction said down the other end of
    // the same lines: a `Bridged` owns a `Stopper` and a stopper says the stop as it goes, so
    // releasing the map is telling every mounted origin to wind down. Said HERE — before the intake
    // stops admitting, before the framework lets go of its edges, and before the wait — so ORIGINS
    // ARE STOPPED FIRST is a step of this sequence rather than a consequence of where a field
    // happens to sit in the struct. The two halves do not fight: the message coalesces, and an
    // origin already told hears the second word as the no-op it is.
    drop(origins);
    // 2. INTAKE STOPS, last started first — the reverse of the order the ignition started them in.
    while let Some(source) = sources.pop() {
      drop(source);
    }
    // 3. And the framework lets go of the edges it was holding open — the feeders among them, since
    // an intake door this world still holds is a live producer on a head node's inbox — which is what
    // lets a node with no live producer see that its stream has ended.
    feeders.clear();
    // A lane NOBODY TOOK goes with them, and it is the same fact one pair over: an unspent mount
    // holds a downstream set of live sending halves, so a world that stopped while still carrying
    // one would be holding its own edges open against the very ending it announced.
    //
    // Its party SETTLES rather than merely vanishing, which is the ignition's own posture for a body
    // that never ran: nobody asked for this lane, so nothing drove it, and a report naming it
    // unanswered would be reporting a loop that was never started as a loop that hung.
    for (_node, (mount, enrolled)) in lanes.drain() {
      drop(mount);
      enrolled.settle();
    }
    senders.clear();

    // A wait that ended with somebody still working is an OVERRUN only where a deadline is what
    // ended it: an abort names the same unanswered parties and ran out of nothing.
    let overran = !Self::settle(&shutdown, &settling) && matches!(settling, Settling::Within(_));
    // 5. THE SETTLE SEAT, READ ONCE — the whole membership of the report, decided here and nowhere
    // else. The chain is in ENROLMENT order (the parties as the wiring registered them, then
    // whatever the ignition still held) and the walks below say it backwards; the names beside it
    // are whoever handed nothing back. Both come out of one take per party, which is what keeps a
    // party out of the other class however it was scheduled — see
    // [`collected`](super::teardown::collected).
    let Collected {
      mut chain,
      unsettled,
    } = collected(&shutdown);
    let settled = shutdown.len() - unsettled.len();

    // 6. THE GOODBYES, and only where the world actually settled. An abort says none by contract,
    // and an overrun says none because a value's teardown may be the very store a node that did not
    // answer is still writing to.
    let untorn = if unsettled.is_empty() && !matches!(settling, Settling::Never) {
      chain.extend(teardowns);
      let untorn = block_on(async {
        // The bodies the framework spawned onto the app's runtime, awaited FIRST: a teardown may
        // flush the very store a task is still writing to, which is the ordering the abort path
        // refuses to guess at and this path can guarantee.
        joined(tasks).await;
        let mut untorn = farewell(chain, &taps).await;
        // 7. THE RESOURCES, last of everything — every node that held a handle has now said its own
        // goodbye and gone, which is what makes the unsealing inside a fair question rather than a
        // race with the deployment it belongs to.
        untorn.extend(released(ctx, &taps).await);
        untorn
      });
      // The THREADS last of all, and only now: a parked body does not return until its goodbye has
      // been said, so joining before the chain would be waiting for a value the chain has not yet
      // told to go. Its party settled long ago and a body settles as its last act, which is what
      // makes this the formality that makes a returned `Stopped` mean the engines are gone rather
      // than merely finished.
      for engine in bodies {
        let _ = engine.join();
      }
      untorn
    } else {
      // The tasks are DETACHED rather than awaited, which is what an abort is: a stop that would not
      // wait for its own nodes must not wait for their engines either. Dropping a join detaches its
      // task exactly as dropping a thread's handle leaves the thread running — and the threads
      // below are left the same way, a parked one waking to find nobody coming and dropping its
      // value where it stands.
      drop(tasks);
      drop(bodies);
      let mut untorn: Vec<Untorn> = chain
        .into_iter()
        .chain(teardowns)
        .map(Farewell::unsaid)
        .collect();
      // The enrolled resources are named for the same reason and let go of the shipped way: nothing
      // is unsealed and nothing is said, so all the report carries is who was enrolled.
      untorn.extend(
        ctx
          .enrolled()
          .map(|resource| Untorn::untold(resource.as_str())),
      );
      drop(ctx);
      untorn
    };

    Stopped {
      settled,
      unsettled,
      untorn,
      overran,
    }
  }

  /// Wait for every party to FINISH, and answer whether they all did within `settling`.
  fn settle(shutdown: &Shutdown, settling: &Settling) -> bool {
    match settling {
      Settling::Never => shutdown.is_finished(),
      Settling::Forever => {
        while !shutdown.is_finished() {
          if !shutdown.park(None) {
            break;
          }
        }
        shutdown.is_finished()
      }
      Settling::Within(within) => {
        let end = Instant::now() + *within;
        loop {
          if shutdown.is_finished() {
            return true;
          }
          let now = Instant::now();
          // The remaining budget, recomputed each pass: the deadline is over the WHOLE settlement
          // and not over each party's share of it.
          let Some(left) = end.checked_duration_since(now) else {
            return false;
          };
          if !shutdown.park(Some(left)) {
            // The park ran out. One more look, because a party may have finished between the wake
            // and this line, and a report that named it unanswered would be reporting a race.
            return shutdown.is_finished();
          }
        }
      }
    }
  }
}

/// What a stopped world settled — and what it did not.
///
/// The ruled report has three classes of unanswered, and two of them are here: the UN-SETTLED
/// parties, by name, and the UN-TORN goodbyes, each with its own refusal or with none where it was
/// never said. The third — un-flushed engines — has nothing to read in this crate today: a write
/// lane commits per delivery and no engine handle outlives the body that holds it, so there is
/// nothing a launch could flush and nothing it could report having failed to. The class is named
/// here rather than invented as an always-empty list.
///
/// # ONE PARTY, ONE CLASS — naming it twice would be the report inventing a fact
///
/// A party is named in [`unsettled`](Self::unsettled) or it hands over a goodbye that
/// [`untorn`](Self::untorn) may carry a row for, and never in both. That is the settle seat read
/// honestly: a goodbye reaches the chain through a party's own completion, so a party that never
/// completed never handed one over — and a party that DID is answered rather than abandoned,
/// whatever it was doing when the stop began.
///
/// It is a fact the stop ENFORCES rather than a schedule it hopes for. Both classes are written
/// from a single take per party — see [`collected`](super::teardown::collected) — so there is no
/// instant between them for a party to settle in, and no load at which the two can disagree. The
/// arithmetic behind [`settled`](Self::settled) rests on that same reading: the registry knew `N`
/// before anything started, and every one of the `N` is in exactly one of *answered* and
/// *named here*.
#[derive(Debug)]
pub struct Stopped {
  settled: usize,
  unsettled: Vec<Utf8Bytes>,
  untorn: Vec<Untorn>,
  overran: bool,
}

impl Stopped {
  /// How many parties answered.
  #[inline]
  #[must_use]
  pub const fn settled(&self) -> usize {
    self.settled
  }

  /// Who did not — a party still working when the wait ended, or one that vanished without firing.
  ///
  /// The registry knows exactly who because it knew N before anything started, so this is the whole
  /// list and never a sample.
  #[inline]
  // NO `#[must_use]`, alone among this type's readers, and the absence is deliberate rather than an
  // oversight to repair: the return is an `Iterator`, which carries the attribute ITSELF, so a
  // second one here tells a caller nothing the first had not. `clippy::double_must_use` refuses the
  // pair outright — see `ci/nightly-divergences.md` §6.1 for the toolchain window in which that
  // refusal reached an `impl Trait` return.
  pub fn unsettled(&self) -> impl ExactSizeIterator<Item = &NodeName> {
    self.unsettled.iter().map(|name| NodeName::new(name))
  }

  /// The goodbyes that were not said cleanly, or at all.
  #[inline]
  #[must_use]
  pub fn untorn(&self) -> &[Untorn] {
    &self.untorn
  }

  /// Whether the deadline ran out before everyone had finished.
  #[inline]
  #[must_use]
  pub const fn overran(&self) -> bool {
    self.overran
  }

  /// Whether everything answered and every goodbye was said.
  #[inline]
  #[must_use]
  pub fn is_clean(&self) -> bool {
    self.unsettled.is_empty() && self.untorn.is_empty()
  }
}

/// Written rather than derived, for [`LaunchError`](super::LaunchError)'s reason: what a report
/// carries is rows, and rendering rows as one line buries them under commas. The first line is the
/// summary and each row after it says one thing that did not happen.
impl core::fmt::Display for Stopped {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    write!(f, "stopped: {} settled", self.settled)?;
    if self.overran {
      write!(f, ", the deadline ran out")?;
    }
    for name in &self.unsettled {
      write!(f, "\n  - `{}` did not answer", name.as_str())?;
    }
    for untorn in &self.untorn {
      write!(f, "\n  - {untorn}")?;
    }
    Ok(())
  }
}