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
//! **INFLIGHT COUNTING, AND THE THREE ACK DISCIPLINES IT RESTS ON.**
//!
//! A root key returns to [`RootState::Idle`] the moment its inflight count reaches zero. That
//! reading is correct only under three rules about WHEN an ack is sent, and this file is where each
//! is asserted against running residents rather than argued in a comment — see [`Resident`]'s own
//! note, which states them.
//!
//! # How these walks avoid proving nothing
//!
//! A count is a race by nature: a walk that sampled it and found a good number may simply have
//! looked at a lucky moment. Every assertion that matters here is therefore taken at a BARRIER the
//! walk itself holds shut, so the reading is a fact about a state the graph cannot leave:
//!
//! * **A full downstream channel.** [`Sink::deliver`](crate::Sink) awaits room, so a node whose
//!   only edge is full is stopped INSIDE `dispatch` — after the count and before the ack. What the
//!   count says while it is stopped there is what R1 claims.
//! * **A held custody token.** A delivery the walk has taken and not answered is one the sender can
//!   never harvest, so the `-1` for it provably has not happened.
//! * **[`Analyzing`](RootState::Analyzing)'s `since`.** A key that reached zero would have gone
//!   `Idle`, and the next dispatch would open a NEW analysis with a new monotonic reading. So an
//!   unchanged `since` across a whole run is a PROOF that the count never touched zero in the
//!   middle of it, rather than a sample of it.
//!
//! # One root carries the whole tree
//!
//! Every walk here projects one root out of every item ([`OneMedia`]), which is what a real lineage
//! does for the records of one media. A tree of nodes over one key is exactly the shape the count
//! has to survive: several nodes hold items for it at once, and each decrements only what it
//! counted out.

use core::time::Duration;

use std::{collections::HashSet, sync::Arc, thread, time::Instant};

use super::super::{
  Ack, AckMode, AckReceiver, Answer, Delivery, Drives, Inbox, Item, ItemId, Lifecycle, Outbox,
  Payload, Registries, RegistryOptions, Resident, RetireOrigin, RootState, Settled, Stamp, Wake,
  ack_channel, channel,
};
use crate::{Arrival, Attributes, Context, Emitter, NodeName, Operator};

/// The one root every item in these walks descends from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct MediaId(u64);

/// The key the whole file works on.
const MEDIA: MediaId = MediaId(7);

/// **THE PROJECTION**, standing in for the one a record declaration emits.
///
/// Every item belongs to [`MEDIA`], which is what a page of one media's records looks like to a
/// node. `observe` is the empty program, exactly as the emitted
/// [`RootProjection`](crate::RootProjection)'s is: the counting is the framework's own act inside
/// the loop and does not go through this seam.
///
/// It NAMES a family, so that opening the table resolves `[registry.media]` where a document wrote
/// one.
struct OneMedia;

impl Attributes<u64> for OneMedia {
  const FAMILY: &'static str = "media";

  type Root = MediaId;

  fn root(&self, _record: &u64) -> MediaId {
    MEDIA
  }

  fn observe(&self, _root: &MediaId, _worker: &NodeName, _arrival: &Arrival) {}
}

/// Emits `2 * item` — one in, one out.
struct Doubling;

