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
//! The ledger's own claims: the table's name, the origin's rank, the mirror's two ops, and — the one
//! everything else here is in service of — that the durable write happens BEFORE the publish and
//! never without it.

use std::sync::{Arc, Mutex};

use crate::{
  Registries, RetireOrigin, RetiredMirror, RetiredRow, RetiredStore, RetiredStoreError,
  RetiredTable, Retirement, RootState, Stamp, Timestamp,
  drive::retired::{Landing, rebuild},
};

/// A stamp with a readable wall reading, so a row's `at` can be asserted rather than merely be
/// present.
fn at(second: i64) -> Timestamp {
  Timestamp::from_parts(second, 0).expect("a whole second is a timestamp")
}

// ─── the table ────────────────────────────────────────────────────────────────────────────────

#[test]
fn a_family_names_its_own_table() {
  let table = RetiredTable::new("media").expect("`media` is a bare identifier");
  assert_eq!(table.family(), "media");
  assert_eq!(table.name(), "__ig_retired_media");
  assert_eq!(
    RetiredTable::new("track")
      .expect("`track` is a bare identifier")
      .name(),
    "__ig_retired_track"
  );
}

#[test]
fn a_family_that_could_not_be_spliced_is_refused() {
  // The SQL audit, at the one door a caller's string reaches a statement through: a name carrying a
  // quote, a semicolon, a comment or whitespace is not a name this ledger will build a table out of.
  for hostile in [
    "media\"; DROP TABLE x --",
    "media x",
    "media;",
    "media'",
    "",
    "9lives",
    "média",
  ] {
    let refused = RetiredTable::new(hostile).expect_err("a spliced name has to be an identifier");
    assert_eq!(refused.family(), hostile);
  }
  // And the shapes a family actually takes are accepted: `Attributes::FAMILY` is a snake-cased Rust
  // type name.
  for legal in ["media", "track", "media_asset", "_private", "v2"] {
    assert!(RetiredTable::new(legal).is_ok());
  }
}

// ─── the origin ───────────────────────────────────────────────────────────────────────────────

#[test]
fn only_vanished_restores_itself() {
  assert!(RetireOrigin::Vanished.restores_itself());
  assert!(!RetireOrigin::User.restores_itself());
  // THE THIRD ARM behaves as `User` does, and this is the assertion that says so: the framework
  // cannot know a reason it has never seen is content-driven, so it does not resurrect.
  assert!(!RetireOrigin::Other("policy".into()).restores_itself());
}

#[test]
fn the_rank_is_the_resurrection_question() {
  let vanished = RetireOrigin::Vanished;
  let user = RetireOrigin::User;
  let other = RetireOrigin::Other("quota".into());

  assert!(user.outranks(&vanished));
  assert!(other.outranks(&vanished));
  // Nothing outranks an origin that already stays down, including another one that stays down: two
  // origins agreeing about the only thing rank decides disagree about nothing, so the first asked
  // is kept.
  assert!(!vanished.outranks(&user));
  assert!(!user.outranks(&other));
  assert!(!other.outranks(&user));
  assert!(!user.outranks(&user));
  assert!(!vanished.outranks(&vanished));
}

#[test]
fn an_origin_round_trips_through_its_word() {
  for origin in [
    RetireOrigin::Vanished,
    RetireOrigin::User,
    RetireOrigin::Other("tenancy-ended".into()),
  ] {
    let word = origin.as_str().to_owned();
    assert_eq!(RetireOrigin::from(word), origin);
  }
  // The two shipped words resolve to their ARMS rather than to `Other`, which is what keeps a row
  // this deployment wrote readable as the arm it was written from.
  assert_eq!(RetireOrigin::from("vanished"), RetireOrigin::Vanished);
  assert_eq!(RetireOrigin::from("user"), RetireOrigin::User);
  assert_eq!(
    RetireOrigin::from("something-else"),
    RetireOrigin::Other("something-else".into())
  );
}

