ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
//! THE WHOLE TRANSITION TABLE, and the refusals in it.
//!
//! Every test here is arithmetic on a value. Nothing waits, nothing locks and nothing reads a clock
//! — a thirty-second drain window and a five-state machine are exercised in microseconds because
//! `now` is an argument, which is the posture [`crate::batch`]'s own suite already takes.

use core::time::Duration;
use std::time::Instant;

use super::{Entry, Flip, RetireOrigin, Retirement, RootAction, RootAdvance, RootState, Stamp};

use crate::RunId;

/// The run every fixed reading below is numbered with — a value, so that a flip's own expectation is
/// a value comparison like everything else here.
const RUN: RunId = RunId::new(7);

/// A fixed set of readings, so that every expectation below is a value comparison.
fn stamp() -> Stamp {
  Stamp::new(Instant::now(), crate::Timestamp::UNIX_EPOCH, RUN)
}

/// A stamp strictly later than `from` on BOTH clocks and numbered with a LATER run, for the tests
/// that care whether a transition read the stamp it was handed or the one it already had.
///
/// Derived from `from` rather than read afresh, so that two calls in one test answer the same
/// value: a fixture built at `later(at)` and an expectation written as `later(at)` have to be
/// comparable, which a second `Instant::now()` would not be.
fn later(from: Stamp) -> Stamp {
  Stamp::new(
    from.monotonic() + Duration::from_secs(60),
    crate::Timestamp::from(jiff::Timestamp::from_second(1_800_000_000).expect("in range")),
    RunId::new(from.run().get() + 1),
  )
}

/// Take `action` and collect whatever durable acts it earned — the retirements, and the flips.
fn spent(
  entry: &mut Entry,
  action: RootAction,
  at: Stamp,
) -> (RootAdvance, Vec<Retirement>, Vec<Flip>) {
  let mut owed = Vec::new();
  let mut turned = Vec::new();
  let advance = entry.advance(action, at, &mut |act| owed.push(act), &mut |act| {
    turned.push(act)
  });
  (advance, owed, turned)
}

/// Take `action` and collect the RETIREMENTS it earned, asserting it earned no flip.
///
/// The suite below is the retirement machine's, so this is what nearly every call in it wants: a
/// transition that quietly started flipping closures would fail here rather than in whichever
/// generations test happened to notice.
fn step(entry: &mut Entry, action: RootAction, at: Stamp) -> (RootAdvance, Vec<Retirement>) {
  // CLONED for the message alone: `RootAction` carries a `RetireOrigin`, which carries a
  // deployment's own word, so it is not `Copy` and the assertion below needs it after the move.
  let named = action.clone();
  let (advance, owed, turned) = spent(entry, action, at);
  assert_eq!(
    turned,
    Vec::new(),
    "{named:?} was not supposed to close a run"
  );
  (advance, owed)
}

/// Take `action`, asserting that it earned nothing durable.
fn quiet(entry: &mut Entry, action: RootAction, at: Stamp) -> RootAdvance {
  let named = format!("{action:?}");
  let (advance, owed) = step(entry, action, at);
  assert_eq!(
    owed,
    Vec::new(),
    "{named} was not supposed to owe the ledger anything"
  );
  advance
}

// ── The absent key, which IS the idle key ───────────────────────────────────────────────────────

/// A fresh entry is idle, holds nothing and is VACANT — which is what lets the table drop it.
#[test]
fn a_fresh_entry_is_the_absence_of_news() {
  let entry = Entry::idle();
  assert_eq!(entry.state(), RootState::Idle);
  assert_eq!(entry.queued(), &[]);
  assert_eq!(entry.retiring_as(), None);
  assert!(entry.is_vacant());
}

/// An intake is the debounced road into `Analyzing`, and it starts with nothing in flight.
#[test]
fn intake_opens_an_analysis_with_nothing_in_flight() {
  let at = stamp();
  let mut entry = Entry::idle();
  assert_eq!(
    quiet(&mut entry, RootAction::Intake, at),
    RootAdvance::Moved
  );
  assert_eq!(
    entry.state(),
    RootState::Analyzing {
      inflight: 0,
      since: at.monotonic(),
    }
  );
  assert!(!entry.is_vacant());
}

/// A DISPATCH IS EVIDENCE: it opens an analysis on its own, so a deployment with no intake driver
/// still reports the roots it is actually working on rather than a table full of idle keys.
#[test]
fn a_dispatch_on_an_idle_key_opens_the_analysis_itself() {
  let at = stamp();
  let mut entry = Entry::idle();
  assert_eq!(
    quiet(&mut entry, RootAction::Dispatched, at),
    RootAdvance::Moved
  );
  assert_eq!(
    entry.state(),
    RootState::Analyzing {
      inflight: 1,
      since: at.monotonic(),
    }
  );
}