impl Operator for Doubling {
  type Error = core::convert::Infallible;
  type In = u64;
  type Out = u64;

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

/// Emits `n` outputs per item — the 1→N shape a tree is built out of.
struct Fanning(u64);

impl Operator for Fanning {
  type Error = core::convert::Infallible;
  type In = u64;
  type Out = u64;

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

// ── The walk's own instruments ──────────────────────────────────────────────────────────────────

/// Send `keys` as one batch and keep the oneshot.
fn send(out: &Outbox<ItemId, u64>, keys: &[u64]) -> AckReceiver<ItemId> {
  let (ack, answers) = ack_channel();
  let items = keys
    .iter()
    .map(|&key| Item::new(ItemId::new(key), key))
    .collect();
  out
    .deliver(Delivery::new(Payload::Batch(items), ack))
    .expect("the resident is listening");
  answers
}

/// Poll until the answer arrives, or give up.
fn settled(answers: &AckReceiver<ItemId>, within: Duration) -> Option<Settled<ItemId>> {
  let deadline = Instant::now() + within;
  loop {
    match answers.take() {
      Answer::Settled(settled) => return Some(settled),
      Answer::HungUp => return None,
      Answer::Waiting if Instant::now() >= deadline => return None,
      Answer::Waiting => thread::sleep(Duration::from_millis(2)),
    }
  }
}

/// Take one delivery off `inbox`, or give up.
fn taken(inbox: &Inbox<ItemId, u64>, within: Duration) -> Option<Delivery<u64>> {
  let deadline = Instant::now() + within;
  loop {
    match inbox.park(Duration::from_millis(5)) {
      Some(Wake::Delivered(delivery)) => return Some(delivery),
      None => return None,
      Some(Wake::Sweep | Wake::Tick(_)) if Instant::now() >= deadline => return None,
      Some(Wake::Sweep | Wake::Tick(_)) => {}
    }
  }
}

/// Answer a delivery in full, and hand back what it carried.
fn release_all(delivery: Delivery<u64>) -> Vec<u64> {
  let (payload, ack) = delivery.into_parts();
  let ack = ack.expect("a delivery off the wire carries its custody token");
  let released: HashSet<ItemId> = payload.keys().copied().collect();
  let values = payload.into_iter().map(|item| *item.value()).collect();
  ack.send(Ack::new(released, "consumer", Lifecycle::Persisted(())));
  values
}

/// The deployment's registries, at the shipped defaults.
fn registries() -> Arc<Registries> {
  Arc::new(Registries::new(RegistryOptions::new()))
}

/// [`MEDIA`]'s state, read through the family this file's projection names.
fn state(registries: &Registries) -> RootState {
  registries
    .of::<MediaId>()
    .map_or(RootState::Idle, |family| family.state(&MEDIA))
}

/// Poll until the inflight count reads `want`, and hand back whatever it read.
///
/// It is a wait for a THREAD to get somewhere and never a wait for a number to settle: every
/// assertion that matters is taken at a barrier the walk holds shut, and this only closes the gap
/// between handing a resident work and that resident's loop having done it.
fn awaiting(registries: &Registries, want: u32, within: Duration) -> u32 {
  let deadline = Instant::now() + within;
  loop {
    let seen = state(registries).inflight();
    if seen == want || Instant::now() >= deadline {
      return seen;
    }
    thread::sleep(Duration::from_millis(2));
  }
}

/// The `since` of the analysis now running, or a panic naming what was found instead.
fn analyzing_since(registries: &Registries) -> Instant {
  match state(registries) {
    RootState::Analyzing { since, .. } => since,
    other => panic!("the key is not analyzing: {other:?}"),
  }
}

// ── R1: dispatch before ack ─────────────────────────────────────────────────────────────────────

/// **R1, HELD OPEN.** A node stopped inside its own dispatch has already counted its output out and
/// has NOT yet answered its input.
///
/// The barrier is a downstream edge with room for ONE delivery and a walk that leaves that one
/// sitting in it. The second delivery's item is counted in `reconcile`, then `dispatch` awaits room
/// that will not come — so the node is parked between the two, which is precisely the window R1 is
/// about, and the walk can look into it for as long as it likes.
///
/// The edge is left FULL rather than drained-and-held, and that distinction is the walk's own
/// footgun: taking a delivery off the channel frees its slot, so a walk that holds the delivery
/// while the channel is empty holds no barrier at all.
///
/// What a REVERSED order would read here is the whole point: an ack sent before the count would
/// release delivery two and leave the count at 1 — the first item, still sitting unanswered on the
/// edge. Two is the reading only the ruled order produces.
#[test]
fn a_node_counts_its_output_out_before_it_answers_the_input() {
  let registries = registries();
  let (feed, inbox) = channel::<ItemId, u64>(8);
  // ROOM FOR ONE. The second dispatch is what parks the node.
  let (out, downstream) = channel::<ItemId, u64>(1);
  let resident = Resident::new("double", Doubling, inbox)
    .attributing(OneMedia)
    .publish(out)
    .with_registries(Arc::clone(&registries))
    .with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });

  let first = send(&feed, &[1]);
  assert!(
    settled(&first, Duration::from_secs(2)).is_some(),
    "the first delivery had room and was answered"
  );
  assert_eq!(awaiting(&registries, 1, Duration::from_secs(2)), 1);

  let second = send(&feed, &[2]);
  // THE BARRIER. The edge holds the first delivery and has room for no second, so the node is
  // inside `dispatch` and cannot reach `settle`.
  assert_eq!(
    awaiting(&registries, 2, Duration::from_secs(2)),
    2,
    "the second item is counted out while its input is still unanswered"
  );
  assert!(
    settled(&second, Duration::from_millis(80)).is_none(),
    "the ack is what has NOT been sent yet — that is the whole of R1"
  );
  assert!(matches!(state(&registries), RootState::Analyzing { .. }));