// ─── the mirror ───────────────────────────────────────────────────────────────────────────────

#[test]
fn the_mirror_holds_what_was_marked() {
  let mirror = RetiredMirror::<i64>::new();
  let reader = mirror.reader();

  assert!(!reader.retired(&7));
  mirror.mark(7);
  assert!(reader.retired(&7));
  assert_eq!(reader.held(), 1);

  mirror.unmark(7);
  assert!(!reader.retired(&7));
  assert_eq!(reader.held(), 0);
}

#[test]
fn a_rebuilt_mirror_publishes_once_and_holds_everything() {
  let mirror = RetiredMirror::rebuilt([1_i64, 2, 3]);
  let reader = mirror.reader();
  assert_eq!(reader.held(), 3);
  for key in [1_i64, 2, 3] {
    assert!(reader.retired(&key));
  }
  assert!(!reader.retired(&4));
}

#[test]
fn a_reader_minted_after_the_fact_sees_what_was_published() {
  let mirror = RetiredMirror::<i64>::new();
  mirror.mark(11);
  // The factory is what crosses threads; a handle taken from it later still sees every publish that
  // came before, because the publish is a fact about the data rather than about the handle.
  assert!(mirror.readers().reader().retired(&11));
}

// ─── the probe store ──────────────────────────────────────────────────────────────────────────

/// WHAT THE PROBE SAW, in the order it saw it.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Seen {
  /// `record` was entered, and this is what the mirror said about the key AT THAT MOMENT.
  Record { key: i64, mirrored: bool },
  /// `erase` was entered, and this is what the mirror said about the key AT THAT MOMENT.
  Erase { key: i64, mirrored: bool },
}

/// A store that writes nothing and REMEMBERS WHEN IT WAS CALLED.
///
/// It holds the mirror so that every verb can ask what the mirror was saying at the instant the
/// durable act began. That is the whole of the ordering assertion: a `record` that finds the key
/// already mirrored is a publish that ran first, and there is no other way to catch one.
struct Probe {
  seen: Mutex<Vec<Seen>>,
  mirror: Arc<RetiredMirror<i64>>,
  rows: Mutex<Vec<RetiredRow<i64>>>,
  refuse: bool,
}

impl Probe {
  fn new(mirror: &Arc<RetiredMirror<i64>>, refuse: bool) -> Arc<Self> {
    Arc::new(Self {
      seen: Mutex::new(Vec::new()),
      mirror: Arc::clone(mirror),
      rows: Mutex::new(Vec::new()),
      refuse,
    })
  }

  fn seen(&self) -> Vec<Seen> {
    self.seen.lock().expect("the probe's own log").clone()
  }

  fn refusal(&self, verb: &'static str) -> Option<RetiredStoreError> {
    self
      .refuse
      .then(|| RetiredStoreError::new(verb, "__ig_retired_probe", std::fmt::Error))
  }
}

impl RetiredStore<i64> for Probe {
  fn ready(&self) -> Landing<'_, ()> {
    Box::pin(core::future::ready(Ok(())))
  }

  fn record<'a>(&'a self, row: &'a RetiredRow<i64>) -> Landing<'a, ()> {
    Box::pin(async move {
      self
        .seen
        .lock()
        .expect("the probe's own log")
        .push(Seen::Record {
          key: *row.key(),
          mirrored: self.mirror.retired(row.key()),
        });
      if let Some(refusal) = self.refusal("record") {
        return Err(refusal);
      }
      let mut rows = self.rows.lock().expect("the probe's own rows");
      rows.retain(|held| held.key() != row.key());
      rows.push(row.clone());
      Ok(())
    })
  }

  fn erase<'a>(&'a self, key: &'a i64) -> Landing<'a, ()> {
    Box::pin(async move {
      self
        .seen
        .lock()
        .expect("the probe's own log")
        .push(Seen::Erase {
          key: *key,
          mirrored: self.mirror.retired(key),
        });
      if let Some(refusal) = self.refusal("erase") {
        return Err(refusal);
      }
      self
        .rows
        .lock()
        .expect("the probe's own rows")
        .retain(|held| held.key() != key);
      Ok(())
    })
  }

  fn roll(&self) -> Landing<'_, Vec<RetiredRow<i64>>> {
    Box::pin(async move { Ok(self.rows.lock().expect("the probe's own rows").clone()) })
  }
}