/// Retiring a key nobody ever analyzed is the ORDINARY case — a person deleting content the graph
/// never touched — so it lands straight in `Retired` with a row owed, never through `Retiring`.
#[test]
fn retiring_an_untouched_key_lands_at_once() {
  let at = stamp();
  let mut entry = Entry::idle();
  let (advance, owed) = step(&mut entry, RootAction::Retire(RetireOrigin::User), at);
  assert_eq!(advance, RootAdvance::Moved);
  assert_eq!(
    entry.state(),
    RootState::Retired {
      at: at.wall(),
      origin: RetireOrigin::User,
      late_tails: false,
    }
  );
  assert_eq!(
    owed,
    vec![Retirement::Recorded {
      at: at.wall(),
      origin: RetireOrigin::User,
      late_tails: false,
    }]
  );
}

/// The three an idle key has no use for.
#[test]
fn an_idle_key_declines_what_it_has_no_work_for() {
  let at = stamp();
  for action in [
    RootAction::Observed,
    RootAction::Restore,
    RootAction::Restored,
  ] {
    let mut entry = Entry::idle();
    assert_eq!(quiet(&mut entry, action, at), RootAdvance::Declined);
    assert_eq!(entry.state(), RootState::Idle);
  }
}

/// A reappearance of a key that never left is ORDINARY rather than a refusal.
#[test]
fn a_reappearance_of_a_live_key_is_unchanged() {
  let at = stamp();
  let mut entry = Entry::idle();
  assert_eq!(
    quiet(&mut entry, RootAction::Reappear, at),
    RootAdvance::Unchanged
  );
  assert!(entry.is_vacant());
}

// ── Analyzing ───────────────────────────────────────────────────────────────────────────────────

/// A second intake on a key already analyzing is the work already happening.
#[test]
fn a_repeat_intake_while_analyzing_changes_nothing() {
  let at = stamp();
  let mut entry = Entry::idle();
  assert_eq!(
    quiet(&mut entry, RootAction::Intake, at),
    RootAdvance::Moved
  );
  assert_eq!(
    quiet(&mut entry, RootAction::Intake, later(at)),
    RootAdvance::Unchanged
  );
  // The `since` is the FIRST intake's — a repeat does not restart the age.
  assert_eq!(
    entry.state(),
    RootState::Analyzing {
      inflight: 0,
      since: at.monotonic(),
    }
  );
}

/// Dispatches raise the count and answers lower it; the last answer returns the key to idle, where
/// it becomes vacant and the table may drop it — and it is the one answer in the sequence that
/// closes the run.
#[test]
fn the_count_rises_and_falls_and_zero_is_idle() {
  let at = stamp();
  let mut entry = Entry::idle();
  for expected in 1..=3 {
    assert_eq!(
      quiet(&mut entry, RootAction::Dispatched, at),
      RootAdvance::Moved
    );
    assert_eq!(
      entry.state(),
      RootState::Analyzing {
        inflight: expected,
        since: at.monotonic(),
      }
    );
  }
  for expected in (1..=2).rev() {
    assert_eq!(
      quiet(&mut entry, RootAction::Observed, at),
      RootAdvance::Moved
    );
    assert_eq!(
      entry.state(),
      RootState::Analyzing {
        inflight: expected,
        since: at.monotonic(),
      }
    );
  }
  let (advance, owed, turned) = spent(&mut entry, RootAction::Observed, at);
  assert_eq!(advance, RootAdvance::Moved);
  assert_eq!(owed, Vec::new(), "reaching zero is not a retirement");
  assert_eq!(
    turned,
    vec![Flip::new(RUN, at.wall())],
    "the last answer closes the run the first dispatch opened"
  );
  assert_eq!(entry.state(), RootState::Idle);
  assert!(entry.is_vacant());
}

/// An answer for work nobody sent is refused rather than counted below zero.
#[test]
fn an_answer_with_nothing_in_flight_is_declined() {
  let at = stamp();
  let mut entry = Entry::idle();
  assert_eq!(
    quiet(&mut entry, RootAction::Intake, at),
    RootAdvance::Moved
  );
  assert_eq!(
    quiet(&mut entry, RootAction::Observed, at),
    RootAdvance::Declined
  );
  assert_eq!(
    entry.state(),
    RootState::Analyzing {
      inflight: 0,
      since: at.monotonic(),
    }
  );
}