  // Let it through: taking the first delivery frees the slot, which lets the parked dispatch land
  // and the second delivery finally settle.
  let held = taken(&downstream, Duration::from_secs(2)).expect("the first delivery");
  assert!(
    settled(&second, Duration::from_secs(2)).is_some(),
    "the ack follows the dispatch that was waiting for room"
  );
  assert_eq!(release_all(held), [2]);
  assert_eq!(awaiting(&registries, 1, Duration::from_secs(2)), 1);

  let last = taken(&downstream, Duration::from_secs(2)).expect("the second delivery");
  assert_eq!(release_all(last), [4]);
  assert_eq!(awaiting(&registries, 0, Duration::from_secs(2)), 0);
  assert_eq!(
    state(&registries),
    RootState::Idle,
    "the last answer is what ends the analysis"
  );

  drop(feed);
  engine.join().expect("the engine thread");
}

// ── R3: never ack what you hold ─────────────────────────────────────────────────────────────────

/// **R3.** A node holding an input under [`Chained`](AckMode::Chained) has its outputs counted out
/// and its input unanswered, and stays that way for exactly as long as the walk holds the outputs.
///
/// This is the buffered and windowed shape stated at the seam that already implements it: a chained
/// node does not release an input until every arm the input produced has come back, so *never ack
/// what you hold* is not a rule a node has to remember — it is what the ack mode IS.
#[test]
fn a_chained_node_holds_its_input_while_its_outputs_are_out() {
  let registries = registries();
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let (out, downstream) = channel::<ItemId, u64>(8);
  let resident = Resident::new("fan", Fanning(3), inbox)
    .attributing(OneMedia)
    .publish(out)
    .with_ack(AckMode::Chained)
    .with_registries(Arc::clone(&registries))
    .with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });

  let answers = send(&feed, &[1]);
  let held = taken(&downstream, Duration::from_secs(2)).expect("the fan-out");
  // THE BARRIER: the walk has the custody token, so no `-1` can have happened.
  assert_eq!(
    awaiting(&registries, 3, Duration::from_secs(2)),
    3,
    "three arms out, and the input still owed"
  );
  assert!(
    settled(&answers, Duration::from_millis(80)).is_none(),
    "the input is HELD — chained does not answer over work that is still out"
  );

  assert_eq!(release_all(held), [10, 11, 12]);
  assert!(
    settled(&answers, Duration::from_secs(2)).is_some(),
    "the input is released once every arm came back"
  );
  assert_eq!(awaiting(&registries, 0, Duration::from_secs(2)), 0);
  assert_eq!(state(&registries), RootState::Idle);

  drop(feed);
  engine.join().expect("the engine thread");
}

// ── The timeline: a tree, and a count that never reaches zero inside it ─────────────────────────