// ─── the ordering ─────────────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn the_row_lands_before_the_mirror_is_told() {
  let registries = Registries::default();
  let registry = registries.open::<i64>("probe");
  let mirror = Arc::new(RetiredMirror::<i64>::new());
  let store = Probe::new(&mirror, false);
  let body = crate::Keeper::seated(
    &registry,
    store.clone() as Arc<dyn RetiredStore<i64>>,
    Arc::clone(&mirror),
  )
  .expect("nothing is seated on a fresh family");

  body
    .perform(
      &42,
      Retirement::Recorded {
        at: at(1_700_000_000),
        origin: RetireOrigin::User,
        late_tails: false,
      },
    )
    .await;

  // THE EVIDENCE: the store was entered while the mirror still said *not retired*, and the mirror
  // says *retired* once the act has returned. Both halves are needed — the first rules out a
  // publish that ran first, the second rules out one that never ran.
  assert_eq!(
    store.seen(),
    vec![Seen::Record {
      key: 42,
      mirrored: false
    }]
  );
  assert!(mirror.retired(&42));
  assert_eq!(
    store.roll().await.expect("the probe never refuses").len(),
    1
  );
}

#[tokio::test]
async fn a_refused_row_publishes_nothing() {
  let registries = Registries::default();
  let registry = registries.open::<i64>("probe");
  let mirror = Arc::new(RetiredMirror::<i64>::new());
  let store = Probe::new(&mirror, true);
  let body = crate::Keeper::seated(
    &registry,
    store.clone() as Arc<dyn RetiredStore<i64>>,
    Arc::clone(&mirror),
  )
  .expect("nothing is seated on a fresh family");

  body
    .perform(
      &42,
      Retirement::Recorded {
        at: at(1_700_000_000),
        origin: RetireOrigin::Vanished,
        late_tails: true,
      },
    )
    .await;

  assert!(
    !mirror.retired(&42),
    "a refused write must leave the mirror exactly where it was"
  );
  assert_eq!(body.report().recorded, 0);
  assert_eq!(body.report().refused, 1);
}

#[tokio::test]
async fn an_erase_unmarks_and_then_tells_the_waiting_state() {
  let registries = Registries::default();
  let registry = registries.open::<i64>("probe");
  let mirror = Arc::new(RetiredMirror::<i64>::new());
  let store = Probe::new(&mirror, false);
  let body = crate::Keeper::seated(
    &registry,
    store.clone() as Arc<dyn RetiredStore<i64>>,
    Arc::clone(&mirror),
  )
  .expect("nothing is seated on a fresh family");

  // The key goes out first, so the erase has something to undo on BOTH sides — the row and the
  // mirror through the body, the registry's own state through the boot door. Driving the body
  // alone would leave the registry at `Idle`, where a restore is refused rather than started.
  body
    .perform(
      &7,
      Retirement::Recorded {
        at: at(1),
        origin: RetireOrigin::Vanished,
        late_tails: false,
      },
    )
    .await;
  registry.rebuilt(&7, at(1), RetireOrigin::Vanished, false);
  // A restore, through the registry — which moves the key to `Restoring` and owes the erase. The
  // seat queued it; this body is what performs it, by hand, so the ORDER inside one act is what is
  // being read rather than the loop's.
  let _asked = registry.restore(&7, Stamp::now());
  assert!(matches!(registry.state(&7), RootState::Restoring));

  body.perform(&7, Retirement::Erased).await;

  assert_eq!(
    store.seen().last(),
    Some(&Seen::Erase {
      key: 7,
      mirrored: true
    }),
    "the row is erased while the mirror still says retired — the durable half first"
  );
  assert!(!mirror.retired(&7));
  // THE THIRD STEP: `Restoring` waits on a write it does not hold and must be told, and this is the
  // party that tells it.
  assert!(matches!(registry.state(&7), RootState::Idle));
  assert_eq!(body.report().erased, 1);
}