/// Retiring a key with work still out goes THROUGH `Retiring`, carrying the count it has to drain
/// and owing the ledger nothing yet.
#[test]
fn retiring_with_work_out_waits_in_retiring() {
  let at = stamp();
  let mut entry = Entry::idle();
  assert_eq!(
    quiet(&mut entry, RootAction::Dispatched, at),
    RootAdvance::Moved
  );
  assert_eq!(
    quiet(&mut entry, RootAction::Dispatched, at),
    RootAdvance::Moved
  );
  assert_eq!(
    quiet(&mut entry, RootAction::Retire(RetireOrigin::Vanished), at),
    RootAdvance::Moved
  );
  assert_eq!(
    entry.state(),
    RootState::Retiring {
      inflight: 2,
      since: at.monotonic(),
    }
  );
  assert_eq!(entry.retiring_as(), Some(RetireOrigin::Vanished));
}

// ── Retiring ────────────────────────────────────────────────────────────────────────────────────

/// A key on its way out REFUSES NEW DISPATCH — which is the whole of what `Retiring` means.
#[test]
fn a_retiring_key_refuses_new_dispatch() {
  let at = stamp();
  let mut entry = retiring(2, RetireOrigin::Vanished, at);
  assert_eq!(
    quiet(&mut entry, RootAction::Dispatched, at),
    RootAdvance::Declined
  );
  assert_eq!(
    entry.state(),
    RootState::Retiring {
      inflight: 2,
      since: at.monotonic(),
    }
  );
}

/// The last answer is what lands the retirement, and the row is owed at exactly that moment and
/// stamped with the reading of the call that drained it.
#[test]
fn the_last_answer_lands_the_retirement() {
  let opened = stamp();
  let drained = later(opened);
  let mut entry = retiring(2, RetireOrigin::Vanished, opened);

  assert_eq!(
    quiet(&mut entry, RootAction::Observed, drained),
    RootAdvance::Moved
  );
  assert_eq!(
    entry.state(),
    RootState::Retiring {
      inflight: 1,
      since: opened.monotonic(),
    },
    "the drain window is measured from when the retirement OPENED"
  );

  let (advance, owed) = step(&mut entry, RootAction::Observed, drained);
  assert_eq!(advance, RootAdvance::Moved);
  assert_eq!(
    entry.state(),
    RootState::Retired {
      at: drained.wall(),
      origin: RetireOrigin::Vanished,
      late_tails: false,
    }
  );
  assert_eq!(
    owed,
    vec![Retirement::Recorded {
      at: drained.wall(),
      origin: RetireOrigin::Vanished,
      late_tails: false,
    }]
  );
  assert_eq!(entry.retiring_as(), None);
}

/// A PERSON standing a key down while a vanish-retirement drains REPLACES the origin rather than
/// waiting behind it — otherwise the key would land as a `Vanished` retiree and resurrect itself on
/// the next re-scan, which is exactly what the person was retiring it against.
#[test]
fn a_user_retire_outranks_a_draining_vanish() {
  let at = stamp();
  let mut entry = retiring(1, RetireOrigin::Vanished, at);
  assert_eq!(
    quiet(&mut entry, RootAction::Retire(RetireOrigin::User), at),
    RootAdvance::Moved
  );
  assert_eq!(entry.retiring_as(), Some(RetireOrigin::User));

  let (_, owed) = step(&mut entry, RootAction::Observed, at);
  assert_eq!(
    owed,
    vec![Retirement::Recorded {
      at: at.wall(),
      origin: RetireOrigin::User,
      late_tails: false,
    }]
  );
}

/// The rank has ONE direction: a vanish arriving behind a person's decision changes nothing.
#[test]
fn a_vanish_does_not_outrank_a_draining_user_retire() {
  let at = stamp();
  let mut entry = retiring(1, RetireOrigin::User, at);
  assert_eq!(
    quiet(&mut entry, RootAction::Retire(RetireOrigin::Vanished), at),
    RootAdvance::Unchanged
  );
  assert_eq!(entry.retiring_as(), Some(RetireOrigin::User));
}

/// **THE BOUNDED DRAIN.** A lapse is the OTHER way out of `Retiring`, and what it costs is written
/// into the retirement rather than swallowed: the key lands with `late_tails`, and so does the row.
#[test]
fn a_lapse_retires_a_drain_that_never_reached_zero() {
  let opened = stamp();
  let spent = later(opened);
  let mut entry = retiring(3, RetireOrigin::Vanished, opened);

  let (advance, owed) = step(&mut entry, RootAction::Lapsed, spent);
  assert_eq!(advance, RootAdvance::Moved);
  assert_eq!(
    entry.state(),
    RootState::Retired {
      at: spent.wall(),
      origin: RetireOrigin::Vanished,
      late_tails: true,
    },
    "stamped with the reading of the call that spent the window, not the one that opened it"
  );
  assert_eq!(
    owed,
    vec![Retirement::Recorded {
      at: spent.wall(),
      origin: RetireOrigin::Vanished,
      late_tails: true,
    }],
    "the durable act carries the flag too — the row is the truth a restart reads"
  );
  assert_eq!(entry.retiring_as(), None);
  assert!(entry.state().has_late_tails());
}

