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

use std::{
  io,
  sync::{Arc, Mutex},
  time::Instant,
};

use crate::{
  AsyncTeardown, ChannelGraph, Delivery, DriverKind, Effect, Emitter, Enablement, FanoutKind,
  GraphBuilder, Item, ItemId, LaunchError, LifecycleTap, NodeId, NodeWiring, Operator, Party,
  Payload, Plan, RecordingTap, Station, Taps, Wired, ack_channel,
};

use super::Ignition;

/// Everything the world did, in the order it did it — starts, items, stops and goodbyes on ONE
/// list, because what these tests claim is mostly about order.
type Record = Arc<Mutex<Vec<String>>>;

fn record() -> Record {
  Arc::new(Mutex::new(Vec::new()))
}

fn note(record: &Record, what: impl Into<String>) {
  record.lock().expect("the world's record").push(what.into());
}

fn seen(record: &Record) -> Vec<String> {
  record.lock().expect("the world's record").clone()
}

struct Shout;

/// The facts a hand-wired node states — the mount predicate is `O: Declared + Driven<O::Mode>`, so
/// a node that is not emitted says what it is too, in the mode a bare declaration has.
macro_rules! declared {
  ($name:ident) => {
    impl crate::Declared for $name {
      const EFFECT: crate::Effect = crate::Effect::Pure;

      type Channels = crate::Unchanneled;
      type Mode = crate::Block;
      type Options = ();
      type Pair = crate::Buffered;
      type Wires<O> = crate::Downstream<O>;
      type Attribution<O> = ();
    }
  };
}

declared!(Shout);

impl Operator for Shout {
  type Error = Infallible;
  type In = String;
  type Out = String;

  fn accept(
    &mut self,
    _ctx: &Context,
    delivery: Delivery<Self::In>,
    emitter: &mut Emitter<String>,
  ) -> Result<(), Self::Error> {
    for item in delivery.into_items() {
      let item = item.into_value();
      emitter.emit(item.to_uppercase());
    }
    Ok(())
  }
}

/// The leaf: it writes down what reached it, so the wave can be read off the far end.
struct Keeping {
  record: Record,
}

declared!(Keeping);

impl Operator for Keeping {
  type Error = Infallible;
  type In = String;
  type Out = String;

  fn accept(
    &mut self,
    _ctx: &Context,
    delivery: Delivery<Self::In>,
    _emitter: &mut Emitter<String>,
  ) -> Result<(), Self::Error> {
    for item in delivery.into_items() {
      let item = item.into_value();
      note(&self.record, item);
    }
    Ok(())
  }
}

/// A body that writes its own name down when the wave has passed through it.
///
/// The note is written by its `Drop`, which the ignition runs on the body's OWN engine after the
/// loop returns and before the party settles — so the list these leave behind is the order the wave
/// actually travelled in.
struct Passing {
  name: &'static str,
  record: Record,
}

declared!(Passing);

impl Operator for Passing {
  type Error = Infallible;
  type In = String;
  type Out = String;

  fn accept(
    &mut self,
    _ctx: &Context,
    delivery: Delivery<Self::In>,
    emitter: &mut Emitter<String>,
  ) -> Result<(), Self::Error> {
    for item in delivery.into_items() {
      let item = item.into_value();
      emitter.emit(item);
    }
    Ok(())
  }
}

impl Drop for Passing {
  fn drop(&mut self) {
    note(&self.record, format!("gone {}", self.name));
  }
}

fn passing(name: &'static str, record: &Record) -> Passing {
  Passing {
    name,
    record: Arc::clone(record),
  }
}

/// A value with a goodbye to say.
struct Says {
  name: &'static str,
  record: Record,
}

impl AsyncTeardown for Says {
  async fn teardown(self) -> Result<(), Box<dyn Error + Send + Sync>> {
    note(&self.record, format!("goodbye {}", self.name));
    Ok(())
  }
}

/// A source: it notes when it is STARTED, and again when it is stopped by being dropped.
struct Admitting {
  name: &'static str,
  record: Record,
}

impl Drop for Admitting {
  fn drop(&mut self) {
    note(&self.record, format!("stopped {}", self.name));
  }
}

fn admitting(name: &'static str, record: &Record) -> Admitting {
  note(record, format!("started {name}"));
  Admitting {
    name,
    record: Arc::clone(record),
  }
}

