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
use std::collections::{HashMap, HashSet, VecDeque};

use super::super::{
  Ack, Custody, ItemId, Lifecycle, Lineage, Outbound, Owed, Owing, Station, ack_channel,
};
use crate::{Skip, SkipReason};

/// The keys one harvest crossed from held to released.
fn released(window: &mut Outbound<ItemId>) -> Vec<ItemId> {
  window.harvest().released().copied().collect()
}

/// Send `keys` as one delivery and answer it with `released`, returning the window's report.
fn round(window: &mut Outbound<ItemId>, keys: &[u64], released: &[u64]) -> Vec<Station> {
  let (ack, answers) = ack_channel::<ItemId>();
  window.record(keys.iter().copied().map(ItemId::new), answers);
  let set: HashSet<ItemId> = released.iter().copied().map(ItemId::new).collect();
  ack.send(Ack::new(set, "consumer", Lifecycle::Persisted(())));
  window
    .harvest()
    .answers()
    .iter()
    .filter_map(|answer| answer.observation().station())
    .collect()
}

#[test]
fn a_fully_released_delivery_moves_the_watermark_to_its_last_key() {
  let mut window = Outbound::new();
  assert!(window.position().is_none());
  assert!(window.is_drained());

  let stations = round(&mut window, &[0, 1, 2], &[0, 1, 2]);
  assert_eq!(stations, [Station::Persisted]);
  assert_eq!(window.position(), Some(&ItemId::new(2)));
  assert_eq!(window.outstanding(), 0);
  assert!(window.is_drained());
}

#[test]
fn a_gap_stops_the_watermark_at_the_item_before_it() {
  // 250 of 256 released and 6 held is an ordinary answer, and the window's job is to advance to the
  // last CONTIGUOUS one rather than the last released one. Here 2 is held, so 3 and 4 being released
  // buys nothing: resuming past 2 would skip it.
  let mut window = Outbound::new();
  round(&mut window, &[0, 1, 2, 3, 4], &[0, 1, 3, 4]);
  assert_eq!(window.position(), Some(&ItemId::new(1)));
  assert_eq!(window.outstanding(), 1);
  assert!(!window.is_drained());
}

#[test]
fn the_gap_closing_lets_the_watermark_cross_everything_behind_it() {
  let mut window = Outbound::new();
  round(&mut window, &[0, 1, 2, 3, 4], &[0, 1, 3, 4]);
  assert_eq!(window.position(), Some(&ItemId::new(1)));

  // A later answer naming the held key — from a re-delivery — completes the prefix in one step.
  let (ack, answers) = ack_channel::<ItemId>();
  window.record([ItemId::new(5)], answers);
  ack.send(Ack::new(
    [ItemId::new(2), ItemId::new(5)].into_iter().collect(),
    "consumer",
    Lifecycle::Persisted(()),
  ));
  window.harvest();
  assert_eq!(window.position(), Some(&ItemId::new(5)));
  assert!(window.is_drained());
}

#[test]
fn the_watermark_walks_the_send_order_and_not_the_key_order() {
  // Keys sent out of order: the window's order is the SEND order, so releasing 9 and 7 (the first
  // two sent) advances past both even though 7 < 9.
  let mut window = Outbound::new();
  round(&mut window, &[9, 7, 8], &[9, 7]);
  assert_eq!(window.position(), Some(&ItemId::new(7)));
}

#[test]
fn an_unanswered_delivery_holds_the_window_and_a_dropped_one_is_reported_lost() {
  let mut window = Outbound::new();
  let (ack, answers) = ack_channel::<ItemId>();
  window.record([ItemId::new(0), ItemId::new(1)], answers);

  // Still waiting: no observation, no advance, nothing lost.
  let harvest = window.harvest();
  assert!(harvest.is_empty());
  assert_eq!(harvest.released().count(), 0);
  assert_eq!(window.lost(), 0);
  assert_eq!(window.outstanding(), 2);

  drop(ack);
  window.harvest();
  assert_eq!(window.lost(), 1, "a dropped oneshot is a lost delivery");
  assert!(window.position().is_none(), "nothing was released");
  assert_eq!(window.outstanding(), 2);
}