/// **THE FAKE TREE.** Intake, a head, two children and three grandchildren — and the count never
/// touches zero until the last leaf is answered.
///
/// # The instrument is `since`, not a sample
///
/// A poll that never SAW zero would prove nothing; a poll can miss. So the proof is
/// [`Analyzing`](RootState::Analyzing)'s `since`: a key that reached zero would have gone `Idle`,
/// and the dispatch that followed would have opened a NEW analysis stamped with a new monotonic
/// reading. The `since` this walk reads at every barrier is the one the INTAKE wrote, before any
/// node had run — so the analysis it belongs to is the same one, unbroken, across every hop.
///
/// # The intake's own two lines
///
/// `intake` then `dispatched` is what the registry's driver does for an item it feeds a head
/// through [`Feed::give_acked`](crate::Feed::give_acked), and `observed` is what it does when that
/// head's ack comes back. The driver is a later knife; the two lines are its, spelled here because
/// the property under test is exactly what they are for. Without the `+1` for the fed item there is
/// a window — between the intake and the head's first dispatch — in which the count is zero, and
/// what keeps that window from reading as *finished* is only that an intake leaves the key
/// `Analyzing` rather than `Idle`.
#[test]
fn the_count_never_reaches_zero_in_the_middle_of_a_tree() {
  let registries = registries();
  let family = registries.open::<MediaId>("media");

  // Leaves first, so the wiring below reads root-downwards.
  let (left_out, left_leaves) = channel::<ItemId, u64>(8);
  let (right_out, right_leaves) = channel::<ItemId, u64>(8);
  let (to_left, left_inbox) = channel::<ItemId, u64>(8);
  let (to_right, right_inbox) = channel::<ItemId, u64>(8);
  let (feed, head_inbox) = channel::<ItemId, u64>(8);

  // TWO grandchildren from the left child, ONE from the right: three leaves in all.
  let left = Resident::new("left", Fanning(2), left_inbox)
    .attributing(OneMedia)
    .publish(left_out)
    .with_registries(Arc::clone(&registries))
    .with_sweep(Duration::from_millis(5));
  let right = Resident::new("right", Fanning(1), right_inbox)
    .attributing(OneMedia)
    .publish(right_out)
    .with_registries(Arc::clone(&registries))
    .with_sweep(Duration::from_millis(5));
  // The head's one emission goes onto BOTH edges — one item per edge, which is the fan-out that
  // makes two children out of one record.
  let head = Resident::new("head", Doubling, head_inbox)
    .attributing(OneMedia)
    .publish(to_left)
    .publish(to_right)
    .with_registries(Arc::clone(&registries))
    .with_sweep(Duration::from_millis(5));

  let engines = [
    thread::spawn(move || {
      let mut left = left;
      left.run()
    }),
    thread::spawn(move || {
      let mut right = right;
      right.run()
    }),
    thread::spawn(move || {
      let mut head = head;
      head.run()
    }),
  ];

  // ── The intake ────────────────────────────────────────────────────────────────────────────────
  let opened = Stamp::now();
  let _taken_in = family.intake(&MEDIA, opened);
  let _fed = family.dispatched(&MEDIA, opened);
  assert_eq!(
    state(&registries),
    RootState::Analyzing {
      inflight: 1,
      since: opened.monotonic(),
    },
    "the fed item is out until the head answers it"
  );

  // ── The head, and the two children it feeds ───────────────────────────────────────────────────
  let fed = send(&feed, &[1]);
  assert!(
    settled(&fed, Duration::from_secs(5)).is_some(),
    "the head answered the fed item"
  );
  // The driver's own `-1`, paired with the `+1` above. It is safe HERE and nowhere earlier: by the
  // time the head's ack is in hand, R1 says the head's own two items are already counted out.
  let _answered = family.observed(&MEDIA, Stamp::now());

  // Three leaves, all held: nothing downstream of the children can be decremented while the walk
  // holds their custody tokens.
  let left_held = taken(&left_leaves, Duration::from_secs(5)).expect("the left leaves");
  let right_held = taken(&right_leaves, Duration::from_secs(5)).expect("the right leaf");
  assert_eq!(
    awaiting(&registries, 3, Duration::from_secs(5)),
    3,
    "two leaves from the left child and one from the right"
  );

  // ── THE ASSERTION THIS WALK EXISTS FOR ────────────────────────────────────────────────────────
  assert_eq!(
    analyzing_since(&registries),
    opened.monotonic(),
    "the analysis the intake opened is the one still running — a count that had touched zero \
     anywhere in the tree would have gone Idle and stamped a new one"
  );

  // ── The leaves come back, one branch at a time ────────────────────────────────────────────────
  // The head doubled 1 into 2, and each child fanned 2 into `2 * 10 + arm`.
  assert_eq!(release_all(right_held), [20]);
  assert_eq!(awaiting(&registries, 2, Duration::from_secs(5)), 2);
  assert_eq!(
    analyzing_since(&registries),
    opened.monotonic(),
    "still the same analysis"
  );

  assert_eq!(release_all(left_held), [20, 21]);
  assert_eq!(
    awaiting(&registries, 0, Duration::from_secs(5)),
    0,
    "the last leaf's answer is what empties it"
  );
  assert_eq!(
    state(&registries),
    RootState::Idle,
    "and zero is what ends the analysis"
  );

  drop(feed);
  for engine in engines {
    engine.join().expect("the engine thread");
  }
}

// ── Retirement, over a count that is actually running ───────────────────────────────────────────