/// A lapse keeps whatever origin was DRAINING, including one that outranked the first — the flag is
/// about the wait, and the origin is about who asked.
#[test]
fn a_lapse_lands_as_the_origin_that_was_draining() {
  let at = stamp();
  let mut entry = retiring(1, RetireOrigin::Vanished, at);
  assert_eq!(
    quiet(&mut entry, RootAction::Retire(RetireOrigin::User), at),
    RootAdvance::Moved
  );

  let (_, owed) = step(&mut entry, RootAction::Lapsed, at);
  assert_eq!(
    owed,
    vec![Retirement::Recorded {
      at: at.wall(),
      origin: RetireOrigin::User,
      late_tails: true,
    }]
  );
}

/// The abandoned answers are what `late_tails` NAMES: they still arrive, and a retired key declines
/// every one of them exactly as it declines any other late tail.
#[test]
fn the_tails_a_lapse_abandoned_still_arrive_and_are_declined() {
  let at = stamp();
  let mut entry = retiring(2, RetireOrigin::Vanished, at);
  // A lapse OWES the ledger a row, so it is taken through `step` rather than `quiet`.
  let (advance, _row) = step(&mut entry, RootAction::Lapsed, at);
  assert_eq!(advance, RootAdvance::Moved);

  assert_eq!(
    quiet(&mut entry, RootAction::Observed, at),
    RootAdvance::Declined
  );
  assert_eq!(
    quiet(&mut entry, RootAction::Observed, at),
    RootAdvance::Declined
  );
  assert!(
    entry.state().has_late_tails(),
    "and the flag still says they were coming"
  );
}

/// **A DISPATCH REFUSED MID-DRAIN IS REMEMBERED**, and the retirement it lands says so.
///
/// The refusal stands — `Retiring` means *no new dispatch* — but the item behind it was already on
/// an edge and its answer IS taken, so the drain reaches zero one answer early. What keeps that
/// honest is the flag rather than a softened refusal: see [`RootAction::Dispatched`].
#[test]
fn a_dispatch_refused_mid_drain_lands_the_retirement_with_late_tails() {
  let at = stamp();
  let mut entry = retiring(1, RetireOrigin::Vanished, at);
  assert_eq!(
    quiet(&mut entry, RootAction::Dispatched, at),
    RootAdvance::Declined,
    "the refusal stands"
  );

  // Two answers arrive — one for the counted item, one for the refused one. The first lands the
  // retirement, because the second was never counted.
  let (advance, owed) = step(&mut entry, RootAction::Observed, at);
  assert_eq!(advance, RootAdvance::Moved);
  assert_eq!(
    owed,
    vec![Retirement::Recorded {
      at: at.wall(),
      origin: RetireOrigin::Vanished,
      late_tails: true,
    }],
    "the drain ended early, and the row says a tail may still land"
  );
  assert_eq!(
    quiet(&mut entry, RootAction::Observed, at),
    RootAdvance::Declined,
    "and here it is"
  );
}

/// The memory belongs to the act that ended, so the NEXT retirement starts without it.
#[test]
fn a_remembered_refusal_is_spent_by_the_retirement_that_landed() {
  let at = stamp();
  let mut entry = retiring(1, RetireOrigin::Vanished, at);
  assert_eq!(
    quiet(&mut entry, RootAction::Dispatched, at),
    RootAdvance::Declined
  );
  let (_, _spent) = step(&mut entry, RootAction::Observed, at);
  assert!(entry.state().has_late_tails());

  // Back to life, then out again with a drain nothing interrupted.
  let (_, _erased) = step(&mut entry, RootAction::Restore, at);
  let (_, _restored) = step(&mut entry, RootAction::Restored, at);
  assert_eq!(entry.state(), RootState::Idle);
  assert!(entry.is_vacant(), "and the memory went with it");

  let (_, owed) = step(&mut entry, RootAction::Retire(RetireOrigin::User), at);
  assert_eq!(
    owed,
    vec![Retirement::Recorded {
      at: at.wall(),
      origin: RetireOrigin::User,
      late_tails: false,
    }],
    "a fresh retirement carries no memory of the last one's tail"
  );
}

/// A lapse offered to a state with no drain to bound changes nothing — the sweep looking at a key
/// that moved between the walk and the act.
#[test]
fn a_lapse_declines_everywhere_but_a_draining_key() {
  let at = stamp();
  for mut entry in [
    Entry::idle(),
    analyzing(2, at),
    retired(RetireOrigin::User, at),
    restoring(at),
  ] {
    let before = entry.state();
    assert_eq!(
      quiet(&mut entry, RootAction::Lapsed, at),
      RootAdvance::Declined,
      "{before:?} has no drain to bound"
    );
    assert_eq!(entry.state(), before);
  }
}