#[test]
fn rewinding_retracts_the_tail_past_the_watermark_and_nothing_before_it() {
  let mut window = Outbound::new();
  round(&mut window, &[0, 1], &[0, 1]);
  assert_eq!(window.position(), Some(&ItemId::new(1)));

  // Two more deliveries: the first answered, the second dropped. The watermark is at 3, so the
  // rewind takes back 4 and 5 and leaves everything up to 3 alone.
  round(&mut window, &[2, 3], &[2, 3]);
  let (ack, answers) = ack_channel::<ItemId>();
  window.record([ItemId::new(4), ItemId::new(5)], answers);
  drop(ack);
  window.harvest();
  assert_eq!(window.lost(), 1);

  let retracted = window.rewind();
  assert_eq!(retracted, [ItemId::new(4), ItemId::new(5)]);
  assert_eq!(window.position(), Some(&ItemId::new(3)));
  assert_eq!(window.lost(), 0, "a rewind clears what it acted on");
  assert!(window.is_drained());
}

#[test]
fn a_key_crosses_from_held_to_released_exactly_once() {
  // The lineage retires an output by its key, so a key reported twice would double-decrement a
  // refcount and release an input whose other arm never landed.
  let mut window = Outbound::new();
  let (first, first_answers) = ack_channel::<ItemId>();
  window.record([ItemId::new(0), ItemId::new(1)], first_answers);
  first.send(Ack::<ItemId, ()>::new(
    [ItemId::new(0)].into_iter().collect(),
    "consumer",
    Lifecycle::Persisted(()),
  ));
  assert_eq!(released(&mut window), [ItemId::new(0)]);

  let (second, second_answers) = ack_channel::<ItemId>();
  window.record([ItemId::new(2)], second_answers);
  // The same key again, plus a new one. Only the new one crosses.
  second.send(Ack::<ItemId, ()>::new(
    [ItemId::new(0), ItemId::new(2)].into_iter().collect(),
    "consumer",
    Lifecycle::Persisted(()),
  ));
  assert_eq!(released(&mut window), [ItemId::new(2)]);
}

#[test]
fn a_harvest_pairs_every_key_with_the_answer_that_spoke_for_it() {
  // The pairing is the whole reason this type is one list rather than two. Two consumers of one
  // edge answer differently in the same pass, and a journal keyed `(root, node)` has to be able
  // to say which station belongs to which key — which two flat lists cannot.
  let mut window = Outbound::new();
  let (first, first_answers) = ack_channel::<ItemId>();
  window.record([ItemId::new(0), ItemId::new(1)], first_answers);
  let (second, second_answers) = ack_channel::<ItemId>();
  window.record([ItemId::new(2)], second_answers);

  first.send(Ack::<ItemId, ()>::new(
    [ItemId::new(0), ItemId::new(1)].into_iter().collect(),
    "titles",
    Lifecycle::Persisted(()),
  ));
  second.send(Ack::<ItemId, ()>::new(
    HashSet::new(),
    "captions",
    Lifecycle::Skipped(Skip::new(SkipReason::Filtered)),
  ));

  let harvest = window.harvest();
  let paired: Vec<(u64, &str, Station)> = harvest
    .pairs()
    .map(|(key, answer)| {
      (
        key.seq(),
        answer.worker().as_str(),
        answer
          .observation()
          .station()
          .expect("an ack carries an arrival"),
      )
    })
    .collect();
  assert_eq!(
    paired,
    [
      (0, "titles", Station::Persisted),
      (1, "titles", Station::Persisted),
      (2, "captions", Station::Skipped),
    ]
  );
}