/// Retiring a key with work out goes through [`Retiring`](RootState::Retiring) and lands when the
/// last answer comes back — the drain, driven by a real node's real dispatch rather than by
/// arithmetic on an entry.
#[test]
fn a_retirement_drains_against_the_work_a_node_actually_has_out() {
  let registries = registries();
  let family = registries.open::<MediaId>("media");
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let (out, downstream) = channel::<ItemId, u64>(8);
  let resident = Resident::new("fan", Fanning(2), inbox)
    .attributing(OneMedia)
    .publish(out)
    .with_registries(Arc::clone(&registries))
    .with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });

  let answers = send(&feed, &[1]);
  assert!(settled(&answers, Duration::from_secs(2)).is_some());
  let held = taken(&downstream, Duration::from_secs(2)).expect("the fan-out");
  assert_eq!(awaiting(&registries, 2, Duration::from_secs(2)), 2);

  let now = Stamp::now();
  let _moved = family.retire(&MEDIA, RetireOrigin::Vanished, now);
  assert_eq!(
    state(&registries),
    RootState::Retiring {
      inflight: 2,
      since: now.monotonic(),
    },
    "the retirement waits on the work already out"
  );

  assert_eq!(release_all(held), [10, 11]);
  let deadline = Instant::now() + Duration::from_secs(5);
  while !matches!(state(&registries), RootState::Retired { .. }) {
    assert!(Instant::now() < deadline, "{:?}", state(&registries));
    thread::sleep(Duration::from_millis(2));
  }
  let RootState::Retired {
    origin, late_tails, ..
  } = state(&registries)
  else {
    unreachable!("the loop above just checked")
  };
  assert_eq!(origin, RetireOrigin::Vanished);
  assert!(
    !late_tails,
    "the drain reached zero on its own, so nothing can land after the row"
  );

  drop(feed);
  engine.join().expect("the engine thread");
}

/// **A CONSUMER THAT LEAVES IS STILL A `-1`.** Work sent to an edge that hung up is never answered,
/// so a count that only ever credited real answers would hold the key analyzing forever.
#[test]
fn a_hung_up_consumer_gives_its_count_back() {
  let registries = registries();
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let (out, downstream) = channel::<ItemId, u64>(8);
  drop(downstream);
  let resident = Resident::new("fan", Fanning(3), inbox)
    .attributing(OneMedia)
    .publish(out)
    .with_registries(Arc::clone(&registries))
    .with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });

  let _answers = send(&feed, &[1]);
  assert_eq!(
    awaiting(&registries, 0, Duration::from_secs(5)),
    0,
    "the three items went nowhere and were credited back"
  );
  assert_eq!(state(&registries), RootState::Idle);

  drop(feed);
  engine.join().expect("the engine thread");
}

// ── The two absences ────────────────────────────────────────────────────────────────────────────

/// **A NODE WITH NO PROJECTION CONTRIBUTES NOTHING** — the documented gap, asserted so that it
/// stays a gap rather than becoming a family of one erased key.
///
/// A resident carrying no attribution has `Root = ()`, which is the absence spelled as a type. It
/// runs with the registries wired and opens no family at all; see
/// [`Registries::counting`](crate::Registries::counting), where that refusal is argued.
#[test]
fn a_node_with_no_attribution_opens_no_family() {
  let registries = registries();
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let (out, downstream) = channel::<ItemId, u64>(8);
  let resident = Resident::new("double", Doubling, inbox)
    .publish(out)
    .with_registries(Arc::clone(&registries))
    .with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });

  let answers = send(&feed, &[1]);
  assert!(settled(&answers, Duration::from_secs(2)).is_some());
  assert_eq!(
    release_all(taken(&downstream, Duration::from_secs(2)).expect("the emission")),
    [2]
  );
  assert!(
    registries.is_empty(),
    "no projection means no family, and never a family keyed by the unit"
  );

  drop(feed);
  engine.join().expect("the engine thread");
}

/// A resident with no registries wired runs exactly as it always did — the ordinary state of every
/// hand-built one, and it must cost nothing: no family, no panic, no changed answer.
#[test]
fn a_resident_with_no_registries_runs_unchanged() {
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let (out, downstream) = channel::<ItemId, u64>(8);
  let resident = Resident::new("double", Doubling, inbox)
    .attributing(OneMedia)
    .publish(out)
    .with_sweep(Duration::from_millis(5));
  assert!(resident.registries().is_none());
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });

  let answers = send(&feed, &[3]);
  assert!(settled(&answers, Duration::from_secs(2)).is_some());
  assert_eq!(
    release_all(taken(&downstream, Duration::from_secs(2)).expect("the emission")),
    [6]
  );

  drop(feed);
  engine.join().expect("the engine thread");
}

// ── The grain of the count ──────────────────────────────────────────────────────────────────────