/// `shout → titles`, one edge, both nodes on `driver`, both launched.
fn pair(driver: DriverKind) -> ChannelGraph {
  let mut builder = GraphBuilder::new();
  let shout = builder.source::<Shout>("shout", driver);
  let titles = builder.node::<Shout>("titles", driver);
  builder.edge(&shout, &titles, FanoutKind::Broadcast);
  builder.validate().expect("one edge validates")
}

fn wired(driver: DriverKind) -> Wired {
  Plan::new(pair(driver))
    .with_enablement(Enablement::new().launching("shout").launching("titles"))
    .wiring(NodeId::new(1), NodeWiring::new(Effect::Lands).landing())
    .validate()
    .expect("the deployment checks out")
}

/// A recorder, and the composite that carries it into every walk this stage runs.
fn watching() -> (Arc<RecordingTap>, Taps) {
  let tap = Arc::new(RecordingTap::new());
  let taps = Taps::new().with(Arc::clone(&tap) as Arc<dyn LifecycleTap>);
  (tap, taps)
}

/// THE SECOND BODY'S ENGINE, refused.
///
/// The machine turning a thread down is not a thing a test can ask for, so what stands in for it is
/// the refusal that arm builds — the same [`LaunchError::Ignition`] under the same node's name — and
/// what the tests below spend is the same [`Ignition::unwind`] the arm spends with it.
fn refused_engine() -> LaunchError {
  LaunchError::ignition("titles", io::Error::from(io::ErrorKind::WouldBlock))
}

#[test]
fn the_bodies_get_their_engines_and_the_sources_start_last() {
  let record = record();
  let wired = wired(DriverKind::Thread);
  let mut wiring = wired.create().wire();
  let head = wiring
    .inbox::<String>(NodeId::new(0))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let leaf = wiring
    .inbox::<String>(NodeId::new(1))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let (head, head_party) = wiring
    .resident(NodeId::new(0), Shout, head)
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let (leaf, leaf_party) = wiring
    .resident(
      NodeId::new(1),
      Keeping {
        record: Arc::clone(&record),
      },
      leaf,
    )
    .expect("nothing to refuse")
    .expect("the deployment launches it");

  let mut ignition = wiring.into_assembly().ignite();
  let intake = Arc::clone(&record);
  ignition.source(move || admitting("intake", &intake));
  let clock = Arc::clone(&record);
  ignition.source(move || admitting("clock", &clock));
  ignition.resident(head, head_party).expect("its engine");
  ignition.resident(leaf, leaf_party).expect("its engine");

  assert_eq!(ignition.bodies(), 2);
  assert_eq!(ignition.sources(), 2);
  assert!(
    seen(&record).is_empty(),
    "a source registered before the bodies still has not started"
  );

  let running = ignition.into_app::<()>();
  assert_eq!(
    seen(&record),
    ["started intake", "started clock"],
    "and they start here, in registration order, once every body has an engine"
  );
  assert_eq!(running.sources(), 2);

  let stopped = running.shutdown(None);
  assert!(stopped.is_clean());
  assert_eq!(
    seen(&record),
    [
      "started intake",
      "started clock",
      "stopped clock",
      "stopped intake"
    ],
    "last on, first off"
  );
}