// ── Retired ─────────────────────────────────────────────────────────────────────────────────────

/// A `Vanished` retiree comes back the moment its content does.
#[test]
fn a_vanished_retiree_restores_itself_on_reappearance() {
  let at = stamp();
  let mut entry = retired(RetireOrigin::Vanished, at);
  let (advance, owed) = step(&mut entry, RootAction::Reappear, at);
  assert_eq!(advance, RootAdvance::Moved);
  assert_eq!(entry.state(), RootState::Restoring);
  assert_eq!(owed, vec![Retirement::Erased]);
}

/// A `User` retiree NEVER does. Only a person saying so again brings it back.
#[test]
fn a_user_retiree_never_restores_itself() {
  let at = stamp();
  let mut entry = retired(RetireOrigin::User, at);
  assert_eq!(
    quiet(&mut entry, RootAction::Reappear, at),
    RootAdvance::Declined
  );
  assert_eq!(
    entry.state(),
    RootState::Retired {
      at: at.wall(),
      origin: RetireOrigin::User,
      late_tails: false,
    }
  );

  let (advance, owed) = step(&mut entry, RootAction::Restore, at);
  assert_eq!(advance, RootAdvance::Moved);
  assert_eq!(entry.state(), RootState::Restoring);
  assert_eq!(owed, vec![Retirement::Erased]);
}

/// A retired key takes no new work, and a late tail is refused rather than counted.
#[test]
fn a_retired_key_takes_no_work_and_no_tail() {
  let at = stamp();
  for action in [
    RootAction::Intake,
    RootAction::Dispatched,
    RootAction::Observed,
    RootAction::Restored,
  ] {
    let mut entry = retired(RetireOrigin::Vanished, at);
    assert_eq!(quiet(&mut entry, action, at), RootAdvance::Declined);
    assert_eq!(
      entry.state(),
      RootState::Retired {
        at: at.wall(),
        origin: RetireOrigin::Vanished,
        late_tails: false,
      }
    );
  }
}

/// Re-retiring an already-retired key on a STRONGER origin rewrites the row rather than doing
/// nothing: the retirement instant stands, and the origin is the one that decides resurrection.
#[test]
fn a_stronger_origin_rewrites_a_standing_retirement() {
  let at = stamp();
  let mut entry = retired(RetireOrigin::Vanished, at);

  let (advance, owed) = step(
    &mut entry,
    RootAction::Retire(RetireOrigin::User),
    later(at),
  );
  assert_eq!(advance, RootAdvance::Moved);
  assert_eq!(
    entry.state(),
    RootState::Retired {
      at: at.wall(),
      origin: RetireOrigin::User,
      late_tails: false,
    },
    "the instant it retired is the FIRST retirement's — only who owns it changed"
  );
  assert_eq!(
    owed,
    vec![Retirement::Recorded {
      at: at.wall(),
      origin: RetireOrigin::User,
      late_tails: false,
    }]
  );

  assert_eq!(
    quiet(&mut entry, RootAction::Retire(RetireOrigin::User), at),
    RootAdvance::Unchanged
  );
}

// ── Restoring ───────────────────────────────────────────────────────────────────────────────────

/// `Restoring` waits on a write this registry does not hold, so it is TOLD the write landed — and
/// only then is the key live again.
#[test]
fn a_restore_completes_when_the_erase_lands() {
  let at = stamp();
  let mut entry = retired(RetireOrigin::User, at);
  let (advance, owed) = step(&mut entry, RootAction::Restore, at);
  assert_eq!(advance, RootAdvance::Moved);
  assert_eq!(
    owed,
    vec![Retirement::Erased],
    "the row is owed an erase the moment the restore starts"
  );
  assert_eq!(entry.state(), RootState::Restoring);

  assert_eq!(
    quiet(&mut entry, RootAction::Restored, at),
    RootAdvance::Moved
  );
  assert_eq!(entry.state(), RootState::Idle);
  assert!(entry.is_vacant());
}

/// Asking a restoring key to come back is asking for what is already happening.
#[test]
fn a_restoring_key_is_unchanged_by_another_restore() {
  let at = stamp();
  let mut entry = restoring(at);
  for action in [RootAction::Restore, RootAction::Reappear] {
    assert_eq!(quiet(&mut entry, action, at), RootAdvance::Unchanged);
    assert_eq!(entry.state(), RootState::Restoring);
  }
}

// ── The per-key queue ───────────────────────────────────────────────────────────────────────────