/// A delivery of MANY records from one root is many ITEMS, and the count is per item.
///
/// It is the same distinction the journal draws one line over — a page of 256 records from one
/// media is ONE `(root, node)` row — and taking it the other way here is what would make a key idle
/// while 255 of its records were still out.
#[test]
fn a_page_of_one_roots_records_counts_per_item() {
  let registries = registries();
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let (out, downstream) = channel::<ItemId, u64>(8);
  let resident = Resident::new("double", Doubling, inbox)
    .attributing(OneMedia)
    .publish(out)
    .with_registries(Arc::clone(&registries))
    .with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });

  let _answers = send(&feed, &[1, 2, 3, 4]);
  let held = taken(&downstream, Duration::from_secs(2)).expect("the batch");
  assert_eq!(
    awaiting(&registries, 4, Duration::from_secs(2)),
    4,
    "four records of one root are four items out, not one"
  );
  assert_eq!(release_all(held), [2, 4, 6, 8]);
  assert_eq!(awaiting(&registries, 0, Duration::from_secs(2)), 0);

  drop(feed);
  engine.join().expect("the engine thread");
}

/// A record fanned onto TWO edges is two items, two consumers and two separate answers — so it is
/// counted twice, and one consumer answering leaves the other's item still out.
#[test]
fn a_record_on_two_edges_is_counted_once_per_edge() {
  let registries = registries();
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let (left_out, left) = channel::<ItemId, u64>(8);
  let (right_out, right) = channel::<ItemId, u64>(8);
  let resident = Resident::new("double", Doubling, inbox)
    .attributing(OneMedia)
    .publish(left_out)
    .publish(right_out)
    .with_registries(Arc::clone(&registries))
    .with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });

  let _answers = send(&feed, &[1]);
  let left_held = taken(&left, Duration::from_secs(2)).expect("the left edge");
  let right_held = taken(&right, Duration::from_secs(2)).expect("the right edge");
  assert_eq!(
    awaiting(&registries, 2, Duration::from_secs(2)),
    2,
    "one record, two edges, two items out"
  );

  assert_eq!(release_all(left_held), [2]);
  assert_eq!(
    awaiting(&registries, 1, Duration::from_secs(2)),
    1,
    "one consumer answered and the other's item is still out"
  );
  assert_eq!(release_all(right_held), [2]);
  assert_eq!(awaiting(&registries, 0, Duration::from_secs(2)), 0);

  drop(feed);
  engine.join().expect("the engine thread");
}

/// Two residents sharing one [`Registries`] count into the SAME family table, which is what makes a
/// tree's count one number rather than one per node.
#[test]
fn every_resident_counts_into_the_one_shared_family() {
  let registries = registries();
  let (feed, inbox) = channel::<ItemId, u64>(8);
  let (out, downstream) = channel::<ItemId, u64>(8);
  let (second_feed, second_inbox) = channel::<ItemId, u64>(8);
  let (second_out, second_downstream) = channel::<ItemId, u64>(8);
  let first = Resident::new("first", Fanning(2), inbox)
    .attributing(OneMedia)
    .publish(out)
    .with_registries(Arc::clone(&registries))
    .with_sweep(Duration::from_millis(5));
  let second = Resident::new("second", Fanning(3), second_inbox)
    .attributing(OneMedia)
    .publish(second_out)
    .with_registries(Arc::clone(&registries))
    .with_sweep(Duration::from_millis(5));
  let engines = [
    thread::spawn(move || {
      let mut first = first;
      first.run()
    }),
    thread::spawn(move || {
      let mut second = second;
      second.run()
    }),
  ];

  let _first = send(&feed, &[1]);
  let held = taken(&downstream, Duration::from_secs(2)).expect("the first fan-out");
  assert_eq!(awaiting(&registries, 2, Duration::from_secs(2)), 2);

  let _second = send(&second_feed, &[1]);
  let second_held = taken(&second_downstream, Duration::from_secs(2)).expect("the second fan-out");
  assert_eq!(
    awaiting(&registries, 5, Duration::from_secs(2)),
    5,
    "the second node's three add to the first node's two"
  );
  assert_eq!(registries.families(), 1, "one root type is one family");

  release_all(held);
  release_all(second_held);
  assert_eq!(awaiting(&registries, 0, Duration::from_secs(5)), 0);

  drop(feed);
  drop(second_feed);
  for engine in engines {
    engine.join().expect("the engine thread");
  }
}