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
//! THE PAIRING RUNTIME, driven.
//!
//! What this module builds once and then drives from every angle is the intake a mixed
//! `subscribe(…)` container needs — the declaration from the design record, in the runtime's own
//! terms:
//!
//! ```text
//! subscribe(
//!   upstream(node = "media::Frame", key),
//!   upstream(node = "asr::Segment", key),
//!   upstream(node = "media::Scene"),
//! )
//! ```
//!
//! [`CaptionIntake`] is hand-written here exactly as `TitleDownstream` is hand-written beside
//! [`Sink`](crate::Sink): it is what the node's own expansion will emit, written by hand so the
//! runtime beneath it is proven before anything emits one. Everything in it that is not this node's
//! own vocabulary comes from the framework — [`Intake`], [`select`], [`arm`], [`Pairing`],
//! [`Owing`], [`Custody`] — and the parts that ARE its own are the three the emission would write:
//! the fields, the `In` enum, and the one line per member that fills a slot.
use crate::Context;

use core::time::Duration;

use std::collections::VecDeque;

use super::{Group, Joins, Pairing};

use crate::{
  Arm, Custody, Delivery, Drives, Emitter, Inbox, Intake, Item, ItemId, Operator, Owing, Payload,
  Resident, Share, Wake, ack_channel, arm, channel, park_on, select,
};

/// The keyed group's first member.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Frame {
  media: u64,
  at: u64,
}

/// Its second.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Segment {
  media: u64,
  said: &'static str,
}

/// The independent flow beside them.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Scene {
  media: u64,
}

/// What arrives at the captioner — the emitted `<Node>In`, written by hand.
#[derive(Debug, Clone, PartialEq, Eq)]
enum CaptionIn {
  /// One message from EACH keyed member, joined by key and delivered together.
  Paired(Frame, Segment),
  /// One message from the independent flow, arriving on its own.
  Scene(Scene),
}

/// The keyed group's partial state: one slot per member.
#[derive(Debug, Default)]
struct CaptionGroup {
  frame: Option<Frame>,
  segment: Option<Segment>,
}

impl Group for CaptionGroup {
  type Complete = (Frame, Segment);

  fn complete(self) -> Result<Self::Complete, Self> {
    match (self.frame, self.segment) {
      (Some(frame), Some(segment)) => Ok((frame, segment)),
      (frame, segment) => Err(Self { frame, segment }),
    }
  }
}

/// The projection the members meet at — one value answering for both message types.
struct ByMedia;

impl Joins<Frame> for ByMedia {
  type Key = u64;

  fn key(&self, message: &Frame) -> u64 {
    message.media
  }
}

impl Joins<Segment> for ByMedia {
  type Key = u64;

  fn key(&self, message: &Segment) -> u64 {
    message.media
  }
}

/// What one arm of the select answered — which upstream, and what it heard.
enum Taken {
  Frames(Wake<ItemId, Frame>),
  Segments(Wake<ItemId, Segment>),
  Scenes(Wake<ItemId, Scene>),
}

/// The captioner's intake: three edges, a select over them, and the by-key join behind two of them.
struct CaptionIntake {
  frames: Inbox<ItemId, Frame>,
  segments: Inbox<ItemId, Segment>,
  scenes: Inbox<ItemId, Scene>,
  joins: ByMedia,
  pairing: Pairing<u64, CaptionGroup>,
  /// What the select has already turned into input, in arrival order.
  ready: VecDeque<Wake<ItemId, CaptionIn>>,
  /// Per upstream, whether it can still answer. A closed arm is never offered again.
  open: [bool; Self::UPSTREAMS],
  /// Where the next select starts, advanced past whoever just won.
  turn: usize,
  /// The joined items' own keys.
  next: u64,
}

impl CaptionIntake {
  const UPSTREAMS: usize = 3;

  fn new(
    frames: Inbox<ItemId, Frame>,
    segments: Inbox<ItemId, Segment>,
    scenes: Inbox<ItemId, Scene>,
  ) -> Self {
    Self {
      frames,
      segments,
      scenes,
      joins: ByMedia,
      pairing: Pairing::new(),
      ready: VecDeque::new(),
      open: [true; Self::UPSTREAMS],
      turn: 0,
      next: 0,
    }
  }

