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
//! The autonomous seat, driven — and the launch door that puts a thread under one.
//!
//! What is proved here is the OPERATIONAL SPACE the third kind exists to open, and it is proved by
//! a body doing things the two per-delivery faces cannot express at all: reading its edges in an
//! order of its own, refusing to read one of them at all while a flag of its own is set, and
//! answering one edge's custody at once while it holds the other's back until the end of its life.
//! Every one of those is a line in one trace, and the trace is deterministic because the whole
//! arrangement is queued before the body starts.
//!
//! One claim is COMPILE-level rather than run-level, exactly as the origin suite's is: that an
//! awaited autonomous body whose future cannot cross threads is drivable at all is proven by this
//! file COMPILING — `Pinned` holds an `Rc` across two awaits, so a `+ Send` anywhere on that road
//! would make the declaration itself the error.
use crate::Context;

use core::{convert::Infallible, time::Duration};

use std::{
  collections::HashSet,
  rc::Rc,
  sync::{Arc, Mutex},
};

use super::{Helm, Runs, Upstreams};
use crate::{
  Ack, Async, AsyncAutonomousOperator, AutonomousOperator, Custody, Declared, Delivery, Downstream,
  Enablement, Fin, GraphBuilder, Inbox, Item, ItemId, Lifecycle, LifecycleTap, NodeId, NodeWiring,
  Payload, Plan, RecordingTap, Station, Taps, Wake, Wired, ack_channel, channel, shutdown_signal,
};

/// How long a park inside a body waits before giving up on an edge that is neither ready nor
/// finished — a DEADLINE and not a sleep, so a broken take reddens a run rather than hanging it.
const PATIENCE: Duration = Duration::from_secs(5);

/// The shared line the bodies below write their own account into.
type Trace = Arc<Mutex<Vec<String>>>;

/// Note one thing the body did, in the order it did it.
fn note(trace: &Trace, line: impl Into<String>) {
  trace.lock().expect("the trace's lock").push(line.into());
}

/// Take one DELIVERY off `edge`, waiting at most [`PATIENCE`].
///
/// `None` is the edge's own end or a sweep — neither is a delivery, and a body that owns its loop
/// treats both as *look again*.
fn took(edge: &Inbox<ItemId, u64>, sweep: Duration) -> Option<Delivery<u64>> {
  match edge.park(sweep)? {
    Wake::Delivered(delivery) => Some(delivery),
    Wake::Sweep | Wake::Tick(_) => None,
  }
}

/// **THE NODE'S OWN CREW**, wound down the ruled way: CLOSE the in-queue, let the worker drain its
/// tail, THEN join.
///
/// The [`Drop`] is the idempotent backstop the lifecycle table names. It matters because a panic
/// unwinding through `run` never reaches the epilogue: dropping this closes the same sender, the
/// parked worker wakes on a hung-up queue and returns, and the join terminates instead of waiting
/// forever on a queue nobody will ever fill.
struct Crew {
  jobs: Option<crate::conduit::Sender<u64>>,
  hand: Option<std::thread::JoinHandle<usize>>,
}

impl Crew {
  /// Close, THEN join — the one order both the epilogue and the drop keep.
  fn wind_down(&mut self) -> usize {
    drop(self.jobs.take());
    self.hand.take().map_or(0, |hand| hand.join().unwrap_or(0))
  }
}

impl Drop for Crew {
  fn drop(&mut self) {
    let _ = self.wind_down();
  }
}

/// **THE OPERATIONAL-SPACE BODY**: two upstream edges, a priority of its own, a gate of its own, an
/// ack schedule of its own and a crew of its own.
///
/// Edge ONE is drained to its end before edge ZERO is looked at, edge ZERO is not touched AT ALL
/// while the gate is shut, edge ONE's custody is answered the instant its delivery is handled, and
/// edge ZERO's is held until the life ends. Not one of the four is expressible at
/// [`Operator`](crate::Operator)'s face, where the driver owns every one of those decisions.
///
/// The value is taken BY VALUE, so the prologue moves its own parts into the worker it spawns and
/// the epilogue winds that worker down before the [`Fin`] is answered.
struct Priority {
  trace: Trace,
  /// How many of edge ONE's deliveries have been taken — the gate's own input, seeded by the test.
  seen: usize,
}