#[tokio::test]
async fn a_refused_erase_leaves_the_key_restoring() {
  let registries = Registries::default();
  let registry = registries.open::<i64>("probe");
  let mirror = Arc::new(RetiredMirror::<i64>::new());
  let store = Probe::new(&mirror, true);
  let body = crate::Keeper::seated(
    &registry,
    store as Arc<dyn RetiredStore<i64>>,
    Arc::clone(&mirror),
  )
  .expect("nothing is seated on a fresh family");

  registry.rebuilt(&7, at(1), RetireOrigin::User, false);
  mirror.mark(7);
  let _asked = registry.restore(&7, Stamp::now());

  body.perform(&7, Retirement::Erased).await;

  assert!(mirror.retired(&7), "a refused erase publishes nothing");
  assert!(
    matches!(registry.state(&7), RootState::Restoring),
    "a key whose erase did not land has not been restored, and is not told that it has"
  );
  assert_eq!(body.report().refused, 1);
}

#[tokio::test]
async fn the_seat_queues_and_the_body_spends() {
  let registries = Registries::default();
  let registry = registries.open::<i64>("probe");
  let mirror = Arc::new(RetiredMirror::<i64>::new());
  let store = Probe::new(&mirror, false);
  let body = crate::Keeper::seated(
    &registry,
    store.clone() as Arc<dyn RetiredStore<i64>>,
    Arc::clone(&mirror),
  )
  .expect("nothing is seated on a fresh family");

  // The transition earns the act, the seat queues it, and NOTHING has been written yet — which is
  // the whole of *queue and return*.
  let _went = registry.retire(&5, RetireOrigin::User, Stamp::now());
  assert!(store.seen().is_empty());
  assert!(!mirror.retired(&5));

  // Dropping the registry drops the seat, which ends the line, which ends the body.
  drop(registry);
  drop(registries);
  body.run().await;

  assert_eq!(store.seen().len(), 1);
  assert!(mirror.retired(&5));
}

#[tokio::test]
async fn a_second_ledger_is_refused_and_the_first_keeps_the_acts() {
  let registries = Registries::default();
  let registry = registries.open::<i64>("probe");
  let mirror = Arc::new(RetiredMirror::<i64>::new());
  let first = crate::Keeper::seated(
    &registry,
    Probe::new(&mirror, false) as Arc<dyn RetiredStore<i64>>,
    Arc::clone(&mirror),
  );
  assert!(first.is_some());
  let second = crate::Keeper::seated(
    &registry,
    Probe::new(&mirror, false) as Arc<dyn RetiredStore<i64>>,
    Arc::clone(&mirror),
  );
  assert!(
    second.is_none(),
    "two writers for one family's rows is two parties disagreeing about what a retirement means"
  );
}