  /// The joined delivery a completed group becomes: one item, and the members' custody composed.
  fn joined(
    &mut self,
    (frame, segment): (Frame, Segment),
    shares: Vec<Share<ItemId>>,
  ) -> Wake<ItemId, CaptionIn> {
    let key = ItemId::new(self.next);
    self.next += 1;
    Wake::Delivered(Delivery::joined(
      Payload::One(Item::new(key, CaptionIn::Paired(frame, segment))),
      Custody::joined(key, shares),
    ))
  }

  /// A keyed member's delivery: every item goes into the buffer under its own key, and whatever
  /// that completed comes straight back out.
  fn keyed<T>(&mut self, delivery: Delivery<T>, fill: impl Fn(&mut CaptionGroup, T))
  where
    ByMedia: Joins<T, Key = u64>,
  {
    let (payload, custody) = delivery.into_parts();
    let owing = Owing::open(payload.keys().copied(), custody);
    for item in payload {
      let (key, message) = item.into_parts();
      let join = self.joins.key(&message);
      let completed = self
        .pairing
        .arrive(join, owing.share(key), |group| fill(group, message));
      if let Some((pair, shares)) = completed {
        let delivered = self.joined(pair, shares);
        self.ready.push_back(delivered);
      }
    }
  }

  /// Classify one arm's answer.
  fn take(&mut self, taken: Taken) {
    match taken {
      Taken::Frames(Wake::Delivered(delivery)) => {
        self.keyed(delivery, |group, frame| group.frame = Some(frame));
      }
      Taken::Segments(Wake::Delivered(delivery)) => {
        self.keyed(delivery, |group, segment| group.segment = Some(segment));
      }
      // The STRAIGHT upstream passes through: wrapped into this node's own input and owing exactly
      // what it owed, the moment it arrives.
      Taken::Scenes(Wake::Delivered(delivery)) => self
        .ready
        .push_back(Wake::Delivered(delivery.map(CaptionIn::Scene))),
      Taken::Frames(Wake::Sweep) | Taken::Segments(Wake::Sweep) | Taken::Scenes(Wake::Sweep) => {
        self.ready.push_back(Wake::Sweep);
      }
      Taken::Frames(Wake::Tick(tick))
      | Taken::Segments(Wake::Tick(tick))
      | Taken::Scenes(Wake::Tick(tick)) => self.ready.push_back(Wake::Tick(tick)),
    }
  }
}

impl Intake<CaptionIn> for CaptionIntake {
  fn park(&mut self, sweep: Duration) -> Option<Wake<ItemId, CaptionIn>> {
    // The THREAD engine drives the same select the async engine awaits, with the sweep as its
    // deadline — the two engines differ in this one call and in nothing else.
    park_on(self.park_async(), sweep).unwrap_or(Some(Wake::Sweep))
  }