/// Actions asked of a mid-act key WAIT, in the order they were asked, and the completion spends
/// them: `retire` + `restore` + `retire` comes out as a retired key, which is the last thing
/// anybody asked for.
#[test]
fn the_queue_keeps_order_through_a_completion() {
  let at = stamp();
  let mut entry = restoring(at);

  assert_eq!(
    quiet(&mut entry, RootAction::Retire(RetireOrigin::User), at),
    RootAdvance::Queued
  );
  assert_eq!(
    quiet(&mut entry, RootAction::Restore, at),
    RootAdvance::Queued
  );
  assert_eq!(
    quiet(&mut entry, RootAction::Retire(RetireOrigin::User), at),
    RootAdvance::Queued
  );
  assert_eq!(
    entry.queued(),
    &[
      RootAction::Retire(RetireOrigin::User),
      RootAction::Restore,
      RootAction::Retire(RetireOrigin::User),
    ]
  );

  let (advance, owed) = step(&mut entry, RootAction::Restored, at);
  assert_eq!(advance, RootAdvance::Moved);
  // Retire → Retired, restore → Restoring (which is busy, so the drain stops there with the last
  // retire still waiting).
  assert_eq!(entry.state(), RootState::Restoring);
  assert_eq!(
    owed,
    vec![
      Retirement::Recorded {
        at: at.wall(),
        origin: RetireOrigin::User,
        late_tails: false,
      },
      Retirement::Erased,
    ]
  );
  assert_eq!(entry.queued(), &[RootAction::Retire(RetireOrigin::User)]);

  // And telling it the second erase landed spends the last one.
  let (_, owed) = step(&mut entry, RootAction::Restored, at);
  assert_eq!(
    entry.state(),
    RootState::Retired {
      at: at.wall(),
      origin: RetireOrigin::User,
      late_tails: false,
    }
  );
  assert_eq!(
    owed,
    vec![Retirement::Recorded {
      at: at.wall(),
      origin: RetireOrigin::User,
      late_tails: false,
    }]
  );
}

/// A BURST of one action is ONE act — the repeat at the back of the line is absorbed rather than
/// queued again.
#[test]
fn a_repeat_at_the_tail_coalesces() {
  let at = stamp();
  let mut entry = restoring(at);
  assert_eq!(
    quiet(&mut entry, RootAction::Intake, at),
    RootAdvance::Queued
  );
  assert_eq!(
    quiet(&mut entry, RootAction::Intake, at),
    RootAdvance::Coalesced
  );
  assert_eq!(
    quiet(&mut entry, RootAction::Intake, at),
    RootAdvance::Coalesced
  );
  assert_eq!(entry.queued(), &[RootAction::Intake]);
}

/// The absorption is at the TAIL and nowhere else: a repeat that is not the last thing asked is a
/// second, real request and keeps its place.
#[test]
fn a_repeat_that_is_not_at_the_tail_still_queues() {
  let at = stamp();
  let mut entry = restoring(at);
  assert_eq!(
    quiet(&mut entry, RootAction::Intake, at),
    RootAdvance::Queued
  );
  assert_eq!(
    quiet(&mut entry, RootAction::Retire(RetireOrigin::User), at),
    RootAdvance::Queued
  );
  assert_eq!(
    quiet(&mut entry, RootAction::Intake, at),
    RootAdvance::Queued
  );
  assert_eq!(
    entry.queued(),
    &[
      RootAction::Intake,
      RootAction::Retire(RetireOrigin::User),
      RootAction::Intake,
    ]
  );
}

/// A queued intake is spent on completion, so a key that was asked for work while it was going out
/// is analyzing again once it comes back.
#[test]
fn a_queued_intake_reopens_the_analysis() {
  let at = stamp();
  let mut entry = restoring(at);
  assert_eq!(
    quiet(&mut entry, RootAction::Intake, at),
    RootAdvance::Queued
  );
  assert_eq!(
    quiet(&mut entry, RootAction::Restored, later(at)),
    RootAdvance::Moved
  );
  assert_eq!(
    entry.state(),
    RootState::Analyzing {
      inflight: 0,
      since: later(at).monotonic(),
    }
  );
  assert_eq!(entry.queued(), &[]);
}

/// A counting call never queues, whichever act is under way.
#[test]
fn the_counting_calls_never_queue() {
  let at = stamp();
  let mut entry = restoring(at);
  for action in [RootAction::Dispatched, RootAction::Observed] {
    assert_eq!(quiet(&mut entry, action, at), RootAdvance::Declined);
    assert_eq!(entry.queued(), &[]);
  }
}

// ── The rank, on its own ────────────────────────────────────────────────────────────────────────