// ─── the boot road ────────────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn a_boot_states_what_the_ledger_says_and_earns_no_act() {
  let registries = Registries::default();
  let registry = registries.open::<i64>("probe");
  let mirror = Arc::new(RetiredMirror::<i64>::new());
  let store = Probe::new(&mirror, false);
  // Two rows, as if a previous process had written them.
  store
    .record(&RetiredRow::new(
      1,
      at(1_000),
      RetireOrigin::Vanished,
      false,
    ))
    .await
    .expect("the probe never refuses");
  store
    .record(&RetiredRow::new(
      2,
      at(2_000),
      RetireOrigin::Other("policy".into()),
      true,
    ))
    .await
    .expect("the probe never refuses");
  // The mirror the probe watched is not the one being rebuilt: a boot starts cold.
  let booted = Arc::new(RetiredMirror::<i64>::new());
  let seen = store.seen().len();

  let read = rebuild(store.as_ref(), &registry, &booted)
    .await
    .expect("the probe never refuses");

  assert_eq!(read, 2);
  assert_eq!(
    store.seen().len(),
    seen,
    "a rebuild WRITES NOTHING — it would otherwise re-record every row it had just read"
  );
  assert!(booted.retired(&1));
  assert!(booted.retired(&2));
  assert!(matches!(
    registry.state(&1),
    RootState::Retired {
      origin: RetireOrigin::Vanished,
      late_tails: false,
      ..
    }
  ));
  // The row's OWN facts come back, not the boot's: `at` is when the key went out, and `late_tails`
  // is a fact about a drain that ended in another process.
  let RootState::Retired {
    at: second_at,
    origin,
    late_tails,
  } = registry.state(&2)
  else {
    panic!("the ledger said this key was out");
  };
  assert_eq!(second_at, at(2_000));
  assert_eq!(origin, RetireOrigin::Other("policy".into()));
  assert!(late_tails);
}

#[tokio::test]
async fn a_rebuilt_vanished_key_still_comes_back_on_its_own() {
  let registries = Registries::default();
  let registry = registries.open::<i64>("probe");
  let mirror = Arc::new(RetiredMirror::<i64>::new());
  let store = Probe::new(&mirror, false);
  store
    .record(&RetiredRow::new(3, at(9), RetireOrigin::Vanished, false))
    .await
    .expect("the probe never refuses");
  let booted = Arc::new(RetiredMirror::<i64>::new());
  let _read = rebuild(store.as_ref(), &registry, &booted)
    .await
    .expect("the probe never refuses");

  // The whole point of writing the origin down: a restarted deployment still knows that THIS key
  // resurrects itself and a `User`-retired one does not.
  let _seen = registry.reappear(&3, Stamp::now());
  assert!(matches!(registry.state(&3), RootState::Restoring));
}

// ─── the statements ───────────────────────────────────────────────────────────────────────────

#[cfg(feature = "sqlite")]
mod sqlite {
  use crate::SqlRetired;

  fn ledger() -> SqlRetired<sqlx::Sqlite, i64> {
    SqlRetired::new(
      sqlx::Pool::connect_lazy("sqlite::memory:").expect("a lazy pool opens nothing"),
      "media",
    )
    .expect("`media` is a bare identifier")
  }

  // A RUNTIME, for a pool that connects to nothing: sqlx 0.9's `connect_lazy` spawns the pool's
  // maintenance task at construction, so even a pool that will never be used has to be built inside
  // one. Nothing here awaits anything.
  #[tokio::test]
  async fn the_four_statements_are_the_bytes_they_were() {
    let ledger = ledger();
    assert_eq!(
      ledger.create_statement(),
      r#"CREATE TABLE IF NOT EXISTS "__ig_retired_media" ("root" TEXT NOT NULL, "retired_second" INTEGER NOT NULL, "retired_nanosecond" INTEGER NOT NULL, "origin" TEXT NOT NULL, "late_tails" INTEGER NOT NULL, PRIMARY KEY ("root"))"#
    );
    assert_eq!(
      ledger.record_statement(),
      r#"INSERT INTO "__ig_retired_media" ("root", "retired_second", "retired_nanosecond", "origin", "late_tails") VALUES (?, ?, ?, ?, ?) ON CONFLICT ("root") DO UPDATE SET "origin" = excluded."origin""#
    );
    assert_eq!(
      ledger.erase_statement(),
      r#"DELETE FROM "__ig_retired_media" WHERE "root" = ?"#
    );
    assert_eq!(
      ledger.roll_statement(),
      r#"SELECT "root", "retired_second", "retired_nanosecond", "origin", "late_tails" FROM "__ig_retired_media""#
    );
  }
}

#[cfg(feature = "postgres")]
mod postgres {
  use crate::SqlRetired;