/// The gate: how many of edge ONE's deliveries must be taken before edge ZERO is read at all.
const GATE: usize = 3;
/// The edge the body PRIORITISES — drained to its end before the other is looked at.
const PRIOR: usize = 1;
/// The edge it defers, and gates.
const DEFERRED: usize = 0;

/// Put one value on the node's own out-edge, minting the id and the token itself — the books, kept
/// by the node.
fn publish(downstream: &Downstream<u64>, seq: &mut u64, value: u64) {
  let Some(edge) = downstream.edges().first() else {
    return;
  };
  let (ack, _answers) = ack_channel();
  let _ = edge.deliver(Delivery::new(
    Payload::One(Item::new(ItemId::new(*seq), value)),
    ack,
  ));
  *seq += 1;
}

/// Handle one of the PRIOR edge's deliveries: hand it to the crew, publish it raised, and ANSWER
/// ITS CUSTODY AT ONCE.
fn prior(
  trace: &Trace,
  crew: &Crew,
  delivery: Delivery<u64>,
  downstream: &Downstream<u64>,
  seq: &mut u64,
) {
  let (payload, custody) = delivery.into_parts();
  let released: HashSet<ItemId> = payload.keys().copied().collect();
  for item in payload {
    let value = item.into_value();
    note(trace, format!("b:{value}"));
    if let Some(jobs) = crew.jobs.as_ref() {
      let _ = jobs.send(value);
    }
    publish(downstream, seq, value + 100);
  }
  if let Some(custody) = custody {
    note(trace, "ack:b");
    custody.send(Ack::new(released, "priority", Lifecycle::Processed(())));
  }
}

/// One delivery of the DEFERRED edge, HELD: what it is owed, and the value a trace row names it by.
type Held = (Custody<ItemId>, HashSet<ItemId>, u64);

/// Handle one of the DEFERRED edge's: hand it to the crew, publish it as it is, and HOLD what it is
/// owed.
fn deferred(
  trace: &Trace,
  crew: &Crew,
  delivery: Delivery<u64>,
  downstream: &Downstream<u64>,
  seq: &mut u64,
  held: &mut Vec<Held>,
) {
  let (payload, custody) = delivery.into_parts();
  let released: HashSet<ItemId> = payload.keys().copied().collect();
  let mut first = 0;
  for item in payload {
    let value = item.into_value();
    first = value;
    note(trace, format!("a:{value}"));
    if let Some(jobs) = crew.jobs.as_ref() {
      let _ = jobs.send(value);
    }
    publish(downstream, seq, value);
  }
  if let Some(custody) = custody {
    held.push((custody, released, first));
  }
}

/// The books, settled — every held token answered, in the order they were taken.
fn settle(trace: &Trace, held: Vec<Held>) {
  for (custody, released, value) in held {
    note(trace, format!("ack:a:{value}"));
    custody.send(Ack::new(released, "priority", Lifecycle::Processed(())));
  }
}

impl AutonomousOperator for Priority {
  type Error = Infallible;
  type In = u64;
  type Out = u64;