#[test]
fn a_fed_world_settles_by_closure_alone_and_loses_nothing_that_was_in_flight() {
  // THE WAVE, and the claim that nothing orchestrates it: the framework announces, stops admitting
  // and releases its own halves of the edges, and everything after that is data-flow causality —
  // the head's inbox goes quiet, the head returns and its outbox goes with it, the leaf sees a
  // closed and drained inbox and returns too. No `drain` is called on anybody, and none exists to
  // call: what is queued is still delivered because a closed channel is drained before it ends.
  let record = record();
  let wired = wired(DriverKind::Thread);
  let mut wiring = wired.create().wire();
  let head_inbox = wiring
    .inbox::<String>(NodeId::new(0))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let leaf_inbox = wiring
    .inbox::<String>(NodeId::new(1))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let feed = wiring
    .outbox::<String>(NodeId::new(0))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let (head, head_party) = wiring
    .resident(NodeId::new(0), Shout, head_inbox)
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let (leaf, leaf_party) = wiring
    .resident(
      NodeId::new(1),
      Keeping {
        record: Arc::clone(&record),
      },
      leaf_inbox,
    )
    .expect("nothing to refuse")
    .expect("the deployment launches it");

  let mut ignition = wiring.into_assembly().ignite();
  ignition.resident(head, head_party).expect("its engine");
  ignition.resident(leaf, leaf_party).expect("its engine");
  ignition.teardown(
    "pool",
    Says {
      name: "pool",
      record: Arc::clone(&record),
    },
  );
  ignition.teardown(
    "device",
    Says {
      name: "device",
      record: Arc::clone(&record),
    },
  );
  let running = ignition.into_app::<()>();

  // The app's own feeder, which is the source this arrangement has: five items, then it lets go.
  for item in 0..5u64 {
    let (ack, _answers) = ack_channel();
    feed
      .deliver(Delivery::new(
        Payload::One(Item::new(ItemId::new(item), format!("item-{item}"))),
        ack,
      ))
      .expect("the head is listening");
  }
  drop(feed);

  let stopped = running.shutdown(None);

  assert_eq!(stopped.settled(), 2, "both bodies answered");
  assert!(stopped.is_clean());
  let seen = seen(&record);
  assert_eq!(
    seen[..5],
    ["ITEM-0", "ITEM-1", "ITEM-2", "ITEM-3", "ITEM-4"],
    "everything in flight when the wave began still reached the far end"
  );
  assert_eq!(
    seen[5..],
    ["goodbye device", "goodbye pool"],
    "and the goodbyes come after the last party settled, last enrolled first"
  );
}

#[test]
fn a_world_nobody_is_feeding_ends_of_itself() {
  let wired = wired(DriverKind::Thread);
  let mut wiring = wired.create().wire();
  let head = wiring
    .inbox::<String>(NodeId::new(0))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let leaf = wiring
    .inbox::<String>(NodeId::new(1))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let (head, head_party) = wiring
    .resident(NodeId::new(0), Shout, head)
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let (leaf, leaf_party) = wiring
    .resident(NodeId::new(1), Shout, leaf)
    .expect("nothing to refuse")
    .expect("the deployment launches it");

  let mut assembly = wiring.into_assembly();
  // The only thing holding the head's inbox open is the framework's own half, and this releases it
  // before anything starts — so the world has nothing that could ever feed it.
  assembly.close();
  let mut ignition = assembly.ignite();
  ignition.resident(head, head_party).expect("its engine");
  ignition.resident(leaf, leaf_party).expect("its engine");
  let running = ignition.into_app::<()>();

  let began = Instant::now();
  running.until_stopped();
  assert!(
    began.elapsed() < Duration::from_secs(5),
    "the wave needs nobody to conduct it"
  );
  assert!(running.parties().iter().all(Party::settled));
  assert!(running.shutdown(None).is_clean());
}

#[test]
fn the_order_emerges_from_the_edges_rather_than_from_a_list() {
  // NOTHING ORCHESTRATES THE WAVE. The framework releases its own halves of the edges and stops
  // there; the head sees a quiet inbox, returns, and its outboxes go with it; only THEN does the
  // leaf's inbox disconnect, and only then can the leaf return. So upstream finishes before
  // downstream — by data-flow causality, with no list of nodes anywhere and no `drain` called on
  // anybody.
  let record = record();
  let wired = wired(DriverKind::Thread);
  let mut wiring = wired.create().wire();
  let head_inbox = wiring
    .inbox::<String>(NodeId::new(0))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let leaf_inbox = wiring
    .inbox::<String>(NodeId::new(1))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let feed = wiring
    .outbox::<String>(NodeId::new(0))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let (head, head_party) = wiring
    .resident(NodeId::new(0), passing("head", &record), head_inbox)
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let (leaf, leaf_party) = wiring
    .resident(NodeId::new(1), passing("leaf", &record), leaf_inbox)
    .expect("nothing to refuse")
    .expect("the deployment launches it");

  let mut ignition = wiring.into_assembly().ignite();
  ignition.resident(head, head_party).expect("its engine");
  ignition.resident(leaf, leaf_party).expect("its engine");
  let running = ignition.into_app::<()>();

  let (ack, _answers) = ack_channel();
  feed
    .deliver(Delivery::new(
      Payload::One(Item::new(ItemId::new(0), "one".to_owned())),
      ack,
    ))
    .expect("the head is listening");
  drop(feed);

  assert!(running.shutdown(None).is_clean());
  assert_eq!(
    seen(&record),
    ["gone head", "gone leaf"],
    "upstream closure is what ends the node below it"
  );
}