  // A RUNTIME for the lazy pool — see the SQLite lane's own note.
  #[tokio::test]
  async fn the_one_dialect_that_counts_its_parameters() {
    let ledger: SqlRetired<sqlx::Postgres, i64> = SqlRetired::new(
      sqlx::Pool::connect_lazy("postgres://ingraph@localhost/ingraph")
        .expect("a lazy pool opens nothing"),
      "media",
    )
    .expect("`media` is a bare identifier");
    assert_eq!(
      ledger.create_statement(),
      r#"CREATE TABLE IF NOT EXISTS "__ig_retired_media" ("root" text NOT NULL, "retired_second" bigint NOT NULL, "retired_nanosecond" integer NOT NULL, "origin" text NOT NULL, "late_tails" boolean NOT NULL, PRIMARY KEY ("root"))"#
    );
    assert_eq!(
      ledger.record_statement(),
      r#"INSERT INTO "__ig_retired_media" ("root", "retired_second", "retired_nanosecond", "origin", "late_tails") VALUES ($1, $2, $3, $4, $5) ON CONFLICT ("root") DO UPDATE SET "origin" = EXCLUDED."origin""#
    );
    assert_eq!(
      ledger.erase_statement(),
      r#"DELETE FROM "__ig_retired_media" WHERE "root" = $1"#
    );
  }
}

#[cfg(feature = "mysql")]
mod mysql {
  use crate::SqlRetired;

  // A RUNTIME for the lazy pool — see the SQLite lane's own note.
  #[tokio::test]
  async fn the_backticked_dialect_names_no_conflict_target() {
    let ledger: SqlRetired<sqlx::MySql, i64> = SqlRetired::new(
      sqlx::Pool::connect_lazy("mysql://ingraph@localhost/ingraph")
        .expect("a lazy pool opens nothing"),
      "media",
    )
    .expect("`media` is a bare identifier");
    assert_eq!(
      ledger.create_statement(),
      "CREATE TABLE IF NOT EXISTS `__ig_retired_media` (`root` varchar(255) NOT NULL, \
       `retired_second` bigint NOT NULL, `retired_nanosecond` int NOT NULL, `origin` \
       varchar(255) NOT NULL, `late_tails` tinyint(1) NOT NULL, PRIMARY KEY (`root`))"
    );
    assert_eq!(
      ledger.record_statement(),
      "INSERT INTO `__ig_retired_media` (`root`, `retired_second`, `retired_nanosecond`, \
       `origin`, `late_tails`) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE `origin` = \
       VALUES(`origin`)"
    );
  }
}

// ─── against a live database ──────────────────────────────────────────────────────────────────

/// What a rendered statement cannot show: that it executes, that the upsert updates the origin and
/// nothing else, and that a row round-trips through the columns it was written into.
#[cfg(feature = "sqlite")]
mod live {
  use super::{at, rebuild};

  use std::sync::Arc;

  use crate::{
    Registries, RetireOrigin, RetiredMirror, RetiredRow, RetiredStore, RootState, SqlRetired,
  };

  async fn ledger() -> SqlRetired<sqlx::Sqlite, i64> {
    // ONE connection, because `sqlite::memory:` is a database per connection — the same pin the DDL
    // lane's own live module takes, and for the same reason.
    let pool = sqlx::sqlite::SqlitePoolOptions::new()
      .max_connections(1)
      .connect("sqlite::memory:")
      .await
      .expect("an in-memory database");
    let ledger = SqlRetired::new(pool, "media").expect("`media` is a bare identifier");
    ledger.ready().await.expect("the table is created");
    ledger
  }

  #[tokio::test]
  async fn a_row_round_trips() {
    let ledger = ledger().await;
    assert!(ledger.roll().await.expect("an empty ledger").is_empty());

    let row = RetiredRow::new(7_i64, at(1_700_000_123), RetireOrigin::Vanished, true);
    ledger.record(&row).await.expect("the row is written");

    let rolled = ledger.roll().await.expect("the ledger reads back");
    assert_eq!(rolled, vec![row]);
  }