  fn run(
    self,
    ctx: Context,
    upstreams: Upstreams<u64>,
    downstream: Downstream<u64>,
  ) -> Result<Fin, Self::Error> {
    // THE PROLOGUE: the value is taken apart and its parts move INTO the crew this call spawns.
    let Self { trace, mut seen } = self;
    let (jobs, to_do) = crate::conduit::bounded::<u64>(16);
    let hand = std::thread::spawn(move || {
      let mut taken = 0;
      while to_do.recv().is_some() {
        taken += 1;
      }
      taken
    });
    let mut crew = Crew {
      jobs: Some(jobs),
      hand: Some(hand),
    };
    let mut held: Vec<Held> = Vec::new();
    let mut seq = 0;

    // THE LOOP, and every decision in it is this node's.
    let fin = loop {
      if ctx.shutdown().is_shutdown() {
        break Fin::Stopped;
      }
      // THE GATE, read once per pass and recorded when it is shut — the deferred edge is not
      // touched at all while it is.
      let open = seen >= GATE;
      if !open {
        note(&trace, "holding");
      }
      // THE PRIORITY: the prior edge is drained to its end before the other is looked at, which is
      // what the `continue` below enforces rather than merely hopes for.
      if let Some(edge) = upstreams.edge(PRIOR)
        && !edge.is_empty()
        && let Some(delivery) = took(edge, PATIENCE)
      {
        prior(&trace, &crew, delivery, &downstream, &mut seq);
        seen += 1;
        continue;
      }
      if open
        && let Some(edge) = upstreams.edge(DEFERRED)
        && !edge.is_empty()
        && let Some(delivery) = took(edge, PATIENCE)
      {
        deferred(&trace, &crew, delivery, &downstream, &mut seq, &mut held);
        continue;
      }
      // NOTHING MORE CAN ARRIVE: every edge hung up and every queue is drained.
      if upstreams.is_spent() {
        break Fin::Spent;
      }
      // Neither ready nor finished — park on the prior edge, which is the one this body would have
      // taken first anyway.
      if let Some(edge) = upstreams.edge(PRIOR)
        && let Some(delivery) = took(edge, PATIENCE)
      {
        prior(&trace, &crew, delivery, &downstream, &mut seq);
        seen += 1;
      }
    };

    // THE EPILOGUE, in the ruled order: close the in-queue, let the worker drain its tail, join it,
    // THEN settle the books and answer.
    let counted = crew.wind_down();
    note(&trace, format!("joined:{counted}"));
    settle(&trace, held);
    Ok(fin)
  }
}

/// One delivery of `value`, with the token its sender waits on.
fn one(seq: u64, value: u64) -> (Delivery<u64>, crate::AckReceiver<ItemId>) {
  let (ack, answers) = ack_channel();
  (
    Delivery::new(Payload::One(Item::new(ItemId::new(seq), value)), ack),
    answers,
  )
}

/// Whether every one of `answers` was settled at the pure station.
fn all_processed(answers: &[crate::AckReceiver<ItemId>]) -> bool {
  answers.iter().all(|answers| match answers.take() {
    crate::Answer::Settled(settled) => settled.observation().station() == Some(Station::Processed),
    crate::Answer::Waiting | crate::Answer::HungUp => false,
  })
}