#[test]
fn a_launch_that_fails_after_the_first_body_started_stops_it_before_it_reports() {
  // THE FAILED-LAUNCH UNWIND, at the moment the ruling is about: `shout` has an engine, `titles`'
  // engine is the one the machine refuses, and a bare bail there would hand back an error while a
  // thread of this deployment's is still running — with nobody outside holding anything that could
  // reach it.
  let record = record();
  let (tap, taps) = watching();
  let wired = wired(DriverKind::Thread);
  let mut wiring = wired.create().wire().with_taps(taps);
  let head_inbox = wiring
    .inbox::<String>(NodeId::new(0))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let leaf_inbox = wiring
    .inbox::<String>(NodeId::new(1))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let (head, head_party) = wiring
    .resident(NodeId::new(0), passing("head", &record), head_inbox)
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let (leaf, leaf_party) = wiring
    .resident(NodeId::new(1), Shout, leaf_inbox)
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  // A party the CALLER runs — an intake it enrolled here and drives itself. It never reaches an
  // engine of this ignition's, so it is the other half of the announce/wait asymmetry: told, and
  // not waited for.
  let intake = wiring.enrol("intake");

  let mut ignition = wiring.into_assembly().ignite();
  ignition
    .resident(head, head_party)
    .expect("the first engine started");
  // A source is registered and NOT started, sources being last: this is the clock the unwind must
  // drop unrun rather than stop, and its note is what would show up if it had ever run.
  let clock = Arc::clone(&record);
  ignition.source(move || admitting("clock", &clock));
  // The refused spawn takes the body and the enrolment down with it — the closure it moved them
  // into is dropped — so the second party finishes without ever settling, and was never marked as
  // one an engine is under.
  drop(leaf);
  drop(leaf_party);

  let began = Instant::now();
  let refusal = ignition.unwind(refused_engine());
  let waited = began.elapsed();

  // (a) The head's own value was dropped, on its own engine, before its party settled — and it is
  // already in the record by the time the refusal is in hand.
  assert_eq!(
    seen(&record),
    ["gone head"],
    "the started body wound down before the error came back, and the source never started at all"
  );
  // THE ASYMMETRY, both halves. The caller's own party was TOLD, because a party that is still
  // admitting is what holds the wave open — and it was not WAITED for, because nothing this
  // ignition started is running it.
  assert!(intake.winding(), "the party the caller runs heard it too");
  assert!(
    waited < Ignition::PATIENCE,
    "and it was not waited for: {waited:?}"
  );
  assert!(
    ignition.shutdown().parties()[0].settled(),
    "and it answered rather than merely stopping"
  );
  assert_eq!(
    ignition.bodies(),
    0,
    "every party settled, so the engines were joined: they are gone, not merely finished"
  );
  assert_eq!(ignition.sources(), 0, "the unspent start was dropped");
  assert!(
    !ignition.shutdown().parties()[1].ignited(),
    "the party whose engine was refused never began"
  );

  // (b) THE ORIGINAL ERROR, unchanged. The unwind is a duty and not a second failure.
  assert!(refusal.is_ignition(), "{refusal}");
  let rendered = refusal.to_string();
  assert!(rendered.contains("titles"), "{rendered}");
  assert!(rendered.contains("could not be started"), "{rendered}");

  // (c) And how the unwind went rides the taps, under the party's own name.
  assert_eq!(tap.seen(), [("shout".to_owned(), Station::Processed)]);
}