  async fn park_async(&mut self) -> Option<Wake<ItemId, CaptionIn>> {
    loop {
      if let Some(wake) = self.ready.pop_front() {
        return Some(wake);
      }
      if self.open.iter().all(|open| !open) {
        return None;
      }
      let answered = {
        let Self {
          frames,
          segments,
          scenes,
          open,
          turn,
          ..
        } = &*self;
        let mut first = core::pin::pin!(arm(open[0], frames, Taken::Frames));
        let mut second = core::pin::pin!(arm(open[1], segments, Taken::Segments));
        let mut third = core::pin::pin!(arm(open[2], scenes, Taken::Scenes));
        let mut arms: [Arm<'_, Option<Taken>>; Self::UPSTREAMS] =
          [first.as_mut(), second.as_mut(), third.as_mut()];
        select(*turn, &mut arms).await
      };
      let (index, taken) = answered?;
      self.turn = (index + 1) % Self::UPSTREAMS;
      match taken {
        Some(taken) => self.take(taken),
        None => self.open[index] = false,
      }
    }
  }

  fn drain(&mut self, into: &mut Vec<Wake<ItemId, CaptionIn>>) {
    for wake in self.frames.drain().collect::<Vec<_>>() {
      self.take(Taken::Frames(wake));
    }
    for wake in self.segments.drain().collect::<Vec<_>>() {
      self.take(Taken::Segments(wake));
    }
    for wake in self.scenes.drain().collect::<Vec<_>>() {
      self.take(Taken::Scenes(wake));
    }
    into.extend(self.ready.drain(..));
  }
}

/// The three sending halves and the intake they feed.
struct Wired {
  frames: crate::Outbox<ItemId, Frame>,
  segments: crate::Outbox<ItemId, Segment>,
  scenes: crate::Outbox<ItemId, Scene>,
  intake: CaptionIntake,
}

fn wired() -> Wired {
  let (frames, frames_in) = channel::<ItemId, Frame>(8);
  let (segments, segments_in) = channel::<ItemId, Segment>(8);
  let (scenes, scenes_in) = channel::<ItemId, Scene>(8);
  Wired {
    frames,
    segments,
    scenes,
    intake: CaptionIntake::new(frames_in, segments_in, scenes_in),
  }
}

/// Send `frames` as ONE delivery, keeping the answer receiver.
fn send<T>(outbox: &crate::Outbox<ItemId, T>, items: Vec<(u64, T)>) -> crate::AckReceiver<ItemId> {
  let (ack, answers) = ack_channel::<ItemId>();
  let batch = items
    .into_iter()
    .map(|(key, value)| Item::new(ItemId::new(key), value))
    .collect();
  outbox
    .deliver(Delivery::new(Payload::Batch(batch), ack))
    .map_err(|_| "the consumer is here")
    .expect("delivered");
  answers
}

/// One park with a short deadline — `None` where nothing was ready.
fn parked(intake: &mut CaptionIntake) -> Option<Wake<ItemId, CaptionIn>> {
  match intake.park(Duration::from_millis(60)) {
    Some(Wake::Sweep) | None => None,
    other => other,
  }
}

/// The input a delivery carries, for the one-item deliveries these tests send.
fn input(wake: Wake<ItemId, CaptionIn>) -> CaptionIn {
  let Wake::Delivered(delivery) = wake else {
    panic!("a delivery");
  };
  delivery.into_items().next().expect("one item").into_value()
}

#[test]
fn two_keyed_streams_join_on_key_whichever_arrives_first() {
  // OUT OF ORDER on purpose: the segment lands before its frame for one key and after it for the
  // other, and both pairs come out whole.
  let mut world = wired();
  let _frames = send(&world.frames, vec![(0, Frame { media: 7, at: 1 })]);
  assert!(
    parked(&mut world.intake).is_none(),
    "a lone member is not a pair"
  );

  let _segments = send(
    &world.segments,
    vec![(
      0,
      Segment {
        media: 7,
        said: "hello",
      },
    )],
  );
  assert_eq!(
    input(parked(&mut world.intake).expect("the pair")),
    CaptionIn::Paired(
      Frame { media: 7, at: 1 },
      Segment {
        media: 7,
        said: "hello"
      }
    )
  );

  let _late = send(
    &world.segments,
    vec![(
      1,
      Segment {
        media: 9,
        said: "again",
      },
    )],
  );
  assert!(
    parked(&mut world.intake).is_none(),
    "the other order waits the same way"
  );
  let _frames = send(&world.frames, vec![(1, Frame { media: 9, at: 2 })]);
  assert_eq!(
    input(parked(&mut world.intake).expect("the pair")),
    CaptionIn::Paired(
      Frame { media: 9, at: 2 },
      Segment {
        media: 9,
        said: "again"
      }
    )
  );
}

#[test]
fn an_unpaired_key_waits_while_every_other_key_flows() {
  // Key 1 never completes. Keys 2 and 3 do, and they come through while it sits there — which is
  // the whole point of a buffer keyed by the item's key rather than a queue.
  let mut world = wired();
  let _frames = send(
    &world.frames,
    vec![
      (0, Frame { media: 1, at: 1 }),
      (1, Frame { media: 2, at: 2 }),
      (2, Frame { media: 3, at: 3 }),
    ],
  );
  let _segments = send(
    &world.segments,
    vec![
      (
        0,
        Segment {
          media: 3,
          said: "three",
        },
      ),
      (
        1,
        Segment {
          media: 2,
          said: "two",
        },
      ),
    ],
  );

  let mut paired = Vec::new();
  while let Some(wake) = parked(&mut world.intake) {
    let CaptionIn::Paired(frame, _) = input(wake) else {
      panic!("a pair");
    };
    paired.push(frame.media);
  }
  paired.sort_unstable();
  assert_eq!(
    paired,
    [2, 3],
    "the two keys that completed, and only those"
  );
  assert_eq!(
    world.intake.pairing.waiting(),
    1,
    "media 1 is still waiting for a segment that never came"
  );
}

#[test]
fn a_straight_source_flows_while_a_pair_is_still_half_arrived() {
  let mut world = wired();
  let _frames = send(&world.frames, vec![(0, Frame { media: 4, at: 1 })]);
  let _scenes = send(&world.scenes, vec![(0, Scene { media: 4 })]);

  assert_eq!(
    input(parked(&mut world.intake).expect("the scene")),
    CaptionIn::Scene(Scene { media: 4 }),
    "an independent flow never waits on a pair that has not assembled"
  );
  assert!(parked(&mut world.intake).is_none());
  assert_eq!(world.intake.pairing.waiting(), 1);
}

#[test]
fn a_straight_source_keeps_its_own_keys_and_its_own_token() {
  // The passthrough owes exactly what it owed: same keys, same oneshot. Nothing about a straight
  // upstream's ack protocol changes because the node beside it pairs.
  let mut world = wired();
  let answers = send(
    &world.scenes,
    vec![(3, Scene { media: 5 }), (4, Scene { media: 6 })],
  );
  let Some(Wake::Delivered(delivery)) = parked(&mut world.intake) else {
    panic!("the scenes");
  };
  let keys: Vec<ItemId> = delivery.payload().keys().copied().collect();
  assert_eq!(keys, [ItemId::new(3), ItemId::new(4)]);

  let (payload, custody) = delivery.into_parts();
  let released = payload.keys().copied().collect();
  assert!(
    custody
      .expect("the token came through")
      .send(crate::Ack::new(
        released,
        "captioner",
        crate::Lifecycle::Processed(())
      ))
  );
  let crate::Answer::Settled(settled) = answers.take() else {
    panic!("answered");
  };
  assert_eq!(settled.released().len(), 2);
}

#[test]
fn a_pair_s_delivery_carries_both_members_custody_and_releases_both() {
  let mut world = wired();
  let frames = send(&world.frames, vec![(0, Frame { media: 8, at: 1 })]);
  let segments = send(
    &world.segments,
    vec![(
      // The senders minted the SAME number for different items, which is what per-share keys are
      // for.
      0,
      Segment {
        media: 8,
        said: "eight",
      },
    )],
  );

  let Some(Wake::Delivered(delivery)) = parked(&mut world.intake) else {
    panic!("the pair");
  };
  let (payload, custody) = delivery.into_parts();
  let released = payload.keys().copied().collect();
  assert!(custody.expect("composed").send(crate::Ack::new(
    released,
    "captioner",
    crate::Lifecycle::Processed(())
  )));

  for answers in [frames, segments] {
    let crate::Answer::Settled(settled) = answers.take() else {
      panic!("every member is answered");
    };
    assert_eq!(settled.released().len(), 1);
    assert!(settled.released().contains(&ItemId::new(0)));
    assert_eq!(settled.worker().as_str(), "captioner");
  }
}

#[test]
fn a_second_message_for_a_filled_slot_replaces_it_and_still_answers_the_first() {
  // Keyed replace, applied to the buffer: the newer frame wins the slot, and the older delivery is
  // answered by the same outcome rather than left waiting forever.
  let mut world = wired();
  let first = send(&world.frames, vec![(0, Frame { media: 2, at: 10 })]);
  let second = send(&world.frames, vec![(1, Frame { media: 2, at: 20 })]);
  // Both frames are absorbed before the segment arrives — a drain takes a whole queue, where a park
  // takes one arm and then gives the next upstream its turn.
  let mut absorbed = Vec::new();
  world.intake.drain(&mut absorbed);
  assert!(absorbed.is_empty(), "neither frame is a pair on its own");
  let segments = send(
    &world.segments,
    vec![(
      0,
      Segment {
        media: 2,
        said: "two",
      },
    )],
  );

  let Some(Wake::Delivered(delivery)) = parked(&mut world.intake) else {
    panic!("the pair");
  };
  let (payload, custody) = delivery.into_parts();
  let CaptionIn::Paired(frame, _) = payload.into_iter().next().expect("one item").into_value()
  else {
    panic!("a pair");
  };
  assert_eq!(frame.at, 20, "the newer message won the slot");

  let mut released = std::collections::HashSet::new();
  released.insert(ItemId::new(0));
  released.insert(ItemId::new(1));
  assert!(custody.expect("composed").send(crate::Ack::new(
    released,
    "captioner",
    crate::Lifecycle::Processed(())
  )));
  for answers in [first, second, segments] {
    let crate::Answer::Settled(settled) = answers.take() else {
      panic!("all three deliveries are answered");
    };
    assert_eq!(settled.released().len(), 1);
  }
}

#[test]
fn a_batch_whose_keys_join_different_groups_answers_only_when_the_last_is_decided() {
  // ONE frame delivery of three items, three different keys, three different groups. Its token is
  // one, so it cannot answer until every one of them has been decided.
  let mut world = wired();
  let frames = send(
    &world.frames,
    vec![
      (0, Frame { media: 1, at: 1 }),
      (1, Frame { media: 2, at: 2 }),
      (2, Frame { media: 3, at: 3 }),
    ],
  );

  let mut released = std::collections::HashSet::new();
  for (key, media) in [(0u64, 1u64), (1, 2)] {
    let _segments = send(&world.segments, vec![(key, Segment { media, said: "s" })]);
    let Some(Wake::Delivered(delivery)) = parked(&mut world.intake) else {
      panic!("the pair for media {media}");
    };
    let (payload, custody) = delivery.into_parts();
    released.extend(payload.keys().copied());
    let taken = payload.keys().copied().collect();
    assert!(custody.expect("composed").send(crate::Ack::new(
      taken,
      "captioner",
      crate::Lifecycle::Processed(())
    )));
    assert!(
      matches!(frames.take(), crate::Answer::Waiting),
      "two of three decided says nothing"
    );
  }

  let _segments = send(
    &world.segments,
    vec![(
      2,
      Segment {
        media: 3,
        said: "s",
      },
    )],
  );
  let Some(Wake::Delivered(delivery)) = parked(&mut world.intake) else {
    panic!("the last pair");
  };
  let (payload, custody) = delivery.into_parts();
  let taken = payload.keys().copied().collect();
  assert!(custody.expect("composed").send(crate::Ack::new(
    taken,
    "captioner",
    crate::Lifecycle::Processed(())
  )));
  let crate::Answer::Settled(settled) = frames.take() else {
    panic!("the pass that finished it answers");
  };
  assert_eq!(
    settled.released().len(),
    3,
    "every item of the batch, each released by the pair it went into"
  );
}

#[test]
fn the_intake_is_shut_down_only_when_every_source_is_gone() {
  let mut world = wired();
  drop(world.frames);
  assert!(
    world.intake.park(Duration::from_millis(60)).is_some(),
    "one upstream gone is not shutdown"
  );
  drop(world.segments);
  assert!(world.intake.park(Duration::from_millis(60)).is_some());
  drop(world.scenes);
  assert!(
    world.intake.park(Duration::from_secs(1)).is_none(),
    "every upstream gone is shutdown, which is what ends the loop"
  );
}

/// The captioner itself: it takes whatever the intake assembled and says what it saw.
struct Captioner;

impl Operator for Captioner {
  type Error = core::convert::Infallible;
  type In = CaptionIn;
  type Out = String;