#[test]
fn a_failed_answer_releases_nothing_and_still_names_every_key_it_covered() {
  // The reason `covered` exists at all. A failure is the observation a reader most wants written
  // down, and it releases NOTHING — so a pairing built out of released keys alone would drop
  // exactly the rows that matter and keep only the ones that went well.
  let mut window = Outbound::new();
  let (ack, answers) = ack_channel::<ItemId>();
  window.record([ItemId::new(0), ItemId::new(1)], answers);
  ack.send(Ack::<ItemId, ()>::holding(
    "decode",
    Lifecycle::Failed(super::super::Failure::new(std::io::Error::other(
      "no codec",
    ))),
  ));

  let harvest = window.harvest();
  assert_eq!(harvest.released().count(), 0, "a failure holds the window");
  let [answer] = harvest.answers() else {
    panic!("one answer");
  };
  assert_eq!(answer.worker().as_str(), "decode");
  assert_eq!(answer.observation().station(), Some(Station::Failed));
  assert_eq!(answer.covered(), [ItemId::new(0), ItemId::new(1)]);
  assert_eq!(harvest.pairs().count(), 2);
  assert!(window.position().is_none());
}

#[test]
fn an_obligation_settles_once_with_what_it_has() {
  let (ack, answers) = ack_channel::<ItemId>();
  let mut owed = Owed::open(
    [ItemId::new(0), ItemId::new(1), ItemId::new(2)],
    Some(Custody::sole(ack)),
  );
  assert_eq!(owed.held(), 3);
  assert!(!owed.is_complete());
  assert!(!owed.is_settled());

  owed.release(ItemId::new(0));
  owed.release(ItemId::new(2));
  // A key it was never opened with speaks for nothing.
  owed.release(ItemId::new(99));
  assert_eq!(owed.held(), 1);

  assert!(owed.settle(
    "consumer",
    Lifecycle::<()>::Skipped(Skip::new(SkipReason::Filtered))
  ));
  assert!(owed.is_settled());
  // A second settle has nothing to answer with: a oneshot answers once.
  assert!(!owed.settle("consumer", Lifecycle::<()>::Processed(())));

  let answer = answers.take();
  let super::super::Answer::Settled(settled) = answer else {
    panic!("answered once");
  };
  assert_eq!(settled.released().len(), 2);
  assert!(settled.released().contains(&ItemId::new(0)));
  assert!(!settled.released().contains(&ItemId::new(1)));
  assert_eq!(settled.observation().station(), Some(Station::Skipped));
  assert_eq!(settled.worker().as_str(), "consumer");
}

#[test]
fn an_obligation_whose_sender_hung_up_reports_that_it_was_not_heard() {
  let (ack, answers) = ack_channel::<ItemId>();
  let mut owed = Owed::open([ItemId::new(0)], Some(Custody::sole(ack)));
  drop(answers);
  owed.release(ItemId::new(0));
  assert!(!owed.settle("consumer", Lifecycle::<()>::Processed(())));
}

#[test]
fn an_input_with_no_outputs_is_complete_at_once() {
  let mut lineage: Lineage<u8, ItemId> = Lineage::new();
  assert!(lineage.is_empty());
  assert!(lineage.expect(7, []), "nothing to wait for");
  assert!(lineage.is_empty());
  assert_eq!(lineage.waiting(), 0);
}

#[test]
fn a_fan_out_joins_on_every_arm_and_not_on_the_first() {
  // The mutation this pins: releasing the input on the FIRST arm's ack. Three arms, and the input
  // is owed until the third comes back.
  let mut lineage: Lineage<u8, ItemId> = Lineage::new();
  let arms = [ItemId::new(10), ItemId::new(11), ItemId::new(12)];
  assert!(!lineage.expect(7, arms));
  assert_eq!(lineage.waiting(), 1);

  assert_eq!(lineage.retire(&arms[0]), None);
  assert_eq!(lineage.retire(&arms[2]), None);
  assert_eq!(
    lineage.retire(&arms[1]),
    Some(7),
    "the last arm completes it"
  );
  assert!(lineage.is_empty());
}