#[test]
fn a_party_that_will_not_settle_is_abandoned_when_the_patience_runs_out() {
  // THE BOUND, and the only way to see one is to let it run out — so this test spends
  // `Ignition::PATIENCE` on purpose. What refuses to settle is the documented case rather than an
  // invented one: an async body that was COMPOSED and never spawned. Its party is marked as begun,
  // because composing is the last moment this crate sees, and it will never fire a completion.
  let (tap, taps) = watching();
  let wired = wired(DriverKind::Async);
  let mut wiring = wired.create().wire().with_taps(taps);
  let head_inbox = wiring
    .inbox::<String>(NodeId::new(0))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let leaf_inbox = wiring
    .inbox::<String>(NodeId::new(1))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let (head, head_party) = wiring
    .resident(NodeId::new(0), Shout, head_inbox)
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let (leaf, leaf_party) = wiring
    .resident(NodeId::new(1), Shout, leaf_inbox)
    .expect("nothing to refuse")
    .expect("the deployment launches it");

  let mut ignition = wiring.into_assembly().ignite();
  let body = Ignition::task(head, head_party);
  drop(leaf);
  drop(leaf_party);

  let began = Instant::now();
  let refusal = ignition.unwind(refused_engine());
  let waited = began.elapsed();

  assert!(
    waited >= Ignition::PATIENCE,
    "the wait was the shipped one and it ran out: {waited:?}"
  );
  assert!(
    waited < Ignition::PATIENCE * 3,
    "and it ended there rather than waiting on a party that will never answer: {waited:?}"
  );
  assert!(
    !ignition.shutdown().parties()[0].settled(),
    "it was abandoned where it stood"
  );
  assert!(
    refusal.is_ignition(),
    "and the caller still gets the original refusal: {refusal}"
  );
  assert_eq!(
    tap.seen(),
    [("shout".to_owned(), Station::Failed)],
    "the tap is where an abandoned party is reported, never a second error"
  );

  drop(body);
}

#[test]
fn an_ignition_that_started_nothing_hands_the_error_straight_back() {
  // THE RULED SCOPE. A launch that failed before the first body started has nothing running, so
  // everything it built unwinds by its own `Drop` as the error propagates — and, the part worth
  // pinning, the unwind does not WAIT: sitting out the patience for an empty set would turn every
  // early refusal into a five-second one.
  let (tap, taps) = watching();
  let wired = wired(DriverKind::Thread);
  let mut wiring = wired.create().wire().with_taps(taps);
  let head_inbox = wiring
    .inbox::<String>(NodeId::new(0))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let leaf_inbox = wiring
    .inbox::<String>(NodeId::new(1))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let head = wiring
    .resident(NodeId::new(0), Shout, head_inbox)
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let leaf = wiring
    .resident(NodeId::new(1), Shout, leaf_inbox)
    .expect("nothing to refuse")
    .expect("the deployment launches it");

  let mut ignition = wiring.into_assembly().ignite();
  drop((head, leaf));

  let began = Instant::now();
  let refusal = ignition.unwind(refused_engine());

  assert!(
    began.elapsed() < Ignition::PATIENCE,
    "an empty set is not something to wait for"
  );
  assert!(refusal.is_ignition(), "{refusal}");
  assert!(
    tap.is_empty(),
    "nothing began, so nothing has an outcome to report"
  );
}

#[tokio::test]
async fn the_async_engine_s_body_is_composed_for_whoever_holds_a_runtime() {
  let record = record();
  let wired = wired(DriverKind::Async);
  let mut wiring = wired.create().wire();
  let head_inbox = wiring
    .inbox::<String>(NodeId::new(0))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let leaf_inbox = wiring
    .inbox::<String>(NodeId::new(1))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let feed = wiring
    .outbox::<String>(NodeId::new(0))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  // An async node cannot time itself, so its liveness floor is a cadence — and the clock that rings
  // it is a SOURCE, started last of all and stopped first.
  let clocks = wiring
    .clock::<String>(NodeId::new(1), Duration::from_millis(20))
    .expect("nothing to refuse");
  assert_eq!(clocks, 1, "the sweep nudge");
  let (head, head_party) = wiring
    .resident(NodeId::new(0), Shout, head_inbox)
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let (leaf, leaf_party) = wiring
    .resident(
      NodeId::new(1),
      Keeping {
        record: Arc::clone(&record),
      },
      leaf_inbox,
    )
    .expect("nothing to refuse")
    .expect("the deployment launches it");

  let ignition = wiring.into_assembly().ignite();
  // The bodies this stage composes, spawned by the party that has a runtime — before the sources
  // start, which is what `into_app` is.
  tokio::spawn(Ignition::task(head, head_party));
  tokio::spawn(Ignition::task(leaf, leaf_party));
  let running = ignition.into_app::<()>();
  assert_eq!(running.sources(), 1, "the cadence clock, and it is started");

  let (ack, _answers) = ack_channel();
  feed
    .deliver_async(Delivery::new(
      Payload::One(Item::new(ItemId::new(0), "one".to_owned())),
      ack,
    ))
    .await
    .expect("the head is listening");
  drop(feed);

  let stopped = tokio::task::spawn_blocking(move || running.shutdown(None))
    .await
    .expect("the shutdown's own thread");
  assert_eq!(stopped.settled(), 2);
  assert!(stopped.is_clean());
  assert_eq!(seen(&record), ["ONE"]);
}