  fn accept(
    &mut self,
    _ctx: &Context,
    delivery: Delivery<CaptionIn>,
    emitter: &mut Emitter<String>,
  ) -> Result<(), Self::Error> {
    for item in delivery.into_items() {
      let caption = match item.into_value() {
        CaptionIn::Paired(frame, segment) => {
          format!("{}@{} said {}", frame.media, frame.at, segment.said)
        }
        CaptionIn::Scene(scene) => format!("{} cut", scene.media),
      };
      emitter.emit(caption);
    }
    Ok(())
  }
}

#[test]
fn a_mixed_node_runs_end_to_end_on_the_thread_engine() {
  let world = wired();
  let (captions, read) = channel::<ItemId, String>(16);
  let mut resident = Resident::new("captioner", Captioner, world.intake).publish(captions);

  let Wired {
    frames,
    segments,
    scenes,
    ..
  } = world;
  let frame_answers = send(&frames, vec![(0, Frame { media: 7, at: 1 })]);
  let scene_answers = send(&scenes, vec![(0, Scene { media: 3 })]);
  let segment_answers = send(
    &segments,
    vec![(
      0,
      Segment {
        media: 7,
        said: "hi",
      },
    )],
  );
  // A frame nobody will ever pair — it must not stop anything else, and it must not be released.
  let orphan = send(&frames, vec![(1, Frame { media: 99, at: 9 })]);
  drop(frames);
  drop(segments);
  drop(scenes);

  let engine = std::thread::spawn(move || {
    let drained = resident.run();
    (drained, resident)
  });
  let (drained, resident) = engine.join().expect("the engine");

  let mut said = Vec::new();
  for wake in read.drain() {
    let Wake::Delivered(delivery) = wake else {
      continue;
    };
    let (payload, custody) = delivery.into_parts();
    let released = payload.keys().copied().collect();
    for item in payload {
      said.push(item.into_value());
    }
    if let Some(custody) = custody {
      custody.send(crate::Ack::new(
        released,
        "reader",
        crate::Lifecycle::Persisted(()),
      ));
    }
  }
  said.sort();
  assert_eq!(said, ["3 cut", "7@1 said hi"]);
  assert_eq!(drained.deliveries(), 2, "one pair and one straight");

  // The pair's members were released; the orphan's delivery was never answered at all, which is the
  // stuck watermark the upstream's own lag sweep is the net for.
  for answers in [frame_answers, segment_answers, scene_answers] {
    let crate::Answer::Settled(settled) = answers.take() else {
      panic!("answered");
    };
    assert_eq!(settled.released().len(), 1);
  }
  assert!(
    matches!(orphan.take(), crate::Answer::Waiting),
    "half a pair is answered by nobody — no timeout, no policy, and the sender's window keeps it"
  );
  drop(resident);
  assert!(
    matches!(orphan.take(), crate::Answer::HungUp),
    "and when the intake goes, the dropped token is what says held"
  );
}

#[test]
fn a_mixed_node_runs_end_to_end_on_the_async_engine() {
  // The same world, the same intake, the other engine: `park_async` awaits the select the thread
  // engine drove with a deadline.
  let world = wired();
  let (captions, read) = channel::<ItemId, String>(16);
  let mut resident = Resident::new("captioner", Captioner, world.intake).publish(captions);

  let Wired {
    frames,
    segments,
    scenes,
    ..
  } = world;
  let _frames = send(&frames, vec![(0, Frame { media: 7, at: 4 })]);
  let _segments = send(
    &segments,
    vec![(
      0,
      Segment {
        media: 7,
        said: "there",
      },
    )],
  );
  let _scenes = send(&scenes, vec![(0, Scene { media: 8 })]);
  drop(frames);
  drop(segments);
  drop(scenes);

  let drained = park_on(resident.run_async(), Duration::from_secs(30)).expect("the loop ended");
  assert_eq!(drained.deliveries(), 2);

  let mut said = Vec::new();
  for wake in read.drain() {
    let Wake::Delivered(delivery) = wake else {
      continue;
    };
    for item in delivery.into_items() {
      said.push(item.into_value());
    }
  }
  said.sort();
  assert_eq!(said, ["7@4 said there", "8 cut"]);
}