#[test]
fn a_node_that_owns_its_loop_reads_its_edges_in_its_own_order_and_keeps_its_own_books() {
  let (into_a, from_a) = channel::<ItemId, u64>(8);
  let (into_b, from_b) = channel::<ItemId, u64>(8);
  // Declaration order: edge ZERO is the deferred one, edge ONE is the prioritised one.
  let upstreams = Upstreams::from_iter([from_a, from_b]);
  assert_eq!(upstreams.len(), 2, "two edges, kept apart");

  let (out, collected) = channel::<ItemId, u64>(64);
  let mut downstream = Downstream::new();
  downstream.attach(out);

  // EVERYTHING IS QUEUED BEFORE THE BODY STARTS, and both senders go with it: what the body then
  // does is decided by the body alone, so the trace below has no schedule in it.
  let mut a_answers = Vec::new();
  let mut b_answers = Vec::new();
  for value in 1..=3 {
    let (delivery, answers) = one(value, value);
    into_a.deliver(delivery).expect("the edge is open");
    a_answers.push(answers);
    let (delivery, answers) = one(value, value);
    into_b.deliver(delivery).expect("the edge is open");
    b_answers.push(answers);
  }
  drop(into_a);
  drop(into_b);

  let trace: Trace = Arc::new(Mutex::new(Vec::new()));
  let node = Priority {
    trace: Arc::clone(&trace),
    seen: 0,
  };
  let (_stopper, halt) = shutdown_signal();

  assert_eq!(
    node.run(
      Context::new("priority").halting(halt),
      upstreams,
      downstream
    ),
    Ok(Fin::Spent),
    "every edge hung up and drained, which is the spent ending"
  );

  assert_eq!(
    trace.lock().expect("the trace's lock").as_slice(),
    [
      // THE GATE: the deferred edge is not touched for three passes, and the body says so.
      "holding", "b:1", "ack:b", "holding", "b:2", "ack:b", "holding", "b:3", "ack:b",
      // THE PRIORITY: the prior edge is spent before the deferred one is read at all.
      "a:1", "a:2", "a:3",
      // THE EPILOGUE, in the ruled order: the in-queue closed, the crew's tail drained, the crew
      // JOINED — and only then the books settled and the `Fin` answered.
      "joined:6",
      // THE BOOKS: the deferred edge's tokens were held for the body's whole life and answered
      // when the body decided to, which is here.
      "ack:a:1", "ack:a:2", "ack:a:3",
    ],
    "the order is the NODE's — no driver decided any part of it"
  );

  assert_eq!(
    collected.drain().count(),
    6,
    "everything the body published crossed its own downstream set"
  );
  assert!(
    all_processed(&b_answers),
    "the prior edge, answered at once"
  );
  assert!(
    all_processed(&a_answers),
    "the deferred edge, answered at the end — held is not lost"
  );
}

#[test]
fn a_stop_said_mid_life_is_the_stopped_ending_and_the_held_books_are_settled() {
  let (into_a, from_a) = channel::<ItemId, u64>(8);
  let (_into_b, from_b) = channel::<ItemId, u64>(8);
  let upstreams = Upstreams::from_iter([from_a, from_b]);
  let (out, _collected) = channel::<ItemId, u64>(8);
  let mut downstream = Downstream::new();
  downstream.attach(out);

  let (delivery, answers) = one(0, 7);
  into_a.deliver(delivery).expect("the edge is open");

  let trace: Trace = Arc::new(Mutex::new(Vec::new()));
  let node = Priority {
    trace: Arc::clone(&trace),
    // The gate starts OPEN here, so the deferred edge is readable and the body has work.
    seen: GATE,
  };
  let (stopper, halt) = shutdown_signal();
  // Said BEFORE the run, which is what makes this deterministic: the body's first look at its stop
  // is the one that answers.
  stopper.announce();

  assert_eq!(
    node.run(
      Context::new("priority").halting(halt),
      upstreams,
      downstream
    ),
    Ok(Fin::Stopped),
    "a body that heard the stop wound down"
  );
  assert_eq!(
    trace.lock().expect("the trace's lock").as_slice(),
    ["joined:0"],
    "it took nothing, because it looked at the stop first — and it still ran its epilogue, which \
     is what makes a wound-down node's crew wound down too"
  );
  // The delivery is still on the edge and still owed, which is the honest state: nothing took it.
  drop(into_a);
  assert!(matches!(answers.take(), crate::Answer::HungUp));
}

/// **THE `!Send` AWAITED BODY** — the whole point of the pinned road at this kind.
///
/// Its VALUE crosses onto the driving thread, which is what a launch needs of it; what does not
/// cross is the `Rc` its life holds between two awaits, which is what makes the FUTURE `!Send` and
/// what a `spawn` door would have refused.
struct Pinned {
  seed: u64,
  taken: Arc<Mutex<Vec<u64>>>,
}

impl AsyncAutonomousOperator for Pinned {
  type Error = Infallible;
  type In = u64;
  type Out = u64;