/// **THE SHUTDOWN TENANT** — a body inside `accept` reads its own [`Context`]'s wind-down line and
/// hears the deployment's broadcast on it.
///
/// This is the whole of what the window bought at the buffered face: an `accept` used to be able to
/// learn nothing about the world it ran in, so a long one ran to its end whatever the deployment
/// had decided. The body below PARKS on the line, and the only thing that can release it is
/// [`App::shutdown`](super::super::App::shutdown)'s first step walking the launch's own half of
/// every node's line — so a test that returns at all is a test in which the broadcast reached the
/// body's stack.
struct Parking {
  /// Fired as the body enters the park, so the test can say the stop at a moment it knows.
  entered: crate::conduit::Sender<()>,
  record: Record,
}

declared!(Parking);

impl Operator for Parking {
  type Error = Infallible;
  type In = String;
  type Out = String;

  fn accept(
    &mut self,
    ctx: &Context,
    delivery: Delivery<Self::In>,
    _emitter: &mut Emitter<String>,
  ) -> Result<(), Self::Error> {
    for item in delivery.into_items() {
      note(&self.record, format!("entered {}", item.into_value()));
      let _ = self.entered.try_send(());
      // A LONG accept: without the window there is no door here at all, and this body would run to
      // its own end whatever the deployment had decided.
      ctx.shutdown().heard();
      note(&self.record, format!("heard it at {}", ctx.node().as_str()));
    }
    Ok(())
  }
}

#[test]
fn a_body_inside_accept_hears_the_deployment_broadcast_on_its_own_window() {
  let record = record();
  let wired = wired(DriverKind::Thread);
  let mut wiring = wired.create().wire();
  let head_inbox = wiring
    .inbox::<String>(NodeId::new(0))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let leaf_inbox = wiring
    .inbox::<String>(NodeId::new(1))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let feed = wiring
    .outbox::<String>(NodeId::new(0))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let (entered, in_the_park) = crate::conduit::bounded::<()>(1);
  let (head, head_party) = wiring
    .resident(
      NodeId::new(0),
      Parking {
        entered,
        record: Arc::clone(&record),
      },
      head_inbox,
    )
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let (leaf, leaf_party) = wiring
    .resident(
      NodeId::new(1),
      Keeping {
        record: Arc::clone(&record),
      },
      leaf_inbox,
    )
    .expect("nothing to refuse")
    .expect("the deployment launches it");

  let mut ignition = wiring.into_assembly().ignite();
  ignition.resident(head, head_party).expect("its engine");
  ignition.resident(leaf, leaf_party).expect("its engine");
  let running = ignition.into_app::<()>();

  let (ack, _answers) = ack_channel();
  feed
    .deliver(Delivery::new(
      Payload::One(Item::new(ItemId::new(0), "one".to_owned())),
      ack,
    ))
    .expect("the head is listening");
  drop(feed);

  // The body is IN the park — asserted rather than assumed, so the broadcast below cannot be
  // mistaken for a race the body would have won anyway.
  assert!(
    in_the_park.recv().is_some(),
    "the body reached its own accept"
  );
  assert_eq!(
    seen(&record),
    ["entered one"],
    "and it has not come out of the park"
  );

  // The whole claim: this returns, which it can only do once the parked accept has been released.
  let stopped = running.shutdown(None);

  assert!(stopped.is_clean(), "{stopped}");
  assert_eq!(
    seen(&record),
    ["entered one", "heard it at shout"],
    "the broadcast reached the body's own stack, under the body's own name"
  );
}