#[test]
fn two_inputs_are_counted_apart() {
  let mut lineage: Lineage<u8, ItemId> = Lineage::new();
  lineage.expect(1, [ItemId::new(10), ItemId::new(11)]);
  lineage.expect(2, [ItemId::new(20)]);
  assert_eq!(lineage.waiting(), 2);

  assert_eq!(lineage.retire(&ItemId::new(20)), Some(2));
  assert_eq!(lineage.waiting(), 1);
  assert_eq!(lineage.retire(&ItemId::new(10)), None);
  assert_eq!(lineage.retire(&ItemId::new(11)), Some(1));
  assert!(lineage.is_empty());
}

#[test]
fn an_output_nobody_recorded_retires_nothing() {
  let mut lineage: Lineage<u8, ItemId> = Lineage::new();
  lineage.expect(1, [ItemId::new(10)]);
  assert_eq!(lineage.retire(&ItemId::new(99)), None);
  // And a second answer for a key already retired is equally inert.
  assert_eq!(lineage.retire(&ItemId::new(10)), Some(1));
  assert_eq!(lineage.retire(&ItemId::new(10)), None);
}

#[test]
fn retracting_an_arm_never_completes_an_input() {
  // A retracted output was NOT released — the consumer hung up — so treating it as one would
  // release an input whose effect never landed. It comes back under a fresh key on the re-send.
  let mut lineage: Lineage<u8, ItemId> = Lineage::new();
  lineage.expect(1, [ItemId::new(10)]);
  assert_eq!(lineage.retract(&ItemId::new(10)), Some(1));
  assert!(lineage.is_empty(), "the count went with the arm");
  assert_eq!(lineage.retire(&ItemId::new(10)), None);

  // The re-send re-attributes, and the join is the same join.
  assert!(!lineage.expect(1, [ItemId::new(11)]));
  assert_eq!(lineage.retire(&ItemId::new(11)), Some(1));
}

#[test]
fn a_window_reserved_for_its_deliveries_starts_where_an_empty_one_does() {
  let mut window = Outbound::<ItemId>::with_capacity(4);
  assert!(window.position().is_none());
  assert!(window.is_drained());
  assert_eq!(window.outstanding(), 0);
  assert_eq!(window.lost(), 0);

  // The reservation is room and never content: the window still starts at no position and the first
  // delivery still moves the watermark exactly as far as its answer says.
  let stations = round(&mut window, &[0, 1], &[0, 1]);
  assert_eq!(stations, [Station::Persisted]);
  assert_eq!(window.position(), Some(&ItemId::new(1)));
}

/// A vector's reallocation count on its way to `pushes` items, starting from `reserved`.
///
/// Growth STEPS and not wall time, because the count is the fact under the timing: reaching a page
/// by doubling allocates once per doubling and copies everything already held, while one sized up
/// front allocates once and copies nothing.
fn growth_steps(reserved: usize, pushes: usize) -> usize {
  let mut items: Vec<ItemId> = Vec::with_capacity(reserved);
  let mut capacity = items.capacity();
  let mut steps = 0;
  for seq in 0..pushes as u64 {
    items.push(ItemId::new(seq));
    if items.capacity() != capacity {
      capacity = items.capacity();
      steps += 1;
    }
  }
  steps
}

#[test]
fn answer_capacity_is_taken_where_the_size_is_known_and_not_where_it_is_guessed() {
  // KNOWN: an answer states the keys it released, so the list a harvest builds for it has an exact
  // ceiling before the first push — which is why `harvest` sizes that one.
  assert_eq!(
    growth_steps(256, 256),
    0,
    "a list reserved for the page it is about never grows again"
  );
  let grown = growth_steps(0, 256);
  assert!(
    grown >= 6,
    "reaching a page by doubling costs {grown} reallocations and {grown} copies of the prefix"
  );

  // GUESSED: the harvest's two outer collections are built on every pass, and most passes find no
  // answer at all. Empty costs nothing; a reservation sized from the flight count would pay a real
  // allocation on every idle look — which is why those two stay `new`.
  assert_eq!(Vec::<ItemId>::new().capacity(), 0);
  assert_eq!(HashMap::<ItemId, usize>::new().capacity(), 0);
  assert!(Vec::<ItemId>::with_capacity(8).capacity() >= 8);
}