  async fn run(
    self,
    _ctx: Context,
    upstreams: Upstreams<u64>,
    _downstream: Downstream<u64>,
  ) -> Result<Fin, Self::Error> {
    // THE PROLOGUE, at the awaited face: `self`'s parts move into the loop rather than being
    // borrowed for it.
    let Self { seed, taken } = self;
    let here = Rc::new(seed);
    let Some(edge) = upstreams.edge(0) else {
      return Ok(Fin::Spent);
    };
    while let Some(wake) = edge.park_async().await {
      // The `Rc` is alive ACROSS the await above and read again after it, which is what makes the
      // whole future `!Send` rather than merely this type.
      if let Wake::Delivered(delivery) = wake {
        for item in delivery.into_items() {
          taken
            .lock()
            .expect("the record's lock")
            .push(item.into_value() + *here);
        }
      }
    }
    Ok(Fin::Spent)
  }
}

#[test]
fn the_awaited_row_is_driven_pinned_on_the_calling_thread() {
  let (into, from) = channel::<ItemId, u64>(8);
  let upstreams = Upstreams::from_iter([from]);
  let (_stopper, halt) = shutdown_signal();

  let (delivery, _answers) = one(0, 1);
  into.deliver(delivery).expect("the edge is open");
  let (delivery, _answers) = one(1, 2);
  into.deliver(delivery).expect("the edge is open");
  drop(into);

  let taken: Arc<Mutex<Vec<u64>>> = Arc::new(Mutex::new(Vec::new()));
  let node = Pinned {
    seed: 10,
    taken: Arc::clone(&taken),
  };
  // No runtime anywhere in this test: the future is pinned on THIS thread's stack and polled by a
  // waker made of `park`/`unpark`, which is the whole of what the pinned road is.
  let ended = Runs::<Async>::drive(
    node,
    Context::new("awaited").halting(halt),
    upstreams,
    Downstream::new(),
  );
  assert_eq!(ended, Ok(Fin::Spent));
  assert_eq!(*taken.lock().expect("the record's lock"), vec![11, 12]);
}

// ─── the launch door ────────────────────────────────────────────────────────────────────────────

/// What a life that DIED reports.
#[derive(Debug)]
struct DeviceGone;

impl core::fmt::Display for DeviceGone {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.write_str("the device went away")
  }
}

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

/// An autonomous node that never ends of itself: it waits for the stop and answers it.
struct Waiting;

impl AutonomousOperator for Waiting {
  type Error = DeviceGone;
  type In = u64;
  type Out = u64;

  fn run(
    self,
    ctx: Context,
    _upstreams: Upstreams<u64>,
    _downstream: Downstream<u64>,
  ) -> Result<Fin, Self::Error> {
    ctx.shutdown().heard();
    Ok(Fin::Stopped)
  }
}

impl Declared for Waiting {
  const EFFECT: crate::Effect = crate::Effect::Pure;

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

/// An autonomous node that DIES rather than ending.
struct Dying;

impl AutonomousOperator for Dying {
  type Error = DeviceGone;
  type In = u64;
  type Out = u64;

  fn run(
    self,
    _ctx: Context,
    _upstreams: Upstreams<u64>,
    _downstream: Downstream<u64>,
  ) -> Result<Fin, Self::Error> {
    Err(DeviceGone)
  }
}

impl Declared for Dying {
  const EFFECT: crate::Effect = crate::Effect::Pure;

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

/// A recorder, and the composite that carries it into a walk — the origin suite's own fixture.
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)
}

/// An arrangement small enough to ignite: one node, wired to land, so nothing here is a pure leaf.
fn wired() -> Wired {
  let mut builder = GraphBuilder::new();
  let _ = builder.source::<Keeping>("keeping", crate::DriverKind::Thread);
  let graph = builder.validate().expect("one node validates");
  Plan::new(graph)
    .with_enablement(Enablement::new().launching("keeping"))
    .wiring(
      NodeId::new(0),
      NodeWiring::new(crate::Effect::Lands).landing(),
    )
    .validate()
    .expect("the deployment checks out")
}