/// An origin that does NOT resurrect outranks one that does, and nothing else outranks anything.
#[test]
fn only_a_retirement_that_stays_down_outranks() {
  assert!(RetireOrigin::User.outranks(&RetireOrigin::Vanished));
  assert!(!RetireOrigin::Vanished.outranks(&RetireOrigin::User));
  assert!(!RetireOrigin::User.outranks(&RetireOrigin::User));
  assert!(!RetireOrigin::Vanished.outranks(&RetireOrigin::Vanished));
  // The open arm takes the same rank as `User` and for the same reason — see
  // `RetireOrigin::restores_itself`, which is the whole predicate the rank is written over.
  let other = RetireOrigin::Other("policy".into());
  assert!(other.outranks(&RetireOrigin::Vanished));
  assert!(!RetireOrigin::Vanished.outranks(&other));
  assert!(!other.outranks(&RetireOrigin::User));
}

/// The two states an action waits behind, and the three it does not.
#[test]
fn only_the_two_mid_act_states_are_busy() {
  let at = stamp();
  assert!(!RootState::Idle.is_busy());
  assert!(
    !RootState::Analyzing {
      inflight: 3,
      since: at.monotonic(),
    }
    .is_busy()
  );
  assert!(
    RootState::Retiring {
      inflight: 1,
      since: Instant::now(),
    }
    .is_busy()
  );
  assert!(
    !RootState::Retired {
      at: at.wall(),
      origin: RetireOrigin::User,
      late_tails: false,
    }
    .is_busy()
  );
  assert!(RootState::Restoring.is_busy());
}

// ── Fixtures ────────────────────────────────────────────────────────────────────────────────────

/// A key with `inflight` items out and nothing else true of it.
fn analyzing(inflight: u32, at: Stamp) -> Entry {
  let mut entry = Entry::idle();
  for _ in 0..inflight {
    assert_eq!(
      quiet(&mut entry, RootAction::Dispatched, at),
      RootAdvance::Moved
    );
  }
  entry
}

/// A key going out with `inflight` answers still owed.
fn retiring(inflight: u32, origin: RetireOrigin, at: Stamp) -> Entry {
  let mut entry = Entry::idle();
  for _ in 0..inflight {
    assert_eq!(
      quiet(&mut entry, RootAction::Dispatched, at),
      RootAdvance::Moved
    );
  }
  assert_eq!(
    quiet(&mut entry, RootAction::Retire(origin), at),
    RootAdvance::Moved
  );
  assert_eq!(
    entry.state(),
    RootState::Retiring {
      inflight,
      since: at.monotonic(),
    }
  );
  entry
}

/// A key already out.
fn retired(origin: RetireOrigin, at: Stamp) -> Entry {
  let mut entry = Entry::idle();
  let (advance, _) = step(&mut entry, RootAction::Retire(origin), at);
  assert_eq!(advance, RootAdvance::Moved);
  entry
}

/// A key on its way back, waiting for the erase to land.
fn restoring(at: Stamp) -> Entry {
  let mut entry = retired(RetireOrigin::User, at);
  let (advance, _) = step(&mut entry, RootAction::Restore, at);
  assert_eq!(advance, RootAdvance::Moved);
  assert_eq!(entry.state(), RootState::Restoring);
  entry
}

/// **THE SHORTCUT HAS A CONDITION.** An ask that agrees with the act now running is *already
/// happening* only while NOTHING waits behind it: once a retirement is queued, a restore that
/// answered `Unchanged` would be a restore that ends retired.
#[test]
fn an_agreeing_ask_still_queues_behind_a_waiting_one() {
  let at = stamp();
  let mut entry = restoring(at);
  assert_eq!(
    quiet(&mut entry, RootAction::Restore, at),
    RootAdvance::Unchanged,
    "nothing waits, so the restore under way IS the answer"
  );

  assert_eq!(
    quiet(&mut entry, RootAction::Retire(RetireOrigin::User), at),
    RootAdvance::Queued
  );
  assert_eq!(
    quiet(&mut entry, RootAction::Restore, at),
    RootAdvance::Queued,
    "a retirement now waits, so where this key is headed is retired — the restore is a real ask"
  );
}

/// The rank applies whatever is queued, because it changes the act NOW RUNNING rather than adding
/// one: the retirement about to land lands as the stronger origin's, and the queue is untouched.
#[test]
fn the_rank_reaches_the_running_act_past_a_queue() {
  let at = stamp();
  let mut entry = retiring(1, RetireOrigin::Vanished, at);
  assert_eq!(
    quiet(&mut entry, RootAction::Intake, at),
    RootAdvance::Queued
  );
  assert_eq!(
    quiet(&mut entry, RootAction::Retire(RetireOrigin::User), at),
    RootAdvance::Moved
  );
  assert_eq!(entry.retiring_as(), Some(RetireOrigin::User));
  assert_eq!(entry.queued(), &[RootAction::Intake]);
}

// ── The run, and the flip it closes with ────────────────────────────────────────────────────────