  #[tokio::test]
  async fn ready_is_idempotent() {
    let ledger = ledger().await;
    ledger
      .record(&RetiredRow::new(1_i64, at(5), RetireOrigin::User, false))
      .await
      .expect("the row is written");
    // `IF NOT EXISTS`, so a second boot over an existing ledger creates nothing and destroys
    // nothing.
    ledger.ready().await.expect("the table already exists");
    assert_eq!(ledger.roll().await.expect("the ledger reads back").len(), 1);
  }

  #[tokio::test]
  async fn a_second_record_moves_the_origin_and_nothing_else() {
    let ledger = ledger().await;
    let first = RetiredRow::new(7_i64, at(1_000), RetireOrigin::Vanished, true);
    ledger.record(&first).await.expect("the row is written");

    // A STRONGER ORIGIN, arriving with a different stamp and a different flag — as the state
    // machine's own arm produces it, carrying the ORIGINAL `at` and `late_tails`. The upsert must
    // not be trusted to be handed the right ones: it is asserted here that it keeps its own.
    let second = RetiredRow::new(7_i64, at(9_999), RetireOrigin::User, false);
    ledger.record(&second).await.expect("the row is rewritten");

    let rolled = ledger.roll().await.expect("the ledger reads back");
    assert_eq!(rolled.len(), 1);
    assert_eq!(rolled[0].origin(), &RetireOrigin::User);
    assert_eq!(rolled[0].at(), at(1_000));
    assert!(rolled[0].late_tails());
  }

  #[tokio::test]
  async fn an_erase_is_total_on_a_key_that_is_not_there() {
    let ledger = ledger().await;
    ledger.erase(&404_i64).await.expect("erasing nothing is Ok");
    assert!(ledger.roll().await.expect("an empty ledger").is_empty());
  }

  #[tokio::test]
  async fn an_open_origin_survives_the_round_trip() {
    let ledger = ledger().await;
    let row = RetiredRow::new(
      3_i64,
      at(42),
      RetireOrigin::Other("tenancy-ended".into()),
      false,
    );
    ledger.record(&row).await.expect("the row is written");
    assert_eq!(
      ledger.roll().await.expect("the ledger reads back")[0].origin(),
      &RetireOrigin::Other("tenancy-ended".into())
    );
  }

  #[tokio::test]
  async fn the_whole_road_end_to_end() {
    let ledger = Arc::new(ledger().await);
    let registries = Registries::default();
    let registry = registries.open::<i64>("media");
    let mirror = Arc::new(RetiredMirror::<i64>::new());
    let body = crate::Keeper::seated(
      &registry,
      Arc::clone(&ledger) as Arc<dyn RetiredStore<i64>>,
      Arc::clone(&mirror),
    )
    .expect("nothing is seated on a fresh family");

    // A person stands a key down; the seat queues, the body spends, the row lands, the mirror is
    // told.
    let _went = registry.retire(&7_i64, RetireOrigin::User, crate::Stamp::now());
    let _brought = registry.restore(&7_i64, crate::Stamp::now());
    drop(registry);
    drop(registries);
    body.run().await;

    assert!(
      ledger
        .roll()
        .await
        .expect("the ledger reads back")
        .is_empty(),
      "the retire's row was written and the restore's erase took it away"
    );
    assert!(!mirror.retired(&7));

    // AND THE BOOT: a fresh world reads the ledger and states what it says. Nothing is retired,
    // because nothing durable says anything is.
    let registries = Registries::default();
    let booted = registries.open::<i64>("media");
    let cold = RetiredMirror::<i64>::new();
    let read = rebuild(ledger.as_ref(), &booted, &cold)
      .await
      .expect("the ledger reads back");
    assert_eq!(read, 0);
    assert!(matches!(booted.state(&7), RootState::Idle));
  }
}