/// An id minter in the two shapes the window's keys could be given, so one scenario can be run
/// under both.
struct Minter {
  next: u64,
  freed: Vec<u64>,
  reusing: bool,
}

impl Minter {
  /// What the drive actually mints: a counter that only ever goes up, so a freed id is dead
  /// forever.
  const fn monotonic() -> Self {
    Self {
      next: 0,
      freed: Vec::new(),
      reusing: false,
    }
  }

  /// What a slab is: a free list, so the next allocation gets the last id handed back.
  const fn reusing() -> Self {
    Self {
      next: 0,
      freed: Vec::new(),
      reusing: true,
    }
  }

  fn mint(&mut self) -> ItemId {
    if self.reusing
      && let Some(seq) = self.freed.pop()
    {
      return ItemId::new(seq);
    }
    let seq = self.next;
    self.next += 1;
    ItemId::new(seq)
  }

  fn free(&mut self, id: ItemId) {
    self.freed.push(id.seq());
  }
}

/// One retracted output, re-emitted, then answered LATE under the id the first emission had.
///
/// What the lineage says about the late answer is the whole test: `Some` released an input, `None`
/// held it.
fn late_answer_for_a_retracted_output(mut minter: Minter) -> Option<(u64, &'static str)> {
  let mut lineage: Lineage<(u64, &'static str), ItemId> = Lineage::new();

  // Delivery 1: input `a` produced one output, which went out under the id it was minted.
  let first = minter.mint();
  lineage.expect((1, "a"), [first]);

  // Its consumer hung up. The arm is retracted, `a` stays held, and the id is handed back to
  // whatever mints them.
  assert_eq!(lineage.retract(&first), Some((1, "a")));
  minter.free(first);

  // `a` is re-delivered — it was never released — and the node emits for it again.
  let second = minter.mint();
  lineage.expect((2, "a"), [second]);

  // And NOW the first delivery's answer arrives, naming the id it was given.
  lineage.retire(&first)
}

#[test]
fn a_reused_id_settles_the_wrong_input_and_a_monotonic_one_refuses_it() {
  // The hazard, demonstrated rather than argued: under key reuse the late answer finds the SECOND
  // delivery's entry, because the id it names is the id that delivery was given. The input is
  // released although the output it is waiting on never landed — silently, with no panic and no
  // refusal anywhere to notice.
  assert_eq!(
    late_answer_for_a_retracted_output(Minter::reusing()),
    Some((2, "a")),
    "a reused id let a dead answer release a live input"
  );

  // Monotonic ids make the same answer inert: the id it names belongs to nothing, so nothing is
  // released and `a` comes back on the sender's next pass, which is the safe outcome. This is what
  // rules `slab` out of the window and the lineage — the reuse IS the API.
  assert_eq!(
    late_answer_for_a_retracted_output(Minter::monotonic()),
    None,
    "a monotonic id made the dead answer inert"
  );
}

/// What one shape of the outstanding set cost over the same traffic.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
struct Counted {
  /// Hash probes: an insert into, or a lookup in, a keyed map.
  probes: usize,
  /// Slot addressings: an index computed from an id and then written.
  indexes: usize,
  /// Keys crossed from held to released — the work all three shapes must produce.
  released: usize,
}

impl Counted {
  const fn operations(&self) -> usize {
    self.probes + self.indexes
  }
}

/// Four pages of 256 with six held on each — the record's own partial-batch shape, run long enough
/// that the held remainder accumulates in front of the window.
const PAGES: usize = 4;
const PAGE: usize = 256;
const HELD: usize = 6;

/// The incumbent: a keyed map of what each answer named, then one pass over everything still
/// outstanding.
fn incumbent() -> Counted {
  let mut counted = Counted::default();
  let mut flights: VecDeque<Vec<(u64, bool)>> = VecDeque::new();
  for page in 0..PAGES {
    let base = (page * PAGE) as u64;
    flights.push_back((0..PAGE as u64).map(|i| (base + i, false)).collect());
    let answered: HashSet<u64> = (0..(PAGE - HELD) as u64).map(|i| base + i).collect();
    counted.probes += answered.len();
    for flight in &mut flights {
      for item in flight.iter_mut() {
        if item.1 {
          continue;
        }
        counted.probes += 1;
        if answered.contains(&item.0) {
          item.1 = true;
          counted.released += 1;
        }
      }
    }
    while let Some(flight) = flights.front_mut() {
      let crossed = flight
        .iter()
        .position(|item| !item.1)
        .unwrap_or(flight.len());
      flight.drain(..crossed);
      if !flight.is_empty() {
        break;
      }
      flights.pop_front();
    }
  }
  counted
}

/// The monotonic-id ring: the id IS the position, so an answer addresses its own slots and there is
/// no pass over the window at all.
fn ring() -> Counted {
  let mut counted = Counted::default();
  let mut slots: VecDeque<bool> = VecDeque::new();
  let mut base = 0u64;
  for page in 0..PAGES {
    let first = (page * PAGE) as u64;
    slots.extend(core::iter::repeat_n(false, PAGE));
    for i in 0..(PAGE - HELD) as u64 {
      counted.indexes += 1;
      let at = (first + i - base) as usize;
      if !slots[at] {
        slots[at] = true;
        counted.released += 1;
      }
    }
    while slots.front() == Some(&true) {
      slots.pop_front();
      base += 1;
    }
  }
  counted
}

/// A generational slot map: the key the map mints never crosses the wire, so the answer's own key
/// has to be translated first — the incumbent's hash, with a slot behind it rather than instead of
/// it.
fn slot_map() -> Counted {
  let mut counted = Counted::default();
  let mut translation: HashMap<u64, usize> = HashMap::new();
  let mut slots: Vec<bool> = Vec::new();
  for page in 0..PAGES {
    let base = (page * PAGE) as u64;
    for i in 0..PAGE as u64 {
      counted.probes += 1;
      translation.insert(base + i, slots.len());
      slots.push(false);
    }
    for i in 0..(PAGE - HELD) as u64 {
      counted.probes += 1;
      let Some(&at) = translation.get(&(base + i)) else {
        continue;
      };
      counted.indexes += 1;
      if !slots[at] {
        slots[at] = true;
        counted.released += 1;
      }
    }
  }
  counted
}

#[test]
fn the_outstanding_set_is_counted_against_a_ring_and_a_slot_map() {
  let incumbent = incumbent();
  let ring = ring();
  let slot_map = slot_map();

  // All three produce the same work, which is what makes the counts comparable at all.
  let crossed = PAGES * (PAGE - HELD);
  assert_eq!(incumbent.released, crossed);
  assert_eq!(ring.released, crossed);
  assert_eq!(slot_map.released, crossed);

  // And the real window agrees with the model of it: the same traffic, the same crossings. Without
  // this the counts would be a comparison of three models and none of the shipped code.
  let mut window = Outbound::<ItemId>::with_capacity(PAGES);
  let mut real = 0usize;
  for page in 0..PAGES {
    let base = (page * PAGE) as u64;
    let (ack, answers) = ack_channel::<ItemId>();
    window.record((0..PAGE as u64).map(|i| ItemId::new(base + i)), answers);
    let set: HashSet<ItemId> = (0..(PAGE - HELD) as u64)
      .map(|i| ItemId::new(base + i))
      .collect();
    ack.send(Ack::new(set, "consumer", Lifecycle::Persisted(())));
    real += window.harvest().released().count();
  }
  assert_eq!(real, crossed, "the model's traffic is the window's traffic");

  // The RING wins the count, and it wins it by removing the pass rather than by hashing faster: the
  // id is the position, so nothing is looked up and nothing that is not answered is visited.
  assert_eq!(ring.probes, 0, "a ring hashes nothing");
  assert!(
    ring.operations() < incumbent.operations(),
    "ring {} vs incumbent {}",
    ring.operations(),
    incumbent.operations()
  );

  // The SLOT MAP loses: a generational key is minted by the map, and the wire carries the sender's
  // own id, so the translation is a hash map the incumbent already has — with a slot indexing added
  // behind it and a dependency added under it.
  assert!(
    slot_map.operations() > incumbent.operations(),
    "slot map {} vs incumbent {}",
    slot_map.operations(),
    incumbent.operations()
  );
}

/// A one-item member delivery, its obligation, and the answer receiver its sender kept.
fn member(keys: &[u64]) -> (Owing<ItemId>, super::super::AckReceiver<ItemId>) {
  let (ack, answers) = ack_channel::<ItemId>();
  (
    Owing::open(
      keys.iter().copied().map(ItemId::new),
      Some(Custody::sole(ack)),
    ),
    answers,
  )
}

/// The released set of an answer that has arrived, or `None` while it has not.
fn answered(answers: &super::super::AckReceiver<ItemId>) -> Option<HashSet<ItemId>> {
  match answers.take() {
    super::super::Answer::Settled(settled) => Some(settled.into_parts().0),
    super::super::Answer::Waiting | super::super::Answer::HungUp => None,
  }
}

#[test]
fn a_joined_delivery_answers_every_member_with_its_own_keys() {
  // Two members, and their senders MINTED THE SAME NUMBERS: item ids come off a per-sender counter,
  // so `ItemId::new(0)` means one thing on the frame edge and another on the segment edge. A
  // composed answer that broadcast one released set would release the wrong item at one of them.
  let (frames, frame_answers) = member(&[0]);
  let (segments, segment_answers) = member(&[0]);
  let joined = ItemId::new(1_000);
  let custody = Custody::joined(
    joined,
    vec![frames.share(ItemId::new(0)), segments.share(ItemId::new(0))],
  );

  let mut owed = Owed::open([joined], Some(custody));
  owed.release(joined);
  assert!(owed.settle("captioner", Lifecycle::Processed(())));

  // Each member is answered on ITS OWN token, with the key it minted, and both are told the same
  // station.
  assert_eq!(
    answered(&frame_answers),
    Some(HashSet::from([ItemId::new(0)]))
  );
  assert_eq!(
    answered(&segment_answers),
    Some(HashSet::from([ItemId::new(0)]))
  );
  assert!(frames.is_settled() && segments.is_settled());
}

#[test]
fn a_joined_delivery_that_was_not_released_holds_every_member() {
  let (frames, frame_answers) = member(&[7]);
  let (segments, segment_answers) = member(&[9]);
  let joined = ItemId::new(1);
  let custody = Custody::joined(
    joined,
    vec![frames.share(ItemId::new(7)), segments.share(ItemId::new(9))],
  );

  let mut owed = Owed::open([joined], Some(custody));
  // Nothing released — the pair failed, so the driver holds its key.
  assert!(owed.settle(
    "captioner",
    Lifecycle::<()>::Skipped(Skip::new(SkipReason::Filtered))
  ));

  // Both are answered — the observation is worth having — and neither releases anything, which is
  // what makes the senders re-deliver.
  assert_eq!(answered(&frame_answers), Some(HashSet::new()));
  assert_eq!(answered(&segment_answers), Some(HashSet::new()));
}

#[test]
fn a_member_delivery_answers_only_when_its_last_item_has_been_decided() {
  // ONE delivery of three frames whose keys join three different groups. Its token is one, so it
  // cannot answer until every one of the three has been decided — which is the shared obligation's
  // whole reason to exist.
  let (frames, answers) = member(&[0, 1, 2]);
  let mut settled = Vec::new();
  for (item, joined, release) in [(0u64, 100u64, true), (1, 101, false), (2, 102, true)] {
    let joined = ItemId::new(joined);
    let custody = Custody::joined(joined, vec![frames.share(ItemId::new(item))]);
    let mut owed = Owed::open([joined], Some(custody));
    if release {
      owed.release(joined);
    }
    owed.settle("captioner", Lifecycle::Processed(()));
    settled.push(answered(&answers));
  }

  assert_eq!(settled[0], None, "one of three decided says nothing");
  assert_eq!(settled[1], None, "two of three still says nothing");
  assert_eq!(
    settled[2],
    Some(HashSet::from([ItemId::new(0), ItemId::new(2)])),
    "the pass that finishes it answers, releasing exactly the pairs that took"
  );
  assert_eq!(frames.held(), 0, "every item is decided");
}

#[test]
fn a_group_that_never_completes_never_answers_and_the_drop_is_what_holds_it() {
  // The v1 pair-timeout ruling, as the types state it: no deadline, no policy. A half-arrived pair
  // holds its member's obligation open, so the sender's window keeps the item outstanding — which
  // is the stuck watermark the upstream's own lag sweep is the net for.
  let (frames, answers) = member(&[3]);
  let share = frames.share(ItemId::new(3));
  assert!(!frames.is_settled());
  assert_eq!(frames.held(), 1);
  assert!(answered(&answers).is_none(), "nothing has been answered");

  // The counterpart never arrives and the intake goes away with the half-pair in it.
  drop(share);
  drop(frames);
  assert!(
    matches!(answers.take(), super::super::Answer::HungUp),
    "a dropped token is the protocol's own second outcome: held, and re-delivered"
  );
}

/// A DECLARED MESSAGE, standing in for the impl a `receipt = "…"` word emits — the seat is on the
/// thing GIVEN, so this is what both ends of the edge read the type off.
struct SceneOpen;

/// The durable id only the consumer could have known.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct SceneId(u64);

impl crate::Receipts for SceneOpen {
  type Receipt = SceneId;
}

/// **A HARVEST CARRIES THE RECEIPT**, and reads it at the type the MESSAGE declared.
///
/// The window's half of the acked give: a sender that harvests rather than waiting on one token
/// still gets its consumers' answers, and `Answered::receipt_of` is where it reads them without
/// inventing the type. It names the message rather than inferring one for the keyed doors' reason —
/// a harvest speaks for a whole window, whose keys may be items of several messages. The two waiting arms cannot arise here — a harvested answer is one that ARRIVED
/// — so `Silent` for an item nobody receipted is the whole of the negative side.
#[test]
fn a_harvested_answer_reads_its_receipt_at_the_declared_type() {
  let mut window = Outbound::new();
  let (ack, answers) = ack_channel::<ItemId>();
  window.record([ItemId::new(1), ItemId::new(2)], answers);
  let released: HashSet<ItemId> = [ItemId::new(1), ItemId::new(2)].into_iter().collect();
  ack.send(
    Ack::new(released, "seat", Lifecycle::Persisted(()))
      .receipting_of::<SceneOpen>(ItemId::new(1), SceneId(4242)),
  );

  let harvest = window.harvest();
  let answered = harvest.answers().first().expect("one answer arrived");
  assert_eq!(
    answered.receipt_of::<SceneOpen>(&ItemId::new(1)),
    Ok(&SceneId(4242)),
    "the declared read takes its type off the message's own impl"
  );
  assert_eq!(
    answered.receipt_of::<SceneOpen>(&ItemId::new(2)),
    Err(crate::Unreceipted::Silent),
    "an item nobody receipted is Silent, not a hang"
  );
}