/// A run is OPENED by whichever road takes the key out of idle, and the number it takes is the
/// stamp's own.
#[test]
fn either_road_out_of_idle_opens_a_run() {
  for road in [RootAction::Intake, RootAction::Dispatched] {
    let at = stamp();
    let mut entry = Entry::idle();
    assert_eq!(quiet(&mut entry, road.clone(), at), RootAdvance::Moved);
    assert_eq!(
      entry.running_as(),
      Some(RUN),
      "{road:?} left the key analyzing with no run on it"
    );
  }
}

/// A key that reached zero flips ONCE, and the number is taken with it — so a later answer for the
/// same key cannot flip the same run a second time.
#[test]
fn a_run_closes_exactly_once() {
  let at = stamp();
  let mut entry = Entry::idle();
  let _opened = quiet(&mut entry, RootAction::Intake, at);
  let _out = quiet(&mut entry, RootAction::Dispatched, at);

  let (advance, owed, turned) = spent(&mut entry, RootAction::Observed, at);
  assert_eq!(advance, RootAdvance::Moved);
  assert_eq!(owed, Vec::new());
  assert_eq!(turned, vec![Flip::new(RUN, at.wall())]);
  assert_eq!(entry.running_as(), None, "the number was not taken");

  // A late answer for work this run never had out is declined, and flips nothing.
  let (advance, _owed, turned) = spent(&mut entry, RootAction::Observed, at);
  assert_eq!(advance, RootAdvance::Declined);
  assert_eq!(turned, Vec::new(), "a declined answer closed a run");
}

/// A SECOND analysis is a second run, numbered with the stamp that opened it — which is what a
/// pointer moving twice means.
#[test]
fn a_second_analysis_is_a_second_run() {
  let at = stamp();
  let mut entry = Entry::idle();
  let _opened = quiet(&mut entry, RootAction::Dispatched, at);
  let (_advance, _owed, first) = spent(&mut entry, RootAction::Observed, at);
  assert_eq!(first, vec![Flip::new(RUN, at.wall())]);

  let again = later(at);
  let _reopened = quiet(&mut entry, RootAction::Dispatched, again);
  let (_advance, _owed, second) = spent(&mut entry, RootAction::Observed, again);
  assert_eq!(second, vec![Flip::new(again.run(), again.wall())]);
  assert_ne!(again.run(), RUN, "the second stamp carried the same run");
}

/// **THE MASK**: a retirement taken over an open run drops that run, so a key going out flips no
/// closure — whatever the drain behind it does.
#[test]
fn a_retirement_masks_the_run_it_interrupted() {
  let at = stamp();
  let mut entry = Entry::idle();
  let _opened = quiet(&mut entry, RootAction::Intake, at);
  let _out = quiet(&mut entry, RootAction::Dispatched, at);
  assert_eq!(entry.running_as(), Some(RUN));

  let (advance, owed, turned) = spent(&mut entry, RootAction::Retire(RetireOrigin::User), at);
  assert_eq!(advance, RootAdvance::Moved);
  assert_eq!(owed, Vec::new(), "the drain has not ended yet");
  assert_eq!(turned, Vec::new(), "a retirement is not a flip");
  assert_eq!(entry.running_as(), None, "the run outlived the retirement");

  // The drain ends: a retirement is owed and STILL no flip, the run having been dropped rather than
  // held for whichever state came next.
  let (advance, owed, turned) = spent(&mut entry, RootAction::Observed, at);
  assert_eq!(advance, RootAdvance::Moved);
  assert_eq!(owed.len(), 1, "the drain's last answer owes the ledger");
  assert_eq!(turned, Vec::new(), "a retiring key closed a run");
}

/// A restored key's next analysis is a run of its OWN — the masked one is gone rather than resumed.
#[test]
fn a_restored_key_runs_again_under_a_new_number() {
  let at = stamp();
  let mut entry = Entry::idle();
  let _opened = quiet(&mut entry, RootAction::Dispatched, at);
  let _out = quiet(&mut entry, RootAction::Retire(RetireOrigin::User), at);
  let (_advance, _owed, turned) = spent(&mut entry, RootAction::Observed, at);
  assert_eq!(turned, Vec::new());

  let _restoring = step(&mut entry, RootAction::Restore, at);
  let _restored = step(&mut entry, RootAction::Restored, at);
  assert_eq!(entry.state(), RootState::Idle);
  assert_eq!(entry.running_as(), None);

  let again = later(at);
  let _reopened = quiet(&mut entry, RootAction::Dispatched, again);
  let (_advance, _owed, turned) = spent(&mut entry, RootAction::Observed, again);
  assert_eq!(
    turned,
    vec![Flip::new(again.run(), again.wall())],
    "the restored key flipped under the run the retirement masked"
  );
}