/// The one node the arrangement above holds — it exists so the walk has something to validate, and
/// nothing here ever gives it an engine.
struct Keeping;

impl crate::Operator for Keeping {
  type Error = Infallible;
  type In = u64;
  type Out = u64;

  fn accept(
    &mut self,
    _ctx: &Context,
    _delivery: Delivery<u64>,
    _emitter: &mut crate::Emitter<u64>,
  ) -> Result<(), Self::Error> {
    Ok(())
  }
}

impl Declared for Keeping {
  const EFFECT: crate::Effect = crate::Effect::Lands;

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

#[test]
fn the_wind_down_reaches_a_body_that_is_inside_run_for_its_whole_life() {
  let (tap, taps) = watching();
  // The plan is BOUND, because a wiring borrows it: the whole walk below lives inside one
  // deployment's lifetime.
  let plan = wired();
  let mut wiring = plan.create().with_taps(taps).wire();
  let enrolled = wiring.enrol("waiting");
  let mut ignition = wiring.into_assembly().ignite();

  let (stopper, halt) = shutdown_signal();
  let helm = Helm::new(
    Context::new("waiting").halting(halt),
    Waiting,
    Upstreams::new(),
    Downstream::new(),
  );
  ignition
    .autonomous_declared::<Waiting>(helm, stopper, enrolled)
    .expect("its engine");

  // NOTHING FEEDS IT and nothing can: the body parks on its stop line, which is the one road a
  // whole-life body listens to. The shutdown says the word through the half the launch kept.
  let stopped = ignition.into_app::<()>().shutdown(None);
  assert_eq!(stopped.settled(), 1, "a wound-down body settles its party");
  assert!(stopped.is_clean(), "{stopped}");
  assert_eq!(tap.seen(), vec![("waiting".to_owned(), Station::Processed)]);
}

#[test]
fn a_launched_autonomous_node_that_dies_is_observed_and_settles_anyway() {
  let (tap, taps) = watching();
  let plan = wired();
  let mut wiring = plan.create().with_taps(taps).wire();
  let enrolled = wiring.enrol("dying");
  let mut ignition = wiring.into_assembly().ignite();

  let (stopper, halt) = shutdown_signal();
  let helm = Helm::new(
    Context::new("dying").halting(halt),
    Dying,
    Upstreams::new(),
    Downstream::new(),
  );
  ignition
    .autonomous_declared::<Dying>(helm, stopper, enrolled)
    .expect("its engine");

  let stopped = ignition.into_app::<()>().shutdown(None);
  // A DEAD body is a FINISHED body: a launch that left it unsettled would hold the shutdown open on
  // a thread that had already returned.
  assert_eq!(stopped.settled(), 1);
  assert!(stopped.is_clean(), "{stopped}");
  assert_eq!(tap.seen(), vec![("dying".to_owned(), Station::Failed)]);
}

#[test]
fn an_empty_seat_is_spent_and_a_live_one_is_not() {
  let empty: Upstreams<u64> = Upstreams::new();
  assert!(empty.is_empty());
  assert!(
    empty.is_spent(),
    "nothing can arrive where there is no edge to arrive on"
  );
  assert!(empty.edge(0).is_none());
  assert_eq!(empty.drain(0).count(), 0);
  assert!(empty.park(0, Duration::ZERO).is_none());

  let (into, from) = channel::<ItemId, u64>(4);
  let upstreams = Upstreams::from_iter([from]);
  assert!(!upstreams.is_spent(), "its sender is alive");
  let (delivery, _answers) = one(0, 1);
  into.deliver(delivery).expect("the edge is open");
  assert_eq!(upstreams.queued(), 1);
  drop(into);
  assert!(
    !upstreams.is_spent(),
    "hung up, but a queued delivery is still work"
  );
  assert_eq!(upstreams.drain(0).count(), 1);
  assert!(upstreams.is_spent());
}